Powershell函数能完全支持二进制命令的特性,因为它里面的函数是很直观的PS代码,所以它更方便人们阅读。
如果你是一个开发者且有兴趣创建一个二进制命令,这里有个简单的例子。它告诉你如果在Powershell中创建和编译一个有效的命令。
# C# definition for cmdlet
$code = @'
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Management.Automation;
namespace CustomCmdlet
{
[Cmdlet("Get", "Magic", SupportsTransactions = false)]
public class test : PSCmdlet
{
private int _Age;
[Alias(new string[]
{
"HowOld", "YourAge"
}), Parameter(Position = 0,ValueFromPipeline = true)]
public int Age
{
get { return _Age; }
set { _Age = value; }
}
private string _Name;
[Parameter(Position = 1)]
public string Name
{
get { return _Name; }
set { _Name = value; }
}
protected override void BeginProcessing()
{
this.WriteObject("Good morning...");
base.BeginProcessing();
}
protected override void ProcessRecord()
{
this.WriteObject("Your name is " + Name + " and your age is " + Age);
base.ProcessRecord();
}
protected override void EndProcessing()
{
this.WriteObject("That's it for now.");
base.EndProcessing();
}
}
}
'@
# compile C# code to DLL
# use a timestamp to create unique file names
# while testing, when a DLL was imported before, it is in use until PowerShell closes
# so to do repeated tests, use different DLL file names
$datetime = Get-Date -Format yyyyMMddHHmmssffff
$DLLPath = "$env:temp\myCmdlet($datetime).dll"
Add-Type -TypeDefinition $code -OutputAssembly $DLLPath
# import a module
Import-Module -Name $DLLPath -Verbose
现在你可以准备去使用一个新的Get-magic命令。它具备了命令的大部分特性,如参数,别名,甚至管道符:
注意Powershell中多数代码例子只需要编译成DLL文件,一旦DLL文件生成后,你就只需要简单的一行命令了(例如,在你的新开发环境):
Import-Module -Name $DLLPath
要制作更复杂的二进制命令,你将需要使用C#语言在类似 Visual Studio的开发环境下制作。你需要引用Powershell集合,下面命令能方便的取到这个集合的路径:
现在命令将Powershell集合的路径复制到了你的剪切板。
注意这样通过PS编辑的C#代码它的属性将没有更好的安全保护,它容易被反编译。所以不要写入类似密码的机密信息。对于二进制命令安全你最好使用专业的加密软件或编辑器开发。PS代码一般是没有特殊的保护和加密的。
本文链接: https://www.pstips.net/compiling-binary-cmdlets.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

