@@ -14,6 +14,10 @@ runspace. The default runspace contains all of the core Windows PowerShell comma
1414your application to expose only a subset of the Windows PowerShell commands, you must create a
1515custom runspace.
1616
17+ > [ !NOTE]
18+ > To run the following samples, you need to have the ` Microsoft.PowerShell.SDK ` NuGet
19+ > package installed.
20+
1721## Using the default runspace
1822
1923To start, we'll use the default runspace, and use the methods of the
@@ -82,14 +86,15 @@ You can also add a dictionary of parameter names and values by calling the
8286method.
8387
8488``` csharp
85- IDictionary parameters = new Dictionary <String , String >();
86- parameters .Add (" Path" , @" C:\Windows" );
87- parameters .Add (" Filter" , " *.exe" );
89+ var parameters = new Dictionary <string , string >
90+ {
91+ { " Path" , @" C:\Windows" },
92+ { " Filter" , " *.exe" }
93+ };
8894
8995PowerShell .Create ().AddCommand (" Get-Process" )
90- .AddParameters (parameters )
91- .Invoke ()
92-
96+ .AddParameters (parameters )
97+ .Invoke ()
9398```
9499
95100### AddStatement
@@ -115,7 +120,7 @@ is already a script named `MyScript.ps1` in a folder named `D:\PSScripts`.
115120
116121``` csharp
117122PowerShell ps = PowerShell .Create ();
118- ps .AddScript (" D:\P SScripts\M yScript.ps1" ).Invoke ();
123+ ps .AddScript (@ " D:\PSScripts\MyScript.ps1" ).Invoke ();
119124```
120125
121126There is also a version of the AddScript method that takes a boolean parameter named
@@ -150,12 +155,15 @@ to create a runspace after creating a default InitialSessionState object.
150155
151156``` csharp
152157InitialSessionState iss = InitialSessionState .CreateDefault ();
158+
153159Runspace rs = RunspaceFactory .CreateRunspace (iss );
154160rs .Open ();
161+
155162PowerShell ps = PowerShell .Create ();
156163ps .Runspace = rs ;
157164ps .AddCommand (" Get-Command" );
158165ps .Invoke ();
166+
159167rs .Close ();
160168```
161169
@@ -194,6 +202,7 @@ SessionStateCmdletEntry getCommand = new SessionStateCmdletEntry(
194202 " Get-Command" , typeof (Microsoft .PowerShell .Commands .GetCommandCommand ), " " );
195203SessionStateCmdletEntry importModule = new SessionStateCmdletEntry (
196204 " Import-Module" , typeof (Microsoft .PowerShell .Commands .ImportModuleCommand ), " " );
205+
197206iss .Commands .Add (getCommand );
198207iss .Commands .Add (importModule );
199208```
@@ -211,8 +220,10 @@ Execute a command and show the result.
211220PowerShell ps = PowerShell .Create ();
212221ps .Runspace = rs ;
213222ps .AddCommand (" Get-Command" );
223+
214224Collection < CommandInfo > result = ps .Invoke <CommandInfo >();
215- foreach (var entry in result )
225+
226+ foreach (CommandInfo entry in result )
216227{
217228 Console .WriteLine (entry .Name );
218229}
0 commit comments