Search code examples
powershellvariablesargumentsquotes

How to pass a variable as an argument to a command with quotes in powershell


My powershell script takes the following parameter:

Param($BackedUpFilePath)

The value that is getting passed into my script is:

"\123.123.123.123\Backups\Website.7z"

I have another variable which is the location I want to extract the file:

$WebsiteDeploymentFolder = "C:\example"

I am trying to extract the archive with the following command:

`7z x $BackedUpFilePath -o$WebsiteDeploymentFolder -aoa

I keep getting the following error:

Error: cannot find archive

The following works but I need $BackedUpFilePath to be dynamic:

`7z x '\123.123.123.123\Backups\Website.7z' -o$WebsiteDeploymentFolder -aoa

I think I need to pass $BackedUpFilePath to 7z with quotes but they seem to get stripped out no matter what I try. I am in quote hell.

Thanks.

EDIT: It turns out the problem was I was passing in "'\123.123.123.123\Backups\Website.7z'". (extra single quotes)


Solution

  • The easiest way to work with external command line applications in PowerShell (in my opinion) is to use aliases. For example, the following works fine for me.

    Set-Alias Szip C:\Utilities\7zip\7za.exe
    
    $Archive = 'C:\Temp\New Folder\archive.7z'
    $Filename = 'C:\Temp\New Folder\file.txt'
    
    SZip a $Archive $Filename
    

    PowerShell takes care of delimiting the parameters correctly.