Reputation: 21
I am trying to remove Exchange contacts using a CSV file, however, I want this script to stop, or never even start, if that list exceeds 25 users.
$RemoveContacts = Import_CSV ".\Removed Contacts_$((Get-Date).ToString('MMddyyyy')).csv"
$RemoveContacts | ForEach { Remove-MailContact -identity $_ -confirm:$false}
What's the best way to achieve this?
Upvotes: 2
Views: 6569
Reputation: 440616
If you don't even want to start processing if array $RemoveContacts
has more than 25 users:
if ($RemoveContacts.Count -gt 25) {
Write-Error "Too many contacts: $($RemoveContacts.Count)"
return
}
Write-Error
creates a non-terminating error and return
exits the script / function.
Note that processing will continue by default, if applicable.
To abort processing instead, use Throw
rather than Write-Error
.
If you want to process 25 elements at most:
Select-Object -First <n>
allows you to stop processing after the first <n>
objects have been received:
$RemoveContacts | Select-Object -First 25 | ForEach { Remove-MailContact -identity $_ -confirm:$false }
Select-Object -First
is the right tool to use in a pipeline.
However, since you've already loaded all objects into an array in memory, you can more simply - and more efficiently - use array slicing:
$RemoveContacts[0..24] | ForEach { Remove-MailContact -identity $_ -confirm:$false }
[0..24]
extracts the first 25 elements from array $RemoveContacts
, and is safe to use even if the array contains fewer elements than that.[1]
In PSv4+ you can further speed this up by using the .ForEach()
method to process each array element:
$RemoveContacts[0..24].ForEach({ Remove-MailContact -identity $_ -confirm:$false })
[1] Unless you have deliberately activated Set-StrictMode
-Version 3
or higher.
Upvotes: 6