VMware Cloud Community
avarcher
Commander
Commander
Jump to solution

Variable is empty yet loop executes

Hi

Can anyone explain the following ...

C:\> $vms = Get-VM

C:\> $vms

C:\> foreach ( $vm in $vms ) { Write-Host "Test $vm" }

Test

C:\> Get-PowerCLIVersion

PowerCLI Version

-


VMware vSphere PowerCLI 4.1 build 264274

Connected to an ESXi 4.1 hosts as root, there are no VMs so why does the loop execute once? I know that to get the above there are easier methods but for other reasons I need to perform a loop, this was just a test to prove what is to me a phenomenon.

Any help appreciated.

Thanks, Andy.

Message was edited by: avarcher

Reply
0 Kudos
1 Solution

Accepted Solutions
Dave_Mishchenko
Immortal
Immortal
Jump to solution

I believe this is due to PowerShell assigning a value of null to $vm. If you want to avoid going through that you can test $vm -eq $Null before starting ForEach, or you could use $vm = @(Get-VM).




Dave

VMware Communities User Moderator

Now available - vSphere Quick Start Guide

Do you have a system or PCI card working with VMDirectPath? Submit your specs to the Unofficial VMDirectPath HCL.

View solution in original post

Reply
0 Kudos
3 Replies
Dave_Mishchenko
Immortal
Immortal
Jump to solution

I believe this is due to PowerShell assigning a value of null to $vm. If you want to avoid going through that you can test $vm -eq $Null before starting ForEach, or you could use $vm = @(Get-VM).




Dave

VMware Communities User Moderator

Now available - vSphere Quick Start Guide

Do you have a system or PCI card working with VMDirectPath? Submit your specs to the Unofficial VMDirectPath HCL.

Reply
0 Kudos
avarcher
Commander
Commander
Jump to solution

Hi Dave

You are spot on ...

C:\> $vms = Get-VM

C:\> $vms -eq $null

True

C:\> $vms = @(Get-VM)

C:\> $vms -eq $null

C:\> foreach ( $vm in $vms ) { Write-Host "Test $vm" }

C:\>

I've now read about @(...) and I'm sorry that I'm none the wiser (Holmes Powershell pocket ref, Hal Rottenberg), your answer gets me on my way but I'd appreciate if you could help me understand why.

Many thanks, Andy.

Reply
0 Kudos
avlieshout
VMware Employee
VMware Employee
Jump to solution

$null is treated as a scalar in powershell, thats why.

You might want to read my blog article about this behaviour.

http://www.van-lieshout.com/2009/12/null-or-nothing/

Arnim

Arnim van Lieshout Blogging: http://www.van-lieshout.com Twitter: http://www.twitter.com/avlieshout If you find this information useful, please award points for "correct" or "helpful".