2016-11-13 44 views
-1

這是我目前使用的代碼:我該如何更新此代碼才能第二次運行,但只能在已解壓縮的zip壓縮文件中運行?

# Don't include "\" at the end of $NewSource - it will stop the script from 
# matching first-level subfolders 
$ignore = "somename" 
$files = gci $NewSource -recurse | Where { 
    $_.Extension -match "zip||prd" -and $_.FullName -notlike $ignore 
} 
foreach ($file in $files) { 
    $NewSource = $file.FullName 
    # Join-Path is a standard Powershell cmdLet 
    $destination = Join-Path (Split-Path -Parent $file.FullName) $file.BaseName 
    Write-Host -Fore green $destination 
    $destination = "-o" + $destination 
    # Start-Process needs the path to the exe and then the arguments passed 
    # separately. You can also add -wait to have the process complete before 
    # moving to the next 
    Start-Process -FilePath "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x -y $NewSource $destination" -Wait 
} 

但是,一旦它完成我需要通過新的目錄回去,只解壓縮.zip文件解壓縮後所創建的我.prd文件。在這裏需要一些幫助,因爲我的嘗試不起作用,並且當前解壓並覆蓋所有以前解壓縮的.prd和.zip文件。

回答

1

already told you$_.Extension -match "zip||prd"匹配,因爲在正則表達式兩個|字符之間的空字符串(所有字符串包含空字符串)的所有擴展。

此外,-notlike-like運營商比較模式的值沒有wildcards在裏面,所以你的第二個條件將匹配全名中的所有文件時表現酷似-ne-eq運營商不確切地說「somename」。

更改此:

$ignore = "somename" 
$files = gci $NewSource -recurse | Where { 
    $_.Extension -match "zip||prd" -and $_.FullName -notlike $ignore 
}

到這一點:

$ignore = "*somename*" 
$files = gci $NewSource -recurse | Where { 
    $_.Extension -match "zip|prd" -and $_.FullName -notlike $ignore 
}

和代碼應該做你的期望。

作爲替代你可以建立要忽略

$ignore = 'C:\path\to\first.zip', 
      'C:\other\path\to\second.zip', 
      'C:\some\file.prd', 
      ... 

路徑的列表,並使用-notin(PowerShell的V3或更新版本)或-notcontains運營商排除這些文件:

$_.FullName -notin $ignore 
$ignore -notcontains $_.FullName 

作爲一個方面說明,我會使用call operatorsplatting而不是Start-Process來調用7zip.exe:從ZIP檔案中提取的

$destination = Join-Path (Split-Path -Parent $file.FullName) $file.BaseName 
$params  = 'x', '-y', $NewSource, "-o$destination" 
& "${env:ProgramFiles}\7-Zip\7z.exe" @params 

要還提取.prd文件添加另一個步驟,以你的循環。

foreach ($file in $files) { 
    ... 
    & "${env:ProgramFiles}\7-Zip\7z.exe" @params 
    Get-ChildItem $destination | Where-Object { 
     $_.Extension -eq 'prd' 
    } | ForEach-Object { 
     # extract matching file here, procedure is the 
     # same as with the files in the outer loop 
    } 
} 

您可能需要包裝代碼爲建設目標路徑和讀取路徑from the pipeline,如果目標路徑包含.prd文件遞歸調用自己的函數提取文件。

function Invoke-Unzip { 
    [CmdletBinding()] 
    Param(
     [Parameter(
      Mandatory=$true, 
      ValueFromPipeline=$true, 
      ValueFromPipelineByPropertyName=$true 
     )] 
     [ValidateScript({Test-Path -LiteralPath $_})] 
     [string]$FullName 
    ) 

    $newSource = $FullName 
    ... 
    & "${env:ProgramFiles}\7-Zip\7z.exe" @params 
    Get-ChildItem $destination | 
     Where-Object { $_.Extension -eq 'prd' } | 
     Invoke-Unzip 
} 
+0

這個答案,雖然它改善了我所有的代碼沒有回答我發佈的問題。 – Underdog

+0

@Underdog現在確實如此。 –