Powershell – Get-Job by State and Name

powershellpowershell-3.0

Powershell v3.

Start-Job -Name "TestJob" -ScriptBlock { Write-Host "foo" }

The job starts fine. I then type

Get-Job

and I see

Id   Name      PSJobTypeName   State      HasMoreData   Location      Command
--   ----      -------------   -----      -----------   --------      -------
18   TestJob   BackgroundJob   Completed  True          localhost     Write-Host "foo"

Everything is going according to plan so far. But now let's say I have many jobs running in this session, and they have various different names. So I want to find only the jobs that are named TestJob:

Get-Job -Name TestJob

This also works exactly as expected, returning only the jobs of that name. But now let's say I want to find jobs that both have the name TestJob and are still running:

PS C:\> Get-Job -Name TestJob -State Running
Get-Job : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Get-Job -Name TestJob -State Running
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Job], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetJobCommand

Is there a way to do this?

Best Answer

Try the following

Get-Job -State Completed | Where-Object {$_.Name.Contains("TestJob")}

Here's a sample run based on your example

PS D:\>  Get-Job -State Completed | Where-Object {$_.Name.Contains("Job")}

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
1               TestJob         Completed  True            localhost             Write-Host "foo"
3               TestJob         Completed  True            localhost             Write-Host "foo"

See Get-Help Where-Object for more info on this.

Related Topic