MAK
MAK

Reputation: 390

How to run powershell code in every virtual machine in the host

I am newbie to powershell, I have a powershell script That should be run on every virtual machine in my host at same time. One of my friend told me that there is a tool which is developed by Phillips but i searched for it but unable to find. can some one help me with solution are there is any tool for that.

Thanks in advance

Upvotes: 0

Views: 1685

Answers (1)

Ben Richards
Ben Richards

Reputation: 3575

You can create your script inside a script block and run it while enumerating the VMs.

# On the host, Get-VM get's you the available VMs.
$runniungVMs = $Get-VM -State 'Running'

foreach ($vm in $runningVMs) {
  Enter-PSSession $vm
  # Write Some code to execute after this line
}

You can also use a script block inside a loop if you can get the actual computer name of the VM:

Invoke-Command –ComputerName <computerName> -Credential  $Cred –ScriptBlock {
  # Write some code to execute
}

Update on additional questions

The Get-VM command gets the list of virtual machines available on the host where the command is running.

If your VM host is not the machine you are running on you can specify the computer name of the VM host. Here is how to get the list of running VMs on Server1:

Get-VM -ComputerName Server1 | Where-Object {$_.State -eq 'Running'}

Posh also comes with great help. If you need to find out more about any command you can use:

get-help Get-VM

or

get-help Get-VM -examples
get-help Get-VM -detailed
get-help Get-VM -full

Upvotes: 1

Related Questions