如何使用PowerShell从名称不包括CSV中列出的字符串的文件夹中删除所有文件 [英] How to delete all the files from folder where name does not include string listed in CSV using PowerShell
问题描述
我要从名称不包含CSV中列出的SKU的文件夹中删除所有文件。
I want to delete all the files from folder where name does not include SKU listed in CSV.
如果SKU与文件库完全匹配,则可以使用此方法,但是我还想保留包含SKU的图像。例如,如果SKU是 1-526-2,则不应删除名称如 1-526-2_1.jpg和 1-526-2_2.jpg的文件。您能以某种方式在SKU周围添加通配符吗?
This works if SKU is exact match with the file base, but I also want keep images which include the SKU. For example if SKU is "1-526-2" files with names like "1-526-2_1.jpg" and "1-526-2_2.jpg" should not be deleted. Can you somehow add wildcards around the SKU?
尝试使用此功能:
$filestokeep = import-csv "C:\Users\exmaple\csv.csv" -Header sku).sku
$files = "C:\users\folder"
$data = Get-ChildItem $files -Recurse |
Where-Object {$filestokeep -notcontains $_.basename} |
Remove-Item -WhatIf
示例CSV:
"SKU"
"1-526-2"
"2-1234"
"1-6435"
文件夹中的示例文件:
1-123.jpg
1-123_1.jpg
1-526-2.jpg
1-526-2_1.jpg
1-6435_2.jpg
2-1234.jpg
5-16547-5.jpg
结果现在是:
"Remove File" on target "C:\Users\folder\1-123.jpg".
"Remove File" on target "C:\Users\folder\1-123_1.jpg".
"Remove File" on target "C:\Users\folder\1-526-2_1.jpg".
"Remove File" on target "C:\Users\folder\1-6435_2.jpg".
"Remove File" on target "C:\Users\folder\5-16547-5.jpg".
结果应为:
"Remove File" on target "C:\Users\folder\1-123.jpg".
"Remove File" on target "C:\Users\folder\1-123_1.jpg".
"Remove File" on target "C:\Users\folder\5-16547-5.jpg".
推荐答案
为此,我将使用正则表达式 -match
运算符:
For this, I'd use the regex -match
operator:
$sourceFolder = "C:\users\folder"
$filestokeep = (Import-Csv "C:\Users\exmaple\csv.csv" -Header sku).sku
# create a regex string of the filestokeep array combining the
# strings with regex OR (`|`). Use [regex]::Escape() to escape any characters
# that have special meaning in regex.
# in this example "^(1-526-2|2-1234|1-6435)"
# the "^" anchors the match at the beginning of the string
$keepThese = '^({0})' -f (($filestokeep | ForEach-Object { [regex]::Escape($_) }) -join '|')
Get-ChildItem -Path $sourceFolder -Filter '*.jpg' -Recurse -File |
Where-Object {$_.BaseName -notmatch $keepThese} |
Remove-Item -WhatIf
输出:
What if: Performing the operation "Remove File" on target "C:\users\folder\1-123.jpg".
What if: Performing the operation "Remove File" on target "C:\users\folder\1-123_1.jpg".
What if: Performing the operation "Remove File" on target "C:\users\folder\5-16547-5.jpg".
P.S。 删除项
cmdlet不返回任何输出,因此无需尝试使用 $ data =
捕获它
P.S. the Remove-Item
cmdlet does not return any output, so no need to try ans capture it by using $data =
这篇关于如何使用PowerShell从名称不包括CSV中列出的字符串的文件夹中删除所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!