在我的其中一台服务器中,我们有一个程序,每个月需要更新一次,该程序在终端服务器上运行。
我的基本脚本正在运行(非常简单):
Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} |select ClientUserName, path |ft -autosize
pause
但是我试图使其更“智能”,因此我尝试使用IF语句:
第一次测试:
$open = Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} |`
select ClientUserName, path |ft -autosize
if ($open -eq "true")
{ write-host "showing open files"
}
elseif ($open -eq "false")
{ "All cloesd"
}
pause
第二次测试:
$open = Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"} |`
select ClientUserName, path |ft -autosize
if ($open -eq $true)
{
write-host "showing open files"
}
elseif ($open -eq $false)
{
"All cloesd"
}
我也尝试过以这种方式定义变量:
$open = Get-SmbOpenFile |where {$_.Path -eq "D:\Shares\Programs\test.exe"}
当我使用IF语句时,实际上根本没有任何输出。
非常感谢你的帮助 !
最佳答案
Format-*
cmdlet(例如ft
(Format-Table
))进行显示格式设置;如果必须对数据进行编程处理,请不要使用。Format-*
cmdlet输出格式说明,而不是数据-请参阅this answer。 | ft -autosize
,也不应将与$open
或$true
进行比较,因为如果LHS尚未为 bool(boolean) 值(类型$false
)[1],则这样的显式比较通常将无法正常工作。相反,利用PowerShell的隐式to-Boolean转换-请参阅this answer的底部。 [bool]
分支实际上并不输出if
;它仅向显示屏输出$open
状态消息。 放在一起:
$open = Get-SmbOpenFile |
Where-Object {$_.Path -eq "D:\Shares\Programs\test.exe"} |
Select-Object ClientUserName, Path
if ($open) {
Write-Host "showing open files"
$open # output the result
}
else {
Write-Host "all closed"
}
Write-Host
返回以下之一:Select-Object
实例[2](具有属性[pscustomobject]
和.ClientUserName
的自定义对象).Path
实例(无论其结构如何)都会在 bool(boolean) 上下文中求值为[pscustomobject]
。 $true
cmdlet在[System.Management.Automation.Internal.AutomationNull]::Value
的输出中找不到指定的路径,则为Where-Object
)。Get-SmbOpenFile
。 同样,请参见this answer的底部,以获取完整的隐式到 bool(boolean) 转换规则。
[1]值得注意的是,由于LHS与
$false
相比,非原始对象始终会产生$false
(尽管操作数取反)。例如$true
;同样,任何不完全是(Get-Item /) -eq $true
的非零数字都将指示1
;例如:$false
。此外,使用数组值的LHS时,2 -eq $true
充当过滤器,返回匹配项的子数组(例如,-eq
返回(1, 2, 1) -eq $true
。[2]通常,
1, 1
可以返回多个对象,在这种情况下,Select-Object
将收到$open
类型的[object[]]
实例数组。具有2个或更多元素的数组在 bool(boolean) 上下文中始终为[pscustomobject]
。
关于powershell - Powershell if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61365415/