Esempio n. 1
0
 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);
 }
Esempio n. 2
0
 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;
 }
Esempio n. 3
0
        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();
            }
        }
Esempio n. 4
0
 public ScriptBlock(System.Management.Automation.ScriptBlock scriptBlock)
 {
     _scriptBlock = scriptBlock;
     _variables   = new List <PSVariable>();
     _toString    = _scriptBlock.ToString();
 }
Esempio n. 5
0
        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);

            }
        }
Esempio n. 6
0
        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);
            }
        }
Esempio n. 7
0
        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" +
                     eOuter.Message,
                    "ErrorInInvokingScriptBlock",
                    ErrorCategory.InvalidOperation,
                    true);
            }
        }
        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);
                }
            }


        }
Esempio n. 9
0
 /// <summary>
 /// For diagnostic purposes.
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(ScriptBlock.ToString());
 }
        private ArrayList ProcessMinishellParameters(ArrayList args, bool outputRedirected, string hostName)
        {
            ArrayList           list = new ArrayList();
            string              str  = null;
            string              str2 = null;
            MinishellParameters seen = 0;

            for (int i = 0; i < args.Count; i++)
            {
                object obj2 = args[i];
                if (StartsWith("-command", obj2))
                {
                    this.HandleSeenParameter(ref seen, MinishellParameters.Command, "-command");
                    list.Add("-encodedCommand");
                    if ((i + 1) >= args.Count)
                    {
                        throw this.NewParameterBindingException(null, ErrorCategory.InvalidArgument, "-command", typeof(ScriptBlock), null, "NoValueForCommandParameter", new object[0]);
                    }
                    ScriptBlock block = args[i + 1] as ScriptBlock;
                    if (block == null)
                    {
                        throw this.NewParameterBindingException(null, ErrorCategory.InvalidArgument, "-command", typeof(ScriptBlock), args[i + 1].GetType(), "IncorrectValueForCommandParameter", new object[0]);
                    }
                    string str3 = StringToBase64Converter.StringToBase64String(block.ToString());
                    list.Add(str3);
                    i++;
                }
                else if (obj2 is ScriptBlock)
                {
                    this.HandleSeenParameter(ref seen, MinishellParameters.Command, "-command");
                    list.Add("-encodedCommand");
                    string str4 = StringToBase64Converter.StringToBase64String(obj2.ToString());
                    list.Add(str4);
                }
                else if (StartsWith("-inputFormat", obj2))
                {
                    this.HandleSeenParameter(ref seen, MinishellParameters.InputFormat, "-inputFormat");
                    list.Add("-inputFormat");
                    if ((i + 1) >= args.Count)
                    {
                        throw this.NewParameterBindingException(null, ErrorCategory.InvalidArgument, "-inputFormat", typeof(string), null, "NoValueForInputFormatParameter", new object[0]);
                    }
                    str = this.ProcessFormatParameterValue("-inputFormat", args[i + 1]);
                    i++;
                    list.Add(str);
                }
                else if (StartsWith("-outputFormat", obj2))
                {
                    this.HandleSeenParameter(ref seen, MinishellParameters.OutputFormat, "-outputFormat");
                    list.Add("-outputFormat");
                    if ((i + 1) >= args.Count)
                    {
                        throw this.NewParameterBindingException(null, ErrorCategory.InvalidArgument, "-outputFormat", typeof(string), null, "NoValueForOutputFormatParameter", new object[0]);
                    }
                    str2 = this.ProcessFormatParameterValue("-outputFormat", args[i + 1]);
                    i++;
                    list.Add(str2);
                }
                else if (StartsWith("-args", obj2))
                {
                    this.HandleSeenParameter(ref seen, MinishellParameters.Arguments, "-args");
                    list.Add("-encodedarguments");
                    if ((i + 1) >= args.Count)
                    {
                        throw this.NewParameterBindingException(null, ErrorCategory.InvalidArgument, "-args", typeof(string), null, "NoValuesSpecifiedForArgs", new object[0]);
                    }
                    string str5 = ConvertArgsValueToEncodedString(args[i + 1]);
                    i++;
                    list.Add(str5);
                }
                else
                {
                    list.Add(obj2);
                }
            }
            if (str == null)
            {
                list.Add("-inputFormat");
                list.Add("xml");
                str = "xml";
            }
            if (str2 == null)
            {
                list.Add("-outputFormat");
                if (outputRedirected)
                {
                    list.Add("xml");
                    str2 = "xml";
                }
                else
                {
                    list.Add("text");
                    str2 = "text";
                }
            }
            if (StartsWith(str, "xml"))
            {
                this.inputFormatValue = NativeCommandIOFormat.Xml;
            }
            else
            {
                this.inputFormatValue = NativeCommandIOFormat.Text;
            }
            if (StartsWith(str2, "xml"))
            {
                this.outputFormatValue = NativeCommandIOFormat.Xml;
            }
            else
            {
                this.outputFormatValue = NativeCommandIOFormat.Text;
            }
            if (string.IsNullOrEmpty(hostName) || !hostName.Equals("ConsoleHost", StringComparison.OrdinalIgnoreCase))
            {
                this.nonInteractive = true;
                list.Insert(0, "-noninteractive");
            }
            return(list);
        }
Esempio n. 11
0
        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();
        }