PowerShell:如果构建正确的话怎么办?

编程入门 行业动态 更新时间:2024-10-27 06:29:48
本文介绍了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:如果构建正确的话怎么办?

本文发布于:2023-07-09 14:56:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1087133.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   PowerShell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!