Escape space and resolve variable in Jenkins powershell script not working Escape space and resolve variable in Jenkins powershell script not working powershell powershell

Escape space and resolve variable in Jenkins powershell script not working


The 7z.exe path in your first command has an extraneous trailing \, which causes problems:

cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\"  # <- trailing \\ shouldn't be there

In your 2nd command, you're using single quotes around the command passed to cmd /c ('...'), but the contents of '...' strings in PowerShell are treated as literals, which explains why $fileName was not expanded (interpolated);
only double-quoted ("...") strings and, within limits, unquoted command arguments are expanded in PowerShell; e.g., compare the output from Write-Output '$HOME' to the output from Write-Output "$HOME" / Write-Output $HOME.

As iRon mentions, there's no need to involve cmd at all - PowerShell is perfectly capable of executing command-line programs directly, so this should work:

Invoke-Command -Session $session -ScriptBlock { & "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$using:filename -oC:\\data\\install\\test -aoa >$null }
  • Due to invoking 7z.exe directly, now there's no outer quoting needed anymore, and $fileName should be expanded.

    • Note, however, that $fileName was replaced with $using:fileName, which is necessary in order for the target session to know about the local $fileName variable - see Get-Help about_Remote_Variables.
  • Since the 7z.exe file path is quoted (of necessity, due to containing spaces), you must use &, the call operator, to invoke it.

  • Since the > redirection is now performed by PowerShell itself, the cmd-style >NUL output suppression was replaced with its PowerShell analog, >$null.


I wonder if it necessarily at all to invoke a CMD shell for this.I guess it would be simpler to directly invoke the 7z.exe with its parameters.

Nevertheless, you can build you own script block like this:

[ScriptBlock]::Create('cmd /c "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\' + $filename + ' -oC:\\data\\install\\test -aoa >NUL')