扩展Windows Powershell snap-in

 1.编写CS程序文件

using System;
using System.ComponentModel;
using System.Management.Automation;
namespace PSBook.Chapter2
{
[RunInstaller(true)]
public class PSBookChater2MySnapin:PSSnapIn
{
public override String Name
{
get {
return "Wiley.PSProfessional.Chapter2";
}
}
public override String Vendor
{
get
{
return "Wiley";
}
}
public override String Description
{
get
{
return "This is a sample Powershell snap-in";
}
}
[Cmdlet(VerbsCommunications.Write,"HI")]
public class SayHi:Cmdlet
{
protected override void ProcessRecord()
{
WriteObject("Hi World");
}
}
[Cmdlet(VerbsCommunications.Write, "Hello")]
public class SayHello : Cmdlet
{
protected override void ProcessRecord()
{
WriteObject("Hello World");
}
}
}

}

管理员权限执行命令
csc /target:library /reference:.\System.Management.Automation.dll PSBook-2-1.cs
csc /target:library /reference:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll PSBook-2-1.cs
(需要进到.Net 安装目录 C:\Windows\Microsoft.NET\Framework64\v4.0.30319)

问题解决方法
csc不是内部命令,环境变量-系统变量-Path添加.Net Framework,C:\Windows\Microsoft.NET\Framework64\v4.0.30319

error CS2001: Source file 'PSBook-2-1.cs' could not be found
把PSBook-2-1.cs拷贝到上面提到的.Net Framework目录中

PSSnapin,cmdlet 找不到
(PSBook-2-1.cs(30,28): error CS0246: The type or namespace name 'cmdlet' could not be found (are you missing a using
directive or an assembly reference?)
需要正确引入System.Management.Automation.dll,可以用绝对路径。还有提示找不到的一定要区分大小写,比如cmdlet应该是Cmdlet

2.注册与取消注册powershell snap-in
步骤1完成之后,直接输入命令 instuallutil PSBook-2-1.dll
取消注册:instuallutil -u PSBook-2-1.dll

3.动态装载到外壳程序中
(步骤2 insutallutil只是将snap-in 写入注册表,要使用其中的cmdlet类和提供程序类,
需要将snap-in装载到powershell中,这里用到Powershell cmdlet add-pssnapin)

命令:add-pssnapin Wiley.PSProfessional.Chapter2
(从外壳中动态删除命令:remove-pssnapin Wiley.PSProfessional.Chapter2)
装载完以后,可以用Get-Pssnapin来查询。
装载成功后输入命令: Get-Command Write-h* 查询我们添加的命令(Write-Hello,Write-HI)


4.保存snap-in配置文件,用配置文件启动powershell
保存命令:export-console MyConsole
文件夹中会生成MyConsole.psc1的文件,里面列出了当前已装载的snap-in

配置文件启动命令:powershell -psconsolefile MyConsole.psc1
$consolefilename 可以查看启动时所使用的配置文件

 

posted @ 2021-01-06 11:25  小鈤犇  阅读(150)  评论(0)    收藏  举报