• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Runspaces.Command类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Management.Automation.Runspaces.Command的典型用法代码示例。如果您正苦于以下问题:C# Command类的具体用法?C# Command怎么用?C# Command使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Command类属于System.Management.Automation.Runspaces命名空间,在下文中一共展示了Command类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
            }
        }
开发者ID:JohnGoldsmith,项目名称:PnP-PowerShell,代码行数:29,代码来源:PSTestScope.cs


示例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;
        }
开发者ID:jamesology,项目名称:AzureVmFarmer,代码行数:26,代码来源:NewAzureVmCommand.cs


示例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();
            }
        }
开发者ID:JamesTryand,项目名称:pash,代码行数:30,代码来源:VariableNode.cs


示例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];
            }
        }
开发者ID:wholroyd,项目名称:ShareFile-PowerShell,代码行数:26,代码来源:MapDriveTests.cs


示例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);
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:34,代码来源:RemoteSessionStateProxy.cs


示例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;
            }
        }
开发者ID:remotex,项目名称:Samples,代码行数:33,代码来源:Service.svc.cs


示例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);
        }
开发者ID:skseth,项目名称:EnvHealthMonitor,代码行数:30,代码来源:MachineCommandController.cs


示例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;
 }
开发者ID:nickchal,项目名称:pash,代码行数:32,代码来源:CompletionExecutionHelper.cs


示例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);
        }
开发者ID:sebastianhallen,项目名称:Goose,代码行数:26,代码来源:PowerShellCommandRunner.cs


示例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;
                }
            }
        }
开发者ID:ScottWeinstein,项目名称:RWCM-Demo,代码行数:30,代码来源:ConfigLoader.cs


示例11: ToCommand

 internal Command ToCommand()
 {
     var command = new Command(CommandName);
     var parameters = GetParameters();
     parameters.ForEach(command.Parameters.Add);
     return command;
 }
开发者ID:neutmute,项目名称:exchange-client,代码行数:7,代码来源:PowerShellCommand.cs


示例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();
                }
            }
        }
开发者ID:JamesTryand,项目名称:pash,代码行数:34,代码来源:AssignmentNode.cs


示例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;
        }
开发者ID:andrewmyhre,项目名称:DeployD,代码行数:31,代码来源:PowershellHelper.cs


示例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;
        }
开发者ID:jamesology,项目名称:AzureVmFarmer,代码行数:31,代码来源:StartAzureStorageBlobCopyCommand.cs


示例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");
        }
开发者ID:jonwbstr,项目名称:Websitepanel,代码行数:35,代码来源:SyncShareService.cs


示例16: GetPS

        //public static VirtualHardDiskInfo GetByPath(PowerShellManager powerShell, string vhdPath)
        //{
        //    VirtualHardDiskInfo info = null;
        //    var vmNames = new List<string>();

        //    Command cmd = new Command("Get-VM");

        //    Collection<PSObject> result = powerShell.Execute(cmd, true);

        //    if (result == null || result.Count == 0)
        //        return null;

        //    vmNames = result.Select(r => r.GetString("Name")).ToList();
        //    var drives = vmNames.SelectMany(n => Get(powerShell, n));

        //    return drives.FirstOrDefault(d=>d.Path == vhdPath);
        //}

        public static Collection<PSObject> GetPS(PowerShellManager powerShell, string vmname)
        {
            Command cmd = new Command("Get-VMHardDiskDrive");
            cmd.Parameters.Add("VMName", vmname);

            return powerShell.Execute(cmd, true);
        }
开发者ID:lwhitelock,项目名称:Websitepanel,代码行数:25,代码来源:HardDriveHelper.cs


示例17: Run

        public override bool Run()
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();

                var pipeline = runspace.CreatePipeline();
                var powershellCommand = new Command(new FileInfo(parameters.ScriptName).FullName);
                foreach (var parameter in ((IDictionary<string, object>)parameters))
                {
                    powershellCommand.Parameters.Add(new CommandParameter(parameter.Key, parameter.Value.ToString()));
                }
                pipeline.Commands.Add(powershellCommand);
                try
                {
                    var psObjects = pipeline.Invoke();
                    foreach (var obj in psObjects)
                    {
                        notificationService.Notify(parameters.ScriptName, obj == null ? String.Empty : obj.ToString(), NotificationType.Information);
                    }
                }
                catch (Exception ex)
                {
                    notificationService.Notify(parameters.ScriptName, ex.Message, NotificationType.Error);
                }
                runspace.Close();
            }
            return true;
        }
开发者ID:pgermishuys,项目名称:Jubilee,代码行数:30,代码来源:Powershell.cs


示例18: FindMatches2

        public static IEnumerable<string> FindMatches2(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var truncatedCommand = TruncatedCommand2(command, out lastToken);

            var teCmd = new Command("TabExpansion");
            teCmd.Parameters.Add("line", command);
            teCmd.Parameters.Add("lastWord", lastToken);
            var teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>();

            var result = new List<string>();
            WrapResults(truncatedCommand, teResult, result, aceResponse);

            var splitPathResult =
                (session.ExecuteScriptPart(string.Format("Split-Path \"{0}*\" -IsAbsolute", lastToken), false, true)
                    .FirstOrDefault());
            var isAbsolute = splitPathResult != null && (bool) splitPathResult;

            if (isAbsolute)
            {
                var commandLine = string.Format("Resolve-Path \"{0}*\"", lastToken);
                var psResults = session.ExecuteScriptPart(commandLine, false, true);
                var rpResult = psResults.Cast<PathInfo>().Select(p => p.Path);
                WrapResults(truncatedCommand, rpResult, result, aceResponse);
            }
            else
            {
                var commandLine = string.Format("Resolve-Path \"{0}*\" -Relative", lastToken);
                var rpResult = session.ExecuteScriptPart(commandLine, false, true).Cast<string>();
                WrapResults(truncatedCommand, rpResult, result, aceResponse);
            }

            return result;
        }
开发者ID:mikaelnet,项目名称:Console,代码行数:34,代码来源:CommandCompletion.cs


示例19: RunPowerShell

    //function to run Powershell commands
    public static void RunPowerShell(string psScript, string psParameters)
    {

      try
      {
        var runspaceConfiguration = RunspaceConfiguration.Create();
        var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        var pipeline = runspace.CreatePipeline();
        var myCommand = new Command(psScript);
        pipeline.Commands.Add(myCommand);
        if (!string.IsNullOrEmpty(psParameters))
        {
          var aryParameters = psParameters.Split(' ');
          for (var i = 0; i < aryParameters.Count(); i++)
          {
            myCommand.Parameters.Add(aryParameters[i].ToString(CultureInfo.InvariantCulture), aryParameters[i + 1].ToString(CultureInfo.InvariantCulture));
            i++;
          }
        }

        var scriptInvoker = new RunspaceInvoke(runspace);

        // Execute PowerShell script
        Collection<PSObject> results = pipeline.Invoke();
        runspace.Close();
        return;

      }
      catch (Exception e)
      {
        Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught running powershell:" + e);
      }
    }
开发者ID:yonglehou,项目名称:Fido,代码行数:35,代码来源:Powershell.cs


示例20: GetCollectionSettings

        private static List<RdsCollectionSetting> GetCollectionSettings(this Runspace runspace, string collectionName, string connectionBroker, string primaryDomainController, string param, out object[] errors)
        {
            Command cmd = new Command("Get-RDSessionCollectionConfiguration");
            cmd.Parameters.Add("CollectionName", collectionName);
            cmd.Parameters.Add("ConnectionBroker", connectionBroker);

            if (!string.IsNullOrEmpty(param))
            {
                cmd.Parameters.Add(param, true);
            }

            var psObject = ExecuteShellCommand(runspace, cmd, false, primaryDomainController, out errors).FirstOrDefault();

            var properties = typeof(RdsCollectionSettings).GetProperties().Select(p => p.Name.ToLower());
            var collectionSettings = new RdsCollectionSettings();
            var result = new List<RdsCollectionSetting>();

            if (psObject != null)
            {
                foreach (var prop in psObject.Properties)
                {                    
                    if (prop.Name.ToLower() != "id" && prop.Name.ToLower() != "rdscollectionid")
                    {
                        result.Add(new RdsCollectionSetting
                        {
                            PropertyName = prop.Name,
                            PropertyValue = prop.Value
                        });
                    }
                }
            }

            return result;
        }
开发者ID:lwhitelock,项目名称:Websitepanel,代码行数:34,代码来源:RdsRunspaceExtensions.cs



注:本文中的System.Management.Automation.Runspaces.Command类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Runspaces.Runspace类代码示例发布时间:2022-05-26
下一篇:
C# Provider.CmdletProvider类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap