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?
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
-Commandis sent as a single command line to PowerShell....
When the value of
-Commandis a string,Commandmust 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With