PowerShell:如何获得正确的 if else 构造?
我正在尝试学习 powershell 并尝试构建一个 if else 语句:
if ((Get-Process | Select-Object name) -eq "svchost") {
Write-Host "seen"
}
else {
Write-Host "not seen"
}
尽管有 svchost 进程,但这最终会变成“未见”。如何修改它才能得到正确的结果?
I'm trying to learn powershell and tried to construct a if else statement:
if ((Get-Process | Select-Object name) -eq "svchost") {
Write-Host "seen"
}
else {
Write-Host "not seen"
}
This ends up into "not seen", although there is svchost processes. How to modify this to get correct results?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 if-else 构造是完美的,但请更改 if 条件,如下所示:
最初,您将一个对象与“svchost”进行比较,该对象的计算结果为 false。使用
-expandProperty
标志,您将获得对象的该属性,该属性是一个字符串,可以与“svchost”正确比较。请注意,在上面,您将包含进程名称的字符串数组与“svchost”进行比较。在数组的情况下,如果数组包含其他表达式,则
-eq
为 true,在本例中为“svchost”还有其他“更好”的方法来检查:
Your if-else construct is perfect, but change the if condition like below:
Initially you were comparing an object to the "svchost" which will evaluate to false. With the
-expandProperty
flag, you are getting that property of the object, which is a string and can be properly compared to "svchost".Note that in the above you are comparing array of strings, which contains the name of process, to "svchost". In case of arrays
-eq
is true if the array contains the other expression, in this case the "svchost"There are other "better" ways to check as well:
您可以简单地要求 Get-Process 来获取您想要的进程:
You can simply ask Get-Process to get the process you're after: