[英]How to exclude files and folders from Get-ChildItem in PowerShell?
我制作了一個 PowerShell 腳本,該腳本使用 md5 檢查運行 robocopy。
它工作正常,但如果我嘗試排除一些目錄或文件,robocopy 會處理排除,而比較 hash 的腳本的 MD5 部分不起作用,會返回一些錯誤,因為源文件/哈希比目標多。 .
我已經嘗試過,也許,我在這里和互聯網上找到的所有方法! 我不能從路徑中排除目錄和/或文件!
以下是我到目前為止所做的。 在這種模式下,md5-copy 工作(不排除):
$Source = "F:\"
$IgnoreDir = @(
$Source + '$RECYCLE.BIN'
$Source + "System Volume Information"
$Source + "VMs"
)
$IgnoreFile = @(
$Source + "SHDrive.vmdk"
$Source + "SHDrive-flat.vmdk"
)
$Ignored = $IgnoreDir + $IgnoreFile
機械復制:
Robocopy.exe /R:1 /W:0 $Source $Dest /E /V /TEE /XD $IgnoreDir /XF $IgnoreFile /LOG:$LogDir\RBCY_MD5_F.txt
MD5:
$SourceHash = Get-ChildItem "$Source\*.*" -Recurse -Force -Exclude $Ignored | Where-Object {!$_.psiscontainer } | Get-FileHash
$SourceHash | Select-Object "Hash", "path" | ft -HideTableHeaders -AutoSize | Out-File -Width "300" $LogDir\SRC_MD5_REF.txt
$SourceHash.Hash | Out-File $LogDir\SRC_MD5.txt
比較:
$Diff = Compare-Object -ReferenceObject $(get-content "$LogDir\SRC_MD5.txt") -DifferenceObject $(get-content "$LogDir\DST_MD5.txt")
F:\ 驅動器的內容:
PS C:\Users\Robbi> Get-ChildItem F:\ -force
Directory: F:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d--hs- 19/03/2019 06:40 $RECYCLE.BIN
d----- 16/05/2020 04:41 DATA
d----- 19/01/2020 06:34 Drivers
d----- 16/05/2020 04:55 Gumball
d----- 16/05/2020 04:58 SW
d--hs- 19/03/2019 06:36 System Volume Information
d----- 13/03/2020 16:08 Tools
d----- 12/12/2019 00:02 VMs
d----- 16/05/2020 04:55 _Pre-Cestino
-a---- 08/02/2020 03:02 21474836480 SHDrive-flat.vmdk
-a---- 08/02/2020 03:02 466 SHDrive.vmdk
如何從 get-children 列表中排除我不想復制的數據? 在這種特定情況下,如果可能,在 Get-ChildItem 必須在整個文件系統中排除顯式內容列表(變量字符串和/或數組)的“所有情況”中。
從 PowerShell 7.1 開始, Get-ChildItem
等 cmdlet 的-Exclude
和-Include
提供程序參數僅對項目名稱(文件/目錄名稱,在文件系統提供程序的情況下)進行操作,而不是完整路徑或目錄子樹。
-ExcludeRecursive
。鑒於您要排除的所有路徑都是目標目錄的直接子路徑,我建議采用兩步方法:
# Get all files and directories in $Source, except those to be excluded.
# Note the use of \* instead of \*.*, so as to also include the
# directories (whose names don't have an extension).
$items = Get-Item $Source\* -Force | Where-Object FullName -NotIn $Ignored
# Recursively process all resulting files and directories and
# calculate their hashes.
# Note the use of -File to limit output to files.
$SourceHash = $items | Get-ChildItem -Recurse -Force -File | Get-FileHash
當然,如果您僅根據文件/目錄名稱定義$Ignored
數組,則可以使用-Exclude
:
# Convert the ignore list to file/directory names only.
$Ignored = $Ignored | Split-Path -Leaf
$SourceHash = Get-ChildItem -File $Source -Recurse -Force -Exclude $Ignored |
Get-FileHash
如果要排除的路徑可以出現在子目錄層次結構的任何級別,則需要做更多的工作:
$ignoredRegex = '(?<=^|\{0})({1})(?=\{0}|$)' -f
[IO.Path]::DirectorySeparatorChar,
($Ignored.ForEach({ [regex]::Escape($_) }) -join '|')
$SourceHash = Get-ChildItem $Source -Recurse -File -Force |
Where-Object FullName -notmatch $ignoredRegex
Get-FileHash
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.