我正在尝试让我的脚本完成以检查远程机器上的powershell版本,我现在归结为最后一部分,我从powershell获取了该文件的版本号,但我正在寻找一种方法来转向6.2.1200.XXX到版本3,到目前为止我的脚本是
Foreach ($Computer in $Computers)
{
Try
{
Write-Host "Checking Computer $Computer"
$path = "\\$Computer\C$\windows\System32\WindowsPowerShell\v1.0\powershell.exe"
if (test-path $path)
{
Write-host "Powershell is installed::"
[bool](ls $path).VersionInfo
Write-host " "
Write-host "Powershell Remoting Enabled::"
[bool](Test-WSMan -ComputerName $Computer -ErrorAction SilentlyContinue)
}
else
{
Write-Host "Powershell isn't installed" -ForegroundColor 'Red'
}
Write-Host "Finished Checking Computer $Computer"
}
答案 0 :(得分:4)
包含修订版的文件版本可能会随着更新安装而更改,但前3个数字应该有用。您可以转换为[version]
,或者您可以使用简单的拆分或替换来摆脱构建。
然后,您可以创建一个哈希表,其中版本号为键,PS版本为值。
$fileVer = [version](Get-Item $path).VersionInfo
$myVer = "{0}.{1}.{2}" -f $fileVer.Major,$fileVer.Minor,$fileVer.Build
$verTable = @{
'6.3.1200' = 3
'6.3.9600' = 4
}
$psVer = $verTable[$myVer]
否则,如果您确定PowerShell远程处理实际上已启用,那么另一种方法就是问它:
$prEnabled = [bool](Test-WSMan -ComputerName $Computer -ErrorAction SilentlyContinue)
if ($prEnabled) {
$psVer = Invoke-Command -ComputerName $computer -ScriptBlock { $PSVersionTable.PSVersion.Major }
}
$myVer
的替代方法:字符串替换:
$fileVer = [version](Get-Item $path).VersionInfo
$myVer = "$($fileVer.Major).$($fileVer.Minor).$($fileVer.Build)"
替换(正则表达式):
$fileVer = (Get-Item $path).VersionInfo
$myVer = $fileVer -replace '\.\d+$',''
# replaces the last dot and any digits with nothing
分割范围:
$fileVer = (Get-Item $path).VersionInfo
$myVer = ($fileVer -split '\.')[0..2]
# splits on a literal dot, then uses a range to get the first 3 elements of the array
使用switch -wildcard
(感谢Ansgar Wiechers):
$fileVer = (Get-Item $path).VersionInfo.ProductVersion
$myVer = switch -Wildcard ($fileVer) {
'6.3.1200.*' { 3 }
'6.3.9600.*' { 4 }
}
答案 1 :(得分:0)
我结束的代码是
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
$ComputerName
)
if (Test-Path $ComputerName)
{
$Computers = Get-Content $ComputerName
}
Else
{
$Computers = $ComputerName
}
Foreach ($Computer in $Computers)
{
Try
{
Write-Host "Checking Computer $Computer"
$path = "\\$Computer\C$\windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$fileVer = (Get-Item $path).VersionInfo.ProductVersion
$myVer = switch -Wildcard ($fileVer)
{
'6.0.6002.*' { 1 }
'6.1.7600.*' { 2 }
'6.2.9200.*' { 3 }
'6.3.9600.*' { 4 }
}
if (test-path $path)
{
Write-host "Powershell is installed::"
[bool](ls $path).VersionInfo
Write-host " "
Write-host "Powershell Version installed::"
Write-host " $myVer "
Write-host " "
Write-host "Powershell Remoting Enabled::"
[bool](Test-WSMan -ComputerName $Computer -ErrorAction SilentlyContinue)
}
else
{
Write-Host "Powershell isn't installed" -ForegroundColor 'Red'
}
Write-Host "Finished Checking Computer $Computer"
}
catch { }
}