简体   繁体   中英

How to limit the number of times ForEach runs

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?

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.

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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM