Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PowerShell not recognize quoted parameters?

Why does PowerShell treat quoted parameters differently when you invoke the script directly (in a PowerShell console or ISE) or when you invoke it via another PowerShell instance?

Here is the script (TestQuotes.ps1):

param
(
    [string]
    $Config = $null
)

"Config = $Config"

Here are the results:

PS D:\Scripts> .\TestQuotes.ps1 -Config "A B C"
Config = A B C
PS D:\Scripts> PowerShell .\TestQuotes.ps1 -Config "A B C"
Config = A
PS D:\Scripts> .\TestQuotes.ps1 -Config 'A B C'
Config = A B C
PS D:\Scripts> PowerShell .\TestQuotes.ps1 -Config 'A B C'
Config = A

Any ideas?

like image 370
Alek Davis Avatar asked Apr 19 '26 19:04

Alek Davis


1 Answers

According to the PowerShell.exe Command-Line Help, the first argument for the powershell executable is -Command:

PowerShell[.exe]
       [-Command { - | <script-block> [-args <arg-array>]
                     | <string> [<CommandParameters>] } ]
       [-EncodedCommand <Base64EncodedCommand>]
       [-ExecutionPolicy <ExecutionPolicy>]
       [-File <FilePath> [<Args>]]
       [-InputFormat {Text | XML}]
       [-Mta]
       [-NoExit]
       [-NoLogo]
       [-NonInteractive]
       [-NoProfile]
       [-OutputFormat {Text | XML}]
       [-PSConsoleFile <FilePath> | -Version <PowerShell version>]
       [-Sta]
       [-WindowStyle <style>]

PowerShell[.exe] -Help | -? | /?

Any text after -Command is sent as a single command line to PowerShell.

...

When the value of -Command is a string, Command must be the last parameter specified because any characters typed after the command are interpreted as the command arguments.

What child PowerShell instance actually receives is easy to check with echoargs:

PS > echoargs .\TestQuotes.ps1 -Config "A B C"
Arg 0 is <.\TestQuotes.ps1>
Arg 1 is <-Config>
Arg 2 is <A B C>

Which is further parsed by the child instance to:

'.\TestQuotes.ps1' '-Config' 'A' 'B' 'C'

And this is where you get your "wrong" result: Config = A

If you specify -File argument, you'll get the desired result:

PS >  PowerShell -File .\TestQuotes.ps1 -Config 'A B C'
Config = A B C

PS >  PowerShell -Command .\TestQuotes.ps1 -Config 'A B C'
Config = A
like image 151
beatcracker Avatar answered Apr 22 '26 15:04

beatcracker