简体   繁体   中英

Escaping characters in a variable for PowerShell's Invoke-Expression

I wrote a script to backup a bunch of files by compressing them using 7-Zip. The problem is some of the files contain "&" and "'" (single quote). I tried replacing those out (in the variables below) with "`'" or "``'", but that didn't work either. I guess I am not sure how escaping characters works when used with Invoke-Expression .

Here are the code lines:

$exec = "& 'C:\Program Files\7-Zip\7z.exe' u -mx5 -tzip -r  '$DestFileZip' '$DestFile'"

Invoke-Expression $exec

This thread mentions:

$exec = @'
& "C:\Program Files\7-Zip\7z.exe" u -mx5 -tzip -r "$DestFileZip" "$DestFile"
'@

Invoke-Expression $exec

Withing the @" "@ delimiters, variables and sub-expressions will get expanded, but quotes and other special characters are treated as literals.

Does it work if you ditch Invoke-Expression and execute 7z directly eg:

& 'C:\Program Files\7-Zip\7z.exe' u -mx5 -tzip -r -ppeople123 $DestFileZip $DestFile

Although given you're updating the zip with a file, I'm not sure why you're using -r - unless $DestFile is really a directory? Anyway, with 7z 9.20 this works for me - no errors:

C:\> $destZip = "foo&bar's.zip"
C:\> $destFile = "foo&bar's.txt"
C:\> & 'C:\Program Files\7-Zip\7z.exe' u -mx5 -tzip -ppeople123 $destZip $destFile

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igo Pavlov  2010-11-18    
Scanning

Creating archive foo&bar's.zip

Compressing foo&bar's.txt

Everything is OK

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