本文整理汇总了C#中PowerShell.AddCommand方法的典型用法代码示例。如果您正苦于以下问题:C# PowerShell.AddCommand方法的具体用法?C# PowerShell.AddCommand怎么用?C# PowerShell.AddCommand使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PowerShell
的用法示例。
在下文中一共展示了PowerShell.AddCommand方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
示例2: PowershellAdminModuleFixture
public PowershellAdminModuleFixture()
{
_powerShell = PowerShell.Create();
_powerShell.AddCommand("Import-Module").AddParameter("Name", typeof(CreateScope).Assembly.Location);
_database = Guid.NewGuid().ToString("N");
var client = new MongoClient("mongodb://localhost");
_server = client.GetServer();
var settings = StoreSettings.DefaultSettings();
settings.Database = _database;
_factory = new Factory(new ServiceFactory(null, settings), new AdminServiceRegistry());
}
示例3: 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);
}
示例4: MyConsole
public MyConsole()
{
InitializeComponent();
powershell = PowerShell.Create();
text = new StringBuilder();
prevcommands = new Stack<string>();
nextcommands = new Stack<string>();
powershell.AddCommand("Out-String");
this.textBox1.KeyUp += new KeyEventHandler(MyConsole_KeyUp);
this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
this.Show();
this.Activate();
}
示例5: 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);
}
示例6: 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);
}
}
}
}
示例7: Job
/// <summary>
/// New job.
/// </summary>
/// <remarks>
/// Keep seconds for UI-less jobs: 0 ~ hidden mode, in this case a job creates UI on errors, as it is not attended.
/// Other UI-less jobs are completely owned creators.
/// </remarks>
internal Job(JobCommand command, object parameters, string name, bool ui, int keepSeconds)
{
JobCommand = command;
Parameters = parameters;
Name = name;
KeepSeconds = keepSeconds;
// create/open runspace
//! *) Do not catch, if we fail, we fail and there is nothing to repair yet (not open)
//! *) Use existing configuration, it is faster! Most of *-Far* cmdlets should not be used,
//! but some of them can be used, e.g. Update-FarDescription; also we want to use ETS types,
//! e.g. FarDescription property.
if (ui)
{
JobUI = new JobUI();
Runspace = RunspaceFactory.CreateRunspace(new FarHost(JobUI), Runspace.DefaultRunspace.InitialSessionState);
}
else
{
//! DefaultHost is created internally. Perhaps it is reasonable to live with it, not with a custom host.
Runspace = RunspaceFactory.CreateRunspace(Runspace.DefaultRunspace.InitialSessionState);
}
Runspace.Open();
// new shell with the command
PowerShell = PowerShell.Create();
PowerShell.Runspace = Runspace;
JobCommand.Add(PowerShell);
// add command parameters
if (parameters != null)
{
IDictionary namedParameters = parameters as IDictionary;
IList argumentList;
if (namedParameters != null)
PowerShell.AddParameters(namedParameters);
else if ((argumentList = parameters as IList) != null)
PowerShell.AddParameters(argumentList);
else
PowerShell.AddParameters(new object[] { parameters });
}
// UI: Write all output, including errors.
if (JobUI != null)
{
PowerShell.Commands.AddCommand(A.OutHostCommand);
}
// Hidden: Write output to "Out-Null" to avoid memory use.
else if (keepSeconds <= 0)
{
//! User can use his Out-Null
PowerShell.AddCommand("Out-Null");
}
// Output: create it once: it is cumulative
else
{
Output = new PSDataCollection<PSObject>();
}
}
示例8: 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;
}
}
}
示例9: ProcessCommand
/// <summary>
/// Process debugger command.
/// </summary>
/// <param name="command">Debugger PSCommand</param>
/// <param name="output">Output</param>
/// <returns>DebuggerCommandResults</returns>
public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
{
CheckForValidateState();
_detachCommand = false;
if (command == null)
{
throw new PSArgumentNullException("command");
}
if (output == null)
{
throw new PSArgumentNullException("output");
}
if (!DebuggerStopped)
{
throw new PSInvalidOperationException(
DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
null,
Debugger.CannotProcessCommandNotStopped,
ErrorCategory.InvalidOperation,
null);
}
DebuggerCommandResults results = null;
// Execute command on server.
bool executionError = false;
using (_psDebuggerCommand = GetNestedPowerShell())
{
foreach (var cmd in command.Commands)
{
cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
_psDebuggerCommand.AddCommand(cmd);
}
PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
internalOutput.DataAdded += (sender, args) =>
{
foreach (var item in internalOutput.ReadAll())
{
if (item == null) { return; }
DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
if (dbgCmd != null)
{
bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
}
else if (item.BaseObject is DebuggerCommandResults)
{
results = item.BaseObject as DebuggerCommandResults;
}
else
{
output.Add(item);
}
}
};
try
{
_psDebuggerCommand.Invoke(null, internalOutput, null);
}
catch (Exception e)
{
CommandProcessor.CheckForSevereException(e);
executionError = true;
RemoteException re = e as RemoteException;
if ((re != null) && (re.ErrorRecord != null))
{
// Allow the IncompleteParseException to throw so that the console
// can handle here strings and continued parsing.
if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name)
{
throw new IncompleteParseException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null,
re.ErrorRecord.FullyQualifiedErrorId);
}
// Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can
// clean up the debug session.
if ((re.ErrorRecord.CategoryInfo.Reason == typeof(InvalidRunspacePoolStateException).Name) ||
(re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name))
{
throw new PSRemotingTransportException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty);
}
}
// Allow all PSRemotingTransportException and RemoteException errors to propagate as this
// indicates a broken debug session.
//.........这里部分代码省略.........