当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何使用 PowerShell 将文件解压缩到文件夹?

作者:精品下载站 日期:2024-12-15 00:29:05 浏览:13 分类:玩电脑

如何使用 PowerShell 将文件解压缩到文件夹?


概述

  • 使用 Expand-Archive 解压缩文件
  • 使用.Net类System.IO. Compression.ZipFile将压缩文件内容提取到文件夹
  • PowerShell 脚本

PowerShell Microsoft.PowerShell.Archive 模块 包含两个 cmdlet,可让您创建 zip 并将存档文件提取或解压缩到文件夹。

这些 cmdlet 是:

Compress-Archive :cmdlet 允许您压缩或压缩指定文件或目录中的文件。

Expand-Archive :cmdlet 允许您将文件从指定的存档文件提取或解压缩到指定的目标目录。

阅读有关使用 PowerShell 从 url 下载 zip 文件的更多信息。

以下步骤描述如何将文件解压缩到文件夹

  • 使用展开存档 cmdlet
Expand-Archive -LiteralPath 'D:\PowerShell\archive[v1].Zip' -DestinationPath D:\PowerShell\UnzippedFolder

上述命令将 archive[v1].zip 文件内容提取到指定的目标路径参数 D:\PowerShell\UnzippedFolder

PowerShell Expand-Archive cmdlet 解压缩文件内容。在上面的命令中,我们使用了 LiteralPath,因为 zip 文件的文件名中包含通配符。

在下面的示例中,我们将使用 Expand-Archive cmdlet,其中 -Path 参数表示 zip 文件位置,并使用 -DestinationPath 参数提取压缩文件内容

Expand-Archive -Path 'D:\PowerShell\archive.Zip' -DestinationPath D:\PowerShell\UnzippedFolder
  • 使用.Net类System.IO. Compression.ZipFile

.Net Framework 4.5 引入了 ZipFile 类来管理存档文件。 ZipFile 类在System.IO.Compression命名空间下可用。 ZipFile类提供静态方法来创建、提取和打开存档文件。

提示:要使用 ZipFile 类,请在脚本中添加 System.IO.Compression.Filesystem 程序集的引用。

下面的示例展示了如何将 zip 文件内容提取到文件夹中:

Add-Type -Assembly "System.IO.Compression.Filesystem"
[System.IO.Compression.ZipFile]::ExtractToDirectory('D:\PowerShell\vscode-docker-master.zip','D:\PowerShell\Zip\UnZipFiles')

我们添加了程序集 System.IO.Compression.Filesystem 引用。 ZipFile 类提供ExtractToDirectory 方法接受源存档文件名路径和目标路径来提取zip文件内容。

PowerShell脚本

# Using Expand-Archive and LiteralPath parameter

Expand-Archive -LiteralPath 'D:\PowerShell\archive[v1].Zip' -DestinationPath D:\PowerShell\UnzippedFolder

#Using Expand-Archive and Path parameter

Expand-Archive -Path 'D:\PowerShell\archive.Zip' -DestinationPath D:\PowerShell\UnzippedFolder

#Using .Net class System.IO.Compression.ZipFile

Add-Type -Assembly "System.IO.Compression.Filesystem"
[System.IO.Compression.ZipFile]::ExtractToDirectory('D:\PowerShell\vscode-docker-master.zip','D:\PowerShell\Zip\UnZipFiles')

结论

上面的文章帮助您了解如何在 PowerShell 脚本中使用多种方式解压缩指定文件夹中的文件。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯