【问题标题】:Deleting CSV the entire row if text in a column matches a specific path or a file name如果列中的文本与特定路径或文件名匹配,则删除整行 CSV
【发布时间】:2021-02-16 08:22:07
【问题描述】:

我是 Powershell 的新手,所以如果可以的话,请尽量解释一下。我正在尝试将目录的内容与 CSV 中的一些其他信息一起导出。

CSV 文件包含有关文件的信息,但我只需要匹配 FileName 列(其中包含完整路径)。如果匹配,我需要删除整行。

$folder1 = OldFiles
$folder2 = Log Files\January
$file1 = _updatehistory.txt
$file2 = websites.config

在 CSV 文件中,如果其中任何一个匹配,则必须删除整行。 CSV 文件以这种方式包含 FileName:

**FileName**
C:\Installation\New Applications\Root

我试过这样做:

Import-csv -Path "C:\CSV\Recursion.csv" | Where-Object { $_.FileName -ne $folder2} | Export-csv -Path "C:\CSV\RecursionUpdated.csv" -NoTypeInformation

但它没有成功。非常感谢您的帮助。

【问题讨论】:

  • 文件名是否完全匹配?如果只是其中的一部分,请使用:$_.fileName -notlike "$folder2*"
  • @guiwhatsthat 是的,文件名将完全匹配。

标签: powershell


【解决方案1】:

您似乎只想匹配完整路径的一部分,因此您应该使用-like or -match 运算符(或其否定变体),它可以进行非精确匹配:

$excludes = '*\OldFiles', '*\Log Files\January', '*\_updatehistory.txt', '*\websites.config'

Import-csv -Path "C:\CSV\Recursion.csv" | 
    Where-Object { 

        # $matchesExclude Will be $true if at least one exclude pattern matches
        # against FileName. Otherwise it will be $null.
        $matchesExclude = foreach( $exclude in $excludes ) {
            # Output $true if pattern matches, which will be captured in $matchesExclude.
            if( $_.FileName -like $exclude ) { $true; break }
        }

        # This outputs $true if the filename is not excluded, thus Where-Object
        # passes the row along the pipeline.
        -not $matchesExclude  

    } | Export-csv -Path "C:\CSV\RecursionUpdated.csv" -NoTypeInformation

此代码大量使用 PowerShell 的隐式输出行为。例如。 foreach 循环体中的文字 $true 是隐式输出,将在 $matchesExclude 中自动捕获。如果不是分配$matchesExclude = foreach ...,则该值将被写入控制台(如果未在调用堆栈中的其他位置捕获)。

【讨论】:

  • 正在从其他地方加载包含完整路径“部分”的变量(实际上是一个 JSON 文件)。所以我不能输入要完全匹配的文件名,因为我需要先加载变量。有没有一种方法可以像您使用 $excludes 那样以类似的方式存储这些变量?
  • @Scripter9700 应该是可能的。如何做到这一点,取决于 JSON 的结构。您可以将此问题作为第二个问题发布。当前问题已得到解答。
猜你喜欢
  • 2012-07-13
  • 2015-04-12
  • 1970-01-01
  • 2017-05-11
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
相关资源
最近更新 更多