【问题标题】:How to remove images from folder which are not listed in CSV with PowerShell如何使用 PowerShell 从 CSV 中未列出的文件夹中删除图像
【发布时间】:2020-10-06 05:31:53
【问题描述】:

我正在尝试删除 CSV 文件中未列出的所有图像。数据以下面描述的格式进入 CSV。

问题是脚本将删除图像文件夹中的每个文件。我只想从 CSV 文件中删除不包含 SKU 的图像(例如“7-5468-XXX7”)。在这里做什么?

尝试使用这个:

$filestokeep = Import-Csv "C:\Users\example\filestokeep.csv"
    $files = Get-ChildItem  "C:\Users\example\images\"

    $files |
        Where-Object Name -notin $filestokeep.sku |
        Remove-Item -WhatIf

filestokeep.csv 看起来像:

"sku"
"1-123-X"
"2-123-XXXXX"
"3-562-XXXX"
"4-215-XXXXXX"
"5-56482-XX-X"
"6-45688"
"7-5468-XXX"
"856-54648-X"

C:\Users\example\images\ 包含以下文件:

1-123-X.jpg
2-123-XXXXX.jpg
1-123-X_1.jpg
1-123-X_2.jpg
7-5468-XXX7.jpg
7-5468-XXX7_1.jpg
7-5468-XXX7_2.jpg
6-45688.jpg

Images 文件夹运行后应该是这样的:

1-123-X.jpg
2-123-XXXXX.jpg
1-123-X_1.jpg
1-123-X_2.jpg
6-45688.jpg

链接到我正在尝试实现的原始代码: https://www.reddit.com/r/PowerShell/comments/8f2z0l/remove_files_not_in_csv/

【问题讨论】:

  • Where-Object Name -notin $filestokeep.sku --> Where-Object { $_.BaseName -notin $filestokeep.sku }。此外,为了安全起见,将开关 -File 添加到 Get-ChildItem cmdlet,这样您就不会处理子文件夹。无论如何,您想要的输出与描述不匹配,因为它还显示 IN csv .. 的文件
  • 感谢您的回答。添加-File 确实可以让一切更加安全。

标签: powershell csv directory notin


【解决方案1】:

您的FilesToKeep.csv 文件包含文件名列表,例如1-123-X。

您将其与包含 FileExtension 的 Name 属性进行比较,因此您将仅包含文件名的列表与包含扩展名的 \1-123-X_1.jpg 之类的内容进行比较。

为了清楚起见,比较看起来像这样:

Name             Sku
1-123-X_1.jpg    1-123-X_1  #doesn't match because Windows cares about the .jpg piece

看看为什么这不起作用?分机在一个组中,而不在另一个组中!

修复非常简单,只需与BaseName 属性进行比较即可,如下所示:

 $files |
        Where-Object BaseName -notin $filestokeep.sku |
        Remove-Item -WhatIf

这将导致发生这种比较:

BaseName     Sku
1-123-X_1    1-123-X_1  #MATCHES!

然后,当您继续运行完整脚本时,您将看到此输出,显示如果您删除 -WhatIf 会发生什么。

What if: Performing the operation "Remove File" on target "C:\temp\Files\1-123-X_1.jpg".
What if: Performing the operation "Remove File" on target "C:\temp\Files\1-123-X_2.jpg".
What if: Performing the operation "Remove File" on target "C:\temp\Files\7-5468-XXX7.jpg".
What if: Performing the operation "Remove File" on target "C:\temp\Files\7-5468-XXX7_1.jpg".
What if: Performing the operation "Remove File" on target "C:\temp\Files\7-5468-XXX7_2.jpg".

【讨论】:

  • Basename 帮助很大,但我也想保留包含 sku 的图像。例如,如果 sku 是“1-123-X”,则不应删除名称为“1-123-X_1.jpg”和“1-123-X_2.jpg”的文件。你能以某种方式在 sku 周围添加通配符吗?到目前为止,感谢您提供的重要信息。
  • 作为一个新问题提出这个问题,这是可能的,但需要完全重写您的逻辑并且不适合这个问题。
  • 记得投票,如果这有助于解决问题,请接受作为答案:)
猜你喜欢
  • 2015-09-28
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 2023-03-30
  • 2020-10-08
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
相关资源
最近更新 更多