0

When I run my powershell command, one of my arguments is getting corrupted with another arg value. Why? This looks so simple .. but it's not working :(

param ( [switch]$help = $false, [string]$version, [string]$apiKey, [string]$source = $PSScriptRoot, [string]$destination = $PSScriptRoot, [string]$feedSource = "https://nuget.org", [string]$nuget, [switch]$clean = $false ) function CleanUpInputArgs() { Write-Host " **** " + $apiKey } CleanUpInputArgs 

Busted Example: $apiKey should be null or empty. NOT True. => & '.\foo.ps1' -version 123 -nuget aaaa -feedSource bbbb -clean True

Correct Example: $apiKey displays XXX. => & '.\foo.ps1' -version 123 -nuget aaaa -feedSource bbbb -clean True -apiKey XXX

As a side note, when i'm using Windows Powershell ISE, the -apiKey arg option does NOT show in the autocomplete drop down box ... ??? Related?

1
  • In order to bind an explicit value to a switch parameter (such as -clean), you need :: -Clean:$true - otherwise, PowerShell will interpret your string True as a positional argument to whatever parameter it may match Commented Oct 19, 2015 at 0:15

1 Answer 1

3

Switch types typically don't take any parameters so the True is getting passed to the next available parameter which is -ApiKey.

If you need to pass a value to a switch parameter it is done like so:

-Clean:$someBoolVariable 

You specified -Version and the -Help parameter has a default value so the next available parameter is -ApiKey.

Sign up to request clarification or add additional context in comments.

6 Comments

Wow - never knew that (obviously)! ta!
Also @keithhill -- how do I use switch statements in my arguments? or should i not do that? is there a better variable type for true | false, for args?
First, you don't need to initialize a switch parameter. By default it is not present or $false if you test against it (unless someone specifies it e.g. -Clean). If you are forwarding a switch value along from one function to another you can do this -CleanInner:$clean where both $CleanInner and $Clean are parameters of type switch.
AH! i just tested this myself!!! so a switch means i don't need to pass a VALUE for the argument .. the argument DEFINES that it's true!!!! So i was mis-using the switch arg in TWO ways .. which caused this variable-corruption. AH! wow. assplosion by me :/
@Pure.Krome I would say just specifying the switch parameter -Clean with no argument defines it as $true. But yeah, I think you've got it. :-)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.