powershellhyper-vfailovercluster

What is wrong with my array?


I cannot figure out what i need to fix to get the script to run.

The code:

$clusterNodeNames = (Get-ClusterNode -Cluster Clu05).Name
$AllVMsInCluster = Get-VM -ComputerName $clusterNodeNames

$AllVMs = $AllVMsInCluster | Select -ExpandProperty Name

$AllVMsInCluster[1] | Set-VM -SnapshotFileLocation C:\ClusterStorage\Volume1\$AllVMs[1]

What is happening is i am creating two arrays

$AllVMsInCluster

$AllVMs 

Output of:

PS C:\Windows\system32> $AllVMsInCluster[1]

Name     State CPUUsage(%) MemoryAssigned(M) Uptime   Status             Version
----     ----- ----------- ----------------- ------   ------             -------
acd-pv06 Saved 0           0                 00:00:00 Operating normally 8.0

PS C:\Windows\system32> $AllVMs[1]
acd-pv06

My end game is to put the last line in a loop however at the end I keep getting the whole array.

When i run the last line it will change the SnapshotFileLocation for only acd-pv06 but the output looks like:

C:\ClusterStorage\Volume1\acd-pv02 acd-pv06 acd-SQL01-ag acd-SQL02-ag[1]

How i can i get it to look like:

C:\ClusterStorage\Volume1\acd-pv06\

Solution

  • You don't need two arrays. You already have the .Name property available to you within the objects in the $AllVMsInCluster array. Use it directly in the loop or pipeline. Wrap the object.property in a sub-expression $() to ensure correct variable expansion.

    $AllVmsInCluster |
        ForEach-Object {
            Write-Host "Changing snapshot file location for $($_.Name)."
            Set-VM -VM $_ -SnapshotFileLocation "C:\ClusterStorage\Volume1\$($_.Name)" -WhatIf
        }
    

    Remove -WhatIf when you're ready to perform the changes for real.