Can I remove a line of a text file after a foreach ($line) in Powershell

Viewed 53

I have a Powershell script for our Exchange online that updates our archiving and litigation settings for mailboxes (see the relevant part below).

Each line within the text file is a user's mailbox

$mailboxes = Get-Content "\\SERVER\c$\Scripts\Enable archiving and litigation\new_mailboxes.txt" #Read text file with applicable users
                              
foreach ($line in $mailboxes) {
    Write-host "Enable Archiving for $line"
    get-mailbox $line | enable-mailbox -archive

    Write-host "Enable Litigation for $line"    
    get-mailbox $line | set-mailbox -litigationHoldEnabled $true -litigationholdduration 2555

    Write-host "Enable Quota for $line"
    get-mailbox $line | set-mailbox -prohibitsendquota 4.5GB -prohibitsendreceivequota 5.0GB -issuewarningquota 4GB

    Write-host "Enable Quota for $line" 
    get-mailbox $line | set-mailbox -retentionpolicy "ORG Retention Policy"

    Write-host "Enable retention policy for $line"
    get-mailbox $line | set-mailbox -RetainDeletedItemsFor 30.00:00:00

    Write-Host "Removing the line $line"
    $mailboxes | Where-Object {$_ -notmatch $line} | Set-Content "\\SERVER\c$\Scripts\Enable archiving and litigation\new_mailboxes.txt"
}

The issue I'm running into is that the file will still save with a few lines intact, for example the text file will contain:

Ross, Bob
Bloggs, Joe

Once the script is run the text file will then be saved with content like:

Bloggs, Joe
1 Answers

Have you tried using Add-Content instead of Set-Content ?

In your case at each step in the loop it overwrites the file.

If you want to reduce your original file you have to do somthing like :

copy-item "\\SERVER\c$\Scripts\Enable archiving and litigation\new_mailboxes.txt" "\\SERVER\c$\Scripts\Enable archiving and litigation\new_mailboxes_tmp.txt"
$mailboxesTmp = Get-Content "\\SERVER\c$\Scripts\Enable archiving and litigation\new_mailboxes_tmp.txt"
$mailboxesTmp | Where-Object {$_ -notmatch $line} | Set-Content "\\SERVER\c$\Scripts\Enable archiving and litigation\new_mailboxes.txt"
Related