2

I know I can add an instance method to a built-in .net class in PowerShell like this.

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").

Thanks.


Edit:

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. When I run the on a machine that only have .net 3.0 installed, I got errors. 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.

2 Answers 2

4

Documentation says

The Add-Member cmdlet lets you add members (properties and methods) to an instance of a Windows PowerShell object.

So I fear it's not possible to add static members that way.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct - it's not possible. You could name a function like that with a hack: new-item function:"[string]::isnullorwhitespace" -value { ... } but powershell will never be able to see it.
0

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.