在 Server 2012 Core 中使用 Powershell 解压缩文件

vcs*_*nes 15 powershell windows-server-core windows-server-2012

我需要用powershell解压缩一个文件。我见过每个人这样做的典型方法是使用脚本自动化 shell。

$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
$destinationFolder = $shellApplication.NameSpace($destination)
$destinationFolder.CopyHere($zipPackage.Items())
Run Code Online (Sandbox Code Playgroud)

这对我不起作用,因为服务器核心没有外壳,所以没有自动化。这会导致 E_FAIL COM 错误。

Powershell 似乎无法自行完成,如果我参加第 3 方,我必须首先想办法将实用程序加载到服务器上。7-Zip 是我的首选,但我似乎无法编写下载和安装它的脚本。Sourceforge 不断向我吐槽 HTML 文件。

如何在 Server 2012 Core 中完全编写解压 zip 文件的脚本?

Pet*_*orf 25

Server 2012 带有 Dot.NET 4.5,它有System.IO.Compression.ZipFile,它有一个 ExtractToDirectory 方法。您应该可以从 PowerShell 中使用它。

这是一个例子。

首先,您需要加载 ZipFile 所在的程序集:

[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
Run Code Online (Sandbox Code Playgroud)

然后提取内容

[System.IO.Compression.ZipFile]::ExtractToDirectory($pathToZip, $targetDir)
Run Code Online (Sandbox Code Playgroud)

编辑:如果您已更新到 PowerShell 5(Windows 管理框架 5.0),您将最终拥有本机 cmdlet:

Expand-Archive $pathToZip $targetDir
Run Code Online (Sandbox Code Playgroud)

  • 现在是该死的时候了,有一个本地解决方案。 (6认同)