Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

PowerShell to remove row from CSV

I run a script internally to fetch the SystemName and its model on my organization LAN Segment. Following is the sample CSV file.

"SystemName","Model"
"DELL-10110","DELL Optiplex"
"DELL-10111","DELL Optiplex"
"Lenovo-30119","Lenovo ThinkCentre"
"DELL-10112","DELL Optiplex"
"HP-21011","HP Prodesk"
"HP-21012","HP Prodesk"

And I run another Powershell script to import the CSV file and remove entire row if the SystemName contains HP. But the output CSV file is still having HP systems.

$DATA = Import-CSv C:ITInventory.csv | ForEach-Object {
    [PSCustomObject]@{
        SystemName = $_.SystemName
        Model = $_.Model
    }
}
$DATA | Where-Object {$_.SystemName -ne "*HP*"} | Export-Csv -NoTypeInformation -Path C:ITInventory-New.csv
question from:https://stackoverflow.com/questions/65857293/powershell-to-remove-row-from-csv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @Theo mentioned, the problem is definitely in the comparison operator -ne. @Theo's comment is an acceptable solution, but I'd point out there's a lot of unnecessary stuff going on here. Import-Csv already outputs PSCustomObjects, there's no reason to create new objects inside a ForEach-Object loop. Once that's realized you can condense this to a single pipeline like:

    Import-CSv 'C:ITInventory.csv' | 
    Where-Object{ $_.SystemName -notmatch '^HP' } |
    Export-Csv -NoTypeInformation -Path 'C:ITInventory-New.csv'

Note: Even if you needed objects with only a subset of the original properties I'd use Select-Object before resorting to creating new objects. Select-Object also outputs PSCustomObjects.

In above sample I used -notmatch with the RegEx anchor ^. The Where clause effectively means where doesn't start with "HP". However, that's just for demonstration sake. -notlike "*HP*" or "HP*" may work just as well all depending on your data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...