如果列中的文本匹配特定路径或文件名,则删除整个CSV行



我刚接触Powershell,所以如果可以的话,也请试着解释一下。我正试图导出目录的内容以及CSV中的其他一些信息。

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

$folder1 = OldFiles
$folder2 = Log FilesJanuary
$file1 = _updatehistory.txt
$file2 = websites.config

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

**FileName**
C:InstallationNew ApplicationsRoot

我已经试过了:

Import-csv -Path "C:CSVRecursion.csv" | Where-Object { $_.FileName -ne $folder2} | Export-csv -Path "C:CSVRecursionUpdated.csv" -NoTypeInformation

但是没有成功。我非常感谢你的帮助。

看起来您只想匹配完整路径的一部分,因此您应该使用-like-match操作符(或其否定变体),它们可以进行非精确匹配:

$excludes = '*OldFiles', '*Log FilesJanuary', '*_updatehistory.txt', '*websites.config'
Import-csv -Path "C:CSVRecursion.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:CSVRecursionUpdated.csv" -NoTypeInformation

这段代码大量使用了PowerShell的隐式输出行为。例如,foreach循环体中的文字$true是隐式输出,它将在$matchesExclude中自动捕获。如果不是赋值$matchesExclude = foreach ...,该值将被写入控制台(如果没有在调用堆栈的其他地方捕获)。

最新更新