PowerShell:如果构建正确的话怎么办? [英] PowerShell: how to get if else construct right?

查看:194
本文介绍了PowerShell:如果构建正确的话怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习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:如果构建正确的话怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆