本文整理汇总了C#中System.Management.Automation.Runspaces.Command类的典型用法代码示例。如果您正苦于以下问题:C# Command类的具体用法?C# Command怎么用?C# Command使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Command类属于System.Management.Automation.Runspaces命名空间,在下文中一共展示了Command类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PSTestScope
public PSTestScope(bool connect = true)
{
SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];
var iss = InitialSessionState.CreateDefault();
if (connect)
{
SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);
iss.Commands.Add(ssce);
}
_runSpace = RunspaceFactory.CreateRunspace(iss);
_runSpace.Open();
if (connect)
{
var pipeLine = _runSpace.CreatePipeline();
Command cmd = new Command("connect-sponline");
cmd.Parameters.Add("Url", SiteUrl);
if (!string.IsNullOrEmpty(CredentialManagerEntry))
{
cmd.Parameters.Add("Credentials", CredentialManagerEntry);
}
pipeLine.Commands.Add(cmd);
pipeLine.Invoke();
}
}
示例2: BuildCommand
protected override Command BuildCommand()
{
var result = new Command(CommandName);
if (String.IsNullOrWhiteSpace(Location) == false)
{
result.Parameters.Add(LocationParameter, Location);
}
if (String.IsNullOrWhiteSpace(ServiceName) == false)
{
result.Parameters.Add(ServiceNameParameter, ServiceName);
}
if (String.IsNullOrWhiteSpace(DeploymentName) == false)
{
result.Parameters.Add(DeploymentNameParameter, DeploymentName);
}
if (WaitForBoot)
{
result.Parameters.Add(WaitForBootParameter);
}
return result;
}
示例3: Execute
internal override void Execute(Pash.Implementation.ExecutionContext context, ICommandRuntime commandRuntime)
{
ExecutionContext nestedContext = context.CreateNestedContext();
if (! (context.CurrentRunspace is LocalRunspace))
throw new InvalidOperationException("Invalid context");
// MUST: fix this with the commandRuntime
Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline();
context.PushPipeline(pipeline);
try
{
Command cmd = new Command("Get-Variable");
cmd.Parameters.Add("Name", new string[] { Text });
// TODO: implement command invoke
pipeline.Commands.Add(cmd);
commandRuntime.WriteObject(pipeline.Invoke(), true);
//context.outputStreamWriter.Write(pipeline.Invoke(), true);
}
catch (Exception)
{
throw;
}
finally
{
context.PopPipeline();
}
}
示例4: InitializeTests
public void InitializeTests()
{
RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("ShareFile", out warning);
runspace = RunspaceFactory.CreateRunspace(config);
runspace.Open();
// do login first to start tests
using (Pipeline pipeline = runspace.CreatePipeline())
{
Command command = new Command("Get-SfClient");
command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));
pipeline.Commands.Add(command);
Collection<PSObject> objs = pipeline.Invoke();
Assert.AreEqual<int>(1, objs.Count);
sfLogin = objs[0];
}
}
示例5: SetVariable
public override void SetVariable(string name, object value)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException("name");
}
if (this.setVariableCommandNotFoundException != null)
{
throw this.setVariableCommandNotFoundException;
}
Pipeline pipeline = this._runspace.CreatePipeline();
Command item = new Command(@"Microsoft.PowerShell.Utility\Set-Variable");
item.Parameters.Add("Name", name);
item.Parameters.Add("Value", value);
pipeline.Commands.Add(item);
try
{
pipeline.Invoke();
}
catch (RemoteException exception)
{
if (string.Equals("CommandNotFoundException", exception.ErrorRecord.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase))
{
this.setVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, exception);
throw this.setVariableCommandNotFoundException;
}
throw;
}
if (pipeline.Error.Count > 0)
{
ErrorRecord record = (ErrorRecord) pipeline.Error.Read();
throw new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, record.Exception);
}
}
示例6: SubscriptionEventNotification
public bool SubscriptionEventNotification(SubscriptionNotification notification)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
var myCmd = new Command( Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "Invoke-Subscriber.ps1" ) );
myCmd.Parameters.Add( new CommandParameter( "event", notification.NotificationType.ToString() ));
myCmd.Parameters.Add( new CommandParameter( "href", notification.RelativeHref ));
myCmd.Parameters.Add( new CommandParameter( "subscriptions", notification.SubscriptionArray ));
myCmd.Parameters.Add( new CommandParameter( "changes", notification.ChangesArray ));
pipeline.Commands.Add( myCmd );
// Execute PowerShell script
// Instead of implementing our own Host and HostUI we keep this extremely simple by
// catching everything to cope with HostExceptions and UnknownCommandExceptions etc.
// The first will be thrown if someone tries to access unsupported (i.e. interactive)
// host features such as Read-Host and the latter will occur for all unsupported commands.
// That can easily happen if a script is missing an import-module or just contains a mispelled command
try
{
var result = pipeline.Invoke().FirstOrDefault();
return result != null && result.BaseObject is bool && (bool)result.BaseObject;
}
catch (Exception ex)
{
Trace.WriteLine("Exception caught when invoking powershell script: " + ex);
return false;
}
}
示例7: ExecuteScript
public ActionResult ExecuteScript(string scriptname, string env, string machine)
{
var model = new MachineCommand {Command = scriptname, Result = ""};
var scriptfilename = Path.Combine(Server.MapPath("~/App_Data/Scripts/"), scriptname);
using (var runspace = RunspaceFactory.CreateRunspace()) {
runspace.Open();
var pipeline = runspace.CreatePipeline();
var newCommand = new Command(scriptfilename);
newCommand.Parameters.Add(new CommandParameter("env", env));
newCommand.Parameters.Add(new CommandParameter("machine", machine));
pipeline.Commands.Add(newCommand);
var results = pipeline.Invoke();
// convert the script result into a single string
var stringBuilder = new StringBuilder();
foreach (var obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
model.Result = stringBuilder.ToString();
}
return View(model);
}
示例8: ExecuteCommand
internal Collection<PSObject> ExecuteCommand(string command, bool isScript, out Exception exceptionThrown, Hashtable args)
{
exceptionThrown = null;
if (this.CancelTabCompletion)
{
return new Collection<PSObject>();
}
this.CurrentPowerShell.AddCommand(command);
Command command2 = new Command(command, isScript);
if (args != null)
{
foreach (DictionaryEntry entry in args)
{
command2.Parameters.Add((string) entry.Key, entry.Value);
}
}
Collection<PSObject> collection = null;
try
{
if (this.IsStopped)
{
collection = new Collection<PSObject>();
this.CancelTabCompletion = true;
}
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
exceptionThrown = exception;
}
return collection;
}
示例9: RunCommand
public CommandResult RunCommand(ShellCommand command)
{
var host = new GoosePSHost();
var results = new List<string>();
using (var runspace = RunspaceFactory.CreateRunspace(host))
{
var setWorkingDirectory = new Command("set-location");
setWorkingDirectory.Parameters.Add("path", command.WorkingDirectory);
var redirectOutput = new Command("out-string");
runspace.Open();
var pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(setWorkingDirectory);
pipeline.Commands.AddScript(command.Command);
pipeline.Commands.Add(redirectOutput);
foreach (var psObject in pipeline.Invoke())
{
var result = FormatCommandResult(psObject);
results.Add(result);
}
runspace.Close();
}
return BuildOutput(results, host);
}
示例10: GetConfigRaw
private Hashtable GetConfigRaw(string env, string scriptFilePath, string xmlDefn = null)
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
using (var pipeline = runspace.CreatePipeline())
{
var getConfigCmd = new Command(scriptFilePath);
var envParam = new CommandParameter("Env", env);
getConfigCmd.Parameters.Add(envParam);
if (xmlDefn != null)
{
var envFileContentParam = new CommandParameter("EnvFileContent", xmlDefn);
getConfigCmd.Parameters.Add(envFileContentParam);
}
pipeline.Commands.Add(getConfigCmd);
runspace.Open();
Collection<PSObject> results = pipeline.Invoke();
var res = results[0].BaseObject as Hashtable;
if (res == null)
{
throw new Exception("Missing Config");
}
return res;
}
}
}
示例11: ToCommand
internal Command ToCommand()
{
var command = new Command(CommandName);
var parameters = GetParameters();
parameters.ForEach(command.Parameters.Add);
return command;
}
示例12: Execute
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime)
{
ExecutionContext nestedContext = context.CreateNestedContext();
if (lValue is VariableNode)
{
VariableNode varNode = (VariableNode)lValue;
if (! (context.CurrentRunspace is LocalRunspace))
throw new InvalidOperationException("Invalid context");
// MUST: fix this with the commandRuntime
Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline();
context.PushPipeline(pipeline);
try
{
Command cmd = new Command("Set-Variable");
cmd.Parameters.Add("Name", new string[] { varNode.Text });
cmd.Parameters.Add("Value", rValue.GetValue(context));
// TODO: implement command invoke
pipeline.Commands.Add(cmd);
pipeline.Invoke();
}
catch (Exception)
{
throw;
}
finally
{
context.PopPipeline();
}
}
}
示例13: ExecuteInlinePowerShellScript
public static StringBuilder ExecuteInlinePowerShellScript(string scriptText, IAgentSettings agentSettings)
{
var serviceCommands = new Command(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts/PS/Services.ps1"));
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
var pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(serviceCommands);
// add the custom script
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
var results = pipeline.Invoke();
runspace.Close();
// convert the script result into a single string
var stringBuilder = new StringBuilder();
foreach (var obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder;
}
示例14: BuildCommand
protected override Command BuildCommand()
{
var result = new Command(CommandName);
if (String.IsNullOrWhiteSpace(SrcBlob) == false)
{
result.Parameters.Add(SrcBlobParameter, SrcBlob);
}
if (String.IsNullOrWhiteSpace(SrcContainer) == false)
{
result.Parameters.Add(SrcContainerParameter, SrcContainer);
}
if (String.IsNullOrWhiteSpace(DestBlob) == false)
{
result.Parameters.Add(DestBlobParameter, DestBlob);
}
if (String.IsNullOrWhiteSpace(DestContainer) == false)
{
result.Parameters.Add(DestContainerParameter, DestContainer);
}
if (Force)
{
result.Parameters.Add(ForceParameter);
}
return result;
}
示例15: CreateSyncShare
internal void CreateSyncShare(string name, string path, string user)
{
Log.WriteStart("CreateSyncShare");
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
// ToDo: Add the correct parameters
Command cmd = new Command("New-SyncShare");
cmd.Parameters.Add("Name", name);
cmd.Parameters.Add("Path", path);
cmd.Parameters.Add("user", user);
var result = ExecuteShellCommand(runSpace, cmd);
if (result.Count > 0)
{
}
}
catch (Exception ex)
{
Log.WriteError("CreateSyncShare", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
Log.WriteEnd("CreateSyncShare");
}