簡體   English   中英

Powershell 掃描多個文件夾中的丟失文件

[英]Powershell Scan for missing files in multiple folders

我正在使用 Powershell 檢查缺少的 XYZ map 瓷磚,但在嵌套循環中出現了問題。 本質上,map 瓦片存在於“基礎”文件夾中,該基礎文件夾中有多個目錄。 每個目錄中都有 map 磁貼。

例如

C:\My Map\17\       # this is the Base folder, zoom level 17
C:\My Map\17\1234\  # this is a folder containing map tiles
C:\My Map\17\1234\30200.png  # this is a map tile
C:\My Map\17\1234\30201.png  # this is a map tile
C:\My Map\17\1234\30203.png  # this is a map tile, but we're missing 30202.png (have tiles either side)
C:\My Map\17\1234\30204.png  # this is a map tile
C:\My Map\17\1235\  # this is another folder containing map tiles [...]

所以我的想法是針對每個文件夾,掃描每邊都有瓷磚的間隙並嘗試下載它們。

這是我到目前為止所擁有的:

$BasePath = "C:\_test\17\"

$ColumnDirectories = Get-ChildItem $BasePath -Directory

$ColumnDirectories | ForEach-Object {
    $ColumnDirectory = $ColumnDirectories.FullName 
    $MapTiles =  Get-ChildItem -Path $ColumnDirectory -Filter *.png -file
    $MapTiles | ForEach-Object {
        #Write-Host $MapTiles.FullName
        $TileName = $MapTiles.Name -replace '.png',''
        $TileNamePlus1 = [int]$TileName + 1
        $TileNamePlus2 = [int]$TileName + 2
        Write-Host $TileName
    }
}

但我無法將“System.Object[]”類型的“System.Object[]”值轉換為“System.Int32”類型。

最終,我想在 $TileName、TileNamePlus1、$TileNamePlus2 中的每一個上進行 go 測試路徑,並且中間的路徑不存在再次下載。

例如

C:\My Map\17\1234\30201.png -- Exists
C:\My Map\17\1234\30202.png -- Not exists, download from https://somemapsrv.com/17/1234/30202.png
C:\My Map\17\1234\30203.png -- Exists

任何幫助表示贊賞。 我對 Powershell 還很陌生。

這里的整個問題是對ForEach-Object循環如何工作的理解。 在循環內,自動變量$_表示循環的當前迭代。 因此,正如 dugas 和 Santiago Squarzon 的評論所建議的,您需要更改此行:

        $TileName = $MapTiles.Name -replace '.png',''

對此:

        $TileName = $_.Name -replace '\.png',''

或者更簡單地說(BaseName 屬性是不帶擴展名的文件名):

        $TileName = $_.BaseName

由於所有 png 文件的基本名稱為 integer 數字,因此您可以執行以下操作:

$BasePath = 'C:\_test\17'
$missing = Get-ChildItem -Path $BasePath -Directory | ForEach-Object {
    $ColumnDirectory = $_.FullName 
    # get an array of the files in the folder, take the BaseName only
    $MapTiles = (Get-ChildItem -Path $ColumnDirectory -Filter '*.png' -File).BaseName
    # create an array of integer numbers taken from the files BaseName
    $sequence = $MapTiles | ForEach-Object { [int]$_ } | Sort-Object

    $sequence[0]..$sequence[-1] | Where-Object { $MapTiles -notcontains $_ } | ForEach-Object {
        Join-Path -Path $ColumnDirectory -ChildPath ('{0}.png' -f $_)
    }
}

# missing in this example has only one file, but could also be an array of missing sequential numbered files

$missing  # --> C:\_test\17\1234\30202.png

如果您的文件名有前導零,這將不起作用..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM