简体   繁体   中英

Powershell 2.0 stripping double quotes

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM