Powershell: How to pass a parameter to a scriptblock

Scriptblock. Very common in the powershell world and used by many cmdlets and functions like Invoke-Command. But how can we pass a parameter to the scriptblock?

Lets say that we are developing a function that will execute a command on remote computers. As a real world example, I want to check the status of a service on remote computers. I need however my function to be agile and accept the name of the service to check.

Since I am going to be using the Invoke-Command cmdlet, I need to pass the name of the service to the scriptblock parameter. Fortunatelly, this is fairly easy and cam be accomplished using the param statement in the scriptblock just like:

Invoke-Command -ComputerName $Computer `
 -ScriptBlock {param($ServiceName) Get-Service -Name $ServiceName } `
 -ArgumentList $ServiceName

Of course, the Get-Service has a ComputerName parameter for this purpose but this is just an example.

Popular posts from this blog

IIS Client Certificate Revocation Check Disable

How to Configure Message Forwarding on a Mailbox Level

Syslog Message Collection for OMS from sources that do not support the agent