通过Powershell在多个远程服务器上解压缩文件

时间:2017-02-13 11:08:39

标签: powershell unzip

我目前正在编写一个简单的PowerShell脚本。 基本上,它应该从记事本中获取服务器列表并开始解压缩每个服务器上的.zip文件并将其解压缩到新文件夹。

但是,该脚本未提取zip文件下的所有文件。 它只会从中提取一个文件,我不确定为什么foreach循环不能正常工作。

请详细说明这个问题。感谢。

$servers = Get-Content "C:\tmp\script\new_unzip\servers.txt"
$Date = ((Get-Date).ToString('dd-MM-yyyy_HH-mm-ss'))
foreach ($server in $servers) {
    $shell = new-object -com shell.application
    $target_path = "\\$server\c$\Temp\FFPLUS_Temp"
    $location = $shell.namespace($target_path)
    $ZipFiles = Get-ChildItem -Path $target_path -Filter *.zip
    $ZipFiles | Unblock-File

    foreach ($ZipFile in $ZipFiles) {
        $ZipFile.fullname | out-default
        $NewLocation = "\\$server\c$\Temp\FFPLUS_Temp\$Date"
        New-Item $NewLocation -type Directory -Force -ErrorAction SilentlyContinue
        Move-Item $ZipFile.fullname $NewLocation -Force -ErrorAction SilentlyContinue
        $NewZipFile = Get-ChildItem $NewLocation *.zip
        $NewLocation = $shell.namespace($NewLocation)
        $ZipFolder = $shell.namespace($NewZipFile.fullname)
        $NewLocation.copyhere($ZipFolder.items())
    }
} 

1 个答案:

答案 0 :(得分:0)

$servers = Get-Content "C:\tmp\script\updated\servers.txt"
$Date = ((Get-Date).ToString('dd-MM-yyyy_HH-mm-ss'))

foreach ($server in $servers)
{

$zipFolder = "\\$server\c$\Temp\FFPLUS_Temp"

Add-Type -assembly System.IO.Compression.Filesystem

$zipFiles = Get-ChildItem -Path $zipFolder -Filter *.zip

foreach($zip in $zipFiles)
    {
        $destPath = "\\$server\c$\Temp\FFPLUS_Temp\$Date"      

        New-Item -ItemType Directory $destPath  

        [io.compression.zipfile]::ExtractToDirectory([string]$zip.FullName, "$destPath")

        Move-Item $zip.fullname $destPath -Force -ErrorAction SilentlyContinue        
    }           

}