PowerShell Getting started with PowerShell Calling .Net Library Methods


Static .Net library methods can be called from PowerShell by encapsulating the full class name in third bracket and then calling the method using ::

#calling Path.GetFileName()
C:\> [System.IO.Path]::GetFileName('C:\Windows\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