Is there a shorter way to write this powershell code? I want to know if there is a better way to query multiple criteria and return the answer at the bottom.
$PC = Read-Host -Prompt 'Give me PC name'
$OSname = $null
$OS = $null
$OS = (get-adcomputer $PC -Properties operatingSystem).OperatingSystem
If ($OS -like "Windows 10*")
{
$OSname = "Win 10"
}
If ($OS -like "*Server 2022*")
{
$OSname = "Win 2022"
}
If ($OS -like "*Server 2019*")
{
$OSname = "Win 2019"
}
If ($OS -like "*Server 2016*")
{
$OSname = "Win 2016"
}
If ($OS -like "*Server 2012*")
{
$OSname = "Win 2012"
}
If ($OS -like "Windows 7*")
{
$OSname = "Win 7"
}
If ($OS -like "*Server 2008*")
{
$OSname = "Win 2008"
}
If ($OS -eq $null)
{
$OSname = "NO OS"
}
$Osname
CodePudding user response:
Use the Switch statement:
$OS = "Microsoft Server 2022 NL"
$OSName = switch -wildcard ($OS) {
"Windows 10*" { "Win 10" }
"*Server 2022*" { "Win 2022" }
"*Server 2019*" { "Win 2019" }
"*Server 2016*" { "Win 2016" }
"*Server 2012*" { "Win 2012" }
"Windows 7*" { "Win 7" }
"*Server 2008*" { "Win 2008" }
"" { "NO OS" }
Default { "Other" }
}
$OSName
Win 2022
CodePudding user response:
@iRon answer is correct and straight forward. Using a switch
statement in place of multiple if
statements is the best way to go.
I wanted to provide an alternative answer if you are looking to just shorten your code. This takes advantage of using calculated properties and regex
Example:
$PC = Read-Host -Prompt 'Give me PC name'
Get-ADComputer $PC -Properties OperatingSystem | Select @{L="OperatingSystem";E={
if($_.OperatingSystem -match ('([Windows]).*(?:\d{1,})')){return $Matches[0] -replace "Windows", "Win" -replace "Server ", "" -replace "R2 ", ""}
else{return "Other"}
}}