本文整理汇总了C#中PowerShell.Invoke方法的典型用法代码示例。如果您正苦于以下问题:C# PowerShell.Invoke方法的具体用法?C# PowerShell.Invoke怎么用?C# PowerShell.Invoke使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PowerShell
的用法示例。
在下文中一共展示了PowerShell.Invoke方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EmsSession
public EmsSession()
{
powershell = PowerShell.Create();
PSSnapInException ex;
powershell
.Runspace
.RunspaceConfiguration
.AddPSSnapIn(
"Microsoft.Exchange.Management.PowerShell.E2013",
out ex);
if (ex != null)
throw ex;
powershell.AddScript(
". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
powershell.AddScript("Connect-ExchangeServer -auto");
powershell.Invoke();
powershell.Streams.ClearStreams();
powershell.Commands.Clear();
}
示例2: SetTestStorageAccount
private void SetTestStorageAccount(PowerShell powershell)
{
if (String.IsNullOrEmpty(EnvConnectionStringInPowerShell))
{
PSCommand currentCommand = powershell.Commands.Clone();
string envConnStringScript = string.Format("$env:{0}", Test.Data.Get("EnvContextKey"));
powershell.AddScript(envConnStringScript);
Collection<PSObject> output = powershell.Invoke();
if (output.Count == 1)
{
EnvConnectionStringInPowerShell = output[0].BaseObject.ToString();
powershell.Commands = currentCommand;
}
else
{
Test.AssertFail("Can not find the environment variable 'AZURE_STORAGE_CONNECTION_STRING' in powershell instance");
}
}
if (String.IsNullOrEmpty(EnvConnectionStringInPowerShell))
{
throw new ArgumentException("Please set the StorageConnectionString element of TestData.xml");
}
CommonStorageAccount = CloudStorageAccount.Parse(EnvConnectionStringInPowerShell);
CommonBlobHelper = new CloudBlobHelper(CommonStorageAccount);
}
示例3: PowerShellSession
public PowerShellSession(ILogger log)
{
_proc = PowerShell.Create();
_log = log;
_proc.Commands.Clear();
_proc.AddCommand("cd\\");
_proc.Invoke();
_proc.Commands.Clear();
_proc.AddCommand("Get-Location");
_proc.AddCommand("Out-String");
CurrentPath = _proc.Invoke()
.First()
.ToString()
.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)[2].Trim();
}
示例4: EnsureInitialized
public static async Task EnsureInitialized(ITaskRunnerCommandContext context)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
Task existing = Interlocked.CompareExchange(ref _initTask, tcs.Task, null);
//If we own the initialization...
if (existing == null)
{
_ps = PowerShell.Create();
_ps.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted –Force");
_ps.Invoke();
_ps.Commands.Clear();
string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
ModulePath = Path.Combine(localAppData, "Ligershark\\tools\\geoffrey-pre\\geoffrey.psm1");
// you can override the location of the PSModule with this env var
string modulePathEnv = Environment.GetEnvironmentVariable("GeoffreyPsModulePath");
if (!string.IsNullOrWhiteSpace(modulePathEnv) && File.Exists(modulePathEnv)) {
ModulePath = modulePathEnv;
}
//If we don't already have geoffrey installed, install it
if (!File.Exists(ModulePath))
{
await InstallGeoffreyAsync();
}
_ps.Commands.Clear();
Command importModule = new Command("Import-Module");
importModule.Parameters.Add("Name", ModulePath);
_ps.Commands.AddCommand(importModule);
_ps.Invoke();
tcs.SetResult(true);
return;
}
await existing;
}
示例5: Global
public Global()
{
var fileName = Path.GetFileName(Assembly.GetCallingAssembly().CodeBase);
var configFileName = fileName + ".ps1";
ps = PowerShell.Create();
if (File.Exists(configFileName))
{
const string initScript = @"
function Add-ConfigItem($name, $value)
{
Set-Variable -Name $name -Value $value -Scope global
}
";
ps.AddScript(initScript);
ps.Invoke();
var profileScript = File.ReadAllText(configFileName);
ps.AddScript(profileScript);
ps.Invoke();
}
}
示例6: RunTest
public override PowerShellTestResult RunTest(PowerShell powerShell, TestCase testCase, IRunContext runContext)
{
var module = FindModule("Pester", runContext);
powerShell.AddCommand("Import-Module").AddParameter("Name", module);
powerShell.Invoke();
powerShell.Commands.Clear();
var fi = new FileInfo(testCase.CodeFilePath);
var tempFile = Path.GetTempFileName();
var describeName = testCase.FullyQualifiedName.Split(new[] {"||"}, StringSplitOptions.None)[1];
var testCaseName = testCase.FullyQualifiedName.Split(new[] { "||" }, StringSplitOptions.None)[3];
powerShell.AddCommand("Invoke-Pester")
.AddParameter("relative_path", fi.Directory.FullName)
.AddParameter("TestName", describeName)
.AddParameter("OutputXml", tempFile);
powerShell.Invoke();
return ParseResultFile(tempFile, fi.Directory.FullName, describeName, testCaseName);
}
示例7: RunTest
public override PowerShellTestResult RunTest(PowerShell powerShell, TestCase testCase, IRunContext runContext)
{
var module = FindModule("PSate", runContext);
powerShell.AddCommand("Import-Module").AddParameter("Name", module);
powerShell.Invoke();
powerShell.Commands.Clear();
powerShell.AddCommand("Invoke-Tests")
.AddParameter("Path", testCase.CodeFilePath)
.AddParameter("Output", "Results")
.AddParameter("ResultsVariable", "Results");
powerShell.Invoke();
powerShell.Commands.Clear();
powerShell.AddCommand("Get-Variable").AddParameter("Name", "Results");
var results = powerShell.Invoke<PSObject>();
if (powerShell.HadErrors && (results == null || !results.Any()))
{
var errors = powerShell.Streams.Error;
var sb = new StringBuilder();
foreach (var error in errors)
{
sb.AppendLine(error.ToString());
}
return new PowerShellTestResult(TestOutcome.Failed, sb.ToString(), errors.FirstOrDefault().ScriptStackTrace);
}
var testFixture = testCase.FullyQualifiedName.Split(new []{"||"}, StringSplitOptions.None)[1];
var testCaseName = testCase.FullyQualifiedName.Split(new[] { "||" }, StringSplitOptions.None)[2];
return ParseTestResult(results.FirstOrDefault(), testFixture, testCaseName);
}
示例8: executeCommand
static void executeCommand(PowerShell ps, String cmd)
{
try
{
ps.AddScript(cmd);
Collection<PSObject> output = ps.Invoke();
if (output != null)
{
foreach (PSObject rtnItem in output)
{
Console.WriteLine(rtnItem.ToString());
}
}
}
catch (Exception e)
{
Console.WriteLine("\n[!] "+e.Message);
}
}
示例9: ExecutePowerShell
static void ExecutePowerShell(PowerShell psi, bool verbose)
{
Collection<PSObject> powershelloutput = psi.Invoke();
foreach (PSObject outputItem in powershelloutput)
{
if (outputItem != null)
{
if (verbose)
{
Console.WriteLine(outputItem.BaseObject.GetType().FullName);
Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
}
}
}
if (psi.Streams.Error.Count > 0)
{
foreach (var e in psi.Streams.Error)
{
Console.WriteLine(e.Exception.Message);
}
Console.ReadKey();
}
}
示例10: ReportException
/// <summary>
/// To display an exception using the display formatter,
/// run a second pipeline passing in the error record.
/// The runtime will bind this to the $input variable,
/// which is why $input is being piped to the Out-String
/// cmdlet. The WriteErrorLine method is called to make sure
/// the error gets displayed in the correct error color.
/// </summary>
/// <param name="e">The exception to display.</param>
private void ReportException(Exception e)
{
if (e == null) return;
var icer = e as IContainsErrorRecord;
object error = icer != null ? icer.ErrorRecord : new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
lock (_instanceLock)
{
_currentPowerShell = PowerShell.Create();
}
_currentPowerShell.Runspace = _runspace;
try
{
_currentPowerShell.AddScript("$input").AddCommand("out-string");
// Do not merge errors, this function will swallow errors.
var inputCollection = new PSDataCollection<object> {error};
inputCollection.Complete();
var result = _currentPowerShell.Invoke(inputCollection);
if (result.Count > 0)
{
var str = result[0].BaseObject as string;
if (!string.IsNullOrEmpty(str))
{
// Remove \r\n, which is added by the Out-String cmdlet.
_host.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
}
}
}
finally
{
// Dispose of the pipeline and set it to null, locking it because
// currentPowerShell may be accessed by the ctrl-C handler.
lock (_instanceLock)
{
_currentPowerShell.Dispose();
_currentPowerShell = null;
}
}
}
示例11: ExecuteHelper
/// <summary>
/// A helper class that builds and executes a pipeline that writes
/// to the default output path. Any exceptions that are thrown are
/// just passed to the caller. Since all output goes to the default
/// outter, this method does not return anything.
/// </summary>
/// <param name="cmd">The script to run.</param>
/// <param name="input">
/// Any input arguments to pass to the script.
/// If null then nothing is passed in.
/// </param>
private void ExecuteHelper(string cmd, object input)
{
// Ignore empty command lines.
if (String.IsNullOrEmpty(cmd))
{
return;
}
// Create the pipeline object and make it available to the
// ctrl-C handle through the currentPowerShell instance
// variable.
lock (_instanceLock)
{
_currentPowerShell = PowerShell.Create();
}
// Add a script and command to the pipeline and then run the pipeline. Place
// the results in the currentPowerShell variable so that the pipeline can be
// stopped.
try
{
_currentPowerShell.Runspace = _runspace;
_currentPowerShell.AddScript(cmd);
// Add the default outputter to the end of the pipe and then call the
// MergeMyResults method to merge the output and error streams from the
// pipeline. This will result in the output being written using the PSHost
// and PSHostUserInterface classes instead of returning objects to the host
// application.
_currentPowerShell.AddCommand("out-default");
_currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
// If there is any input pass it in, otherwise just invoke the
// the pipeline.
if (input != null)
{
_currentPowerShell.Invoke(new[] {input});
}
else
{
_currentPowerShell.Invoke();
}
}
finally
{
// Dispose the PowerShell object and set currentPowerShell to null.
// It is locked because currentPowerShell may be accessed by the
// ctrl-C handler.
lock (_instanceLock)
{
_currentPowerShell.Dispose();
_currentPowerShell = null;
}
}
}
示例12: Start
void Start(ScriptBlock scriptBlock, Hashtable parameters)
{
SessionStateAssemblyEntry windowsBase = new SessionStateAssemblyEntry(typeof(Dispatcher).Assembly.ToString());
SessionStateAssemblyEntry presentationCore = new SessionStateAssemblyEntry(typeof(UIElement).Assembly.ToString());
SessionStateAssemblyEntry presentationFramework = new SessionStateAssemblyEntry(typeof(Control).Assembly.ToString());
initialSessionState.Assemblies.Add(windowsBase);
initialSessionState.Assemblies.Add(presentationCore);
initialSessionState.Assemblies.Add(presentationFramework);
initialSessionState.Assemblies.Add(presentationFramework);
runspace = RunspaceFactory.CreateRunspace(this.initialSessionState);
runspace.ThreadOptions = PSThreadOptions.ReuseThread;
runspace.ApartmentState = ApartmentState.STA;
runspace.Open();
powerShellCommand = PowerShell.Create();
powerShellCommand.Runspace = runspace;
jobThread = powerShellCommand.AddScript("[Threading.Thread]::CurrentThread").Invoke<Thread>()[0];
powerShellCommand.Streams.Error = this.Error;
this.Error.DataAdded += new EventHandler<DataAddedEventArgs>(Error_DataAdded);
powerShellCommand.Streams.Warning = this.Warning;
this.Warning.DataAdded += new EventHandler<DataAddedEventArgs>(Warning_DataAdded);
powerShellCommand.Streams.Verbose = this.Verbose;
this.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded);
powerShellCommand.Streams.Debug = this.Debug;
this.Debug.DataAdded += new EventHandler<DataAddedEventArgs>(Debug_DataAdded);
powerShellCommand.Streams.Progress = this.Progress;
this.Progress.DataAdded += new EventHandler<DataAddedEventArgs>(Progress_DataAdded);
this.Output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded);
powerShellCommand.Commands.Clear();
powerShellCommand.Commands.AddScript(scriptBlock.ToString(), false);
if (parameters.Count > 0)
{
powerShellCommand.AddParameters(parameters);
}
Collection<Visual> output = powerShellCommand.Invoke<Visual>();
if (output.Count == 0)
{
return;
}
powerShellCommand.Commands.Clear();
powerShellCommand.Commands.AddCommand("Show-Window").AddArgument(output[0]).AddParameter("OutputWindowFirst");
Object var = powerShellCommand.Runspace.SessionStateProxy.GetVariable("NamedControls");
if (var != null && ((var as Hashtable) != null))
{
namedControls = var as Hashtable;
}
JobDispatcher = Dispatcher.FromThread(jobThread);
JobDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(jobDispatcher_UnhandledException);
powerShellCommand.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(powerShellCommand_InvocationStateChanged);
powerShellCommand.BeginInvoke<Object, PSObject>(null, this.Output);
DateTime startTime = DateTime.Now;
if (output[0] is FrameworkElement)
{
while (JobWindow == null)
{
if ((DateTime.Now - startTime) > TimeSpan.FromSeconds(30))
{
this.SetJobState(JobState.Failed);
return;
}
System.Threading.Thread.Sleep(25);
}
}
}
示例13: Remove_AcceptedDomain
/// <summary>
/// Removes a new accepted domain in Exchange
/// </summary>
/// <param name="domainName">DomainName to remove</param>
public void Remove_AcceptedDomain(string domainName)
{
try
{
// Start clock
Stopwatch stopwatch = Stopwatch.StartNew();
// INFO //
this.logger.Info("Disabling " + domainName + " as an Accepted Domain in Exchange");
// Run commands
powershell = PowerShell.Create();
powershell.Runspace = runspace;
PSCommand cmd = new PSCommand();
cmd.AddCommand("Remove-AcceptedDomain");
cmd.AddParameter("Identity", domainName);
cmd.AddParameter("DomainController", domainController);
cmd.AddParameter("Confirm", false);
powershell.Commands = cmd;
powershell.Invoke();
// Stop the clock
stopwatch.Stop();
// Check for errors
CheckErrors(ref powershell);
// INFO //
this.logger.Info("Successfully disabled " + domainName + " as an Accepted Domain in Exchange in " + stopwatch.Elapsed.ToString() + " second(s)");
}
catch (Exception)
{
// FATAL //
this.logger.Fatal("Failed to disable " + domainName + " as an Accepted Domain in Exchange.");
throw;
}
finally
{
if (powershell != null)
powershell.Dispose();
}
}
示例14: NewAzureStorageContext
internal bool NewAzureStorageContext(PowerShell ps)
{
ParseContainerCollection(ps.Invoke());
ParseErrorMessages(ps);
return !ps.HadErrors;
}
示例15: New_AddressList
/// <summary>
/// Creates a new address list for a specific company
/// </summary>
/// <param name="companyCode">CompanyCode to create address list for</param>
/// <param name="addrType">Type of address list to add</param>
public void New_AddressList(string companyCode, AddressListType addrType)
{
try
{
// Strip whitespace from company code
companyCode = companyCode.Replace(" ", string.Empty);
// Start clock
Stopwatch stopwatch = Stopwatch.StartNew();
// DEBUG //
logger.Debug("Creating new address list [" + addrType.ToString() + "] for company code " + companyCode);
// Run commands
powershell = PowerShell.Create();
powershell.Runspace = runspace;
// Figure out what address list we are creating
string recipientFilter = string.Empty;
string addressListName = string.Empty;
switch (addrType)
{
case AddressListType.ConferenceRoomMailbox:
recipientFilter = string.Format(@"((Alias -ne $null) -and (CustomAttribute1 -eq '{0}') -and (((RecipientDisplayType -eq 'ConferenceRoomMailbox') -or (RecipientDisplayType -eq 'SyncedConferenceRoomMailbox'))))", companyCode);
addressListName = string.Format("{0} - {1}", companyCode, "All Rooms");
break;
case AddressListType.User:
recipientFilter = string.Format(@"((Alias -ne $null) -and (CustomAttribute1 -eq '{0}') -and (((((ObjectCategory -like 'person') -and (ObjectClass -eq 'user') -and (-not(Database -ne $null)) -and (-not(ServerLegacyDN -ne $null)))) -or (((ObjectCategory -like 'person') -and (ObjectClass -eq 'user') -and (((Database -ne $null) -or (ServerLegacyDN -ne $null))))))))", companyCode);
addressListName = string.Format("{0} - {1}", companyCode, "All Users");
break;
case AddressListType.Contact:
recipientFilter = string.Format(@"((Alias -ne $null) -and (CustomAttribute1 -eq '{0}') -and (((ObjectCategory -like 'person') -and (ObjectClass -eq 'contact'))))", companyCode);
addressListName = string.Format("{0} - {1}", companyCode, "All Contacts");
break;
case AddressListType.Group:
recipientFilter = string.Format(@"((Alias -ne $null) -and (CustomAttribute1 -eq '{0}') -and (ObjectCategory -like 'group'))", companyCode);
addressListName = string.Format("{0} - {1}", companyCode, "All Groups");
break;
default:
throw new Exception("Invalid address list type was supplied. Supplied value: " + addrType.ToString());
}
PSCommand cmd = new PSCommand();
cmd.AddCommand("New-AddressList");
cmd.AddParameter("Name", addressListName);
cmd.AddParameter("RecipientFilter", recipientFilter);
cmd.AddParameter("DomainController", domainController);
powershell.Commands = cmd;
powershell.Invoke();
// Stop the clock
stopwatch.Stop();
// Check for errors
CheckErrors(ref powershell);
// DEBUG //
logger.Debug("Successfully created new address list [" + addrType.ToString() + "] for company code " + companyCode + " in " + stopwatch.Elapsed.ToString() + " second(s)");
}
catch (Exception ex)
{
// Do not throw error if it already exists
if (!ex.ToString().Contains("already exists"))
throw;
else
this.logger.Info("Powershell error was thrown because the address list already existed. Continuing without error.");
}
finally
{
if (powershell != null)
powershell.Dispose();
}
}