Is it possible to do something like $test = [string]::IsNullOrWhiteSpace
and then check whether a $var
is Null/Empty/WhiteSpace with $test
? I'm not just asking specific to that static method, but in general I've seen folks assign an object to a variable and then take action on the object without typing its full name and I'm wondering if a similar syntax is possible with a string method or any method.
CodePudding user response:
Yes, you can assign .NET methods to variables!
PowerShell returns a PSMethod
object when you access a method without a parameter list ( the (...)
part after the method name).
This is really just a thin wrapper around the underlying .NET method, and it conveniently allows you to invoke it, using Invoke()
:
PS ~> $test = [string]::IsNullOrWhiteSpace
PS ~> $test.Invoke("")
True
PS ~> $test.Invoke(" ")
True
PS ~> $test.Invoke("!")
False
CodePudding user response:
To complement Mathias R. Jessen's helpful answer:
If it's acceptable to specify the type every time and only store the method name (or property name) in a variable, you can use normal invocation syntax:
$n = 'IsNullOrWhiteSpace'
[string]::$n('foo') # -> $false
[string]::$n('') # -> $true
The same technique works with instance members:
# Method
$n = 'ToUpper'
'foo'.$n() # -> 'FOO'
# Property
$n = 'Length'
'foo'.$n # -> 3
The above techniques also work with expressions (enclosed in (...)
):
# Method
'foo'.('To' 'Upper')() # -> 'FOO'
# Property
'foo'.('Le' 'ngth') # -> 3