Search code examples
powershellparameter-passingparameter-splatting

how do I turn on a param switch from an env variable?


How do I turn -one on with the environment? "-one" Ends up in the opts string if I don't specify one, or it's ignored.

function test-run {
  Param (
    [switch]$one = $false,
    [switch]$two = $false,
    [switch]$tre = $false,
    [string]$branch = "release",
    [int]$forkid = -1,
    [string]$opts = ""
  )
  "one: $one, two: $two, tre: $tre" | Out-Host
  "branch: $branch, forkid: $forkid, opts: $opts" | Out-Host
}
$env:setupflag = "-one"
test-run $env:setupflag -two -tre -branch "test" -forkid 0 -opts ""

test-param
one: False, two: True, tre: True
branch: test, forkid: 0, opts:


Solution

    • Since you're calling a PowerShell-native command (function), what you're trying to do requires splatting based on hashtables.

    • This isn't exactly straightforward if the splatting source is an environment variable:

    $env:setupflag = '-one'
    
    # Construct a hashtable that, when used with splatting, 
    # in effect passes the -one switch.
    # The literal equivalent of this is:
    #   $htSetupFlag = @{
    #     one = $true
    #   }
    $htSetupFlag = @{
      $env:setupflag.Substring(1) = $true
    }
    
    # Pass the hashtable via sigil @ instead of $ in order to perform splatting
    test-run @htSetupFlag -two -tre -branch "test" -forkid 0 -opts ""