Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell mandatory bool always true

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.

like image 303
Tim Brigham Avatar asked Jan 18 '13 18:01

Tim Brigham


Video Answer


2 Answers

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
like image 136
Keith Hill Avatar answered Sep 27 '22 19:09

Keith Hill


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
like image 24
Frode F. Avatar answered Sep 27 '22 19:09

Frode F.