0

Using the below code I'm trying to find servers that have mismatching power status in our SQL database (manually entered, so prone to mistakes) and vCenter. I doesn't quite work though since at -And $VM.PowerState -like "PoweredOn" it gets the status of all servers (about 500) rather than just one server at a time, causing the statement to always fail.

# $VM = List of Virtual Machines, properties Name and PowerState
# $ServerList = List of Servers, properties Name and Status.

foreach ($serverEntry in $ServerList) {
    if ($VM.Name -contains $serverEntry.Name -And $VM.PowerState -like "PoweredOn" -And $serverEntry.Status -like "In Use") {
        Stuff will happen
    } else {
        Some other stuff
    }
 }

I tried a nested loop but can't get that to work, and since the servers aren't listed in the same order I can't use a simple counter ($i).

How do I solve this?

2 Answers 2

1

Put the elements of the list $VM in a hashtable:

$vmlist = @{}
$VM | ForEach-Object { $vmlist[$_.Name] = $_ }

That gives you a data structure where you can access your VM objects by the name of the VM. Use that in the $ServerList loop:

foreach ($serverEntry in $ServerList) {
    if ($vmlist[$serverEntry.Name].PowerState -eq 'PoweredOn' -and $serverEntry.Status -eq 'In Use') {
        # do some
    } else {
        # do other
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Almost but not quite. In Use is getting matched/true with both PoweredOn and PoweredOff.The only time it´s not matched and goes to the else part is when the the Status is something other then In Use (for example 'removed' or 'waiting for removal'
I doubt that. Please provide evidence.
Show your modified code. Show sample input data. Show the generated output.
imgur.com/a/lbdq9 Here is sample output, the PS is the output from your code and the Excel is a refrence list i created earlier pastebin.com/CpUpvPU0 Here is my updated code
The excel list can also be considerd the input data since its a export-csv result of my $Table and $VMList variables
|
0
foreach ($serverEntry in $ServerList)
{
    $currentVM = $VM | ? {$_.Name -eq $serverEntry.Name}
    if ($currentVM.PowerState -like "PoweredOn" -And $serverEntry.Status -like "In Use") {Stuff will happen} else {Some other stuff}

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.