I'm new to PowerShell and am trying to write a script that's dependant on a Hyper-V VM's status. Here's my (basic) if statement:

if((get-vm WMDC2 | out-string) -like '*Running*') { echo "running"}

I feel like there has to be a better way of doing this, but I don't know what it is. I don't think this is a bad way of doing it, but as I'm trying to learn, I'd like to know if there is a better way and if this is a bad way of doing this, why.


As mentioned in the first answer, my only idea was to convert to a string to check the object's properties against something I'm looking for. I'd like if there were a way to do this without converting my output to a string, and that is essentially what I'm looking for.

| improve this question | | | | |

The Format-* cmdlets (your fl is Format-List) are to format output for view in the console. Do not re-parse them for values. Collect the object(s) returned by the Get-VM and access the properties directly.

# Get the VM object
$vm = Get-VM WMDC2
# check if the 'state' property equals 'Running'
if ($vm.state -eq 'Running') {
   Write-Host 'Running'

And if you absolutely do not want to store the VM object for some reason you can also shorthand it like this.

if ((Get-VM WMDC2).state -eq 'Running'){
  Write-Host 'Running'

I don't think this is a bad way of doing it

It is a bad way of doing it, but it's not your fault. It's common that beginning Powershellers jump in and start trying to string-ify all the things. Without delving too far into Powershell objects, the worst part of this approach is that you lose the usefulness built-in (properties, methods, pipeline-ability) to the object returned by Get-VM.

| improve this answer | | | | |
  • I tagged the question as Hyper-V, but I'll add it to the question for clarity. I was unaware that PowerCLI was PowerShell compatible so I didn't think to specify. Also, I thought converting the one line I needed to a string would be better than converting the whole output to a string. Is there a way to optimize in that way? I realize that in this situation, the full list of properties is really short, but I'll eventually be working with things that have a great many more properties. On top of that, I'd like to be able to target specific properties rather than the whole output. – MagnaVis Aug 24 '17 at 15:23
  • @MagnaVis PowerCLI is VMware's Powershell modules/console for working with vSphere and more. – jscott Aug 24 '17 at 15:25
  • Cool, I don't use VMware's offerings, so I had no idea. Thanks! – MagnaVis Aug 24 '17 at 15:27
  • @MagnaVis Both my examples show how to only target the state property. I've change the -like to -eq to remove any ambiguity. – jscott Aug 24 '17 at 15:43
  • This is exactly what I was looking for, thank you! – MagnaVis Aug 24 '17 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.