Reputation: 585
Is it possible to keep the quotes in $args
?
The script is called like this:
.\test1.ps1 a=application o="this object" msg_text="this is a text"
The quotes are mandatory for further processing. Is there a way to keep them inside $args
?
Upvotes: 4
Views: 3716
Reputation: 15685
The only way I can think of without being able to modify the input parameters would still require modifying the command called somewhat.
In order to preserve the quotes, perhaps try capturing the full command-line that the PowerShell script was called with.
So I put this in the test1.ps1 script:
Write-Host (Get-WmiObject -Query "select CommandLine from Win32_Process where CommandLine like '%test1%'").CommandLine
Then this is what is returned if the script is called in this manner:
PS C:\temp> powershell .\test1.ps1 a=application o="this object" msg_text="this is a text"
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" .\test1.ps1 a=application "o=this object" "msg_text=this is a text"
This is only possible if a new instance of PowerShell is called, however, otherwise the parameters won't be available by this method:
PS C:\temp> .\test1.ps1 a=application o="this object" msg_text="this is a text" > zzz3.txt
PS C:\temp>
Of course if this approach is taken, you'll then need to parse the input arguments manually, which you might be able to do with help of the $args
object. It's a long-shot, but does preserve the quotes.
Upvotes: 2
Reputation: 23225
You can escape quotes in PowerShell with a backtick:
.\test1.ps1 a=application o="`"this object`"" msg_text="`"this is a text`""
You can also nest double quotes inside single quotes (or vice versa) but beware that variables are not evaluated in a string delimited with single quotes.
.\test1.ps1 a=application o='"this object"' msg_text='"this is a text"'
Additionally, why use $args
at all? Why not use the massively powerful inbuilt parameter system?
Further reading:
Stack Overflow - How to Handle Command Line Arguments in PowerShell
TechNet Magazine - Windows PowerShell: Defining Parameters
Upvotes: 3