0

I am creating a wrapper and in my ps1 file I want to invoke:

ConnectTo-PSSession -Path "test" -Confirm

Since I want to wrap this call I've created a ps1 file with those same params:

Param(
  [string]$Path,
  [switch]Confirm
)

Now I would like to call the ConnectTo-PSSession with those parameters but the main problem is that I dont want to even call the flag if its not required:

ConnectTo-PSSession -Path $Path $Confirm //Confirm here is not working

I took a look at Invoke-Expression but it seems like it will have security issues. Is there a way for me to achieve my result without Invoke-Expression? I can of course start writing If statements but this does not scale well with multiple parameters since I will need a insane amount of those checks.

2 Answers 2

2

Since you have made Confirm as switch parameter (but forgot to prefix it with a dollar sign), change the script like this:

Param(
  [string]$Path,
  [switch]$Confirm
)
ConnectTo-PSSession -Path $Path -Confirm:$Confirm

Now, if you invoke that script with the -Confirm switch, it will be interpreted as $true, whereas when you leave the swith off, ConnectTo-PSSession with Confirm being interpreted as $false

Sign up to request clarification or add additional context in comments.

Comments

0

Two things:

you can provide a default value in the param block:

Param(
  [string]$Path = $PWD ,
  [switch]$Confirm = $True
)

The Switch parameter won't accept the value of $Confirm without especialy beeing called. To calle the switch parameter use ... -Confirm:$Confirm without a space after :

3 Comments

Why would you give a switch parameter a default value of $True, where it already has a default value of $False when not present in the call?
@Theo Depends on how you implement it. I have seen a lot of switch parameters, that do the opposite of what their name would suggest. Others are inversed like -NoConfirmation or something like that. In one of my scripts I calculate the value of a switch based uppon if another parameter is filled: [switch]$useGUI = $([string]::IsNullOrEmpty($CsvPath)) > Switch is $true if no CsvPath is provided. in that case I show a GUI. Otherwise the script is pure commandline. But I can force it to show GUI and provide the path, too!
But then I suggest you define it as [bool] and not use [switch] contrary to what it is designed for..

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.