Calling a function

The parenthesis are important when you are calling a function in PowerShell. The parenthesis tells PowerShell that you intend to call the method, not acquire a reference to it. This code illustrates this.

$random = New-Object System.Random
$response1 = $random.next
$response2 = $random.next()

The $response1 variable will contain a reference to the function next, and the $response2 variable will contain an integer value, like 1611459187. The type of $response1 is System.Management.Automation.PSMethod and the type of $response2 is int32. If you want to use the reference to the function, use its Invoke method:

Write-Output $response1.Invoke()

To call static function, type the path to the function (namespaces and classes) followed by a double colon (::), and then the name of the function. Parenthesis are required, even if the function doesn’t take any parameters.

[System.Reflection.Assembly]::Load
("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

[System.Windows.Forms.MessageBox]::Show("Hello!")

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll:

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Comments

Important information: If you have not commented before, your comment will be reviewed before it is published. This means that you will not see it immediately, but I have received it. This is not because I want to filter comments, but because I want to prevent spam and advertising.

Leave a Reply

Your email address will not be published. Required fields are marked *