Powershell Scriptblock parameters

I would like to use a PowerCli command “Start-VM -vm Server1 …” in one of my scripts.

I have not yet figured out why it doesn’t work.

I have made a .PS1 file and when I pass a parameter it works fine. But when I use a Scriptblock, my parameters are not being passed.

Could anyone give me an example how to do it?

Thank you very much

Hi, welcome to the forum :wave:

Please post your code and any errors that you’re receiving and maybe we can help you resolve this.

When posting code, data, and errors, please use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working).

How to format code on PowerShell.org


write-host "VM: $VM_to_Shutdown"
$test  = Stop-VMGuest -vm "$VM_to_Shutdown" -Confirm:$false
return $test

The above is the Script-file I will use below.

Start-job -Scriptblock {c:\users\adm-user\Stop-VMGuest.ps1 -VM_to_Shutdown $args[0] } -Argumentlist 'PRESAOUHB1004v'

I have tried a lot of other ways / methods but I cannot get it working.
When I use the script-file alone with a parameter the server shuts down. I can see that in the vCenter.

When I use “Start-job …” nothing happens.

Looks OK when you omit the Stop-VMGuest command (I don’t have VMware to test against).

Do you get anything back with Receive-Job? Might also be worth specifying -Verbose on the Stop-VMGuest.

I hadn’t tried the Receive-job.
It seems that I have no connection to the vCenter. When I move my “Connection-code” to the script, things seems to be working.
Something about the variable scope or what it is called.

Normally I connect to the vCenter after logging in and am passing the credentials to the vCenter.
It seems that when I use the “Scriptblock” I am in another scope. ???

I don’t quite understand but thanks for the tip.

Glad it’s sorted.

When you run Start-Job it creates a new PowerShell session and your existing connection is not inherited.

Think of it this way:
You open a PowerShell window (session 1) and connect to vSphere.
You then open a second PowerShell window (session 2) and try to run Stop-VMGuest. It won’t work because session 2 is not aware of the connection you made in session 1.

While it’s not exactly the same, think of Start-Job as opening a second PowerShell window.

Thanks for your help. I made a few adjustments and have got the things working. Have a nice day