编写一个PowerShell类,可在powershell中调用

时间:2016-07-01 06:47:12

标签: c# powershell cmdlets pscmdlet

使用Cmdlet,(和/或PSCmdlet),我可以创建

[Cmdlet(VerbsCommunications.Read, "Blah", SupportsShouldProcess = true)]
public class BlahBlah : PSCmdlet
{
  /// ...
}

然后,在powershell中,我可以调用命令

import-module .\Blah.dll -Verbose
Read-Blah
...

一切都很好。

但是我想创建一个而不是函数,这样我就可以得到一个对象,然后在powershell中使用它

这样的东西
import-module .\Blah.dll -Verbose
$myClass = New-Object Blah
$myClass.Read
$myClass.Save -File x.txt
$myClass.BlahBlah
...

以上是否可以在C#中完成?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

如果要从.NET程序集导入类,则需要使用Add-Type,而不是Import-Module

Add-Type -Path .\Blah.dll

此时,程序集中定义的所有公共类都可以从PowerShell中获得。