正在检查powershell版本



嗨,我目前有一个非常基本的PowerShell脚本,当计算机安装Windows(任何版本(时都会运行。此脚本位于下方

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
Write-Output "Installing OS Updater Modules Please Wait...."
Write-Output " "
Install-PackageProvider -Name NuGet -Force
Install-Module -Name PSWindowsUpdate -Force
Write-Output " "
Write-Output "Installing Updates...."
Write-Output " "
Install-WindowsUpdate -AcceptAll -Install -IgnoreReboot | Out-File "c:tempWindowsUpdate.log" -force

正如我所说的非常简单的代码,这将安装一些模块,然后用任何更新更新窗口,然而,它只适用于PowerShell 5及以上版本。有一种方法,我可以检查安装了什么版本,然后继续执行脚本,如果是PowerShell 4及以下版本,则停止执行脚本。

我知道可以将Windows Management Framework 5.1安装到install.wim/esd中,这样可以解决这个问题,但对于没有这个功能的人,我希望脚本停止,不会有任何错误。

u可以使用名为"的cmdlet;获得主机";,它在ps版本>2.0

if ((get-host).version.major -le 4)
{
#code
}
else
{
#code
}

或者,如果你需要精确匹配,你可以使用交换机结构

switch ((get-host).version.major)
{        
4 {#installcode4}
5 {#installcode5}
7 {#installcode7}      
}

最新更新