我正在尝试学习powershell,并尝试构建一个if else语句:
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" }尽管有svchost流程,但最终会变成未见。如何修改它以获得正确的结果?
This ends up into "not seen", although there is svchost processes. How to modify this to get correct results?
推荐答案你的if-else结构是完美的,但改变if条件如下:
Your if-else construct is perfect, but change the if condition like below:
(Get-Process | Select-Object -expand name) -eq "svchost"最初你将一个对象与svchost进行比较,后者将评估为false。使用 -expandProperty 标志,您将获得该对象的属性,该属性是一个字符串,可以正确地与svchost进行比较。
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".
请注意,在上面您要将包含进程名称的字符串数组与svchost进行比较。如果数组 -eq 如果数组包含另一个表达式,则为true,在这种情况下为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:
if (Get-Process | ?{ $_.Name -eq "svchost"}) { Write-Host "seen" } else { Write-Host "not seen" }更多推荐
PowerShell:如果构建正确的话怎么办?
发布评论