csv 我得到一个除以零错误的状态栏部分脚本

56lgkhnf  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(89)

我一直在使用这个脚本,没有任何问题,突然,我得到了一个除以零的错误。该脚本是更新或更改几个属性和一个同事添加了计数器/状态,因为我们有时有数百个更改。我一直在使用powershell伊势,因为去win 11,因为我有问题,与常规的PS。
我试着从一个新的csv文件中提取数据,认为这可能是问题所在;没什么进展。这是我得到的:

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

字符串

huwehgph

huwehgph1#

把我的评论作为答案:
...在这一行(multi-line syntax used for clarity):

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

字符串
... -PercentComplete参数参数表达式为:

( $counter / $total )*100


...所以当$total0时,这将导致被零 debugging 误(-PercentComplete参数的类型是Int32而不是浮点类型,所以被零除是一个致命错误,而不是导致Infinity(至少是by default)。这是微软的一个奇怪的设计选择。
作为 * 快速修复 *(即一个黑客),可以通过简单地将+1添加到$total来防止被零除:

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


.虽然奇怪的是,它运行的是Write-Progress命令,因为当$CSV.count(即foreach($row in $csv) {)执行时,不应该进入foreach($row in $csv) {循环。$total)是0)。我假设在脚本的其他地方也有相同的$counter/$total表达式。

相关问题