이 샘플에서는 System.Management.Automation.Runspaces.InitialSessionState 개체를 사용하여 Runspace의 기능을 제한하는 방법을 보여 줍니다. 이 샘플의 출력은 Runspace의 언어 모드를 제한하는 방법, cmdlet을 프라이빗으로 표시하는 방법, cmdlet 및 공급자를 추가 및 제거하는 방법, 프록시 명령을 추가하는 방법 등을 보여 줍니다. 이 샘플에서는 프로그래밍 방식으로 Runspace를 제한하는 방법을 집중적으로 설명합니다. runspace를 제한하는 스크립팅 대안에는 $ExecutionContext.SessionState.LanguageMode 및 PSSessionConfiguration 명령이 포함됩니다.
요구 사항
이 샘플에는 Windows PowerShell 2.0이 필요합니다.
입증합니다
이 샘플에서는 다음을 보여 줍니다.
System.Management.Automation.Runspaces.InitialSessionState.LanguageMode 속성을 설정하여 언어를 제한합니다.
System.Management.Automation.Runspaces.SessionStateAliasEntry 개체를 사용하여 초기 세션 상태에 별칭을 추가합니다.
명령을 프라이빗으로 표시합니다.
System.Management.Automation.Runspaces.InitialSessionState.Providers 속성을 사용하여 초기 세션 상태에서 공급자를 제거합니다.
System.Management.Automation.Runspaces.InitialSessionState.Commands 속성을 사용하여 초기 세션 상태에서 명령을 제거합니다.
system.Management.Automation.Runspaces.InitialSessionState 개체에 명령 및 공급자를 추가합니다.
예시
이 샘플에서는 Runspace의 기능을 제한하는 여러 가지 방법을 보여줍니다.
namespace Sample
{
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
/// <summary>
/// This class contains the Main entry point for the application.
/// </summary>
internal class PowerShell01
{
/// <summary>
/// The runspace used to run commands.
/// </summary>
private Runspace runspace;
/// <summary>
/// Return the first index of the entry in <paramref name="entries"/>
/// with the name <paramref name="name"/>. Return -1 if it is not found.
/// </summary>
/// <typeparam name="T">Type of ConstrainedSessionStateEntry</typeparam>
/// <param name="entries">Collection of entries to search for <paramref name="name"/> in.</param>
/// <param name="name">Named of the entry we are looking for</param>
/// <returns>
/// The first index of the entry in <paramref name="entries"/> with the
/// name <paramref name="name"/>, or return -1 if it is not found.
/// </returns>
private static int GetIndexOfEntry<T>(
InitialSessionStateEntryCollection<T> entries,
string name) where T : ConstrainedSessionStateEntry
{
int foundIndex = 0;
foreach (T entry in entries)
{
if (entry.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return foundIndex;
}
foundIndex++;
}
return -1;
}
/// <summary>
/// Run commands to demonstrate the ways to constrain the runspace.
/// </summary>
/// <param name="args">This parameter is unused.</param>
private static void Main(string[] args)
{
new PowerShell01().RunCommands();
}
/// <summary>
/// Run a script to display the results and errors.
/// </summary>
/// <param name="script">Script to be run.</param>
/// <param name="scriptComment">Comment to be printed about
/// the script.</param>
private void RunScript(string script, string scriptComment)
{
Console.WriteLine("Running '{0}'\n{1}.\n\nPowerShell Output:", script, scriptComment);
// Using a PowerShell object, create a pipeline, add the script to the
// pipeline, and specify the runspace where the pipeline is invoked.
PowerShell powerShellCommand = PowerShell.Create();
powerShellCommand.AddScript(script);
powerShellCommand.Runspace = this.runspace;
try
{
Collection<PSObject> results = powerShellCommand.Invoke();
// Display the results.
foreach (PSObject result in results)
{
Console.WriteLine(result);
}
// Display any non-terminating errors.
foreach (ErrorRecord error in powerShellCommand.Streams.Error)
{
Console.WriteLine("PowerShell Error: {0}", error);
}
}
catch (RuntimeException ex)
{
Console.WriteLine("PowerShell Error: {0}", ex.Message);
Console.WriteLine();
}
Console.WriteLine("\n-----------------------------\n");
}
/// <summary>
/// Run some commands to demonstrate the script capabilities.
/// </summary>
private void RunCommands()
{
this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
this.runspace.Open();
this.RunScript("$a=0;$a", "Assigning to a variable will work for a default InitialSessionState");
this.runspace.Close();
this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
this.runspace.InitialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
this.runspace.Open();
this.RunScript("$a=0;$a", "Assigning to a variable will not work in RestrictedLanguage LanguageMode");
this.runspace.Close();
this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
this.runspace.InitialSessionState.LanguageMode = PSLanguageMode.NoLanguage;
this.runspace.Open();
this.RunScript("10/2", "A script will not work in NoLanguage LanguageMode.");
this.runspace.Close();
this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
this.runspace.Open();
string scriptComment = "Get-ChildItem with a default InitialSessionState will work since the standard \n" +
"PowerShell cmdlets are included in the default InitialSessionState";
this.RunScript("Get-ChildItem", scriptComment);
this.runspace.Close();
InitialSessionState defaultSessionState = InitialSessionState.CreateDefault();
defaultSessionState.Commands.Add(new SessionStateAliasEntry("dir2", "Get-ChildItem"));
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
this.RunScript("dir2", "An alias, like dir2, can be added to InitialSessionState");
this.runspace.Close();
defaultSessionState = InitialSessionState.CreateDefault();
int commandIndex = GetIndexOfEntry(defaultSessionState.Commands, "Get-ChildItem");
defaultSessionState.Commands.RemoveItem(commandIndex);
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
scriptComment = "Get-ChildItem was removed from the list of commands so it\nwill no longer be found";
this.RunScript("Get-ChildItem", scriptComment);
this.runspace.Close();
defaultSessionState = InitialSessionState.CreateDefault();
defaultSessionState.Providers.Clear();
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
this.RunScript("Get-ChildItem", "There are no providers so Get-ChildItem will not work");
this.runspace.Close();
// Marks a command as private, and then defines a proxy command
// that uses the private command. One reason to define a proxy for
// a command is to remove a parameter of the original command.
// For a more complete sample of a proxy command, see the Runspace11
// sample.
defaultSessionState = InitialSessionState.CreateDefault();
commandIndex = GetIndexOfEntry(defaultSessionState.Commands, "Get-ChildItem");
defaultSessionState.Commands[commandIndex].Visibility = SessionStateEntryVisibility.Private;
CommandMetadata getChildItemMetadata = new CommandMetadata(
typeof(Microsoft.PowerShell.Commands.GetChildItemCommand));
getChildItemMetadata.Parameters.Remove("Recurse");
string getChildItemBody = ProxyCommand.Create(getChildItemMetadata);
defaultSessionState.Commands.Add(new SessionStateFunctionEntry("Get-ChildItem2", getChildItemBody));
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
this.RunScript("Get-ChildItem", "Get-ChildItem is private so it will not be available");
scriptComment = "Get-ChildItem2 is a proxy to Get-ChildItem. \n" +
"It works even when Get-ChildItem is private.";
this.RunScript("Get-ChildItem2", scriptComment);
scriptComment = "This will fail. Unlike Get-ChildItem, Get-ChildItem2 does not have -Recurse";
this.RunScript("Get-ChildItem2 -Recurse", scriptComment);
InitialSessionState cleanSessionState = InitialSessionState.Create();
this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
this.runspace.Open();
scriptComment = "A script will not work because \n" +
"InitialSessionState.Create() will have the default LanguageMode of NoLanguage";
this.RunScript("10/2", scriptComment);
this.runspace.Close();
cleanSessionState = InitialSessionState.Create();
cleanSessionState.LanguageMode = PSLanguageMode.FullLanguage;
this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
this.runspace.Open();
scriptComment = "Get-ChildItem, standard cmdlets and providers are not present \n" +
"in an InitialSessionState returned from InitialSessionState.Create()";
this.RunScript("Get-ChildItem", scriptComment);
this.runspace.Close();
cleanSessionState = InitialSessionState.Create();
cleanSessionState.Commands.Add(
new SessionStateCmdletEntry(
"Get-ChildItem",
typeof(Microsoft.PowerShell.Commands.GetChildItemCommand),
null));
cleanSessionState.Providers.Add(
new SessionStateProviderEntry(
"FileSystem",
typeof(Microsoft.PowerShell.Commands.FileSystemProvider),
null));
cleanSessionState.LanguageMode = PSLanguageMode.FullLanguage;
this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
this.runspace.Open();
scriptComment = "Get-ChildItem and the FileSystem provider were explicitly added\n" +
"so Get-ChildItem will work";
this.RunScript("Get-ChildItem", scriptComment);
this.runspace.Close();
Console.Write("Done...");
Console.ReadLine();
}
}
}
또한 참조하십시오
PowerShell