过滤列大于或等于数字的 CSV

Filter CSV where column is greater or equal to a number

我有以下 CSV 文件:

"Count";"Computername";"Files and paths"
"3";"Computer1";"%OSDRIVE%\USERS[=10=]00008\APPDATA\LOCAL\TEMP\__PSSCRIPT.PS1"
"1";"Computer1";"%OSDRIVE%\USERS[=10=]00008\APPDATA\LOCAL\TEMP\__PSSCRIPT.PS1"
"5";"Computer3";"\SRV\TOTO$\HELLO.BAT"
"8";"Computer4";"\192.168.8.18\TOTO\DNS.BAT"
"10";"Computer15";"%OSDRIVE%\Hello.exe"
"12";"Computer6";"\SRV\SCRIPTS\REBOOT.BAT"
"88";"Computer7";"%OSDRIVE%\Winword.exe"
"154";"Computer2";"%OSDRIVE%\excel.exe"

我想保留 "Count" 大于或等于 8 的所有行。

我试过以下命令:

Import-Csv -Path MyFile.csv -Delimiter ";" | Where-Object {$_.Count -ge 8}

但对我来说只有 returns 8 或 88 或 18 行...但并非所有其他行都优于 8(例如 10、12、154 ...)。

为什么?

Count 被读取为字符串,因此您需要将其更改为整数才能进行比较。

一种方法是将您的 Where-Object 语句更改为

where {($_.Count -as [int]) -ge 8}

除非嵌入了类型信息 (see documentation),否则每个值都会变成字符串。这导致按字母顺序比较而不是整数一。请参阅以下内容:

$csv = ConvertFrom-Csv @'
"Count";"Computername";"Files and paths"
"3";"Computer1";"%OSDRIVE%\USERS[=10=]00008\APPDATA\LOCAL\TEMP\__PSSCRIPT.PS1"
"1";"Computer1";"%OSDRIVE%\USERS[=10=]00008\APPDATA\LOCAL\TEMP\__PSSCRIPT.PS1"
"5";"Computer3";"\SRV\TOTO$\HELLO.BAT"
"8";"Computer4";"\192.168.8.18\TOTO\DNS.BAT"
"10";"Computer15";"%OSDRIVE%\Hello.exe"
"12";"Computer6";"\SRV\SCRIPTS\REBOOT.BAT"
"88";"Computer7";"%OSDRIVE%\Winword.exe"
"154";"Computer2";"%OSDRIVE%\excel.exe"
'@ -Delimiter ';'

$csv | gm

所有属性都是字符串:

   TypeName: System.Management.Automation.PSCustomObject

Name            MemberType   Definition                                                                      
----            ----------   ----------                                                                      
Equals          Method       bool Equals(System.Object obj)                                                  
GetHashCode     Method       int GetHashCode()                                                               
GetType         Method       type GetType()                                                                  
ToString        Method       string ToString()                                                               
Computername    NoteProperty string Computername=Computer1                                                   
Count           NoteProperty string Count=3                                                                  
Files and paths NoteProperty string Files and paths=%OSDRIVE%\USERS[=11=]00008\APPDATA\LOCAL\TEMP\__PSSCRIPT.PS1

最简单的解决方案是使用转换:

$csv | Where-Object {[int]$_.Count -ge 8}