有没有办法检查运行PowerShell脚本的操作系统,并制作一个If
语句,其中包含:
[伪代码]
if its this OS
do this
if its this other OS
do this
仅适用于脚本中的某一行?我必须创建一个设置私人消息队列的PowerShell脚本。遗憾的是,我公司的一些客户端不使用Windows Server 2012,因此添加私有消息队列的更简单版本的方式不适用于Windows Server 2008和过时的PowerShell版本。为了解决这个问题,我还必须采用大规模复杂的旧方法,但我希望两种方法都存在。
答案 0 :(得分:4)
开关会更干净,但是因为你询问了如何以特定方式进行操作......
设置变量以检查操作系统版本(从链接的线程Get operating system without using WMI解除):
$OSVersion = (get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
构建您的IF语句:
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"
}
希望有所帮助。我假设你是PowerShell的新手,但是当你感觉舒服时,就开始学习开关。
答案 1 :(得分:0)
对于switches的新用户,这里的Switch语句等效于@Nate的答案以进行比较。还有更多advanced种可供选择的方法,如果它们得到truly complicated,您可以将测试移至命名函数
$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"
}
}