How to Pass Switch Parameters in Invoke-Command for Custom Functions?

0
20
Asked By LuminaryBee83 On

I'm working on a function for auditing that uses parameter sets with switch parameters like `-Update`, `-Verify`, and `-Revoke`. The function works fine locally and in a PSSession, but I'm running into issues when I try to call it remotely using `Invoke-Command`. When I run it without any parameters, it uses the default values correctly. However, when I attempt to specify a parameter with the command `Invoke-Command -ComputerName PC -Scriptblock ${function:Do-Thing} -ArgumentList "-Verify"`, I get an error saying 'A positional parameter cannot be found that accepts argument '-Verify'.'

What is the correct syntax for passing a switch parameter when using Invoke-Command? It seems like I'm doing something wrong. I really need to get this working for scaling purposes.

1 Answer

Answered By TechGuru47 On

When using `Invoke-Command`, you should remember that it only accepts positional arguments. To pass a switch parameter like `-Verify`, you can call the switch directly by passing `$true` instead of `-Verify`. For example: `Invoke-Command -ComputerName PC -ScriptBlock {param($Verify) Do-Thing -Verify:$Verify} -ArgumentList $true` will work fine. Also, don't forget to define the parameters inside your script block using a `param()` section. This way, you can easily control which parameters are passed to your function from the remote session.

So your command would look something like this:
```
Invoke-Command -ComputerName PC -ScriptBlock {param($Verify) Do-Thing -Verify:$Verify} -ArgumentList $true
```

CuriousCat22 -

Got it, but how would that work if I have multiple switch parameters? For instance, if I want `-Update` as well, do I just add more argument lists?

TechGuru47 -

Yes, exactly! You can just add more switch parameters in the same way. For multiple switches, you might do something like this:
```
Invoke-Command -ComputerName PC -ScriptBlock {param($Verify, $Update) Do-Thing -Verify:$Verify -Update:$Update} -ArgumentList $true, $false
```
In this example, you're turning on the `-Verify` switch and leaving `-Update` off.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.