$PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 22621 4391
考虑以下代码片段
# Function to determine if the OS is Windows Server
function Is-WindowsServer {
$osVersion = (Get-WmiObject -Class Win32_OperatingSystem).Caption
return $osVersion -like "*Server*"
}
# Function to check if SMB/Network Sharing is installed
function Is-SMBInstalled {
if (Is-WindowsServer) {
Write-Output "Detected Windows Server. This should print."
$smbFeature = Get-WindowsFeature -Name FS-SMB1 -ErrorAction SilentlyContinue
if ($smbFeature -and $smbFeature.Installed) {
return $true
} else {
return $false
}
} else {
Write-Output "Detected Windows 10/11 client. This should print."
$smbFeature = Get-WindowsOptionalFeature -Online -FeatureName "SMB1Protocol" -ErrorAction SilentlyContinue
if ($smbFeature -and $smbFeature.State -eq "Enabled") {
return $true
} else {
return $false
}
}
Write-Output "This should be unreachable."
}
Is-SMBInstalled # probe
if (Is-SMBInstalled -eq $true) {
Write-Output "If above line is False. This should not print."
}
在禁用 Samba 的 Windows 10/11 上的预期输出:
Detected Windows 10/11 client. This should print.
False
禁用 Samba 的 Windows 10/11 上的脚本输出:
Detected Windows 10/11 client.
False
If above line is False. This should not print.
此外,就其本身而言,
if (Is-SMBInstalled -eq $true) {
Write-Output "If above line is False. This should not print."
}
似乎无法正确调用 Is-SMBInstalled。如果没有Is-SMBInstalled # probe
,输出只是If above line is False. This should not print.
我尝试过将 Is-SMBInstalled 放入 $variable 中进行重构,这在某种意义上是有效的,因为该函数被正确调用。但条件仍然表现异常。
我也尝试了按照https://stackoverflow.com/a/66585435/14097947 if ((Is-SMBInstalled)) {
的分组功能,但这也不起作用。
通过使用
Write-Output
的结果Is-SMBInstalled
始终是一个混合内容数组,因为Write-Output
将其内容推送到成功流(又名 stdOut)与相同Return
。因此,与左侧相比,其始终为真。
Write-Output
用替换Write-Host
,这样就不会在成功流中写入。既然您已经在那里:
Get-WimObject
为Get-CimInstance
:这些Wim
cmdlet 自 Powershell 3 以来已过时,并且已从 powershell 6+ 中删除。这样做将使其向前兼容。
有一个例子