joon
joon

Reputation: 4017

Generate multiple scriptblock through the pipeline in PowerShell

Basically I want to make the following concise using the pipeline:

{Remove-Job 27}, {Remove-Job 29} | % { Invoke-Command -Session $s -ScriptBlock $_; };

To something like (conceptually)

@(27, 29) | % {Remove-Job $_;} | % { Invoke-Command -Session $s -ScriptBlock $_; };

What would be a good way to do this?

Upvotes: 0

Views: 481

Answers (4)

Shay Levy
Shay Levy

Reputation: 126752

The Id parameter of the Remove-Job cmdlet accepts an array of ID's so you could speicfy them like so:

Invoke-Command -Session $s -ScriptBlock { Remove-Job -Id 27,29 }

Upvotes: 0

user189198
user189198

Reputation:

Your second example isn't quite right, because you have to emit a ScriptBlock in order to call Invoke-Command on it. Therefore, rather than actually calling Remove-Job on the local machine, you'd want to pass it as a ScriptBlock to the remote computer. Here is the most concise way I can think of at the moment, to achieve what you're after:

27, 29 | % { Invoke-Command -Session $s -ScriptBlock { Remove-Job -Id $args[0]; } -ArgumentList $_; };

Even though you didn't explicitly come out and display the code, it's obvious that you are pre-creating the PowerShell Session (aka. PSSession) object, prior to calling Invoke-Command. You can also simplify things by not pre-creating the PSSession, and simply using Invoke-Command with the -ComputerName parameter. Here is an example:

$ComputerList = @('server01.contoso.com', 'server02.contoso.com', 'server03.contoso.com');
Invoke-Command -ComputerName $ComputerList -ScriptBlock { Remove-Job -Id $args[0]; } -ArgumentList 27,29;

Note: I also moved the Job IDs directly into -ArgumentList, rather than piping them in. I generally try to avoid using the PowerShell pipeline, unless it really makes sense (eg. taking advantage of Where-Object, Get-Member, or Select-Object). Everyone has a different approach.

Upvotes: 4

beavel
beavel

Reputation: 1087

Another approach would be to use variable expansion, and the Create() method on the ScriptBlock type.

27, 29 | % { Invoke-Command -Session $s -ScriptBlock $([ScriptBlock]::Create("Remove-Job -Id $_")) };

I'm not sure that is any more concise than Trevor's approach.

Upvotes: 1

mjolinor
mjolinor

Reputation: 68273

Any reason this wouldn't work?

Invoke-Command -Session $s -ScriptBlock { 27,29 |% {Remove-Job -Id $_ } }

Upvotes: 1

Related Questions