VMware Cloud Community
joeflint
Enthusiast
Enthusiast
Jump to solution

Powershell syntax to check whether a VM exists

I've written a Powershell script that prompts the user for a VM host name and stores the value into variable "$desktop". Following this the VM is powered on via the get-vm command i.e. (get-vm -name "$desktop") ..... However, if the hostname does not exist a powershell error is displayed and the script is aborted.

What I'd like to ask is whether there is a method to query VirtualCenter to check whether the VM hostname exists, prior to issuing get-vm command. Can anyone help with the appropriate syntax?

Thanks

1 Solution

Accepted Solutions
alanrenouf
VMware Employee
VMware Employee
Jump to solution

one way of doing this could be:

$Exists = get-vm -name $desktop -ErrorAction SilentlyContinue
If ($Exists){
	Write "VM is there"
}
Else {
	Write "VM not there"
}

If you found this information useful, please consider awarding points for Correct or Helpful.

Alan Renouf

Blog: http://virtu-al.net Twitter: http://twitter.com/alanrenouf Co-author of the PowerCLI Book: http://powerclibook.com

View solution in original post

2 Replies
alanrenouf
VMware Employee
VMware Employee
Jump to solution

one way of doing this could be:

$Exists = get-vm -name $desktop -ErrorAction SilentlyContinue
If ($Exists){
	Write "VM is there"
}
Else {
	Write "VM not there"
}

If you found this information useful, please consider awarding points for Correct or Helpful.

Alan Renouf

Blog: http://virtu-al.net Twitter: http://twitter.com/alanrenouf Co-author of the PowerCLI Book: http://powerclibook.com
joeflint
Enthusiast
Enthusiast
Jump to solution

Alan, thanks for the prompt feedback and the issue is now resolved.

When I initially attempted the code you advised e.g. "$Exists = get-vm -name $desktop", I still recieved the same error I previosuly experienced. However, I then added "-ErrorAction SilentlyContinue", which allows the script to continue without displying the error.

Thanks

Reply
0 Kudos