繁体   English   中英

使用PowerShell脚本从.zip文件中提取特定文件

[英]Extract specific files from a .zip file with PowerShell script

我目前有一个脚本,可以用来从某些文件夹中提取特定的.xml文件。 但是,我需要对这些文件夹中的zip文件执行相同的操作,并且Expand-Archive cmdlet不能完全满足我的需要。 有人可以提供任何帮助吗? 这是我的原始脚本:

param (
    [string]$loannumber,
    [string]$mids
)

$ErrorActionPreference = "Continue"

$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
$config = [xml][IO.File]::ReadAllText("$MyDir\MessageGatherConfig.xml")

#$loannumber = '1479156692'
#$mids = 'M1,M2,DUREQ'

$selectedmids = $mids.Split(",")

foreach ($mid in $selectedmids) {
    $filestocopy = @()
    Write-Host "Checking for $mid messages..."

    $midfile = ($config.MessageGatherConfig.MessageFilePatterns.FilePattern | Where-Object {$_.messageid -eq $mid})
    $pattern = $midfile.pattern

    $copyfiles = $false

    foreach ($path in $midfile.Path) {

        $searchval = $pattern.Replace("LOANNUMBER", $loannumber)

        Write-Host "Searching $path for $searchval"

        $dircmd = "dir /b $path\$searchval"
        $files = ""

        $files = cmd.exe /c $dircmd

        if ($files -ne $null) {
            $copyfiles = $true
            $files = $files.replace('[', '`[')
            $files = $files.replace(']', '`]')

            $files2 = $files.Split([Environment]::NewLine)

            foreach ($filename in $files2) {
                $filestocopy += "$path\$filename"
            }
        }       

    }

    if ($copyfiles) {
        Write-Host "Copying $mid files to local folder"

        if (Test-Path $MyDir\$loannumber\$mid) {
            Remove-Item $MyDir\$loannumber\$mid -Force -Recurse 
        }

        New-Item $MyDir\$loannumber\$mid -type directory
    }
}

我会选择一种方法,将zip解压缩到一个临时目录,然后使用上面的函数复制所需的文件。 这个简单的函数会将内容提取到临时目录中,并返回提取内容的路径。

function extractZipToTemp () {
    Param (
        $ZipFilePath
    )

    # Generate the path to extract the ZIP file content to.
    $extractedContentPath = "$([System.IO.Path]::GetTempPath())$(([guid]::NewGuid()).tostring())"
    # Extract the ZIP file content.
    Expand-Archive -Path $ZipFilePath -DestinationPath $extractedContentPath -Force
    # Return the path to the extracted content.
    return $extractedContentPath
}

如果您希望内容在执行脚本的目录中保持本地状态,只需对上述函数进行如下调整。

function extractZipToTemp () {
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [String]$ZipFilePath,

        [Parameter(Mandatory = $true, Position = 1)]
        [String]$ExtractPath
    )

    # Generate the path to extract the ZIP file content to.
    $extractedContentPath = "$extractPath\$($ZipFilePath | Split-Path -Leaf)"
    # Extract the ZIP file content.
    Expand-Archive -Path $ZipFilePath -DestinationPath $extractedContentPath -Force
    # Return the path to the extracted content.
    return $extractedContentPath
}

使用上述任何一种方法,请记住在复制所需文件后进行清理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM