I have a fairly complex ForEach-Object loop. It is processing a lot of information. For testing, I want to stop it after a number of iterations. This is triggered by the if (!$live -and $count -gt 10)
I have tried using break
, exit
, and continue
. All of them exit the script entirely without performing any of the remaining code following the ForEach-Object. The Write-Output ("Success") is just the first example.
I have managed to work around this by using an empty If statement and wrapping the rest of the contents in an Else, but his seems a cludge. Can anyone help me understand why this is not behaving the way I expect it to?
$update_list | ForEach-Object {
$count ++
if (!$live -and $count -gt 10){
continue
}
$id = $_.event_id
if ($_.app_username) {
$user = $_.app_username
$body = "stuff"
Write-Output ("Begin $count of $total")
Write-Output ("Sending: stuff `r`n")
#Get the current owner
$test_owner_before = stuff
#Check to see if it is the same as the user we are going to send.
#If it is then skip
if ($test_owner_before.object_ownership.object.owner_username -eq $user) {
$correct += [pscustomobject]@{event_id = $id; owner_username = $test_owner; provided_username = $user}
Write-Output ("The current owner $($test_owner_before.object_ownership.object.owner_username) matches the proposed owner $user - Skipping.")
}
#Otherwise send the update
else {
#Only make changes if the -live flag has been set
if ($live){
$response = stuff
}
#Get the current owner
$test_owner_after = stuff
$test_owner = $test_owner_after.object_ownership.object.owner_username
#Check to be sure the current owner matches the user we sent
#If so then report success
if ($test_owner -eq $user -and $user -in $userid_username_list.app_username){
Write-Output ("Success")
Write-Output ("Current Owner $($test_owner) matches the sent sent owner $user and is found in the 25Live user list")
$match += [pscustomobject]@{event_id = $id; owner_username = $test_owner; provided_username = $user}
}
#If not report the error and details
else {
Write-Output ("Mismatch")
Write-Output ("Current Owner $($test_owner) does not match the sent sent owner $user or is found in the 25Live user list")
$mismatch += [pscustomobject]@{event_id = $id; owner_username = $test_owner; provided_username = $user}
}
if ($response) {
Write-Output ("Response:`r`n`t $($response.OuterXml)`r`n")
}
}
}
else {
#If there is no Requestor Username then skip
Write-Output ("$count of $total - No user id for Event ID: $id - Skipping.")
}
}
Write-Output ("Success")