【问题标题】:PowerShell script to download a zip file and unzip it用于下载 zip 文件并解压缩的 PowerShell 脚本
【发布时间】:2026-02-01 06:45:01
【问题描述】:

我需要一些帮助才能将我的想法整合到一个工作代码中。

这就是我所拥有的:

第 1 步:我正在获取 FTP 用户名和密码作为参数。

param(#define parameters
[Parameter(Position=0,Mandatory=$true)]
    [string]$FTPUser
[Parameter(Position=1,Mandatory=$true)]
    [string]$FTPPassword    
[Parameter(Position=2,Mandatory=$true)]
    [string]$Version    
)

然后我设置这些变量:

$FTPServer = "ftp.servername.com"
$SetType = "bin"

现在,我想建立一个连接。我用谷歌搜索语法并找到了这个。不确定这是否会建立 FTP 连接。我还没有测试,

$webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($FTPUser,$FTPPassword) 

这是我不知道如何编码的部分:

$Version 是我的输入参数之一。我在 FTP 中有一个 zip 文件:

ftp.servername.com\builds\my builds\$Version\Client\Client.zip

我想将该 Client.zip 下载到我的本地计算机(运行脚本的位置)"C:\myApp\$Version" 文件夹中。 因此,每次运行时,FTP 下载都会创建一个名为 $version 的新子文件夹,并在 C:\myApp 中。

完成后,我还需要知道如何解压C:\myApp\$Version\Client\<content of the zip file will be here>下的这个client.zip文件

【问题讨论】:

标签: powershell zip powershell-2.0


【解决方案1】:

您可以使用Expand-Archive cmdlet。它们在 Powershell 版本 5 中可用。不确定以前的版本。请参阅下面的语法:

Expand-Archive $zipFile -DestinationPath $targetDir -Force

-Force 参数将强制覆盖目标目录中的文件(如果存在)。

使用您的参数,它将如下所示:

Expand-Archive "C:\myApp\$Version\Client.zip" -DestinationPath "C:\myApp\$Version" -Force

【讨论】:

    【解决方案2】:
    Add-Type -assembly "System.IO.Compression.Filesystem";
    [String]$Source = #pathA ;
    [String]$Destination = #pathB ;
    [IO.Compression.Zipfile]::ExtractToDirectory($Source, $Destination);
    

    [IO.Compression.Zipfile]::CreateFromDirectory($Source,$Destination);
    

    取决于您是尝试压缩还是解压缩。

    【讨论】: