2

Sometimes I invoke powershell scripts from Linux bash/shell scripts like so:

pwsh MyScript.ps1 win-x64 false

And in my MyScript.ps1 file, I set up parameters like so:

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string] $runtime,
    [Parameter()]
    [bool] $singleFile = $true
)

I get an error for the second parameter:

Cannot process argument transformation on parameter 'singleFile'. Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.

I tried passing '$false' as well as 0 but it treats everything as a string. When invoking powershell scripts from outside of a PWSH terminal, how do I get it to coerce my string-boolean value into an actual Powershell boolean type?

1
  • 1
    In fact your code is working with : & '.\Sans titre1.ps1' toto -singleFile 1. I had it a the end of my answer. Commented Jul 24, 2022 at 18:55

1 Answer 1

4

I propose to use [switch]

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string] $runtime,
    [Parameter()]
    [switch] $singleFile
)
Write-Host $runtime

It works for me with :

pwsh ".\MyScript.ps1" "toto" -singlefile

In fact your code is working with :

pwsh ".\MyScript.ps1" toto -singleFile 1
Sign up to request clarification or add additional context in comments.

5 Comments

I love this. It doesn't answer my question, but I'm OK with that since it's apparent that my approach is wrong.
My code is not working on Windows when I execute the following using Git Bash: pwsh MyScript.ps1 foo 0.
@void.pointer When called like this, 0 will be passed as a string, which doesn't convert to [bool]. Only actual numeric literals, which you can only define by PowerShell script, do convert. Try this: pwsh -command "& {.\MyScript.ps1 foo 0}". Of course, you could also just write pwsh -command "& {.\MyScript.ps1 foo $false}".
@zett42, note that here's no reason to use "& { ... }" in order to invoke code passed to PowerShell's CLI via the -Command (-c) parameter - just use "..." directly. Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected. In other words: pwsh -c ".\Myscript.ps1 foo 0" will do, for example.
@zett42 I'm marking this as the answer, so thank you. I think it would be helpful to amend your answer to include your solution (with the more concise syntax described by @mklement0). Thanks to you both!

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.