0

I've been using this script with no issues and all of the sudden, i'm getting a divide by zero error. the script is to update or change a couple of attributes and a colleague added the counter/status since we sometimes have hundreds of changes to make. I've been using powershell ise since going to Win11 as I was having issues with regular PS.

I tried pulling the data from a fresh csv file thinking that may have been the issue; no luck. Here is what I have:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -force

    import-module Activedirectory
    $Path = "C:\Users\cn116943\Input\ad_data_TN_IP_update.csv"
    $CSV = import-csv $Path
    $CRED = get-credential "Centene\a_cn116943"

    #Counter for progress status
    $counter = 0
    $total = $CSV.count

    foreach($row in $csv){

        $counter++
        Write-Progress -Activity "Processing: $row" -Status "$($counter) of $($total)" -        PercentComplete (($counter/$total)*100)

    if($row.action -eq 'update'){
        set-aduser $row.user -credential $cred -replace @{ipPhone= "$($row.phone)"}
        set-aduser $row.user -credential $cred -replace @{telephonenumber= "$($row.phone)"} 
    }

    if($row.action -eq 'remove'){
        set-aduser $row.user -credential $cred -Clear ipPhone
        set-aduser $row.user -credential $cred -Clear telephonenumber
Dai
  • 141,631
  • 28
  • 261
  • 374
  • As a quick-fix, change `PercentComplete (($counter/$total)*100)` to `PercentComplete (($counter/($total+1))*100)` (though it's curious how `$total` is zero when it has to enter the `foreach` which can't happen when it is empty... – Dai Jul 01 '23 at 23:25
  • Dai, that was perfect. My counter/status bar is now working. thank you very much. – a069585 Jul 03 '23 at 15:00

1 Answers1

0

Posting my comment as an answer:

...in this line (multi-line syntax used for clarity):

Write-Progress `
    -Activity "Processing: $row" `
    -Status "$($counter) of $($total)" `
    -PercentComplete (($counter/$total)*100)

...the -PercentComplete parameter argument expression is:

( $counter / $total )*100

...so when $total is 0 this will cause a divide-by-zero error (the -PercentComplete parameter is typed as Int32 instead of a floating-point type, so a divide-by-zero is a fatal error instead of resulting in Infinity (at least by default). An odd design choice by Microsoft there.

As a quick-fix (i.e. a hack), one can prevent divide-by-zero by simply adding +1 to $total:

Write-Progress `
    -Activity "Processing: $row" `
    -Status "$($counter) of $($total)" `
    -PercentComplete (($counter/($total+1))*100)

...though it's curiuous that it's running the Write-Progress command given the foreach($row in $csv) { loop shouldn't be entered when $CSV.count (i.e. $total) is 0). I assume you had the same $counter/$total expression elsewhere in your script.

Dai
  • 141,631
  • 28
  • 261
  • 374