brauown
brauown

Reputation: 17

Use expression/property in a condition

I would like to use a certain expression/property in a if statement, and also want to list a certain output. I simply don't know how to use these further down the script.

$tools = Get-VM | select name, @{N=”ToolsStatus”; E={$_.Extensiondata.Summary.Guest.ToolsStatus}}

[string]$Output = ""
foreach ($vm in $vmtools){
$Output = $Output + "$($vm.name) ----- $($vm.ToolsVersion)`n"


}
if ("ToolsStatus" -eq "toolsOld") {
    Write-Output "CRITICAL, These VM's have out of date tools: `n $Output"
    $Status = 2 enter code here
  1. How do I go about using "ToolStatus"/E={$_.Extensiondata.Summary.Guest.ToolsStatus}} in my if statement?
  2. I know that i can use $vm.name to list the names, but let's say I wanted to have the output from @{N=”ToolsStatus”; E={$_.Extensiondata.Summary.Guest.ToolsStatus}} as well?

Upvotes: 1

Views: 674

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25031

$tools here will contain a collection of VM objects with properties Name and ToolStatus. $tools.ToolStatus returns the value of all ToolStatus properties for every object in $tools. For comparing a single value to a collection of values, you can use either the -contains or the -in operator.

# Checking if any ToolStatus is toolsOld
if ($tools.ToolStatus -contains 'toolsOld') {
    # Any number of VMs has a toolstatus of toolsOld
}

# Return the VM objects(s) that contain(s) toolStatus value of toolsOld
$tools | Where ToolStatus -eq 'toolsOld'

# Check Individual VMs for ToolStatus
foreach ($tool in $tools) {
    if ($tool.ToolStatus -eq 'toolsOld') {
        Write-Output "$($tool.Name) has a tool status of toolsOld"
    }
}

# List ToolStatus Value for VM Name MyServer
$tools | Where Name -eq 'MyServer' | Select -Expand ToolStatus
($tools | Where Name -eq 'MyServer').ToolStatus
$tools.where({$_.Name -eq 'MyServer'}).ToolStatus

# List ToolStatus for all VMs
$tools.ToolStatus

When you use Select-Object, you create a custom object with the properties that you have selected. ToolStatus here is a calculated property. Even though the syntax is different to create the property as opposed to just typing the name of a property, you still retrieve its value the same as any other property on your object. It is easiest to use the member access operator . in the syntax object.property.

Upvotes: 1

Related Questions