/// <summary>
        /// InitServerNodeConfiguration2016 method implementation
        /// </summary>
        private static NamedPipeRegistryRecord InitServerNodeConfiguration2016(NamedPipeRegistryRecord reg)
        {
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                RunspaceConfiguration SPRunConfig = RunspaceConfiguration.Create();
                SPRunSpace            = RunspaceFactory.CreateRunspace(SPRunConfig);
                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline  = SPRunSpace.CreatePipeline();
                Command  exportcmd = new Command("(Get-AdfsFarmInformation).FarmNodes", true);

                pipeline.Commands.Add(exportcmd);

                Collection <PSObject> PSOutput = pipeline.Invoke();
                foreach (var item in PSOutput)
                {
                    if (reg.FQDN.ToLower().Equals(item.Members["FQDN"].Value.ToString().ToLower()))
                    {
                        reg.FQDN               = item.Members["FQDN"].Value.ToString();
                        reg.MachineName        = GetMachineName(reg.FQDN);
                        reg.BehaviorLevel      = Convert.ToInt32(item.Members["BehaviorLevel"].Value);
                        reg.HeartbeatTimestamp = Convert.ToDateTime(item.Members["HeartbeatTimeStamp"].Value);
                        break;
                    }
                }
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
            }
            return(reg);
        }
Esempio n. 2
0
        public Runspace ConnectRemotePSSession(string serverpath)
        {
            PSSessionOption option = new PSSessionOption();
            string          url    = serverpath;

            System.Uri uri = new Uri(url);

            Runspace runspace = RunspaceFactory.CreateRunspace();

            PowerShell powershell = PowerShell.Create();
            PSCommand  command    = new PSCommand();

            command.AddCommand("New-PSSession");
            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", uri);
            command.AddParameter("Authentication", "Default");
            powershell.Commands = command;
            runspace.Open();
            powershell.Runspace = runspace;
            Collection <PSSession> result = powershell.Invoke <PSSession>();

            powershell = PowerShell.Create();
            command    = new PSCommand();
            command.AddCommand("Set-Variable");
            command.AddParameter("Name", "ra");
            command.AddParameter("Value", result[0]);

            powershell.Commands = command;
            powershell.Runspace = runspace;
            powershell.Invoke();

            powershell = PowerShell.Create();
            command    = new PSCommand();
            command.AddScript("Import-PSSession -Session $ra");
            powershell.Commands = command;
            powershell.Runspace = runspace;
            powershell.Invoke();
            Debug.WriteLine("About to make it out of the util controller");
            return(runspace);
        }
        static List <String> GetPodsNames(string prefix)
        {
            var response = new List <String>();

            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it

            runspace.Open();

            // create a pipeline and feed it the script text

            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript("kubectl get pods");

            pipeline.Commands.Add("Out-String");

            Collection <PSObject> results = pipeline.Invoke();

            // close the runspace

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                response.AddRange(
                    obj.ToString()
                    .Split('\n')
                    .Where(w => w.StartsWith(prefix))
                    .Select(s => s.Split(' ')[0])
                    );
            }

            return(response);
        }
        /// <summary>
        /// Continue method implementation
        /// PowerShell Resume-Service
        /// </summary>
        public void Continue()
        {
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                bool islocal = (Dns.GetHostEntry("LocalHost").HostName.ToLower().Equals(MachineName.ToLower()));
                if (!islocal)
                {
                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, MachineName, 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", null, 30000);
                    SPRunSpace = RunspaceFactory.CreateRunspace(connectionInfo);
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential;
                }
                else
                {
                    SPRunSpace = RunspaceFactory.CreateRunspace();
                }

                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline = SPRunSpace.CreatePipeline();
                Command  cmd      = new Command("Resume-Service " + this.ServiceName, true);
                pipeline.Commands.Add(cmd);
                Collection <PSObject> PSOutput = pipeline.Invoke();
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
                if (SPPowerShell != null)
                {
                    SPPowerShell.Dispose();
                }
            }
        }
Esempio n. 5
0
        public void InitializeTests()
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {
                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection <PSObject> psObjects = pipeline.Invoke();
                Assert.AreEqual <int>(1, psObjects.Count);
                sfLogin = psObjects[0];
            }

            using (Pipeline pipeline = runspace.CreatePipeline())
            {
                Command command = new Command("New-PSDrive");
                command.Parameters.Add("Name", Utils.ShareFileDriveLetter);
                command.Parameters.Add("PSProvider", "ShareFile");
                command.Parameters.Add("Root", "/");
                command.Parameters.Add("Client", sfLogin);

                pipeline.Commands.Add(command);

                Collection <PSObject> psObjects = pipeline.Invoke();

                // Drive is successfully mapped to root folder
                Assert.AreEqual <int>(1, psObjects.Count);
            }
        }
Esempio n. 6
0
        private IEnumerable <harddisk> runCommand()
        {
            PSSnapInException warning  = new PSSnapInException();
            Runspace          runspace = RunspaceFactory.CreateRunspace();

            runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning);
            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();

            String Script     = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n";
            String preCommand = "Get-HardDisk -VM + \"" + VMName + "\" | ? {$_.Name -eq \"" + DiskName + "\"}";

            String command = "Remove-HardDisk";

            Script += preCommand + " | " + command + " -Confirm:$False";

            pipeline.Commands.AddScript(Script);

            Collection <PSObject> results = new Collection <PSObject>();

            try
            {
                results = pipeline.Invoke();
            }

            catch (Exception ex)
            {
                throw ex;
            }

            foreach (PSObject obj in results)
            {
                if (obj.BaseObject.GetType().ToString().Contains("DiskImpl"))
                {
                    yield return(new harddisk(obj));
                }
            }
            runspace.Close();
        }
Esempio n. 7
0
        /// <summary>
        /// Do really cool powershell things
        /// </summary>
        /// <param name="script"></param>
        /// <param name="request"></param>
        private void ExecuteScriptForRequest(Script script, IServiceRequest request)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();

            // create a pipeline and feed it the script
            Pipeline pipeline = runspace.CreatePipeline();

            try
            {
                pipeline.Commands.AddScript(@"C:\Scripts\" + script.FileName);
            }
            catch (Exception exception)
            {
                Displaymessage($"Error: {exception.Message}", MessageType.Failure);
            }
            // add parameters
            runspace.SessionStateProxy.SetVariable("RequestedFor", request.RequestedForGuids);
            runspace.SessionStateProxy.SetVariable("Requestor", request.RequestedByGuid);
            foreach (var userInput in request.ServiceRequestUserInputs)             //just add everything
            {
                runspace.SessionStateProxy.SetVariable(userInput.Name, userInput.Value);
            }
            try
            {
                Collection <PSObject> results = pipeline.Invoke();
                Displaymessage("Script results: ", MessageType.Info);

                foreach (var psObject in results)
                {
                    Displaymessage(psObject.ToString(), MessageType.ScriptResult);
                }
            }
            catch (Exception exception)
            {
                Displaymessage($"Error in executing script: {exception.Message}", MessageType.Failure);
            }
            Console.WriteLine($"Completed execution of {request.Name}");
        }
        //AD用户启用、禁用时,操作Exchange中的用户显示属性并更新地址列表
        // 参数addresslistname3是地址列表的名字,adName市用户的AD路径全名,如test.com/xd-ad/集团公司/办公室/spider,第三个参数表示启用为true,禁用为false
        public string UpdateAddressList3(string addresslistname3, string adName, bool enble)
        {
            #region 2007 编写方法

            #endregion

            try
            {
                // 生成一个连接类型,传入exchange服务器IP、将要使用的Scheme以及管理员凭据
                var connectionInfo = ExchangeScriptInit();

                using (var rs = RunspaceFactory.CreateRunspace(connectionInfo))
                {
                    var psh = PowerShell.Create();
                    psh.Runspace = rs;
                    rs.Open();
                    var sScript2 = "";
                    if (enble == true)
                    {
                        sScript2 = "Set-Mailbox -HiddenFromAddressListsEnabled $false -identity '" + adName + "'";
                    }
                    else
                    {
                        sScript2 = "Set-Mailbox -HiddenFromAddressListsEnabled $true -identity '" + adName + "'";
                    }
                    psh.Commands.AddScript(sScript2);

                    var sScript1 = "Update-AddressList -identity '" + addresslistname3 + "'";
                    psh.Commands.AddScript(sScript1);
                    psh.Invoke();
                    rs.Close();
                    psh.Runspace.Close();
                    return("1");
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        private void RunTests(RunContext runContext, string describeName, string scenarioName)
        {
            StringBuilder   testOutput  = new StringBuilder();
            TestAdapterHost testAdapter = new TestAdapterHost();

            testAdapter.HostUi.OutputString = s =>
            {
                if (!string.IsNullOrEmpty(s))
                {
                    testOutput.Append(s);
                }
            };

            using (Runspace runspace = RunspaceFactory.CreateRunspace(testAdapter))
            {
                runspace.Open();

                using (_powerShell = PowerShell.Create())
                {
                    _powerShell.Runspace = runspace;

                    try
                    {
                        RunTests(describeName, scenarioName, runContext);
                    }
                    catch (Exception ex)
                    {
                        foreach (TestFile file in runContext.TestFiles.Values)
                        {
                            file.SetOutcome(TestOutcome.None);
                        }
                        foreach (TestFeature feature in runContext.TestFeatures.Values)
                        {
                            feature.SetOutcome(TestOutcome.None);
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        private Runspace CreateNamedPipeRunspace(int procId, string appDomainName)
        {
            NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(procId, appDomainName);
            TypeTable      typeTable      = TypeTable.LoadDefaultTypeFiles();
            RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, this.Host, typeTable) as RemoteRunspace;

            remoteRunspace.Name             = NamedPipeRunspaceName;
            remoteRunspace.ShouldCloseOnPop = true;
            _connectingRemoteRunspace       = remoteRunspace;

            try
            {
                remoteRunspace.Open();
                remoteRunspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
            }
            catch (RuntimeException e)
            {
                string msgAppDomainName = (!string.IsNullOrEmpty(appDomainName)) ? appDomainName : NamedPipeUtils.DefaultAppDomainName;

                // Unwrap inner exception for original error message, if any.
                string errorMessage = (e.InnerException != null) ? (e.InnerException.Message ?? string.Empty) : string.Empty;

                ThrowTerminatingError(
                    new ErrorRecord(
                        new RuntimeException(
                            StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess,
                                              msgAppDomainName, procId, errorMessage),
                            e.InnerException),
                        "EnterPSHostProcessCannotConnectToProcess",
                        ErrorCategory.OperationTimeout,
                        this));
            }
            finally
            {
                _connectingRemoteRunspace = null;
            }

            return(remoteRunspace);
        }
        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();

            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
Esempio n. 12
0
        static string DoIt(string cmd)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline       pipeline      = runspace.CreatePipeline();

            pipeline.Commands.AddScript(cmd);
            pipeline.Commands.Add("Out-String");
            Collection <PSObject> results = pipeline.Invoke();

            runspace.Close();

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                stringBuilder.Append(obj);
            }
            return(stringBuilder.ToString().Trim());
        }
Esempio n. 13
0
        protected PSObject ExecuteScript(string script)
        {
            if (this.powershellHost == null)
            {
                this.powershellHost          = PowerShell.Create();
                this.powershellHost.Runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
                this.powershellHost.Runspace.Open();
            }

            this.powershellHost.AddScript(script);
            this.WriteVerbose(script);

            var output = this.powershellHost.Invoke();

            if (output == null || !output.Any())
            {
                throw new InvalidDataException(StringResources.Error_InvalidPowershellScriptOutput);
            }

            this.WriteOutput(output);
            return(output[output.Count - 1]);
        }
        static void Main(string[] args)
        {
            String machinename = "";
            String username    = @"";
            String password    = @"";


            string tsScript = $"mstsc /v:{machinename}";
            string cmdKey   = $"cmdkey /generic:TERMSVR/{machinename} /user:{username} /pass:{password}";

            using (Runspace rs = RunspaceFactory.CreateRunspace())
            {
                rs.Open();

                using (Pipeline pl = rs.CreatePipeline())
                {
                    pl.Commands.AddScript(cmdKey);
                    pl.Commands.AddScript(tsScript);
                    pl.Invoke();
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        ///     Executes a powershell script
        /// </summary>
        /// <param name="folder">Folder where to execute the script</param>
        /// <param name="file">Script to execute</param>
        /// <param name="configuration">Configuration used</param>
        /// <param name="log">Logger to use</param>
        /// <param name="parameters">Parameters for the script</param>
        public static void Execute(string folder, string file, string configuration, ILogger log, Dictionary <string, string> parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(new Host(), runspaceConfiguration);

            runspace.Open();
            runspace.SessionStateProxy.Path.SetLocation(folder);

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
            Pipeline pipeline = runspace.CreatePipeline();

            Command myCommand = new Command(Path.Combine(folder, file));

            foreach (var param in parameters.Keys)
            {
                myCommand.Parameters.Add(new CommandParameter("-" + param, parameters[param]));
            }

            myCommand.Parameters.Add(new CommandParameter("-Verb", "RunAs"));
            pipeline.Commands.Add(myCommand);

            Collection <PSObject> results = new Collection <PSObject>();

            try
            {
                results = pipeline.Invoke();
            }
            catch (RuntimeException e)
            {
                log.Log(e.Message, true);
            }
            finally
            {
                results.ToList().ForEach(x => log.Log(x.ToString()));
                pipeline.Error.ReadToEnd().ToList().ForEach(x => log.Log(x.ToString(), true));
            }
        }
Esempio n. 16
0
    public static void UsingPowerShell(string[] filesToMerge, string outputFilename)
    {
        // create Powershell runspace
        Runspace runspace = RunspaceFactory.CreateRunspace();

        runspace.Open();
        RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);

        runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
        // create a pipeline and feed it the script text
        Pipeline pipeline = runspace.CreatePipeline();
        Command  command  = new Command(SCRIPT_PATH);

        foreach (var file in filesToMerge)
        {
            command.Parameters.Add(null, file);
        }
        command.Parameters.Add(null, outputFilename);
        pipeline.Commands.Add(command);
        pipeline.Invoke();
        runspace.Close();
    }
Esempio n. 17
0
        public MSActorReturnMessageModel ModifyDirQuota(string computername, string path, string limit)
        {
            // Project P0975: Replace old command line scripts with new PowerShell commands,
            // required after upgrading the Windows Server version on the file servers
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("Set-FsrmQuota");
                        command.AddParameter("Path", path);
                        command.AddParameter("Size", NumericLimit(limit));
                        powershell.Commands = command;
                        Collection <PSObject> result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Esempio n. 18
0
        public void CanGetPackages()
        {
            InitialSessionState s = InitialSessionState.CreateDefault();

            s.ImportPSModule(new[] { @".\DevAudit.PowerShell.dll" });
            Runspace r = RunspaceFactory.CreateRunspace(s);

            r.Open();
            Pipeline pipeline = r.CreatePipeline();
            Command  c        = new Command("Get-AuditPackages");

            c.Parameters.Add("Source", "msi");
            pipeline.Commands.Add(c);
            Collection <PSObject> results = pipeline.Invoke();

            r.Close();
            IEnumerable <Package> packages = results.Select(result => (Package)result.BaseObject);

            Assert.NotEmpty(packages);
            Assert.NotEmpty(packages.Where(p => p.PackageManager == "msi"));
            Assert.NotEmpty(packages.Where(p => p.Name.Contains("Microsoft")));
        }
Esempio n. 19
0
        public static string ExecPowerShellCommand(string sCommand, bool bRemoveEmptyLines)
        {
            if (runspace == null)
            {
                PSSnapInInfo      info = null;
                PSSnapInException ex   = null;
                bool error             = false;

                try
                {
                    runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create());
                    runspace.Open();

                    foreach (string pssnapin in ExchangePsSnapin)
                    {
                        if (Execute("$(Get-PSSnapin -Registered | Select-String " + pssnapin + ") -ne $null", true).Trim() == "True")
                        {
                            info = runspace.RunspaceConfiguration.AddPSSnapIn(pssnapin, out ex);
                        }
                    }
                }
                catch (Exception)
                {
                    error = true;
                }

                if (ex != null || info == null || error)
                {
                    if (runspace != null)
                    {
                        runspace.Dispose();
                        runspace = null;
                    }
                    throw new ExchangeServerException("Couldn't initialize PowerShell runspace.");
                }
            }

            return(Execute(sCommand, bRemoveEmptyLines));
        }
Esempio n. 20
0
        private static void RunPowershellScript(string scriptFile, string scriptParameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline       pipeline      = runspace.CreatePipeline();
            Command        scriptCommand = new Command(scriptFile);
            Collection <CommandParameter> commandParameters = new Collection <CommandParameter>();

            foreach (string scriptParameter in scriptParameters.Split(' '))
            {
                CommandParameter commandParm = new CommandParameter(null, scriptParameter);
                commandParameters.Add(commandParm);
                scriptCommand.Parameters.Add(commandParm);
            }
            pipeline.Commands.Add(scriptCommand);
            Collection <PSObject> psObjects;

            psObjects = pipeline.Invoke();
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the PSListenerConsoleSample class.
        /// </summary>
        public PSListenerConsoleSample()
        {
            // Create the host and runspace instances for this interpreter.
            // Note that this application does not support console files so
            // only the default snap-ins will be available.
            this.myHost     = new MyHost(this);
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost);
            this.myRunSpace.Open();

            // Create a PowerShell object to run the commands used to create
            // $profile and load the profiles.
            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;

                PSCommand[] profileCommands = HostUtilities.GetProfileCommands("SampleHost06");
                foreach (PSCommand command in profileCommands)
                {
                    this.currentPowerShell.Commands = command;
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose the PowerShell object and set currentPowerShell
                // to null. It is locked because currentPowerShell may be
                // accessed by the ctrl-C handler.
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Esempio n. 22
0
        private List <string> RunScript(string scriptText)
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script output objects into nicely formatted strings
            // remove this line to get the actual objects that the script returns. For example, the script
            // "Get-Process" returns a collection of System.Diagnostics.Process instances.
            pipeline.Commands.Add("Out-String");

            List <string> ComputerList = new List <string>();

            string[] computerNames = new string[] { };
            // execute the script
            try
            {
                Collection <PSObject> results = pipeline.Invoke();
                string[] stringSeparators     = new string[] { "\r\n" };
                computerNames = results[0].ToString().Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
            }
            catch { }

            // close the runspace
            runspace.Close();

            //convert to list
            ComputerList = computerNames.ToList();
            // return the results of the script that has
            // now been converted to text
            return(ComputerList);
        }
Esempio n. 23
0
        ////////////////////////////////////////////////////////////////////////////////
        // Working
        ////////////////////////////////////////////////////////////////////////////////
        internal static String runPowerShell(string command)
        {
            StringBuilder stringBuilder = new StringBuilder();
            Runspace      runspace      = RunspaceFactory.CreateRunspace();

            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(command);
            pipeline.Commands.Add("Out-String");
            Collection <PSObject> results = pipeline.Invoke();

            runspace.Close();

            foreach (PSObject obj in results)
            {
                stringBuilder.Append(obj.ToString());
            }
            return(stringBuilder.ToString());
        }
Esempio n. 24
0
        static IEnumerable <string> CmdletDirGlobbing(string basePath, string glob)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();

            // cd to basePath
            if (basePath != null)
            {
                Pipeline cdPipeline = runspace.CreatePipeline();
                Command  cdCommand  = new Command("cd");
                cdCommand.Parameters.Add("Path", basePath);
                cdPipeline.Commands.Add(cdCommand);
                cdPipeline.Invoke();                 // run the cmdlet
            }

            // run the "dir" cmdlet (e.g. "dir C:\*\*\*.txt" )
            Pipeline dirPipeline = runspace.CreatePipeline();
            Command  dirCommand  = new Command("dir");

            dirCommand.Parameters.Add("Path", glob);
            dirPipeline.Commands.Add(dirCommand);

            Collection <PSObject> dirOutput = dirPipeline.Invoke();

            // for each found file
            foreach (PSObject psObject in dirOutput)
            {
                PSMemberInfoCollection <PSPropertyInfo> a = psObject.Properties;
                // look for the full path ("FullName")
                foreach (PSPropertyInfo psPropertyInfo in psObject.Properties)
                {
                    if (psPropertyInfo.Name == "FullName")
                    {
                        yield return(psPropertyInfo.Value.ToString());                        // yield it
                    }
                }
            }
        }
        /// <summary>
        /// InitLocalNodeType method implementation
        /// </summary>
        private bool InitLocalNodeType()
        {
            string     nodetype     = string.Empty;
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                SPRunSpace            = RunspaceFactory.CreateRunspace();
                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline  = SPRunSpace.CreatePipeline();
                Command  exportcmd = new Command("(Get-AdfsSyncProperties).Role", true);
                pipeline.Commands.Add(exportcmd);

                Collection <PSObject> PSOutput = pipeline.Invoke();
                foreach (var result in PSOutput)
                {
                    if (!result.BaseObject.ToString().ToLower().Equals("primarycomputer"))
                    {
                        return(false);
                    }
                }
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
                if (SPPowerShell != null)
                {
                    SPPowerShell.Dispose();
                }
            }
            return(true);
        }
        public async Task RemoteExitCode()
        {
            //hack for remote connection
            if (Runspace.DefaultRunspace == null)
            {
                var defaultRunspace = RunspaceFactory.CreateRunspace();
                defaultRunspace.Open();

                Runspace.DefaultRunspace = defaultRunspace;
            }

            var localRs = RunspaceFactory.CreateRunspace();

            var localPipe = localRs.CreatePipeline("pwsh -c 'exit 123'");

            localRs.Open();

            var localResult = localPipe.Invoke();

            Assert.True(localPipe.HadErrors);
            Assert.Empty(localResult);

            localRs.Close();


            var connectionInfo = new SSHConnectionInfo("root", "lnx1513", null);
            var remoteRS       = RunspaceFactory.CreateRunspace(connectionInfo);

            var remotePipe = remoteRS.CreatePipeline("pwsh -c 'exit 123'");

            remoteRS.Open();

            var remoteResult = remotePipe.Invoke();

            Assert.True(remotePipe.HadErrors);
            Assert.Empty(remoteResult);

            remoteRS.Close();
        }
        /// <summary>
        /// Create an instance of the console listener.
        /// </summary>
        public PSListenerConsole(PanelHandler powerShellConsolePrinter)
        {
            this.PowerShellConsolePrinter = powerShellConsolePrinter;
            // Create the host and runspace instances for this interpreter. Note that
            // this application doesn't support console files so only the default snapins
            // will be available.
            this.myHost     = new MyHost(this);
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost);
            this.myRunSpace.Open();

            // Create a PowerShell object to run the commands used to create
            // $profile and load the profiles.
            lock (this.instanceLock) {
                this.currentPowerShell = PowerShell.Create();
            }

            try {
                this.currentPowerShell.Runspace = this.myRunSpace;

                PSCommand[] profileCommands = Microsoft.PowerShell.Host.HostUtilities.GetProfileCommands("InteractiveConsoleHost");
                foreach (PSCommand command in profileCommands)
                {
                    this.currentPowerShell.Commands = command;
                    this.currentPowerShell.Invoke();
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Error Message",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            finally {
                // Dispose of the pipeline line and set it to null, locked because currentPowerShell
                // may be accessed by the ctrl-C handler...
                lock (this.instanceLock) {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Esempio n. 28
0
        public EmbeddedShellView()
        {
            InitializeComponent();

            commandTextBox.PreviewKeyDown += OnCommandTextBoxPreviewKeyDown;

            // ignore execution-policy
            var iis = InitialSessionState.CreateDefault();

            iis.AuthorizationManager = new AuthorizationManager(Guid.NewGuid().ToString());
            iis.Providers.Add(new SessionStateProviderEntry(ShellConstants.DriveName, typeof(VisualTreeProvider),
                                                            string.Empty));

            host     = new SnoopPSHost(x => outputTextBox.AppendText(x));
            runspace = RunspaceFactory.CreateRunspace(host, iis);
            runspace.ThreadOptions  = PSThreadOptions.UseCurrentThread;
            runspace.ApartmentState = ApartmentState.STA;
            runspace.Open();

            // default required if you intend to inject scriptblocks into the host application
            Runspace.DefaultRunspace = runspace;
        }
Esempio n. 29
0
        private void LoadPowerShell()
        {
            var iss = InitialSessionState.CreateDefault();

            iss.ThreadOptions  = PSThreadOptions.UseCurrentThread;
            iss.ApartmentState = ApartmentState.STA;

            var rs = RunspaceFactory.CreateRunspace(iss);

            rs.Open();

            Runspace.DefaultRunspace = rs;

            _powerShellHost          = PowerShell.Create();
            _powerShellHost.Runspace = rs;
            _powerShellHost.AddScript(InitScript);
            _powerShellHost.Invoke();
            _powerShellHost.Streams.Warning.DataAdded += Warning_DataAdded;
            _powerShellHost.Streams.Error.DataAdded   += Error_DataAdded;
            _powerShellHost.Streams.Verbose.DataAdded += Verbose_DataAdded;

            _powerShellHost.AddCommand("Init").AddParameter("viewModel", _shellViewModel);
            _powerShellHost.Invoke();

            try
            {
                foreach (var scriptFile in ScriptFiles)
                {
                    var contents = File.ReadAllText(scriptFile);
                    _powerShellHost.AddScript(contents);
                }

                _powerShellHost.Invoke();
            }
            finally
            {
                _powerShellHost.Commands.Clear();
            }
        }
Esempio n. 30
0
        public static string RunScript(string scriptText)
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script
            // output objects into nicely formatted strings

            // remove this line to get the actual objects
            // that the script returns. For example, the script

            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.
            pipeline.Commands.Add("Out-String");

            // execute the script
            Collection <PSObject> results = pipeline.Invoke();

            // close the runspace
            runspace.Close();

            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            return(stringBuilder.ToString());
        }