How can I extract a ZIP file from a batch script using relative paths?

0
1
Asked By MellowQuill47 On

I want to extract a ZIP file from a Windows batch script without hard-coding absolute paths. My current command launches PowerShell and uses the Shell.Application COM object, but its NameSpace method does not seem to accept the relative paths I am providing. Hard-coded paths such as C:temp and C:ethernetspeed.zip work, but I need the script to be portable and run from different locations. The minimum target is Windows 10 with the standard PowerShell installation. Is there a straightforward way to resolve the batch file's directory and use it for the ZIP and destination paths, or should I use a different built-in extraction command?

3 Answers

Answered By CedarFox88 On

You can avoid the COM object entirely and use PowerShell's built-in Expand-Archive command. Relative paths are resolved from the current working directory, so this works as long as the batch file is run from the directory containing the ZIP: powershell.exe -NoLogo -NoProfile -Command "Expand-Archive -LiteralPath '.ethernetspeed.zip' -DestinationPath '.temp'". If the script might be launched from another directory, have the batch file change to its own location first with pushd "%~dp0", then run the command and popd afterward.

SunnyKite26 -

The destination folder needs to exist unless you rely on PowerShell to create it, and adding -Force is useful if the folder may already contain extracted files.

Answered By IvoryMango3 On

If you want to build absolute paths from the batch file's location, pass %~dp0 into PowerShell. For example: powershell.exe -NoLogo -NoProfile -Command "$base = [IO.Path]::GetFullPath('%~dp0'); Expand-Archive -LiteralPath (Join-Path $base 'ethernetspeed.zip') -DestinationPath (Join-Path $base 'temp') -Force". %~dp0 expands to the drive and directory containing the batch file, so the command does not depend on the current working directory.

Answered By NorthStar19 On

On current Windows versions, tar.exe is another built-in option: mkdir "temp" 2>nul, then tar.exe -xf "ethernetspeed.zip" -C "temp". It is simpler if you want to stay entirely in the batch environment, but the destination directory must already exist.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.