public async Task <ICollection <Disk> > GetDisks()
        {
            ps.Commands.Clear();
            ps.AddScript("Get-Disk");

            var results = await Task.Factory.FromAsync(ps.BeginInvoke(), r => ps.EndInvoke(r));

            var disks = results
                        .Select(x => x.ImmediateBaseObject)
                        .Select(x => ToDisk(this, x));

            return(disks.ToList());
        }
示例#2
0
        //! Called by the job thread.
        void AsyncInvoke(IAsyncResult ar)
        {
            // end; it may throw, e.g. if stopped
            try
            {
                PowerShell.EndInvoke(ar);
            }
            catch (RuntimeException)
            { }

            // state
            switch (PowerShell.InvocationStateInfo.State)
            {
            case PSInvocationState.Completed:
                if (IsHidden)
                {
                    // OK: discard
                    if (PowerShell.Streams.Error.Count == 0)
                    {
                        Dispose();
                        return;
                    }

                    // KO: make it UI
                    JobUI = new JobUI();
                    JobList.Add(this);
                    JobUI.HasError = true;
                    A.WriteErrors(JobUI.GetWriter(), PowerShell.Streams.Error);
                }
                break;

            case PSInvocationState.Failed:

                // make UI for a hidden job, and (!) write not terminating errors first
                if (IsHidden)
                {
                    JobUI = new JobUI();
                    JobList.Add(this);
                    A.WriteErrors(JobUI.GetWriter(), PowerShell.Streams.Error);
                }

                // UI
                if (JobUI != null)
                {
                    JobUI.HasError = true;
                    A.WriteException(JobUI.GetWriter(), PowerShell.InvocationStateInfo.Reason);
                }
                break;
            }

            // UI
            if (JobUI != null)
            {
                // close not needed now UI
                JobUI.Close();

                // post notificator
                Far.Api.PostJob(WatchJobs);
            }
        }
示例#3
0
        void AsyncInvoke(IAsyncResult ar)
        {
            // end; it may throw, e.g. on [CtrlC]
            try
            {
                PowerShell.EndInvoke(ar);
            }
            catch (RuntimeException)
            { }

            // write failure
            if (PowerShell.InvocationStateInfo.State == PSInvocationState.Failed)
            {
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.Runspace = Runspace;
                    A.OutReason(ps, PowerShell.InvocationStateInfo.Reason);
                }
            }

            // complete output
            var writer = (EditorOutputWriter1)FarUI.PopWriter();

            EndOutput(writer);
            EndInvoke();

            // kill
            PowerShell.Dispose();
        }
        }                                //= "Dog";

        // This method gets called once for each cmdlet in the pipeline when the pipeline starts executing
        protected override void BeginProcessing()
        {
            WriteVerbose("Begin!");
            PowerShell ps = PowerShell.Create()
                            .AddCommand("Get-Process")
                            .AddCommand("Where-Object")
                            .AddParameter("Property", "Name")
                            .AddParameter("Value", Name)
                            .AddParameter("Match");

            IAsyncResult async = ps.BeginInvoke();

            foreach (PSObject result in ps.EndInvoke(async))
            {
                //Console.WriteLine("{0,-20}{1}",
                //        result.Members["ProcessName"].Value,
                //        result.Members["Id"].Value);
                var procName = result.Members["ProcessName"].Value.ToString();
                var procId   = result.Members["Id"].Value.ToString();
                WriteObject(new Results
                {
                    Name = procName,
                    PID  = procId
                }
                            );
            } // End foreach.
              //System.Console.WriteLine("Hit any key to exit.");
              //System.Console.ReadKey();
        }
示例#5
0
        public static string GetComputerObject(string computer, string computerProperty)
        {
            IDictionary parameters = new Dictionary <string, string>();

            parameters.Add("ClassName", "CIM_ComputerSystem");
            parameters.Add("ComputerName", computer);
            parameters.Add("Property", "*");


            PowerShell CIM_ComputerSystem = PowerShell.Create()
                                            .AddCommand("Get-CimInstance")
                                            .AddParameters(parameters);

            /*PowerShell Win32_LogicalDisk = PowerShell.Create()
             *  .AddCommand("Get-CimInstance")
             *  .AddParameter("ComputerName", computer)
             *  .AddParameter("ClassName", "Win32_LogicalDisk");*/


            // GIT TEST

            IAsyncResult asyncCIM_ComputerSystem = CIM_ComputerSystem.BeginInvoke();

            //IAsyncResult asyncWin32_LogicalDisk = Win32_LogicalDisk.BeginInvoke();


            foreach (PSObject item in CIM_ComputerSystem.EndInvoke(asyncCIM_ComputerSystem))
            {
                computer = item.Members[computerProperty].Value.ToString();
            }


            return(computer);
        }
示例#6
0
        //获取cpu使用率
        public static object GetCPUCounter()
        {
            //PerformanceCounter cpuCounter = new PerformanceCounter
            //{
            //    CategoryName = "Processor",
            //    CounterName = "% Processor Time",
            //    InstanceName = "_Total"
            //};

            //// will always start at 0
            ////dynamic firstValue = cpuCounter.NextValue();
            //System.Threading.Thread.Sleep(1000);
            //// now matches task manager reading
            //dynamic secondValue = cpuCounter.NextValue();



            using (PowerShell ps = PowerShell.Create())
            {
                ps.AddCommand("Get-WmiObject").AddArgument("win32_processor");
                IAsyncResult async = ps.BeginInvoke();
                foreach (PSObject result in ps.EndInvoke(async))
                {
                    var LoadPercentage = result.Members["LoadPercentage"].Value;
                    return(LoadPercentage);

                    //Console.WriteLine(result);
                }
            }

            return(0);
            //return secondValue;
        }
示例#7
0
        /// <summary>
        /// Waits for the pipeline to finish and returns its output.
        /// </summary>
        /// <returns></returns>
        public PSDataCollection <PSObject> EndInvoke()
        {
            if (_async == null)
            {
                return(null);
            }

            return(_posh.EndInvoke(_async));
        }
        internal Hashtable InvokeOrchestrationFunction(
            AzFunctionInfo functionInfo,
            string contextParamName,
            OrchestrationContext context)
        {
            context.ActionEvent = _actionEvent;

            try
            {
                if (!functionInfo.FuncParameters.ContainsKey(contextParamName))
                {
                    // TODO: we should do more analysis in FunctionLoadRequest phase
                    throw new InvalidOperationException($"Orchestration function should define the parameter '-{contextParamName}'");
                }

                _pwsh.AddCommand("Microsoft.Azure.Functions.PowerShellWorker\\Set-FunctionInvocationContext")
                .AddParameter("OrchestrationContext", context)
                .InvokeAndClearCommands();

                _pwsh.AddCommand(string.IsNullOrEmpty(functionInfo.EntryPoint) ? functionInfo.ScriptPath : functionInfo.EntryPoint)
                .AddParameter(contextParamName, context);

                var outputBuffer = new PSDataCollection <object>();
                var asyncResult  = _pwsh.BeginInvoke <object, object>(input: null, output: outputBuffer);

                var waitHandles         = new[] { _actionEvent, asyncResult.AsyncWaitHandle };
                var signaledHandleIndex = WaitHandle.WaitAny(waitHandles);
                var signaledHandle      = waitHandles[signaledHandleIndex];

                OrchestrationMessage retResult = null;
                if (ReferenceEquals(signaledHandle, _actionEvent))
                {
                    // _actionEvent signaled
                    _pwsh.Stop();
                    retResult = new OrchestrationMessage(isDone: false, actions: context.Actions, output: null);
                }
                else
                {
                    // asyncResult.AsyncWaitHandle signaled
                    _pwsh.EndInvoke(asyncResult);
                    var result = CreateReturnValueFromFunctionOutput(outputBuffer);
                    retResult = new OrchestrationMessage(isDone: true, actions: context.Actions, output: result);
                }

                return(new Hashtable {
                    { AzFunctionInfo.DollarReturn, retResult }
                });
            }
            finally
            {
                _pwsh.Streams.ClearStreams();
                _pwsh.Commands.Clear();

                ClearInvocationContext();
                ResetRunspace();
            }
        }
        /// <summary>
        /// Invokes a PowerShell pipeline asynchronously
        /// </summary>
        /// <param name="powerShell">The <see cref="PowerShell"/> instance to invoke</param>
        /// <param name="taskScheduler">An optional <see cref="TaskScheduler"/></param>
        /// <returns>A <see cref="Task"/> representing the asynchronous invocation</returns>
        public static async Task <IReadOnlyCollection <ErrorRecord> > InvokeAsync(this PowerShell powerShell, TaskScheduler taskScheduler = null)
        {
            await Task.Factory.FromAsync(
                powerShell.BeginInvoke(),
                r => powerShell.EndInvoke(r),
                TaskCreationOptions.None, taskScheduler ?? TaskScheduler.Default).ConfigureAwait(false);

            return(powerShell.Streams.Error.ToList());
        }
示例#10
0
        private bool runPowershell(string logTarget, string script)
        {
            ThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                // You're now on the UI thread.
            });

            ThreadHelper.ThrowIfNotOnUIThread();

            log($"Starting {logTarget}");
            var now = DateTime.UtcNow;

            using (PowerShell psInstance = PowerShell.Create())
            {
                psInstance.AddScript(script);
                var asyncResult = psInstance.BeginInvoke();

                var i = 0;
                while (true && i < 150) //5 seconds
                {
                    System.Threading.Thread.Sleep(100);
                    if (asyncResult.IsCompleted)
                    {
                        break;
                    }
                    else
                    {
                        i++;
                    }
                }
                log($"[{logTarget}] waited { i * 100 } ms for script to complete");

                //need a better way to kill a running Powershell Session
                if (!asyncResult.IsCompleted)
                {
                    psInstance.Stop();
                }
                var psOutputs = psInstance.EndInvoke(asyncResult);

                foreach (var psOutput in psOutputs)
                {
                    log($"[{logTarget}] {psOutput.ToString()}");
                }

                if (psInstance.HadErrors)
                {
                    log($"[{logTarget}] errors occurred"); return(false);
                }

                var elapsed = DateTime.UtcNow - now;
                log($"Done {logTarget}, {elapsed.TotalSeconds} seconds");

                return(true);
            }
        }
示例#11
0
        /// <summary>
        /// This is the primary method for executing powershell scripts
        /// </summary>
        /// <param name="script"></param>
        /// <param name="args"></param>(optional)
        /// <returns>ICollection<PSObject></returns>
        public ICollection <PSObject> executeScript(string script, IDictionary <string, object> args = null)
        {
            try
            {
                // create runspace if it is null
                if (_runspace == null)
                {
                    _runspace = createRunspace();
                }

                // The PowerShell class implements a Factory Pattern, offering a Create() method that returns a new PowerShell object
                _ps = PowerShell.Create();

                // assign the runspace to the Powershell object
                _ps.Runspace = _runspace;

                // create a Command object, initializing it with the script path
                Command psCommand = new Command(script);

                // if the args Dictionary is not null, add them to the Command.Parameters collection
                if (args != null)
                {
                    foreach (var arg in args)
                    {
                        psCommand.Parameters.Add(arg.Key, arg.Value);
                    }
                }

                // add the psCommands object to the Commands property of our PowerShell object
                _ps.Commands.Commands.Add(psCommand);

                // Invoke PowerShell asynchronously
                var asyncResult = _ps.BeginInvoke();

                // Could perform other tasks here while waiting for script to complete, if needed

                // this is analogous to the "await" keyword in an async method
                asyncResult.AsyncWaitHandle.WaitOne();

                // get the result from PowerShell execution
                var result = _ps.EndInvoke(asyncResult);

                // release the resources used by the WaitHandle
                asyncResult.AsyncWaitHandle.Close();

                // return the collection of PSObjects
                return(result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(null);
            }
        }
示例#12
0
        internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed)
        {
            lock (this._localSyncObject)
            {
                this._stopInvoke = false;
            }
            try
            {
                if (syncObject != null)
                {
                    lock (syncObject)
                    {
                        this._runspaceRef.Override(remoteRunspace);
                        isRunspacePushed = true;
                        goto Label_0063;
                    }
                }
                this._runspaceRef.Override(remoteRunspace);
                isRunspacePushed = true;
Label_0063:
                using (PowerShell shell = PowerShell.Create())
                {
                    shell.AddCommand("Get-Command");
                    shell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" });
                    shell.Runspace = this._runspaceRef.Value;
                    bool flag2 = this._runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC;
                    shell.IsGetCommandMetadataSpecialPipeline = !flag2;
                    int num = flag2 ? 2 : 3;
                    shell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCall);
                    IAsyncResult asyncResult          = shell.BeginInvoke();
                    PSDataCollection <PSObject> datas = new PSDataCollection <PSObject>();
                    while (!this._stopInvoke)
                    {
                        asyncResult.AsyncWaitHandle.WaitOne(0x3e8);
                        if (asyncResult.IsCompleted)
                        {
                            datas = shell.EndInvoke(asyncResult);
                            break;
                        }
                    }
                    if ((shell.Streams.Error.Count > 0) || (datas.Count < num))
                    {
                        throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException();
                    }
                    return;
                }
            }
            catch (Exception)
            {
                this._runspaceRef.Revert();
                isRunspacePushed = false;
                throw;
            }
        }
        async public Task <PSDataCollection <PSObject> > Invoke(string script)
        {
            powershell          = PowerShell.Create();
            powershell.Runspace = runspace;

            powershell.AddScript(script);

            var   task = Task.Factory.FromAsync(powershell.BeginInvoke(), result => powershell.EndInvoke(result));
            await task;

            return(task.Result);
        }
示例#14
0
        public Task <bool> CreateAsync(string name)
        {
            PowerShell shell = CreateShell(name);

            return(new TaskFactory().FromAsync(shell.BeginInvoke(), (res) =>
            {
                shell.EndInvoke(res);
                bool succeeded = !shell.HadErrors;
                shell.Dispose();
                return succeeded;
            }));
        }
示例#15
0
        public static void SetRdpStatus(bool swicth)
        {
            string       cm1      = $"(gwmi -class win32_terminalservicesetting -namespace \"root\\cimv2\\terminalservices\").setallowtsconnections({Convert.ToInt32(swicth)})";
            string       cm2      = $"Get-NetFirewallRule -Name RemoteDesktop* | Set-NetFirewallRule -Enabled {swicth}";
            PowerShell   ps       = PowerShell.Create().AddScript(cm1);
            PowerShell   ps2      = PowerShell.Create().AddScript(cm2);
            IAsyncResult asyncpl  = ps.BeginInvoke();
            IAsyncResult asyncpl2 = ps2.BeginInvoke();

            ps.EndInvoke(asyncpl);
            ps2.EndInvoke(asyncpl2);
        }
示例#16
0
        public async Task ExecuteAsync(string file, string arguments = null)
        {
            await Task.Run(() =>
            {
                using PowerShell ps = PowerShell.Create();

                ps.AddScript(file);

                var result = ps.BeginInvoke();

                ps.EndInvoke(result);
            });
        }
示例#17
0
        private void InvokeAsyncIfPossible()
        {
            var output = NewOutputCollection();

            Task.Factory.StartNew(() => {
                var input = new PSDataCollection <object>();
                input.Complete();

                var asyncResult = _powershell.BeginInvoke(input, output);

                _powershell.EndInvoke(asyncResult);
                _result.Completed();
            }, TaskCreationOptions.LongRunning);
        }
示例#18
0
        public static bool GetRdpStatus()
        {
            PowerShell ps = PowerShell.Create().AddCommand("Get-ItemProperty")
                            .AddParameter("Path", @"HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\")
                            .AddParameter("Name", "fDenyTSConnections");
            IAsyncResult asyncpl = ps.BeginInvoke();
            PSObject     result  = ps.EndInvoke(asyncpl)[0];

            if (Convert.ToInt32(result.Members["fDenyTSConnections"].Value) == 0)
            {
                return(true);
            }
            return(false);
        }
示例#19
0
        public static Task <List <PSObject> > FindAsync(string server)
        {
            PowerShell shell = PowerShell.Create();

            shell.AddScript(GetFindScript(server));

            return(new TaskFactory().FromAsync(shell.BeginInvoke(), (res) =>
            {
                List <PSObject> psOutput = shell.EndInvoke(res).ToList();
                shell.Dispose();
                psOutput.RemoveAll(item => item == null);
                return psOutput;
            }));
        }
示例#20
0
        /// <summary>
        /// Executes the PowerShell commands and waits utill it is complete
        /// or cancelled by <paramref name="cancelToken"/>.
        /// </summary>
        /// <param name="powerShell">The <seealso cref="PowerShell"/> object.</param>
        /// <param name="cancelToken">Cancel a long running command.</param>
        /// <returns>
        /// True: successfully completed the script execution.
        /// False: Received some error in script execution or the execution is cancelled.
        /// </returns>
        private bool WaitComplete(PowerShell powerShell, CancellationToken cancelToken)
        {
            var iAsyncResult = powerShell.BeginInvoke();
            int returnIndex  = WaitHandle.WaitAny(new[] { iAsyncResult.AsyncWaitHandle, cancelToken.WaitHandle });

            Debug.WriteLine($"Execution has stopped. The pipeline state: {powerShell.InvocationStateInfo.State}");
            if (cancelToken.IsCancellationRequested || returnIndex != 0 || !iAsyncResult.IsCompleted)
            {
                return(false);
            }
            var outputCollection = powerShell.EndInvoke(iAsyncResult);

            PrintOutput(outputCollection);
            return(!powerShell.HadErrors);
        }
示例#21
0
        public static string GetRdpPort()
        {
            PowerShell ps = PowerShell.Create().AddCommand("Get-ItemProperty")
                            .AddParameter("Path", @"HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp");
            IAsyncResult asyncpl = ps.BeginInvoke();
            PSObject     result  = ps.EndInvoke(asyncpl)[0];

            //foreach (PSObject result in ps.EndInvoke(asyncpl))
            //{
            //    Console.WriteLine("{0}",
            //            result.Members["PortNumber"].Value);
            //}

            return(result.Members["PortNumber"].Value.ToString());
        }
示例#22
0
        internal static IEnumerable <T> InvokeFunction <T>(this PowerShell powershell, string command, params object[] args)
        {
            if (powershell != null)
            {
                powershell.Clear().AddCommand(command);
                foreach (var arg in args)
                {
                    powershell.AddArgument(arg);
                }
#if DEBUG
                PackageManagement.Utility.Platform.NativeMethods.OutputDebugString("[Cmdlet:debugging] -- InvokeFunction ({0}, {1})".format(command, args.Select(each => (each ?? "<NULL>").ToString()).JoinWithComma(), powershell.InvocationStateInfo.Reason));
#endif
                return((powershell.EndInvoke(powershell.BeginInvoke()) ?? Enumerable.Empty <PSObject>()).Select(each => each.ImmediateBaseObject).Cast <T>());
            }
            return(Enumerable.Empty <T>());
        }
示例#23
0
 internal List <ExtendedTypeDefinition> GetRemoteFormatData()
 {
     if (((this.FormatTypeName == null) || (this.FormatTypeName.Length == 0)) || (this.commandParameterSpecified && !this.formatTypeNamesSpecified))
     {
         return(new List <ExtendedTypeDefinition>());
     }
     this.WriteProgress(StringUtil.Format(ImplicitRemotingStrings.ProgressStatusGetFormatDataStart, new object[0]), null, null);
     using (PowerShell shell = this.BuildPowerShellForGetFormatData())
     {
         IAsyncResult asyncResult = null;
         try
         {
             int expectedCount = -1;
             using (PowerShell shell2 = this.BuildPowerShellForGetFormatData())
             {
                 expectedCount = this.CountRemoteObjects(shell2);
             }
             using (new PowerShellStopper(base.Context, shell))
             {
                 DateTime utcNow = DateTime.UtcNow;
                 PSDataCollection <PSObject> output = new PSDataCollection <PSObject>();
                 asyncResult = shell.BeginInvoke <PSObject, PSObject>(null, output);
                 int num2 = 0;
                 List <ExtendedTypeDefinition> listOfTypeDefinitions = new List <ExtendedTypeDefinition>();
                 foreach (PSObject obj2 in output)
                 {
                     this.AddRemoteTypeDefinition(listOfTypeDefinitions, obj2);
                     this.DuplicatePowerShellStreams(shell);
                     this.WriteProgress(utcNow, ++num2, expectedCount, ImplicitRemotingStrings.ProgressStatusGetFormatDataProgress);
                 }
                 this.DuplicatePowerShellStreams(shell);
                 shell.EndInvoke(asyncResult);
                 if ((num2 == 0) && this.formatTypeNamesSpecified)
                 {
                     base.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-FormatData"));
                 }
                 return(listOfTypeDefinitions);
             }
         }
         catch (RuntimeException exception)
         {
             base.ThrowTerminatingError(this.GetErrorFromRemoteCommand("Get-FormatData", exception));
         }
     }
     return(null);
 }
示例#24
0
        static void ExecutePowerShellRoutone2()
        {
            try
            {
                PowerShell   ps    = PowerShell.Create().AddCommand("Get-Process");
                IAsyncResult async = ps.BeginInvoke();

                foreach (PSObject result in ps.EndInvoke(async))
                {
                    Console.WriteLine("{0,-20}{1}", result.Members["ProcessName"].Value, result.Members["Id"].Value);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception thrown : {0}", ex);
            }
        }
示例#25
0
        public static void Main(string[] args)
        {
            PSDataCollection <PSObject> results;

            using (PowerShell ps = PowerShell.Create())
            {
                var script = @".\Get-AllTechnicians.ps1";
                ps.AddScript(File.ReadAllText(script));
                ps.AddParameter("User", "me");
                IAsyncResult asyncres = ps.BeginInvoke();
                do
                {
                    //Wait
                }while (!asyncres.IsCompleted);

                results = ps.EndInvoke(asyncres);
            }
        }
示例#26
0
        private void RemoveAllBtn_Click_1(object sender, RoutedEventArgs e)
        {
            if (PSObjectCount() == 0)
            {
                CustomMessageBox.Show("You have already removed all the apps listed.", "No Apps Found", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                PowerShell removePS = PowerShell.Create();
                if (CustomMessageBox.ShowYesNo("You are about to remove ALL apps from your system.\n\n\t\tContinue?",
                                               "WARNING",
                                               "Yes, I'm sure.",
                                               "NO!", MessageBoxImage.Warning) == MessageBoxResult.No)
                {
                    //DO NOTHING
                }
                else
                {
                    removePS.AddScript(removeAllScript);

                    _busyIndicator.BusyContent = "Removing all apps...";
                    _busyIndicator.IsBusy      = true;

                    removePS.BeginInvoke <PSObject>(null, new PSInvocationSettings(), ar =>
                    {
                        try
                        {
                            //Just to show work being done
                            //It goes too fast to give the message to the user
                            Thread.Sleep(2000);
                            var removeAllVar = removePS.EndInvoke(ar);
                            this.Dispatcher.Invoke(() => _busyIndicator.IsBusy = false);
                            MessageBox.Show("All apps removed successfully.\n\nYou can visit the App Store to reinstall the apps.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        finally
                        {
                            removePS.Dispose();
                        }
                    }, null);
                }
            }
        }
示例#27
0
        public static void ExecuteCommand(String command, PSHost host)
        {
            Console.WriteLine("Executing command:");

            string outputLine = command;
            int    ichNewline = command.IndexOfAny("\r\n".ToCharArray());

            if (ichNewline > 0)
            {
                outputLine = command.Substring(0, ichNewline);
            }

            Console.WriteLine(outputLine);

            using (Runspace space = RunspaceFactory.CreateRunspace(host))
            {
                space.Open();
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.Runspace = space;
                    ps.AddScript(command);

                    // Create the output buffer for the results.
                    IAsyncResult async = ps.BeginInvoke();
                    foreach (PSObject result in ps.EndInvoke(async))
                    {
                        Console.WriteLine(result.ToString());
                    }

                    PSDataStreams streams = ps.Streams;

                    if (streams.Error != null)
                    {
                        foreach (ErrorRecord record in streams.Error)
                        {
                            Console.WriteLine(GetMessageFromErrorRecord(record));
                            throw record.Exception;
                        }
                    }
                }
            }
        }
 public void Dispose()
 {
     try
     {
         var results = _ps.EndInvoke(_result);
         if (!_ps.HadErrors)
         {
             return;
         }
         foreach (var result in results)
         {
             Debug(result.ToString());
         }
         throw new InvalidOperationException(CollectAsString(results));
     }
     finally
     {
         _ps?.Dispose();
     }
 }
示例#29
0
        private void RemoveSelectedApp(string str)
        {
            string capitalizedStr = (char.ToUpper(str[0]) + str.Substring(1));

            PowerShell ps = PowerShell.Create();

            if (CustomMessageBox.ShowYesNo("You are about to remove " + capitalizedStr + " from your system.\n\n\t\tContinue?",
                                           "WARNING",
                                           "Yes. I got this.",
                                           "NO!", MessageBoxImage.Warning) == MessageBoxResult.No)
            {
                //DO NOTHING
            }
            else
            {
                //Create PS Script
                ps.AddScript("Get-AppxPackage | Where-Object {$_.Name -like '*" + str.ToLower() + "*'} | Remove-AppxPackage");

                //Show BusyIndicator
                _busyIndicator.BusyContent = "Removing " + capitalizedStr;
                _busyIndicator.IsBusy      = true;

                //Invoke Async PS
                ps.BeginInvoke <PSObject>(null, new PSInvocationSettings(), ar =>
                {
                    try
                    {
                        //Just a little extra time to show work for user
                        Thread.Sleep(2000);
                        var removeVar = ps.EndInvoke(ar);
                        this.Dispatcher.Invoke(() => _busyIndicator.IsBusy = false);
                        MessageBox.Show(capitalizedStr + " removed successfully\n\nYou can visit the App Store to reinstall the app.", "Success");
                    }
                    finally
                    {
                        //Throw away PS instance
                        ps.Dispose();
                    }
                }, null);
            }
        }
示例#30
0
        } // End Main.

        public static void ListarUsuario()
        {
            //Create a PowerShell object.
            PowerShell ps = PowerShell.Create();

            //New-LocalUser usuario -Password (ConvertTo-SecureString "11234aaadsf" -asplaintext -force)
            ps.AddScript("Get-LocalUser");

            IAsyncResult result = ps.BeginInvoke();

            // do something else until execution has completed.
            // this could be sleep/wait, or perhaps some other work
            while (result.IsCompleted == false)
            {
            }
            foreach (PSObject result2 in ps.EndInvoke(result))
            {
                Console.WriteLine("{0}",
                                  result2.Members["Name"].Value);
            } // End foreach.
            System.Console.WriteLine("Hit any key to exit.");
        }     // End Main.
示例#31
0
        /// <summary>
        /// This is the primary method for executing powershell scripts
        /// </summary>
        /// <param name="script"></param>
        /// <param name="args"></param>(optional)
        /// <returns>ICollection<PSObject></returns>
        public ICollection<PSObject> executeScript(string script, IDictionary<string, object> args = null)
        {
            try
            {
                // create runspace if it is null
                if (_runspace == null)
                {
                    _runspace = createRunspace();
                }

                // The PowerShell class implements a Factory Pattern, offering a Create() method that returns a new PowerShell object
                _ps = PowerShell.Create();

                // assign the runspace to the Powershell object
                _ps.Runspace = _runspace;

                // create a Command object, initializing it with the script path
                Command psCommand = new Command(script);

                // if the args Dictionary is not null, add them to the Command.Parameters collection
                if (args != null)
                {
                    foreach (var arg in args)
                    {
                        psCommand.Parameters.Add(arg.Key, arg.Value);
                    }
                }

                // add the psCommands object to the Commands property of our PowerShell object
                _ps.Commands.Commands.Add(psCommand);

                // Invoke PowerShell asynchronously
                var asyncResult = _ps.BeginInvoke();

                // Could perform other tasks here while waiting for script to complete, if needed

                // this is analogous to the "await" keyword in an async method
                asyncResult.AsyncWaitHandle.WaitOne();

                // get the result from PowerShell execution
                var result = _ps.EndInvoke(asyncResult);

                // release the resources used by the WaitHandle
                asyncResult.AsyncWaitHandle.Close();

                // return the collection of PSObjects
                return result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return null;
            }
        }
示例#32
0
 private PSDataCollection<PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args)
 {
     string str;
     HostInfo hostInfo = this.remoteHost.HostInfo;
     IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start();
     PSDataCollection<PSObject> datas = powershell.EndInvoke(asyncResult);
     ArrayList dollarErrorVariable = (ArrayList) powershell.Runspace.GetExecutionContext.DollarErrorVariable;
     if (dollarErrorVariable.Count <= 0)
     {
         return datas;
     }
     ErrorRecord record = dollarErrorVariable[0] as ErrorRecord;
     if (record != null)
     {
         str = record.ToString();
     }
     else
     {
         Exception exception = dollarErrorVariable[0] as Exception;
         if (exception != null)
         {
             str = (exception.Message != null) ? exception.Message : string.Empty;
         }
         else
         {
             str = string.Empty;
         }
     }
     throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), new object[] { str });
 }
示例#33
0
        /// <summary>
        /// Invokes a PowerShell instance 
        /// </summary>
        /// <param name="powershell"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private PSDataCollection<PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args)
        {
            Debug.Assert(powershell != null, "powershell shouldn't be null");

            // run the startup script on the runspace's host
            HostInfo hostInfo = _remoteHost.HostInfo;
            ServerPowerShellDriver driver = new ServerPowerShellDriver(
                powershell,
                null,
                true,
                Guid.Empty,
                this.InstanceId,
                this,
#if !CORECLR // No ApartmentState In CoreCLR
                args.Runspace.ApartmentState,
#endif                
                hostInfo,
                RemoteStreamOptions.AddInvocationInfo,
                false,
                args.Runspace);

            IAsyncResult asyncResult = driver.Start();

            // if there was an exception running the script..this may throw..this will
            // result in the runspace getting closed/broken.
            PSDataCollection<PSObject> results = powershell.EndInvoke(asyncResult);

            // find out if there are any error records reported. If there is one, report the error..
            // this will result in the runspace getting closed/broken.
            ArrayList errorList = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable;
            if (errorList.Count > 0)
            {
                string exceptionThrown;
                ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord;
                if (lastErrorRecord != null)
                {
                    exceptionThrown = lastErrorRecord.ToString();
                }
                else
                {
                    Exception lastException = errorList[0] as Exception;
                    if (lastException != null)
                    {
                        exceptionThrown = (lastException.Message != null) ? lastException.Message : string.Empty;
                    }
                    else
                    {
                        exceptionThrown = string.Empty;
                    }
                }

                throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.StartupScriptThrewTerminatingError, exceptionThrown);
            }

            return results;
        }