简体   繁体   中英

Commands executed in PowerShell with variables surrounded in quotes fail. Why?

I'm having a surprisingly difficult time embedding variables with quotes to an external command with PoSH. For example, this command

 dfsradmin membership list /rgname:`"stuff I want`"

gives me the following expected result:

 Failed:
 Replication group with name stuff I want cannot be found.

This command, however

 $group = "stuff I want"
 dfsradmin membership list /rgname:`"$group`"

fails with this error:

 Failed:
 The subobject "/rgname:"stuff is not a valid subobject.

Is this a bug with Powershell or am I missing/misunderstanding something?

Yeah there are known issues in Powershell ( including v2.0) around this: http://connect.microsoft.com/PowerShell/feedback/details/376207/executing-commands-which-require-quotes-and-variables-is-practically-impossible

See if the alternatives discussed in the link above work for you. I cannot try it out as I don't have that executable.

Also echoargs.exe is a useful tool that you can use to see what arguments have been recevied from Powershell.

I found that defining

$quote = '"'

and then using /command$quote"test"$quote works as well

I found a workaround which doesn't call cmd but uses Invoke-Expression instead. The command has to be put in a variable first:

$var = "string with spaces"

$command = "first part " + [char]96 + [char]34 + $var + [char]96 + [char]34 + " second part"

Invoke-Expression $command

Not that pretty but it works. You can replace [char]96 with '`' and [char]34 with '"' if you prefer. Easy to create a function which does it if you use it a lot.

So I was able to get around this by executing it in CMD.exe and doing string manipulations to get what I need.

$str = &cmd /c 'dfsradmin membership list /rgname:"blah blah"'
$str = &cmd /c "dfsradmin membership list /rgname:$blah"       # with vars

Thanks for the help! I hope this has been resolved in Powershell 3.0.

All of the above did not work for me but based on Carlos idea, this is the solution that worked posted here

# get msdeploy exe
$MSDeploy = ${env:ProgramFiles}, ${env:ProgramFiles(x86)} |
        ForEach-Object {Get-ChildItem -Path $_ -Filter 'MSDeploy.exe' -Recurse} |
        Sort-Object -Property @{Expression={[version]$_.VersionInfo.FileVersion}} -Descending |
        Select-Object -First 1 -ExpandProperty FullName

#build deploy command        
$deplyCmd = """""$MSDeploy"" -verb:sync -dest:iisApp=""Default Web Site"" -enableRule:DoNotDeleteRule -source:iisApp=""$ExtraWebFilesFolder"""    

#execute    
&cmd /c $deplyCmd

There's no need to add back ticks in front of quotes. Does this work for you?

 $group = "stuff I want"
 dfsradmin membership list /rgname:"$group"

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