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
$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
.