Calling .NET library methods

suggest change

Call static .NET methods from PowerShell by wrapping the full class name in square brackets and calling the method with ::.

#calling Path.GetFileName()
C:\> [System.IO.Path]::GetFileName('C:\Windows\explorer.exe')
explorer.exe

Static methods can be called from the class itself, but calling non-static methods requires an instance of the .NET class (an object).

For example, the AddHours method cannot be called from the System.DateTime class itself. It requires an instance of the class :

C:\> [System.DateTime]::AddHours(15)
Method invocation failed because [System.DateTime] does not contain a method named 'AddHours'.
At line:1 char:1
+ [System.DateTime]::AddHours(15)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

In this case, we first create an object, for example :

C:\> $Object = [System.DateTime]::Now

Then, we can use methods of that object, even methods which cannot be called directly from the System.DateTime class, like the AddHours method :

C:\> $Object.AddHours(15)

Monday 12 September 2016 01:51:19

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents