如何使用 C# 在 Powershell 脚本中编写和导入 Cmdlet
How to write and import Cmdlet inside Powershell script with C#
我想在 powershell 脚本中用 c# 编写 cmdlet,这样我就不需要自己编译它,也可以利用 WriteObject()/WriteError() 函数,但它不起作用,有人知道怎么做吗?
$code = @"
using System;
using System.Management.Automation;
[Cmdlet("Write", "Hello")]
public class WriteHello : PSCmdlet
{
[Parameter(Position =0)]
public String Msg { get; set; }
protected override void ProcessRecord()
{
//WriteObject("Hello: " + Msg);
Console.WriteLine("Hello: " + Msg);
}
}
"@
Add-Type $code
$cmdlet = [WriteHello]::new()
# Error when invoke().
$cmdlet.Invoke()
首先,请分享错误信息:
An error occurred while enumerating through a collection: Cmdlets derived from PSCmdlet cannot be invoked directly.
很明显。
解决方案 1
如果满足您的需要,请使用 Cmdlet
而不是 PSCmdlet
。
解决方案 2
$code = ...
Add-Type $code
$WriteHello = [System.Management.Automation.CmdletInfo]::new("Write-Hello", [WriteHello])
& $WriteHello -msg "abcd"
我还是建议编译源代码。 Add-Type
基本上是预装 "cscript.exe" 的包装。它在 Temp 目录中创建一个 CS 文件并编译它。
编辑
Import-Module
来自源代码。
Add-Type $code -PassThru | % { Import-Module $_.Assembly }
我想在 powershell 脚本中用 c# 编写 cmdlet,这样我就不需要自己编译它,也可以利用 WriteObject()/WriteError() 函数,但它不起作用,有人知道怎么做吗?
$code = @"
using System;
using System.Management.Automation;
[Cmdlet("Write", "Hello")]
public class WriteHello : PSCmdlet
{
[Parameter(Position =0)]
public String Msg { get; set; }
protected override void ProcessRecord()
{
//WriteObject("Hello: " + Msg);
Console.WriteLine("Hello: " + Msg);
}
}
"@
Add-Type $code
$cmdlet = [WriteHello]::new()
# Error when invoke().
$cmdlet.Invoke()
首先,请分享错误信息:
An error occurred while enumerating through a collection: Cmdlets derived from PSCmdlet cannot be invoked directly.
很明显。
解决方案 1
如果满足您的需要,请使用 Cmdlet
而不是 PSCmdlet
。
解决方案 2
$code = ...
Add-Type $code
$WriteHello = [System.Management.Automation.CmdletInfo]::new("Write-Hello", [WriteHello])
& $WriteHello -msg "abcd"
我还是建议编译源代码。 Add-Type
基本上是预装 "cscript.exe" 的包装。它在 Temp 目录中创建一个 CS 文件并编译它。
编辑
Import-Module
来自源代码。
Add-Type $code -PassThru | % { Import-Module $_.Assembly }