Powershell OS check before running a command using an IF statement
Solution 1
Switches would be cleaner, but since you asked how to do it that specific way...
Set your variable to check against OS version (lifted from linked thread Get operating system without using WMI):
$OSVersion = (get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
Construct your IF statement:
If($OSVersion -eq "Windows Server 2008 R2 Standard")
{
Write-Host "Hooray It's Server 2K8 r2!"
Invoke-Item "C:\Pictures\Hooray.jpg"
}
ElseIf($OSVersion -eq "Windows 7 Professional")
{
Write-Host "Okay, Windows 7 is cool, too!"
Invoke-Item "C:\Pictures\Smiley.jpg"
}
ElseIf($OSVersion -eq "Windows Vista")
{
Write-Host "What have I done with my life?!"
Invoke-Item "C:\Pictures\GunToHead.jpg"
}
ElseIf($OSVersion -eq "Windows Millennium Edition")
{
Write-Host "Go away, operating system. You are drunk."
Invoke-Item "C:\Pictures\LiquorAndHiccups.jpg"
}
Hope that helps. I'm assuming you're new to PowerShell, but when you get comfortable, start learning switches.
Solution 2
For anyone else who's new to switches here's the Switch statement equivalent of @Nate's answer for comparison. There's also more advanced ways you can choose with them (including regex), and if they get truly complicated you can move the tests to well named functions
$OSVersion = (get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
switch ($OSVersion)
{
"Windows Server 2008 R2 Standard"
{
Write-Host "Hooray It's Server 2K8 r2!"
Invoke-Item "C:\Pictures\Hooray.jpg"
}
"Windows 7 Professional"
{
Write-Host "Okay, Windows 7 is cool, too!"
Invoke-Item "C:\Pictures\Smiley.jpg"
}
"Windows Vista"
{
Write-Host "What have I done with my life?!"
Invoke-Item "C:\Pictures\GunToHead.jpg"
}
"Windows Millennium Edition"
{
Write-Host "Go away, operating system. You are drunk."
Invoke-Item "C:\Pictures\LiquorAndHiccups.jpg"
}
}
Dpw808
Updated on July 22, 2022Comments
-
Dpw808 almost 2 years
Is there a way to check the OS that a PowerShell script is running on, and make an
If
Statement which says:[pseudo code]
if its this OS do this if its this other OS do this
Only for a certain line in the script? I have to make a PowerShell script that is setting up private message queues. Sadly, some of the clients of my company don't use Windows Server 2012, so the way more simple version of adding a private message queue wont work on Windows Server 2008 and the outdated PowerShell version. To resolve this problem, I have to also put in the massively complex old way of doing it instead, but I want both methods to be there.