English 中文(简体)
PowerShell:如何获得其他权利?
原标题:PowerShell: how to get if else construct right?

我试图学习权力,并试图作另外的发言:

if ((Get-Process | Select-Object name) -eq "svchost") {
    Write-Host "seen"
    }
    else {
    Write-Host "not seen"
    }

尽管存在幽灵进程,但这一结果却成了“未见的”。 如何加以修改以取得正确结果?

最佳回答

你们的建设是完美的,但改变以下条件:

(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".

请注意,在以上所述,你将包含过程名称的阵列与“幽灵”相比较。 如阵列包含其他表述,则<代码>-eq为真实情况,在这种情况下,“svchost”

There are other "better" ways to check as well:

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

你可以简单地要求Get-Process在以下几段之后恢复工作:

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




相关问题
Mutually exclusive powershell parameters

SCENARIO I m writing a cmdlet for Powershell 2.0 using Visual Studio 2008 and .NET 3.5 the cmdlet requires 3 arguments. my intended grammar of the cmdlet is something like this: cmdletname [foo|...

Run a program from PowerShell with timeout

I ll write a script that runs a program and wait for it finished. But if the program is not finished within a specified time I want that the program is killed.

How to transpose data in powershell

I have a file that looks like this: a,1 b,2 c,3 a,4 b,5 c,6 (...repeat 1,000s of lines) How can I transpose it into this? a,b,c 1,2,3 4,5,6 Thanks

Powershell v2 remoting and delegation

I have installed Powershell V2 on 2 machines and run Enable-PsRemoting on both of them. Both machines are Win 2003 R2 and are joined to the same active directory domain and I can successfully run ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

热门标签