使用PowerShell脚本

时间:2017-09-26 17:22:39

标签: powershell zipfile cmdlets

我目前有一个脚本,用于从某些文件夹中提取特定的.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
    }
}

1 个答案:

答案 0 :(得分:0)

我会使用一种方法将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
}

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

相关问题