i'm trying to create a power shell script that when executed, will list all stopped services matching a specific, user input wildcard. I would like for the wildcard to be saved as a string, then used in get service. Here's what I have so far.

 param([string] $SearchPrefix=$(throw "Please specify the search prefix:"))


 Get-Service  | Where-Object { $_.Status -eq "Stopped" } | Where-Object { $_.Name -eq $SearchPrefix} | foreach {$_.Status} | foreach {$_.Name}

I'm new to learning Powershell so i'm a bit stuck. Any help will be appreciated.

有帮助吗?

解决方案

Replace -eq with -match

  • -eq is for strict equality
  • -matchis for patterns. If you asked for a prefix then add a Circumflex Accent at start: $_.Name -match "^$SearchPrefix"

As a side note, your two last foreach are useless and will block ouput AFAICS.

Get-Service  | Where-Object { $_.Status -eq "Stopped" } | Where-Object { $_.Name -match $SearchPrefix} 

will output something like

Status   Name               DisplayName
------   ----               -----------
Stopped  WinHttpAutoProx... Service de découverte automatique d...
Stopped  WinRM              Gestion à distance de Windows (Gest...

If you want only the two first columns, then add

| Format-Table -auto -property Status, Name

其他提示

Lets say you want a list of stopped services which starts with wc.

PS C:\> $SearchPrefix = "wc*"
PS C:\> Get-Service -Name $SearchPrefix | where{$_.status -eq 'Stopped'}

Status   Name               DisplayName
------   ----               -----------
Stopped  wcncsvc            Windows Connect Now - Config Registrar
Stopped  WcsPlugInService   Windows Color System
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top