当前位置: 首页>>代码示例>>C#>>正文


C# ScriptBlock.ToString方法代码示例

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


在下文中一共展示了ScriptBlock.ToString方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AsyncJob

 public AsyncJob(ScriptBlock Script)
     : base(Script.ToString())
 {
     this.Pipeline = PSRunspace.Instance.NewPipeline();
     this.Pipeline.AddCommand(Script.ToString());
     this.Pipeline.InvocationStateChanged += Pipeline_InvocationStateChanged;
     this.PSJobTypeName = "RunspaceJob";
     this.Name = string.Format("Async{0}", this.Id);
 }
开发者ID:GoodOlClint,项目名称:PSAsync,代码行数:9,代码来源:AsyncJob.cs

示例2: PowerShellProcessInstance

 public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
 {
     this._syncObject = new object();
     string pSExePath = PSExePath;
     if (useWow64)
     {
         string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
         if (!string.IsNullOrEmpty(environmentVariable) && (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
         {
             pSExePath = PSExePath.ToLowerInvariant().Replace(@"\system32\", @"\syswow64\");
             if (!System.IO.File.Exists(pSExePath))
             {
                 throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.IPCWowComponentNotPresent, new object[] { pSExePath }));
             }
         }
     }
     string str4 = string.Empty;
     Version version = powerShellVersion ?? PSVersionInfo.PSVersion;
     if (null == version)
     {
         version = new Version(3, 0);
     }
     str4 = string.Format(CultureInfo.InvariantCulture, "-Version {0}", new object[] { new Version(version.Major, version.Minor) });
     str4 = string.Format(CultureInfo.InvariantCulture, "{0} -s -NoLogo -NoProfile", new object[] { str4 });
     if (initializationScript != null)
     {
         string str5 = initializationScript.ToString();
         if (!string.IsNullOrEmpty(str5))
         {
             string str6 = Convert.ToBase64String(Encoding.Unicode.GetBytes(str5));
             str4 = string.Format(CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", new object[] { str4, str6 });
         }
     }
     ProcessStartInfo info = new ProcessStartInfo {
         FileName = useWow64 ? pSExePath : PSExePath,
         Arguments = str4,
         UseShellExecute = false,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         WindowStyle = ProcessWindowStyle.Hidden,
         CreateNoWindow = true,
         LoadUserProfile = true
     };
     this._startInfo = info;
     if (credential != null)
     {
         NetworkCredential networkCredential = credential.GetNetworkCredential();
         this._startInfo.UserName = networkCredential.UserName;
         this._startInfo.Domain = string.IsNullOrEmpty(networkCredential.Domain) ? "." : networkCredential.Domain;
         this._startInfo.Password = credential.Password;
     }
     System.Diagnostics.Process process = new System.Diagnostics.Process {
         StartInfo = this._startInfo,
         EnableRaisingEvents = true
     };
     this._process = process;
 }
开发者ID:nickchal,项目名称:pash,代码行数:58,代码来源:PowerShellProcessInstance.cs

示例3: PSDataSource

        public PSDataSource( ScriptBlock script,
                             IEnumerable<PSObject> input = null,
                             TimeSpan interval = new TimeSpan(), 
                             bool invokeImmediately = false, 
                             bool accumulateOutput = false) : base(new PSDataCollection<PSObject>()) {

            Script = script;
            TimeSpan = TimeSpan.Zero;
            AccumulateOutput = accumulateOutput;

            _powerShellCommand = PowerShell.Create().AddScript( Script.ToString() );            

            Error = new ListCollectionView(_powerShellCommand.Streams.Error);
            Warning = new ListCollectionView(_powerShellCommand.Streams.Warning);
            Verbose = new ListCollectionView(_powerShellCommand.Streams.Verbose);
            Progress = new ListCollectionView(_powerShellCommand.Streams.Progress);

            if (invokeImmediately || TimeSpan.Zero < interval) { Invoke(input); }

            if (TimeSpan.Zero < interval) {
               _timer = new DispatcherTimer(TimeSpan, DispatcherPriority.Normal, Invoke, Dispatcher.CurrentDispatcher);
               _timer.Start();
            }
        }
开发者ID:ForNeVeR,项目名称:PoshConsole,代码行数:24,代码来源:PsDataSource.cs

示例4: runSBActionWithParams

        private void runSBActionWithParams(
            ScriptBlock sb,
            object[] parameters)
        {
            Collection<PSObject> psObjects = null;
            try {

                this.WriteVerbose(
                    this,
                    "select whether a scriptblock has parameters or doesn't");

                if (null == parameters || 0 == parameters.Length) {

                    this.WriteVerbose(
                        this,
                        "without parameters");

                    psObjects =
                        sb.Invoke();

                } else {

                    this.WriteVerbose(
                        this,
                        "with parameters");

                    psObjects =
                        sb.Invoke(parameters);

                }

                this.WriteVerbose(
                    this,
                    "scriptblock has been fired successfully");

            } catch (Exception eOuter) {

                // 20130318
            //                ErrorRecord err =
            //                    new ErrorRecord(eOuter,
            //                                    "ErrorInInvokingScriptBlock",
            //                                    ErrorCategory.InvalidOperation,
            //                                    System.Management.Automation.Runspaces.Runspace.DefaultRunspace);
            //                err.ErrorDetails =
            //                    new ErrorDetails(
            //                        "Unable to issue the following command:\r\n" +
            //                        sb.ToString() +
            //                        "\r\nThe exception raised is\r\n" +
            //                        eOuter.Message);
            //                                     //"System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();");
            //                WriteError(err);

                // 20130606
            //                this.WriteVerbose(
            //                    this,
            //                    eOuter.InnerException.Message);

                this.WriteError(
                    this,
                    "Unable to issue the following command:\r\n" +
                    sb.ToString() +
                    "\r\nThe exception raised is\r\n" +
                    eOuter.Message,
                    "ErrorInInvokingScriptBlock",
                    ErrorCategory.InvalidOperation,
                    // 20130318
                    //false);
                    true);

            }
        }
开发者ID:krukovskiy,项目名称:STUPS,代码行数:71,代码来源:PSCmdletBase.cs

示例5: runSBAction

        private void runSBAction(ScriptBlock sb, 
                                 AutomationElement src,
                                 AutomationEventArgs e)
        {
            Collection<PSObject> psObjects = null;
            try {
                psObjects =
                    sb.Invoke();
            // int counter = 0;
            // foreach (PSObject pso in psObjects) {
            //  //if pso.
            // counter++;
            // WriteVerbose("result " + counter.ToString() + ":");
            // WriteVerbose(pso.ToString());
            //  //WriteObject(pso.TypeNames
            // foreach ( string typeName in pso.TypeNames) {
            // WriteVerbose(typeName);
            // }
            // }
            } catch (Exception eOuter) {
                // 20130318
            //                ErrorRecord err =
            //                    new ErrorRecord(eOuter,
            //                                    "ErrorInInvokingScriptBlock",
            //                                    ErrorCategory.InvalidOperation,
            //                                    System.Management.Automation.Runspaces.Runspace.DefaultRunspace);
            //                err.ErrorDetails =
            //                    new ErrorDetails(
            //                        "Unable to issue the following command:\r\n" +
            //                        sb.ToString() +
            //                        "\r\nThe exception raised is\r\n" +
            //                        eOuter.Message);
            //                                     //"System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();");
            //                WriteError(err);

                this.WriteError(
                    this,
                    "Unable to issue the following command:\r\n" +
                    sb.ToString() +
                    "\r\nThe exception raised is\r\n" +
                    eOuter.Message,
                    "ErrorInInvokingScriptBlock",
                    ErrorCategory.InvalidOperation,
                    // 20130318
                    //false);
                    true);
            }
        }
开发者ID:krukovskiy,项目名称:STUPS,代码行数:48,代码来源:PSCmdletBase.cs

示例6: runSBEvent

        private void runSBEvent(ScriptBlock sb, 
                                AutomationElement src,
                                AutomationEventArgs e)
        {
            // inform the Wait-UIAEventRaised cmdlet
            SaveEventInput(
                src,
                e,
                e.EventId.ProgrammaticName,
                true);
            //            try {
            //                CurrentData.LastEventSource = src; // as AutomationElement;
            //                CurrentData.LastEventArgs = e; // as AutomationEventArgs;
            //                CurrentData.LastEventType = e.EventId.ProgrammaticName;
            //                CurrentData.LastEventInfoAdded = true;
            //            }
            //            catch {
            //                //WriteVerbose(this, "failed to register an event in the collection");
            //            }

            // 20120206 Collection<PSObject >  psObjects = null;
            try {
                System.Management.Automation.Runspaces.Runspace.DefaultRunspace =
                    RunspaceFactory.CreateRunspace();
                try {
                    System.Management.Automation.Runspaces.Runspace.DefaultRunspace.Open();
                } catch (Exception e1) {
                    // 20130318
            //                    ErrorRecord err =
            //                        new ErrorRecord(e1,
            //                                        "ErrorOnOpeningRunspace",
            //                                        ErrorCategory.InvalidOperation,
            //                                        sb);
            //                    err.ErrorDetails =
            //                        new ErrorDetails(
            //                            "Unable to run a scriptblock:\r\n" +
            //                            sb.ToString());
            //                    WriteError(this, err, false);

                    this.WriteError(
                        this,
                        "Unable to run a scriptblock:\r\n" +
                        sb.ToString() +
                        "." +
                        e1.Message,
                        "ErrorOnOpeningRunspace",
                        ErrorCategory.InvalidOperation,
                        // 20130318
                        //false);
                        true);
                }
                try {
                    System.Collections.Generic.List<object> inputParams =
                        new System.Collections.Generic.List<object>();
                    inputParams.Add(src);
                    inputParams.Add(e);
                    object[] inputParamsArray = inputParams.ToArray();
                    // psObjects =
                        sb.InvokeReturnAsIs(inputParamsArray);
                        // sb.Invoke(inputParamsArray);

                } catch (Exception e2) {
                    // 20130318
            //                    ErrorRecord err =
            //                        new ErrorRecord(e2,
            //                                        "ErrorInOpenedRunspace",
            //                                        ErrorCategory.InvalidOperation,
            //                                        sb);
            //                    err.ErrorDetails =
            //                        new ErrorDetails("Unable to run a scriptblock");
            //                    WriteError(this, err, true);

                    this.WriteError(
                        this,
                        "Unable to run a scriptblock." +
                        e2.Message,
                        "ErrorInOpenedRunspace",
                        ErrorCategory.InvalidOperation,
                        true);
                }
            // psObjects =
            // sb.Invoke();
            } catch (Exception eOuter) {
                // 20130318
            //                ErrorRecord err =
            //                    new ErrorRecord(eOuter,
            //                                    "ErrorInInvokingScriptBlock", //"ErrorinCreatingRunspace",
            //                                    ErrorCategory.InvalidOperation,
            //                                    System.Management.Automation.Runspaces.Runspace.DefaultRunspace);
            //                err.ErrorDetails =
            //                    new ErrorDetails("Unable to issue the following command:\r\n" +
            //                                     "System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();" +
            //                                     "\r\nException raised is\r\n" +
            //                                     eOuter.Message);

                this.WriteError(
                    this,
                    "Unable to issue the following command:\r\n" +
                     "System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();" +
                     "\r\nException raised is\r\n" +
//.........这里部分代码省略.........
开发者ID:krukovskiy,项目名称:STUPS,代码行数:101,代码来源:PSCmdletBase.cs

示例7: 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);
                }
            }


        }
开发者ID:hugodahl,项目名称:powershell-for-developers,代码行数:67,代码来源:ShowUICore.CLR2.0.50727.5446.cs

示例8: Invoke

        public void Invoke(ScriptBlock scriptBlock, PSParameter[] parameters)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.ApartmentState = System.Threading.ApartmentState.STA;
            runspace.ThreadOptions = PSThreadOptions.ReuseThread;
            runspace.Open();

            foreach (PSParameter arg in parameters)
            {
                runspace.SessionStateProxy.SetVariable(arg.Name, arg.Value);

            }

            try
            {
                pipeline = runspace.CreatePipeline(scriptBlock.ToString());
            }
            catch (Exception ex)
            {
                throw new NullReferenceException("Either no scriptblock property has been set on the BackgroundWorker or the scriptblock is not valid.", ex);
            }

            switch (windowType)
            {
                case WorkerWindowType.WPF:
                    executeAction += ExecuteWPFAction;
                    break;
                case WorkerWindowType.Form:
                    executeAction += ExecuteFrmAction;
                    break;
                default:
                    executeAction += ExecuteConsoleAction;
                    break;
            }

            pipeline.Output.DataReady += HandleDataReady;
            pipeline.Error.DataReady += HandleDataReady;
            pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(Handle_StateChanged);

            // Start the pipeline
            pipeline.InvokeAsync();
            pipeline.Input.Close();
        }
开发者ID:cassdotcom,项目名称:ardbeg,代码行数:43,代码来源:BackgroundWorker.cs


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