PS ~ Multi XOR & Set Values

Discussion in 'Scripting' started by Dark Dinosaur, May 3, 2023.

  1. Dark Dinosaur

    Dark Dinosaur X Æ A-12

    Feb 2, 2011
    4,188
    6,014
    150
    Let's begin with XOR

    multi xor in PowerShell with unlimited variables
    so there are basic things like AND - OR ... and also XOR
    xor is different because it returns $true only if one of the statements is true
    you want that use will able to choice between x,y,z but not x,y or y,z
    for basic xor use :: $a -xor $b

    for more than 2 variables, we can convert Varialble into [bool]
    found a great solution ... here
    $var_1 = $item_1 -as [bool]
    $var_2 = $item_2 -as [bool]
    $var_3 = $item_3 -as [bool]

    and the same for each item...

    if this statement is true :: ($var_1 + $var_2 + $var_3 == 1)
    it means the user chooses Only 1 option

    multi option to Set variable

    let's say you use foreach statement.
    $selected is the variable you want to be set in every loop.

    Hard labor way .....
    Code:
    Switch ($Selected)
      {
        "Item" { $Item = $true }
      }
    
    if we like to work easily...
    Code:
    New-Variable -Name $Selected -Value 1 -Force -Scope 1 -PassThru -ErrorAction SilentlyContinue | Out-Null
    Set-Variable -Name $Selected -Value 1 -Force -Scope 1 -PassThru -ErrorAction SilentlyContinue | Out-Null
    
    Sometimes it fails too.
    is such a case ... as here
    there is this statement too.
    Code:
    $PSCmdlet.SessionState.PSVariable.Set($variable,$value)
    
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...