Reputation: 2866
Similar questions have been asked on SO, however this is slightly different from those questions.
I am working on a Powershell script that dynamically builds a command and attempts to execute it against TFS. This command requires quotes for some of the arguments, and no matter what I try I can't seem to figure out how to inject them. I have this code snippet:
$files = Get-ChildItem $pathToDefinitions -Filter *.xml
Foreach ($file in $files){
$fileName = $file.fullName
$cmd = "importwitd /collection: $tfsProjectCollectionUrl /p:`"$projectName`" /f:`"$fileName`""
Write-Host $cmd
#iex "`"" + $($cmd) +"`""
& $witadmin "importwitd /collection: $tfsProjectCollectionUrl /p: "\`" $projectName \`"" /f: "\`"$fileName \`"""
}
This is my most recent attempt at escaping the quotes but to no avail. On the accepted answer for this question there is a link to Microsoft but that link appears to be broken. Additionally many of the examples that I have come across use constants rather than a dynamic string which is apparently adding a level of complexity. Is there any way to pass quotes into this command call in powershell?
Upvotes: 0
Views: 447
Reputation: 36277
Another alternative is to use a formatted string, such as:
$cmd = 'importwitd /collection: {0} /p:"{1}" /f:"{2}"' -f $tfsProjectCollectionUrl, $projectName, $fileName
That will get you the desired string.
Upvotes: 3
Reputation: 13537
I like Chris' approach, but another way to escape a boat load of quotes is to use a here-string. In PowerShell format, they take the form of a string which begins and ends with a paired quote and at sign on their own line, like so.
$hereString = @"
some stuff here, anything goes!
"@
This is an awesome solution because you actually don't worry about escaping anything. Just start and end your string with the appropriate symbols and you can put anything within them and it will be executed precisely as you'd like it to be.
$cmd = @"
importwitd /collection: $tfsProjectCollectionUrl /p:"$projectName" /f:"$fileName"
"@
I tried to remove what looked like escape characters from you $cmd
line in your sample. Let me know if this make sense.
Upvotes: 3
Reputation: 4240
Without really knowing anything about the command you're running I'd have thought it would accept this:
$argumentList = @(
"importwitd"
"/collection:$tfsProjectCollectionUrl"
"/p:""$projectName"""
"/f:""$fileName"""
)
& $witadmin $argumentList
Where " can be used to escape " giving you a literal quote in your argument string.
Upvotes: 1