[玩转系统] Runspace11 示例
作者:精品下载站 日期:2024-12-14 02:44:51 浏览:12 分类:玩电脑
Runspace11 示例
此示例演示如何使用 System.Management.Automation.Proxycommand 类创建调用现有 cmdlet 但限制可用参数集的代理命令。然后,代理命令被添加到用于创建受限运行空间的初始会话状态。这意味着用户只能通过代理命令访问 cmdlet 的功能。
要求
此示例需要 Windows PowerShell 2.0。
示范
该示例演示了以下内容。
创建描述现有 cmdlet 元数据的 System.Management.Automation.Commandmetadata 对象。
创建 System.Management.Automation.Runspaces.Initialsessionstate 对象。
-
修改 cmdlet 元数据以删除 cmdlet 的参数。
将 cmdlet 添加到 System.Management.Automation.Runspaces.Initialsessionstate 对象并将 cmdlet 设为私有。
创建一个调用现有 cmdlet 的代理函数,但仅公开一组有限的参数。
在初始会话状态中添加代理功能。
创建使用 System.Management.Automation.Runspaces.Runspace 对象的 System.Management.Automation.Powershell 对象。
使用 System.Management.Automation.Powershell 对象调用私有 cmdlet 和代理函数来演示受限运行空间。
例子
这会为私有 cmdlet 创建一个代理命令来演示受限的运行空间。
namespace Microsoft.Samples.PowerShell.Runspaces
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using PowerShell = System.Management.Automation.PowerShell;
#region GetProcCommand
/// <summary>
/// This class implements the get-proc cmdlet. It has been copied
/// verbatim from the GetProcessSample02.cs sample.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Proc")]
public class GetProcCommand : Cmdlet
{
#region Parameters
/// <summary>
/// The names of the processes to act on.
/// </summary>
private string[] processNames;
/// <summary>
/// Gets or sets the list of process names on which
/// the Get-Proc cmdlet will work.
/// </summary>
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string[] Name
{
get { return this.processNames; }
set { this.processNames = value; }
}
#endregion Parameters
#region Cmdlet Overrides
/// <summary>
/// The ProcessRecord method calls the Process.GetProcesses
/// method to retrieve the processes specified by the Name
/// parameter. Then, the WriteObject method writes the
/// associated processes to the pipeline.
/// </summary>
protected override void ProcessRecord()
{
// If no process names are passed to the cmdlet, get all
// processes.
if (this.processNames == null)
{
WriteObject(Process.GetProcesses(), true);
}
else
{
// If process names are passed to cmdlet, get and write
// the associated processes.
foreach (string name in this.processNames)
{
WriteObject(Process.GetProcessesByName(name), true);
}
} // if (processNames...
} // ProcessRecord
#endregion Cmdlet Overrides
} // GetProcCommand
#endregion GetProcCommand
/// <summary>
/// This class contains the Main entry point for this host application.
/// </summary>
internal class Runspace11
{
/// <summary>
/// This shows how to use 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 initial
/// session state that is used to create a constrained runspace. This
/// means that the user can access the cmdlet only 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 initial session state. The default initial 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 accessible.
cmdletEntry.Visibility = SessionStateEntryVisibility.Private;
// Set the language mode of the initial session state to NoLanguage 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 initial 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();
}
}
}
参见
编写 Windows PowerShell 主机应用程序
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag