grisha
grisha

Reputation: 399

Set bool value only when parameter is used Powershell

I have an optional Boolean parameter

[Parameter(Mandatory=$false,Position=15)]
[bool]$MyBoolValue,

that I would like to set to my variable later in the code:

$SomeVariable=$MyBoolValue

but only if the parameter is set in the cmdlet

Do-MyStuff -Name blabla -MyBoolValue $false

if the cmdlet does not include the parameter

Do-MyStuff -Name blabla 

$SomeVariable should remain unchanged (it may be false or true depending on other elements of the function)

I found this:

if($MyBoolValue.IsPresent)
  {
  $SomeVariable=$MyBoolValue
  }

but it is completely ignored (there is no .IsPresent property??)

Any advice?

Upvotes: 0

Views: 3235

Answers (1)

user4003407
user4003407

Reputation: 22132

Use $PSBoundParameters auto variable:

if($PSBoundParameters.ContainsKey("MyBoolValue")){
    $SomeVariable=$MyBoolValue
}

Upvotes: 4

Related Questions