2

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!

7
  • 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}? Commented Jul 2, 2014 at 22:03
  • @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.. Commented Jul 2, 2014 at 22:05
  • Not if you make it a function. That's one reason why we have functions, to avoid repetition. Commented Jul 2, 2014 at 22:09
  • 2
    You can use splatting to construct conditional parameter lists. Commented Jul 2, 2014 at 22:11
  • That's a better option, you should add that as an answer @Bill_Stewart Commented Jul 2, 2014 at 22:12

1 Answer 1

3

You can use splatting to construct conditional parameter lists.

You can also view this topic at the PowerShell prompt:

PS C:\> help about_Splatting
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.