[英]How to add a class method to a built-in .net class in PowerShell?
I know I can add an instance method to a built-in .net class in PowerShell like this. 我知道我可以像这样将实例方法添加到PowerShell中的内置.net类中。
PS C:\Users\a> [string] | Add-Member -MemberType ScriptMethod -Name test -Value {
>> param(
>> $name
>> )
>> Write-Host $name
>> }
>>
PS C:\Users\a> [string].test("Joe")
Joe
PS C:\Users\a>
I want to know if it's possible to add a class method that I can call it like [string]::test("blah")
. 我想知道是否可以添加一个我可以调用它的类方法,例如[string]::test("blah")
。
Thanks. 谢谢。
The reason I want to do this is because I have written a PowerShell script against .net 4.5 and I used the method [string]::isnullorwhitespace
which is a .net 4 and .net 4.5 method. 我想要这样做的原因是因为我针对.net 4.5编写了PowerShell脚本,并且使用了[string]::isnullorwhitespace
,这是.net 4和.net 4.5方法。 When I run the on a machine that only have .net 3.0 installed, I got errors. 当我在仅安装.net 3.0的计算机上运行时,出现错误。 I don't want to modify all the place that used that method, instead I want to just add that method if it does not exist. 我不想修改使用该方法的所有位置,相反,我只想添加该方法(如果不存在)。 Thanks. 谢谢。
Documentation says 文件说
The Add-Member cmdlet lets you add members (properties and methods) to an instance of a Windows PowerShell object. 使用Add-Member cmdlet,可以将成员(属性和方法)添加到Windows PowerShell对象的实例 。
So I fear it's not possible to add static members that way. 因此,我担心不可能以这种方式添加静态成员。
I don't think you add members to a class, only to instances of a class. 我认为您不是将成员添加到类中,而只是添加到类的实例中。 I would create your own function, Test-StringIsNullOrWhiteSpace
, that uses the built-in IsNullOrWhiteSpace
method when running under .NET 4.0/4.5, but your own implementation under previous versions of .NET: 我将创建自己的函数Test-StringIsNullOrWhiteSpace
,该函数在.NET 4.0 / 4.5下运行时使用内置的IsNullOrWhiteSpace
方法,但在.NET Test-StringIsNullOrWhiteSpace
版本下使用您自己的实现:
filter Test-StringIsNullOrWhiteSpace
{
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]
# The string to test.
$InputObject
)
if( [string].GetMethods() | Where-Object { $_.Name -eq 'IsNullOrWhiteSpace' } )
{
return [string]::IsNullOrWhitespace( $InputObject )
}
return ($InputObject -eq $null -or $InputObject -match '^\s*$')
}
You should be able to use it like so: 您应该能够像这样使用它:
if( Test-StringIsNullOrWhiteSpace $var )
{
Write-Host ('$var is null or only whitespace.')
}
$emptyVars = $vars | Test-StringIsNullOrWhiteSpace
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.