Avatar of jbla9028
jbla9028
Flag for United States of America asked on

Import-CSV and remove specified values

I have a powershell script to export some account info from AD. I want to read this CSV file in and remove certain accounts. I can't do it dynamically as it's something a manager needs to specify. The CSV file output is below

"Email","FirstName","LastName","Department","whenCreated"
"User1@domain.com","UserF1","UserL1l","Cashiering","9/8/2006 11:33:53 AM"
"User2@domain.com","UserF2","UserL2l","Cashiering","9/13/2006 11:50:59 AM"
"User3@domain.com","UserF3","UserL3l","Cashiering","12/6/2012 2:51:43 PM"
"User4@domain.com","UserF4","UserL4l","Cashiering","12/6/2012 2:51:43 PM"




I'd like to be able to loop through a where clause and remove lines based on "Email address" I specify in the file. I forsee the need to add additonal accounts in the future so if I could use an array of some sort that would be best. I see a couple solutions online but not quite what I need. logic would be

Import CSV

If account is in the list below, remove the line from the CSV
"User1@domain.com"
"User4@domain.com"
"User9@domain.com"
"User10@domain.com"

Export-CSV Contents


any help is appreciated!
Powershell

Avatar of undefined
Last Comment
Qlemo

8/22/2022 - Mon
Qlemo

$ignore = @"
User1@domain.com
User4@domain.com
User9@domain.com
User10@domain.com
"@ -split "`r`n"

(Get-Content file.txt  | Select-String -NotMatch -SimpleMatch $ignore) | Out-File file2.txt

Open in new window

As I suppose comparing parts of the line with the email addresses is enough of a match to reliable exclude the unwanted lines. We can make the pattern more restrictive, or switch to your suggestion handling CSV data, if required.
jbla9028

ASKER
Sorry for the delay, I was on vacation. I tried to add this statement but it's not removing the line from the CSV file. it's just outputing the same exact text file it read back in.
Qlemo

There seems to be an EE issue with the backtick used, I suspect. Let's try something slightly different:
$ignore = 'User1@domain.com',
          'User4@domain.com',
          'User9@domain.com',
          'User10@domain.com'

(Get-Content file.txt  | Select-String -NotMatch -SimpleMatch $ignore) | Out-File file2.txt

Open in new window

Your help has saved me hundreds of hours of internet surfing.
fblack61
jbla9028

ASKER
]Thank you for the help again. So this time the user was removed but the CSV file structure was manipulated in a way that makes it unusable. For some reason records are now traversing multiple lines in the CSV file.


CSV Prior



CSV Post
ASKER CERTIFIED SOLUTION
Qlemo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.