I have a script that includes the following settings which returns an incorrect result if I use the mandatory parameter screen. It feels like it is failing to do some kind of type verification or casting on my input. How can I resolve it?
param ( [Parameter(Mandatory=$true)] [bool]$autoinstall )
if ( $autoinstall )
{
echo "Autoinstall true"
}
else
{
echo "Autoinstall false"
}
This works perfectly if I call it with .\myscript.ps1 -autoinstall $false but the $autoinstall variable is always true regardless of what I pass if I use the mandatory password prompt and enter '$false'.
EDIT:
Using a switch doesn't work for me. I really need to have this be both scriptable and the mandatory parameter function for user shortcuts for on the fly use.
The issue occurs because the input is interpreted as a string and you're seeing the results of PowerShell's coercion of string to bool e.g.:
59> [bool]'0'
True
60> [bool]'false'
True
61> [bool]'False'
True
62> [bool]'$false'
True
To get the "false" path to execute, just press enter when you're prompted for the parameter i.e.:
63> [bool]''
False
Why not just use switch? Try this:
param ( [switch]$autoinstall )
if ( $autoinstall )
{
echo "Autoinstall true"
}
else
{
echo "Autoinstall false"
}
Output:
[20:40:46] PS-ADMIN C:\Users\Graimer\Desktop> .\Untitled4.ps1
Autoinstall false
[20:42:36] PS-ADMIN C:\Users\Graimer\Desktop> .\Untitled4.ps1 -autoinstall
Autoinstall true
[20:42:38] PS-ADMIN C:\Users\Graimer\Desktop> .\Untitled4.ps1 -autoinstall:$true
Autoinstall true
[20:42:41] PS-ADMIN C:\Users\Graimer\Desktop> .\Untitled4.ps1 -autoinstall:$false
Autoinstall false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With