PowerShell:如何获得正确的 if else 构造?

发布于 2024-12-07 20:56:04 字数 249 浏览 1 评论 0原文

我正在尝试学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

意犹 2024-12-14 20:56:04

您的 if-else 构造是完美的,但请更改 if 条件,如下所示:

(Get-Process | Select-Object -expand name) -eq "svchost"

最初,您将一个对象与“svchost”进行比较,该对象的计算结果为 false。使用 -expandProperty 标志,您将获得对象的该属性,该属性是一个字符串,可以与“svchost”正确比较。

请注意,在上面,您将包含进程名称的字符串数组与“svchost”进行比较。在数组的情况下,如果数组包含其他表达式,则 -eq 为 true,在本例中为“svchost”

还有其他“更好”的方法来检查:

if (Get-Process | ?{ $_.Name -eq "svchost"}) {
  Write-Host "seen"
}
else {
  Write-Host "not seen"
}

Your if-else construct is perfect, but change the if condition like below:

(Get-Process | Select-Object -expand name) -eq "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".

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"
}
注定孤独终老 2024-12-14 20:56:04

您可以简单地要求 Get-Process 来获取您想要的进程:

if (Get-Process -Name svchost -ErrorAction SilentlyContinue) 
{
  Write-Host "seen"
}
else 
{
  Write-Host "not seen"
}

You can simply ask Get-Process to get the process you're after:

if (Get-Process -Name svchost -ErrorAction SilentlyContinue) 
{
  Write-Host "seen"
}
else 
{
  Write-Host "not seen"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文