2
votes

I need to use Invoke-Command to execute Powershell script blocks on remote machines that are on/off the domain.

I have something like the following below:

Invoke-Command -ComputerName $targetServer -ArgumentList @($selectedProjects, $targetURI, $buildRetention) -ScriptBlock $cleanupSB -Credential $PSCred

The property "-Credential $PSCred" is only needed when I want to execute on a machine off the domain, and so I'd like to dynamically construct the properties that are used with "Invoke-Command"

I tried to create an array such as:

$prop = @("-Credential", "`$PSCred")
Invoke-Command -ComputerName $targetServer -ArgumentList @($selectedProjects, $targetURI, $buildRetention) -ScriptBlock $cleanupSB $($prop)

However, this is not interpreted as I intended. Is there a I can dynamically create these arguments and use them with Invoke-Command? Thanks!

1
I know it's not what you're looking for, but couldn't you just check if the machine is on the domain and then do something like If(Machine is on domain){Invoke-Command}Else{Invoke-Command with creds}?TheMadTechnician
@TheMadTechnician Yes, that is what I have now. But imagine if I have multiple scriptblocks with multiple Invoke-Command expressions. Now that conditional statement starts to get repetitive..Ci3
Not if you make it a function. That's one reason why we have functions, to avoid repetition.TheMadTechnician
You can use splatting to construct conditional parameter lists.Bill_Stewart
That's a better option, you should add that as an answer @Bill_StewartTheMadTechnician

1 Answers

3
votes

You can use splatting to construct conditional parameter lists.

You can also view this topic at the PowerShell prompt:

PS C:\> help about_Splatting