本文整理汇总了C#中PowerShell.AddScript方法的典型用法代码示例。如果您正苦于以下问题:C# PowerShell.AddScript方法的具体用法?C# PowerShell.AddScript怎么用?C# PowerShell.AddScript使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PowerShell
的用法示例。
在下文中一共展示了PowerShell.AddScript方法的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: ExecuteScript
public void ExecuteScript(ScriptConfigElement e)
{
using (_instance = PowerShell.Create())
{
_instance.AddScript(File.ReadAllText(e.PathToScript));
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += outputCollection_DataAdded;
_instance.Streams.Progress.DataAdded += Progress_DataAdded;
_instance.Streams.Error.DataAdded += Error_DataAdded;
_instance.Streams.Verbose.DataAdded += Verbose_DataAdded;
_instance.Streams.Debug.DataAdded += Debug_DataAdded;
_instance.Streams.Warning.DataAdded += Warning_DataAdded;
IAsyncResult result = _instance.BeginInvoke<PSObject, PSObject>(null,
outputCollection);
while (result.IsCompleted == false)
{
Thread.Sleep(500);
}
foreach (PSObject o in outputCollection)
{
Console.WriteLine(o.GetType());
Console.WriteLine(o);
}
}
}
示例4: Start
/// <summary>
/// Called to start the COM handler.
/// </summary>
/// <param name="data">Data string passed in from Task Scheduler action.</param>
public override void Start(string data)
{
psInstance = PowerShell.Create();
psInstance.AddScript(data);
result = psInstance.BeginInvoke();
psInstance.InvocationStateChanged += PowerShellInstance_InvocationStateChanged;
}
示例5: SetupPowerShellEnvironment
public void SetupPowerShellEnvironment(PowerShell powerShell, string credentials, string profile)
{
powerShell.RemoveCredentials();
string profileFile = Path.Combine(this.downloadDirectoryPath, profile);
if (File.Exists(profileFile))
{
string dest = Path.Combine(GlobalPathInfo.GlobalSettingsDirectory, profile);
powerShell.AddScript(string.Format("Copy-Item -Path '{0}' -Destination '{1}' -Force", profileFile, dest));
powerShell.AddScript("[Microsoft.WindowsAzure.Commands.Utilities.Common.WindowsAzureProfile]::Instance.Load()");
}
else
{
string credentialFile = Path.Combine(this.downloadDirectoryPath, credentials);
Assert.IsTrue(File.Exists(credentialFile), string.Format("Did not download file {0}", credentialFile));
Console.WriteLine("Using default.PublishSettings for setting up credentials");
powerShell.ImportCredentials(credentialFile);
}
foreach (string key in this.environment.Keys) powerShell.AddEnvironmentVariable(key, environment[key]);
foreach (string key in this.PowerShellVariables.Keys) powerShell.SetVariable(key, PowerShellVariables[key]);
}
示例6: TestSetup
public virtual void TestSetup()
{
powershell = PowerShell.Create();
foreach (string moduleName in modules)
{
powershell.AddScript(string.Format("Import-Module \"{0}\"", Testing.GetTestResourcePath(moduleName)));
}
powershell.AddScript("$VerbosePreference='Continue'");
powershell.AddScript("$DebugPreference='Continue'");
powershell.AddScript("$ErrorActionPreference='Stop'");
}
示例7: 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();
}
}
示例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: 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;
}
示例10: AttachPipeline
private void AttachPipeline(PowerShell ps)
{
foreach (string cmd in pipeLine)
{
if (cmd.Length > 0 && cmd[0] == '$')
{
ps.AddScript(cmd);
}
else
{
string[] cmdOpts = cmd.Split(' ');
string cmdName = cmdOpts[0];
ps.AddCommand(cmdName);
string opts = string.Empty;
bool skip = false;
for (int i = 1; i < cmdOpts.Length; i++)
{
if (skip)
{
skip = false;
continue;
}
if (cmdOpts[i].IndexOf("-") != 0)
{
ps.AddArgument(cmdOpts[i]);
}
else
{
if (i + 1 < cmdOpts.Length && cmdOpts[i + 1].IndexOf("-") != 0)
{
ps.AddParameter(cmdOpts[i].Substring(1), cmdOpts[i + 1]);
skip = true;
}
else
{
ps.AddParameter(cmdOpts[i].Substring(1));
skip = false;
}
}
}
//add storage context for azure storage cmdlet
//It make sure all the storage cmdlet in pipeline use the same storage context
if (cmdName.ToLower().IndexOf("-azurestorage") != -1)
{
AddCommonParameters(ps);
}
}
}
}
示例11: OpenRunspace
/// <summary>
/// Opens a embedded PowerShell runspace.
/// </summary>
private void OpenRunspace()
{
if (!isRunspaceActive)
{
rs = RunspaceFactory.CreateRunspace();
rs.ThreadOptions = PSThreadOptions.UseCurrentThread;
ps = PowerShell.Create();
ps.Runspace = rs;
rs.Open();
// Loads form objects into runspace
LoadFormObjects();
try
{
foreach (string cmd in textBoxRunspaceStartup.Lines)
{
ps.AddScript(cmd);
}
ps.Invoke();
isRunspaceActive = true;
}
catch (Exception ex)
{
textBoxLog.Text += ex.ToString() + System.Environment.NewLine;
}
ps.Commands.Clear();
}
}
示例12: StartPowerShellCommand
internal void StartPowerShellCommand(
PowerShell powershell,
Guid powershellId,
Guid runspacePoolId,
ServerRunspacePoolDriver runspacePoolDriver,
#if !CORECLR // No ApartmentState In CoreCLR
ApartmentState apartmentState,
#endif
ServerRemoteHost remoteHost,
HostInfo hostInfo,
RemoteStreamOptions streamOptions,
bool addToHistory)
{
// For nested debugger command processing, invoke command on new local runspace since
// the root script debugger runspace is unavailable (it is running a PS script or a
// workflow function script).
Runspace runspace = (remoteHost != null) ?
RunspaceFactory.CreateRunspace(remoteHost) : RunspaceFactory.CreateRunspace();
runspace.Open();
try
{
powershell.InvocationStateChanged += HandlePowerShellInvocationStateChanged;
powershell.SetIsNested(false);
string script = @"
param ($Debugger, $Commands, $output)
trap { throw $_ }
$Debugger.ProcessCommand($Commands, $output)
";
PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
PSCommand Commands = new PSCommand(powershell.Commands);
powershell.Commands.Clear();
powershell.AddScript(script).AddParameter("Debugger", this).AddParameter("Commands", Commands).AddParameter("output", output);
ServerPowerShellDriver driver = new ServerPowerShellDriver(
powershell,
null,
true,
powershellId,
runspacePoolId,
runspacePoolDriver,
#if !CORECLR // No ApartmentState In CoreCLR
apartmentState,
#endif
hostInfo,
streamOptions,
addToHistory,
runspace,
output);
driver.Start();
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
runspace.Close();
runspace.Dispose();
}
}
示例13: RunScript
private async Task<bool> RunScript(string path)
{
PowerShellInstance = PowerShell.Create();
PowerShellInstance.AddScript(LoadScript(path));
PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.SourceRepoUserName));
PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.SourceRepoPassword));
PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.TargetRepoUserName));
PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.TargetRepoPassword));
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += outputCollection_DataAdded;
PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded;
IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject,PSObject>(null, outputCollection);
while (result.IsCompleted == false)
{
await Task.Delay(100);
}
return PowerShellInstance.HadErrors;
}
示例14: IsWorkflowConfigurationType
private bool IsWorkflowConfigurationType(PowerShell ps)
{
ps.AddScript(string.Format(CultureInfo.InvariantCulture, @"(Get-Item 'WSMan:\localhost\Plugin\{0}\InitializationParameters\assemblyname').Value", new object[] { CommandMetadata.EscapeSingleQuotedString(base.Name) }));
Collection<PSObject> collection = ps.Invoke(new object[] { base.Name });
if (collection != null)
{
int count = collection.Count;
}
if (collection[0] == null)
{
return false;
}
return collection[0].BaseObject.ToString().Equals("Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL", StringComparison.OrdinalIgnoreCase);
}
示例15: 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;
}
}
}