예제 #1
0
        /// <summary>
        /// Execute the given cmdlet in powershell with the given parameters after injecting the given exception.  It is expected that the cmdlet has a runtime that can be used for receiving output
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cmdlet">The cmdlet to execute</param>
        /// <param name="name">The name of the cmdlet</param>
        /// <param name="exception">The exception to inject into the error stream</param>
        /// <param name="cmdletParameters">The parameters to pass to the cmdlet on the pipeline</param>
        public static void ExecuteCmdletWithExceptionInPipeline <T>(this PSCmdlet cmdlet, string name, Exception exception, params KeyValuePair <string, object>[] cmdletParameters)
        {
            List <T> output = new List <T>();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace))
            {
                var info = new CmdletInfo(name, cmdlet.GetType());
                powershell.AddCommand("Write-Error");
                powershell.AddParameter("Exception", exception);
                powershell.Invoke();
                powershell.Commands.Clear();
                powershell.AddCommand(info);
                foreach (var pair in cmdletParameters)
                {
                    if (pair.Value == null)
                    {
                        powershell.AddParameter(pair.Key);
                    }
                    else
                    {
                        powershell.AddParameter(pair.Key, pair.Value);
                    }
                }
                Collection <T> result = powershell.Invoke <T>();
                powershell.Streams.Error.ForEach(cmdlet.WriteError);
                powershell.Streams.Debug.ForEach(d => cmdlet.WriteDebug(d.Message));
                powershell.Streams.Verbose.ForEach(v => cmdlet.WriteWarning(v.Message));
                powershell.Streams.Warning.ForEach(w => cmdlet.WriteWarning(w.Message));

                if (result != null && result.Count > 0)
                {
                    result.ForEach(r => cmdlet.WriteObject(r));
                }
            }
        }
예제 #2
0
        private void LoadPowerShellProfile()
        {
            BuildShell();

            try
            {
                shell.Runspace = host.Runspace;
                PSCommand[] profileCommands = HostUtilities.GetProfileCommands("TexoUI");

                foreach (PSCommand command in profileCommands)
                {
                    shell.Commands = command;
                    shell.Invoke();
                }
            }
            catch (Exception e)
            {
                // Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
                logger.Error("Error during of profile loading in PowerShell.", e);
            }
            finally
            {
                ReleaseShell();
            }
        }
예제 #3
0
        public void FindAzModuleV2()

        {
            pwsh.Commands.Clear();
            pwsh.AddScript("Find-Module -Name Az -Repository LocalRepo");
            pwsh.Invoke();
        }
        /// <summary>
        /// A helper class that builds and executes a pipeline that writes to the default output path, depending on the value of <paramref name="quiet"/>. Any
        /// exceptions that are thrown are just passed to the caller.
        /// </summary>
        /// <param name="command">The script to run.</param>
        /// <param name="input">Any input arguments to pass to the script. If null then nothing is passed in.</param>
        /// <param name="quiet">Whether or not the results of the call should be written to the console.</param>
        /// <returns>The results of the call to _currentPowerShell.<see cref="PowerShell.Invoke()"/>.</returns>
        protected Collection <PSObject> ExecuteHelper(string command, object input, bool quiet = false)
        {
            // Ignore empty command lines.
            if (String.IsNullOrEmpty(command))
            {
                return(null);
            }

            lock (_executionLock)
            {
                // Create the pipeline object and make it available to the Ctrl-C handle through the _currentPowerShell instance variable.
                lock (_instanceLock)
                {
                    _currentPowerShell = Shell.Create();
                }

                // Create a pipeline for this execution, and then place the result in the _currentPowerShell variable so it is available to be stopped.
                try
                {
                    _currentPowerShell.Runspace = Runspace;
                    _currentPowerShell.AddScript(command);

                    if (!quiet)
                    {
                        // Add the default outputter to the end of the pipe and then call the MergeMyResults method to merge the output and error streams from
                        // the pipeline. This will result in the output being written using the PSHost and PSHostUserInterface classes instead of returning
                        // objects to the host application.
                        _currentPowerShell.AddCommand("out-default");
                        _currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    }

                    // If there is any input pass it in, otherwise just invoke the the pipeline.
                    if (input != null)
                    {
                        return(_currentPowerShell.Invoke(
                                   new object[]
                        {
                            input
                        }));
                    }

                    else
                    {
                        return(_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 (_instanceLock)
                    {
                        _currentPowerShell.Dispose();
                        _currentPowerShell = null;
                    }
                }
            }
        }
예제 #5
0
 private Collection <PSObject> InvokeCommand(string cmdLet, Dictionary <string, object> parameters)
 {
     powerShell.Commands.Clear();
     powerShell.AddCommand(cmdLet, false);
     if (parameters != null)
     {
         powerShell.AddParameters(parameters);
     }
     return(powerShell.Invoke());
 }
예제 #6
0
 internal bool ValidStorageAccountCred(string storageAccountName, string storageAccountKey, string endpoint)
 {
     using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
     {
         bool   valid             = true;
         Random rnd               = new Random();
         string testContainerName = string.Format("storsimplesdkvalidation{0}", rnd.Next());
         //create a storage container and then delete it
         string validateScript = string.Format(
             @"$context = New-AzureStorageContext -StorageAccountName {0} -StorageAccountKey {1} -Endpoint {2};"
             + @"New-AzureStorageContainer -Name {3} -Context $context;"
             + @"Remove-AzureStorageContainer -Name {3} -Context $context -Force;",
             storageAccountName, storageAccountKey, endpoint, testContainerName);
         ps.AddScript(validateScript);
         ps.Invoke();
         if (ps.HadErrors)
         {
             var    exception = ps.Streams.Error[0].Exception;
             string getScript = string.Format(
                 @"$context = New-AzureStorageContext -StorageAccountName {0} -StorageAccountKey {1};"
                 + @"Get-AzureStorageContainer -Name {2} -Context $context;",
                 storageAccountName, storageAccountKey, testContainerName);
             ps.AddScript(getScript);
             var result = ps.Invoke();
             if (result != null && result.Count > 0)
             {
                 //storage container successfully created and still exists, retry deleting it
                 int    retryCount   = 1;
                 string removeScript = string.Format(
                     @"$context = New-AzureStorageContext -StorageAccountName {0} -StorageAccountKey {1};"
                     + @"Remove-AzureStorageContainer -Name {2} -Context $context -Force;",
                     storageAccountName, storageAccountKey, testContainerName);
                 do
                 {
                     WriteVerbose(string.Format(Resources.StorageAccountCleanupRetryMessage, retryCount));
                     ps.AddScript(removeScript);
                     ps.Invoke();
                     Thread.Sleep(retryCount * 1000);
                     ps.AddScript(getScript);
                     result = ps.Invoke();
                 } while (result != null && result.Count > 0 && ++retryCount <= 5);
             }
             else
             {
                 valid = false;
                 HandleException(exception);
             }
         }
         return(valid);
     }
 }
예제 #7
0
        private List <string> CopyRequiredModules(String configurationPath, String tempZipFolder)
        {
            WriteVerbose(
                String.Format(
                    CultureInfo.CurrentUICulture,
                    Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscParsingConfiguration,
                    configurationPath));

            var requiredModules = GetRequiredModules(configurationPath);
            var metadataModules = new List <string>();

            foreach (var module in requiredModules)
            {
                metadataModules.Add(module.Key);
                using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                {
                    // Wrapping script in a function to prevent script injection via $module variable.
                    powershell.AddScript(
                        @"function Copy-Module([string]$moduleName, [string]$moduleVersion, [string]$tempZipFolder) 
                        {
                            if([String]::IsNullOrEmpty($moduleVersion))
                            {
                                $module = Get-Module -List -Name $moduleName                                
                            }
                            else
                            {
                                $module = (Get-Module -List -Name $moduleName) | Where-Object{$_.Version -eq $moduleVersion}
                            }
                            
                            $moduleFolder = Split-Path $module.Path
                            Copy-Item -Recurse -Path $moduleFolder -Destination ""$tempZipFolder\$($module.Name)""
                        }"
                        );
                    powershell.Invoke();
                    powershell.Commands.Clear();
                    powershell.AddCommand("Copy-Module")
                    .AddParameter("moduleName", module.Key)
                    .AddParameter("moduleVersion", module.Value)
                    .AddParameter("tempZipFolder", tempZipFolder);
                    WriteVerbose(String.Format(
                                     CultureInfo.CurrentUICulture,
                                     Microsoft.Azure.Commands.Compute.Properties.Resources.PublishVMDscExtensionCopyModuleVerbose,
                                     module,
                                     tempZipFolder));
                    powershell.Invoke();
                }
            }

            return(metadataModules);
        }
        public void TranslatePSPathThatShouldExist()
        {
            string psPath = "mytemp:\\" + Path.GetFileName(_tempFilePath);

            // test against PSDrive
            _ps.Commands.AddScript(String.Format(ScriptTemplate, psPath));

            Hashtable result = _ps.Invoke <Hashtable>().SingleOrDefault();

            Assert.NotNull(result);
            Assert.True(_ps.Streams.Error.Count == 0);
            Assert.True((bool)result["success"]);
            Assert.True((bool)result["exists"]);
            Assert.Equal(_tempFilePath, (string)result["path"], StringComparer.OrdinalIgnoreCase);
        }
예제 #9
0
 /// <summary>
 /// Execute PSScriptAnalyzer cmdlets in PowerShell while preserving the PSModulePath.
 /// Attempts to prevent PSModulePath mutation by runspace creation within the PSScriptAnalyzer module.
 /// </summary>
 /// <param name="powershell">The PowerShell instance to execute.</param>
 /// <returns>The output of PowerShell execution.</returns>
 private Collection <PSObject> InvokePowerShellWithModulePathPreservation(System.Management.Automation.PowerShell powershell)
 {
     using (PSModulePathPreserver.Take())
     {
         return(powershell.Invoke());
     }
 }
        public static string GetModuleNameForDscResource(string resourceName)
        {
            string moduleName;

            if (!_resourceName2ModuleNameCache.TryGetValue(resourceName, out moduleName))
            {
                try
                {
                    using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                    {
                        powershell.AddCommand("Get-DscResource").
                        AddCommand("Where-Object").AddParameter("Property", "ResourceType").AddParameter("Value", resourceName).AddParameter("EQ", true).
                        AddCommand("Foreach-Object").AddParameter("MemberName", "Module").
                        AddCommand("Foreach-Object").AddParameter("MemberName", "Name");
                        moduleName = powershell.Invoke <string>().First();
                    }
                }
                catch (InvalidOperationException e)
                {
                    throw new GetDscResourceException(resourceName, e);
                }
                _resourceName2ModuleNameCache.TryAdd(resourceName, moduleName);
            }
            return(moduleName);
        }
예제 #11
0
        static Settings Load()
        {
            var path     = Scripts.GetSettings;
            var settings = new Settings();

            using (var runspace = RunspaceFactory.CreateRunspace())
            {
                runspace.Open();
                using (A.PowerShell ps = A.PowerShell.Create())
                {
                    ps.Runspace = runspace;

                    var script = String.Format("new-object -property ({0}) -typename '{1}'",
                                               path,
                                               typeof(Settings).FullName);
                    ps.AddScript(script);

                    try
                    {
                        var results = ps.Invoke();
                        if (results.Any())
                        {
                            settings = (results.First().BaseObject as Settings) ?? settings;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            return(settings);
        }
예제 #12
0
        private List <object> ExecuteCommand(bool stringOutput, bool marshallResults = true)
        {
            var jobManager = TypeResolver.ResolveFromCache <IJobManager>();
            var job        = jobManager.GetContextJob();

            JobName = job?.Name;

            if (stringOutput)
            {
                powerShell.Commands.AddCommand(OutDefaultCommand);
            }

            if (Runspace.DefaultRunspace == null)
            {
                Runspace.DefaultRunspace = host.Runspace;
            }

            if (Debugging)
            {
                host.Runspace.Debugger.DebuggerStop      += DebuggerOnDebuggerStop;
                host.Runspace.Debugger.BreakpointUpdated += DebuggerOnBreakpointUpdated;
                SetVariable("SpeDebug", true);
                if (Interactive)
                {
                    var message = Message.Parse(this, "ise:debugstart");
                    SendUiMessage(message);
                }
            }
            else
            {
                Engine.SessionState.PSVariable.Remove("SpeDebug");
            }
            abortRequested = false;

            LastErrors?.Clear();
            // execute the commands in the pipeline now
            var execResults = powerShell.Invoke();

            if (powerShell.HadErrors)
            {
                LastErrors = powerShell.Streams.Error.ToList();
            }

            LogErrors(powerShell, execResults);

            if (Interactive && Debugging)
            {
                host.Runspace.Debugger.DebuggerStop      -= DebuggerOnDebuggerStop;
                host.Runspace.Debugger.BreakpointUpdated -= DebuggerOnBreakpointUpdated;

                var message = Message.Parse(this, "ise:debugend");
                SendUiMessage(message);
                Debugging = false;
            }

            JobName = string.Empty;
            return(marshallResults
                ? execResults?.Select(p => p?.BaseObject).ToList()
                : execResults?.Cast <object>().ToList());
        }
        /// <summary>
        /// Invoke script with parameters.
        /// </summary>
        /// <param name="script">Script command to be invoked.</param>
        /// <param name="parameters">Parameters for the command.</param>
        public void Invoke(string script, params PowerShellScriptParameter[] parameters)
        {
            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddScript(script);

                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        powerShell.AddParameter(parameter.Name, parameter.Value);
                    }
                }

                // invoke execution on the pipeline (collecting output)
                var output = powerShell.Invoke();

                foreach (var outputItem in output)
                {
                    if (outputItem != null)
                    {
                        this.logger.LogDebug(outputItem.BaseObject.GetType().FullName);
                        this.logger.LogDebug(outputItem.BaseObject.ToString() + "\n");
                    }
                }

                this.ProcessPowerShellStreams(powerShell);
            }
        }
예제 #14
0
        public void GetLocalAdminPassword(string computerName)
        {
            IComputer computer = directory.GetComputer(computerName);

            this.provider.ClearPassword(computer);
            this.provider.ClearPasswordHistory(computer);

            CollectionAssert.IsEmpty(this.provider.GetPasswordHistory(computer));
            Assert.IsNull(this.provider.GetCurrentPassword(computer, null));

            DateTime created  = DateTime.UtcNow.Trim(TimeSpan.TicksPerSecond);
            DateTime expired  = DateTime.UtcNow.AddDays(-5).Trim(TimeSpan.TicksPerSecond);
            string   password = Guid.NewGuid().ToString();

            this.provider.UpdateCurrentPassword(computer, password, created, expired, 0, MsMcsAdmPwdBehaviour.Ignore);

            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create();
            ps.AddCommand(new CmdletInfo("Get-LithnetLocalAdminPassword", typeof(GetLocalAdminPassword)));
            ps.AddParameter("ComputerName", computerName);
            var output = ps.Invoke();

            Assert.AreEqual(1, output.Count);
            var result = output[0];

            Assert.AreEqual(password, result.Properties["Password"].Value);
        }
        public static Collection <PSObject> Invoke(this Runspace runspace, string script, IDictionary parameters = null, Action <PSDataStreams> psDataStreamAction = null)
        {
            if (script == null)
            {
                throw new ArgumentOutOfRangeException("script");
            }

            if (runspace == null)
            {
                throw new ArgumentOutOfRangeException("runspace");
            }

            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                ps.Runspace = runspace;
                ps.AddScript(script);

                if (parameters != null && parameters.Count > 0)
                {
                    ps.AddParameters(parameters);
                }

                psDataStreamAction?.Invoke(ps.Streams);

                return(ps.Invoke());
            }
        }
        public PSPathTranslationTests()
        {
            // create temp file
            _tempFilePath = Path.GetTempFileName();

            // initialize
            var state = InitialSessionState.CreateDefault();

            state.ThreadOptions  = PSThreadOptions.UseCurrentThread;
            state.ApartmentState = ApartmentState.STA;
            _ps          = System.Management.Automation.PowerShell.Create();
            _ps.Runspace = RunspaceFactory.CreateRunspace(state);
            _ps.Runspace.Open();

            // create a new PSDrive for translation tests
            _ps.AddCommand("New-PSDrive")
            .AddParameter("Name", "mytemp")
            .AddParameter("PSProvider", FileSystemProvider.ProviderName)
            .AddParameter("Root", Path.GetTempPath());
            _ps.Invoke();
            Assert.True(_ps.Streams.Error.Count == 0, "Failed to create mytemp psdrive.");

            _ps.Streams.ClearStreams();
            _ps.Commands.Clear();
        }
예제 #17
0
        /// <summary>
        /// Load global aliases for ARM
        /// </summary>
        public void OnImport()
        {
#if DEBUG
            try
            {
#endif
            AzureSessionInitializer.InitializeAzureSession();
            ResourceManagerProfileProvider.InitializeResourceManagerProfile();
#if DEBUG
            if (!TestMockSupport.RunningMocked)
            {
#endif
            AzureSession.Instance.DataStore = new DiskDataStore();
#if DEBUG
        }
#endif
            System.Management.Automation.PowerShell invoker = null;
            invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
            invoker.AddScript(File.ReadAllText(FileUtilities.GetContentFilePath(
                                                   Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                   "AzureRmProfileStartup.ps1")));
            invoker.Invoke();
#if DEBUG
        }
        catch (Exception) when(TestMockSupport.RunningMocked)
        {
            // This will throw exception for tests, ignore.
        }
#endif
        }
예제 #18
0
        public static Dictionary <string, object> start()
        {
            // We need to be explicit that we got this far.
            System.Console.WriteLine("INTERACTIVE_START");

            // Enter the shell
            ConsoleHost.GetMethod("EnterNestedPrompt").Invoke(pshost, new object[] { });

            // This ensures that we won't immediately exit next time we enter a prompt
            // with the same Runspace/ConsoleHost
            ConsoleHost.GetProperty("ShouldEndSession", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(pshost, false);

            // Let pwncat know we exited the shell
            System.Console.WriteLine("\nINTERACTIVE_COMPLETE");

            // Match our CWD w/ powershell
            System.Management.Automation.PowerShell ps2 = System.Management.Automation.PowerShell.Create();
            ps2.Runspace             = runspace;
            Runspace.DefaultRunspace = runspace;
            ps2.AddScript("[System.IO.Directory]::SetCurrentDirectory($ExecutionContext.SessionState.Path.CurrentFileSystemLocation)");
            ps2.Invoke();

            return(new Dictionary <string, object>()
            {
            });
        }
예제 #19
0
        public void AddToPasswordHistory(string computerName)
        {
            IComputer computer = directory.GetComputer(computerName);

            provider.ClearPassword(computer);
            provider.ClearPasswordHistory(computer);
            CollectionAssert.IsEmpty(provider.GetPasswordHistory(computer));

            DateTime firstCreated  = DateTime.UtcNow.Trim(TimeSpan.TicksPerSecond);
            DateTime firstExpiry   = DateTime.UtcNow.AddDays(-3).Trim(TimeSpan.TicksPerSecond);
            string   firstPassword = Guid.NewGuid().ToString();

            provider.UpdateCurrentPassword(computer, firstPassword, firstCreated, firstExpiry, 0, MsMcsAdmPwdBehaviour.Ignore);

            DateTime secondCreated  = DateTime.UtcNow.AddDays(2).Trim(TimeSpan.TicksPerSecond);
            DateTime secondExpiry   = DateTime.UtcNow.AddDays(-5).Trim(TimeSpan.TicksPerSecond);
            string   secondPassword = Guid.NewGuid().ToString();

            provider.UpdateCurrentPassword(computer, secondPassword, secondCreated, secondExpiry, 30, MsMcsAdmPwdBehaviour.Ignore);

            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create();
            ps.AddCommand(new CmdletInfo("Get-LithnetLocalAdminPasswordHistory", typeof(GetLocalAdminPasswordHistory)));
            ps.AddParameter("ComputerName", computerName);
            var output = ps.Invoke();

            Assert.AreEqual(1, output.Count);

            var passwords = output.Select(t => t.Properties["Password"].Value as string).ToList();

            CollectionAssert.AreEquivalent(new[] { firstPassword }, passwords);
        }
예제 #20
0
        public override void ExecuteCmdlet()
        {
            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create();
            ps.AddCommand("Connect-AzAccount");

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Credential)))
            {
                ps.AddParameter("Credential", Credential);
            }

            if (MyInvocation.BoundParameters.ContainsKey(nameof(ServicePrincipal)))
            {
                ps.AddParameter("ServicePrincipal", ServicePrincipal);
            }

            if (MyInvocation.BoundParameters.ContainsKey(nameof(TenantId)))
            {
                ps.AddParameter("Tenant", TenantId);
            }

            if (MyInvocation.BoundParameters.ContainsKey(nameof(ApplicationId)))
            {
                ps.AddParameter("ApplicationId", ApplicationId);
            }

            if (MyInvocation.BoundParameters.ContainsKey(nameof(CertificateThumbprint)))
            {
                ps.AddParameter("CertificateThumbprint", CertificateThumbprint);
            }

            ps.Invoke();
        }
예제 #21
0
 public void OnImport()
 {
     System.Management.Automation.PowerShell invoker = null;
     invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
     invoker.AddScript(File.ReadAllText(FileUtilities.GetContentFilePath("ServiceManagementStartup.ps1")));
     invoker.Invoke();
 }
예제 #22
0
        public string GetPowershellVersion()
        {
            log.Info("Checking to see what version of Powershell is installed");
            string version = String.Empty;

            using (PWS ps = PWS.Create())
            {
                ps.AddScript("./Scripts/PowerShell/PSVersion.ps1");
                if (ps.Streams.Error.Count > 0)
                {
                    foreach (var item in ps.Streams.Error)
                    {
                        log.Error(item.ErrorDetails.Message.ToString());
                        version = "ERROR";
                    }
                }
                else
                {
                    foreach (PSObject item in ps.Invoke())
                    {
                        version = item.Members["Major"].Value + "." + item.Members["Minor"].Value;
                        log.Info("Powershell version: " + version);
                    }
                }
            }
            return(version);
        }
예제 #23
0
        /// <summary>
        /// Invokes a PowerShell script block.
        /// </summary>
        /// <param name="script">A script to be invoked.</param>
        /// <param name="powerShell">PowerShell instance.</param>
        /// <param name="errorAction">Error callback function.</param>
        /// <returns></returns>
        internal static ICollection <PSObject> CallPowerShellScript(
            string script,
            System.Management.Automation.PowerShell powerShell,
            EventHandler <DataAddedEventArgs> errorAction)
        {
            try
            {
                powerShell.Clear();

                var input = new PSDataCollection <PSObject>();
                input.Complete();

                var output = new PSDataCollection <PSObject>();
                output.DataAdded += output_DataAdded;

                if (errorAction != null)
                {
                    powerShell.Streams.Error.DataAdded += errorAction;
                }

                powerShell.AddScript(script);
                powerShell.Invoke(null, output, new PSInvocationSettings());

                return(output.Count == 0 ? null : output);
            }
            finally
            {
                powerShell.Streams.Error.DataAdded -= errorAction;
            }
        }
예제 #24
0
        public object InvokeFunction(string name, List <object> arguments)
        {
            try
            {
                var command = GetFunction(name);
                powershell.AddCommand(command);
                foreach (var argument in arguments)
                {
                    powershell.AddArgument(argument);
                }

                var result = powershell.Invoke();
                if (result.Count == 1)
                {
                    return(result[0].BaseObject);
                }
                else
                {
                    return(result.Select(a => a?.BaseObject).ToList());
                }
            }
            finally
            {
                powershell.Streams.ClearStreams();
                powershell.Commands.Clear();
            }
        }
        private Process GetProcessByName(string name)
        {
            Collection <Process> foundProcesses;

            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                ps.AddCommand("Get-Process").AddParameter("Name", name);
                foundProcesses = ps.Invoke <Process>();
            }

            if (foundProcesses.Count == 0)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithName, name)),
                        "EnterPSHostProcessNoProcessFoundWithName",
                        ErrorCategory.InvalidArgument,
                        this)
                    );
            }
            else if (foundProcesses.Count > 1)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessMultipleProcessesFoundWithName, name)),
                        "EnterPSHostProcessMultipleProcessesFoundWithName",
                        ErrorCategory.InvalidArgument,
                        this)
                    );
            }

            return(foundProcesses[0]);
        }
예제 #26
0
        private static PowerShellResult ExecutePowershell(System.Management.Automation.PowerShell powershell, bool logInformationStream)
        {
            try
            {
                var execution = powershell.Invoke();
                var result    = new PowerShellResult
                {
                    // Powershell return values are usually wrapped inside of a powershell object, unwrap it or if it does not have a baseObject, return the actual object
                    Result = execution?.Select(GetResultObject).ToList(),
                    Errors = GetErrorMessages(powershell.Streams.Error),
                    Log    = logInformationStream == false ? "" : string.Join("\n", powershell.Streams.Information.Select(info => info.MessageData.ToString()))
                };

                return(result);
            }
            catch (Exception e)
            {
                throw new Exception($"Encountered terminating error while executing powershell: \n{e}\nErrors:\n{string.Join("\n", GetErrorMessages(powershell.Streams.Error))}");
            }
            finally
            {
                powershell.Commands.Clear(); // Clear the executed commands from the session so they do not get executed again
                powershell.Streams.ClearStreams();
            }
        }
예제 #27
0
 public void OnImport()
 {
     DebugHelper.WriteLogEx();
     System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
     using (powerShell)
     {
         CimCmdletsAssemblyInitializer.CimCmdletAliasEntry[] aliases = CimCmdletsAssemblyInitializer.Aliases;
         for (int i = 0; i < (int)aliases.Length; i++)
         {
             CimCmdletsAssemblyInitializer.CimCmdletAliasEntry cimCmdletAliasEntry = aliases[i];
             object[] name = new object[3];
             name[0] = cimCmdletAliasEntry.Name;
             name[1] = cimCmdletAliasEntry.Value;
             name[2] = cimCmdletAliasEntry.Options;
             powerShell.AddScript(string.Format(CultureInfo.CurrentUICulture, "New-Alias -Name {0} -Value {1} -Option {2}", name));
             object[] value = new object[3];
             value[0] = cimCmdletAliasEntry.Name;
             value[1] = cimCmdletAliasEntry.Value;
             value[2] = cimCmdletAliasEntry.Options;
             DebugHelper.WriteLog("Add commands {0} of {1} with option {2} to current runspace.", 1, value);
         }
         Collection <PSObject> pSObjects = powerShell.Invoke();
         object[] count = new object[1];
         count[0] = pSObjects.Count;
         DebugHelper.WriteLog("Invoke results {0}.", 1, count);
     }
 }
예제 #28
0
        /// <summary>
        /// This method creates the form where the output is displayed.
        /// </summary>
        private static void CreateForm()
        {
            Form         form = new Form();
            DataGridView grid = new DataGridView();

            form.Controls.Add(grid);
            grid.Dock = DockStyle.Fill;

            // Create a PowerShell object. Creating this object takes care of
            // building all of the other data structures needed to run the command.
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddCommand("get-process").AddCommand("sort-object").AddArgument("ID");
                if (Runspace.DefaultRunspace == null)
                {
                    Runspace.DefaultRunspace = powershell.Runspace;
                }

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

                // The generic collection needs to be re-wrapped in an ArrayList
                // for data-binding to work.
                ArrayList objects = new ArrayList();
                objects.AddRange(results);

                // The DataGridView will use the PSObjectTypeDescriptor type
                // to retrieve the properties.
                grid.DataSource = objects;
            }

            form.ShowDialog();
        }
예제 #29
0
        /// <summary>
        /// IsServerCoreORHeadLessServer is a helper function that checks if the current SKU is a
        /// Server Core machine or if the Server-GUI-Shell feature is removed on the machine.
        /// </summary>
        /// <returns>True if the current SKU is a Server Core machine or if the Server-GUI-Shell
        /// feature is removed on the machine or else returns false.</returns>
        private bool IsServerCoreOrHeadLessServer()
        {
            bool result = false;

            using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"))
            {
                Dbg.Assert(installation != null, "the CurrentVersion subkey should exist");

                string installationType = (string)installation.GetValue("InstallationType", string.Empty);

                if (installationType.Equals("Server Core"))
                {
                    result = true;
                }
                else if (installationType.Equals("Server"))
                {
                    using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
                    {
                        ps.AddScript(TestHeadlessServerScript);
                        Collection <PSObject> psObjectCollection = ps.Invoke(new object[0]);
                        Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item");
                        if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0])))
                        {
                            result = true;
                        }
                    }
                }
            }

            return(result);
        }
예제 #30
0
        public virtual Collection <PSObject> RunPowerShellTest(params string[] scripts)
        {
            Collection <PSObject> output = null;

            for (int i = 0; i < scripts.Length; ++i)
            {
                Console.WriteLine(scripts[i]);
                powershell.AddScript(scripts[i]);
            }
            try
            {
                output = powershell.Invoke();

                if (powershell.Streams.Error.Count > 0)
                {
                    throw new RuntimeException(ErrorIsNotEmptyException);
                }

                return(output);
            }
            catch (Exception psException)
            {
                powershell.LogPowerShellException(psException, this.TestContext);
                throw;
            }
            finally
            {
                powershell.LogPowerShellResults(output, this.TestContext);
                powershell.Streams.Error.Clear();
            }
        }
예제 #31
0
        public PSPathTranslationTests()
        {
            // create temp file
            _tempFilePath = Path.GetTempFileName();

            // initialize 
            var state = InitialSessionState.CreateDefault();
            state.ThreadOptions = PSThreadOptions.UseCurrentThread;
            state.ApartmentState = ApartmentState.STA;
            _ps = System.Management.Automation.PowerShell.Create();
            _ps.Runspace = RunspaceFactory.CreateRunspace(state);
            _ps.Runspace.Open();

            // create a new PSDrive for translation tests
            _ps.AddCommand("New-PSDrive")
               .AddParameter("Name", "mytemp")
               .AddParameter("PSProvider", FileSystemProvider.ProviderName)
               .AddParameter("Root", Path.GetTempPath());
            _ps.Invoke();
            Assert.True(_ps.Streams.Error.Count == 0, "Failed to create mytemp psdrive.");

            _ps.Streams.ClearStreams();
            _ps.Commands.Clear();
        }
예제 #32
0
        /// <summary>
        /// A helper class that builds and executes a pipeline that writes to the
        /// default output path. Any exceptions that are thrown are just passed to
        /// the caller. Since all output goes to the default outter, this method()
        /// won't return anything.
        /// </summary>
        /// <param name="cmd">The script to run</param>
        /// <param name="input">Any input arguments to pass to the script. If null
        /// then nothing is passed in.</param>
        void executeHelper(string cmd, object input)
        {
            // Just ignore empty command lines...
            if (String.IsNullOrEmpty(cmd))
                return;

            // Create the pipeline object and make it available
            // to the ctrl-C handle through the currentPowerShell instance
            // variable

            lock (instanceLock)
            {
                currentPowerShell = PowerShell.Create();
            }

            currentPowerShell.Runspace = myRunSpace;

            // Create a pipeline for this execution - place the result in the currentPowerShell
            // instance variable so it is available to be stopped.
            try
            {
                currentPowerShell.AddScript(cmd);

                // Now add the default outputter to the end of the pipe and indicate
                // that it should handle both output and errors from the previous
                // commands. This will result in the output being written using the PSHost
                // and PSHostUserInterface classes instead of returning objects to the hosting
                // application.

                currentPowerShell.AddCommand("out-default");
                currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                // If there was any input specified, pass it in, otherwise just
                // execute the pipeline...

                if (input != null)
                {
                    currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose of the pipeline line and set it to null, locked because currentPowerShell
                // may be accessed by the ctrl-C handler...
                lock (instanceLock)
                {
                    currentPowerShell.Dispose();
                    currentPowerShell = null;
                }
            }
        }