gpt4 book ai didi

powershell - 使用 PowerShell 过滤具有多个条件的 CSV 文件

转载 作者:行者123 更新时间:2023-12-03 07:55:17 27 4
gpt4 key购买 nike

以下是 CSV 文件中的一小部分数据示例,需要对其进行过滤以删除包含 Branch 102 或名称等于 Admin 的所有行。

数据源.csv

branch,ID,name
102,11056,Jones
103,11057,Henry
102,22000,Admin
103,22001,Admin
102,22002,White
103,22003,George

这是我的 PowerShell 脚本的第一个版本,demo.ps1,可以运行 -

$path = "C:\users\knot22\PowerShell"

Import-CSV "$($path)\DataSource.csv" | Where Branch -NotLike '*102*' | Where Name -NotLike '*Admin*' |
Export-CSV "$($path)\DataTarget.csv" -NoTypeInformation -UseQuotes Never

DataTarget.csv 的结果输出是 -

branch,ID,name
103,11057,Henry
103,22003,George

但是,我想修改 demo.ps1,以便条件位于单个 Where block 中。我已经尝试过了

$path = "C:\users\knot22\PowerShell"

Import-CSV "$($path)\DataSource.csv" | Where Branch -NotLike '*102*' -or Name -NotLike '*Admin*' |
Export-CSV "$($path)\DataTarget.csv" -NoTypeInformation -UseQuotes Never

但是会导致错误

"Cannot bind parameter because parameter 'NotLike' is specified morethan once. To provide multiple values to parameters that can acceptmultiple values, use the array syntax. For example, "-parametervalue1,value2,value3".

此错误消息意味着多个条件适用于一个参数。在上面的用例中,多个条件适用于不同的参数。

有没有办法修改 demo.ps1 第二个版本中的语法,尝试将条件与 -and 结合起来,以便它成功运行?我希望保持语法简洁。

此外,我正在使用 PowerShell 7。

最佳答案

Where-Object cmdlet (别名 Where)有两种不同的过滤模式 - 一种用于简单的属性比较(又名 simplified syntax ,这是您当前正在使用的),另一种用于更复杂的过滤场景。

对于后者,您需要提供一个脚本 block ,然后将其用作每个输入项的谓词:

Where { $_.Branch -notlike '*102*' -or $_.Name -notlike '*Admin*' }

请注意,这与您当前的管道不同 - 为此,您需要使用 -and 运算符:

Where { $_.Branch -notlike '*102*' -and $_.Name -notlike '*Admin*' }

关于powershell - 使用 PowerShell 过滤具有多个条件的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76217794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com