How to Chain Commands at a Special PowerShell 4 Command Prompt?

只愿长相守 提交于 2019-11-29 18:24:02

The double quotes around the strings are removed when the daisy-chained commands are passed to powershell.exe. Add-Type isn't affected by this, since the path doesn't contain spaces, so it doesn't require quotes:

Add-Type -Path C:\x\System.IO.Compression.FileSystem.dll   # <- this works

However, in an assignment operation PowerShell requires strings to be in quotes, otherwise it will interpret the string as a command and try to execute it:

$src = C:\x\xl  # <- this would try to run a (non-existent) command 'C:\x\xl'
                #    and assign its output to the variable instead of assigning
                #    the string "C:\x\xl" to the variable

That is what causes the first two errors you observed. The third error is a subsequent fault, because the two path variables weren't properly initialized.

You should be able to avoid this behavior by escaping the double quotes:

ps4 Add-Type -Path \"C:\x\System.IO.Compression.FileSystem.dll\"; $src = \"C:\x\xl\"; $zip=\"C:\x\xl.zip\"; [io.compression.zipfile]::CreateFromDirectory($src, $zip)

or by replacing them with single quotes (because the latter are not recognized by CMD as quoting characters and are thus passed as-is to PowerShell, which does recognize them as quoting characters):

ps4 Add-Type -Path 'C:\x\System.IO.Compression.FileSystem.dll'; $src = 'C:\x\xl'; $zip='C:\x\xl.zip'; [io.compression.zipfile]::CreateFromDirectory($src, $zip)

However, rather than working around this issue I'd recommend creating and running proper PowerShell scripts, so you can avoid this problem entirely:

#requires -version 4
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true)]
  [string]$Path,
  [Parameter(Mandatory=$true)]
  [string]$Zipfile,
)

Add-Type -Assembly 'System.IO.Compression.FileSystem' | Out-Null
[IO.Compression.ZipFile]::CreateFromDirectory($Path, $Zipfile)

The script would be run like this:

powershell.exe -File zip.ps1 -Path "C:\x\xl" -Zipfile "C:\x\xl.zip"

If you change the execution policy to RemoteSigned or Unrestricted and also change the default handler for .ps1 files you could even run the script like this:

zip.ps1 -Path "C:\x\xl" -Zipfile "C:\x\xl.zip"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!