Home > Enterprise >  Powershell Switch-Statement doesn't change value
Powershell Switch-Statement doesn't change value

Time:03-03

This is the Powershell script I wrote:

$varCompList = Get-ADComputer -Filter "Name -like '*Name of Computers*'" -Properties OperatingSystemVersion | select DNSHostName, OperatingSystemVersion
foreach ($System in $varCompList){
    $Restult=switch ($System.OperatingSystemVersion){
        "10.0 (20348)"{"Server 2022"}
        "10.0 (19042)"{"Server 2019 20H2"}
        "10.0 (18363)"{"Server 2019 1909"}
        "10.0 (17763)"{"Server 2019 1809"}
        "10.0 (14393)"{"Server 2016"}
    }
}
echo $varCompList

It displays all the Servers like it should but the OperatingSystemVersion is still displayed as 10.0 (14393).

What am I missing?

CodePudding user response:

You're currently assigning the mapped OS names to a variable, but you never use it for anything and you never update the original input object.

Instead of assigning the result to a variable, assign it to the OperatingSystemVersion property on each object instead:

foreach ($System in $varCompList){
    $System.OperatingSystemVersion = switch ($System.OperatingSystemVersion){
        "10.0 (20348)"{"Server 2022"}
        "10.0 (19042)"{"Server 2019 20H2"}
        "10.0 (18363)"{"Server 2019 1909"}
        "10.0 (17763)"{"Server 2019 1809"}
        "10.0 (14393)"{"Server 2016"}
        default { $_ }
    }
}

The default case will ensure you preserve the original version string for any computer that doesn't have any of the listed versions installed.

  • Related