You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本遍历账户时提前终止问题及需求咨询

解决方案

核心修改思路

不再在遍历过程中直接执行exit,而是先收集所有已存在的AD账户,遍历完成后再判断是否终止脚本——既输出所有重复账户的警告,又能阻止后续创建逻辑执行。

修改后的完整脚本

$csv = Import-CSV "c:\accounts.csv"
$existingAccounts = @()  # 存储所有已存在的账户

foreach ($name in $csv)  {
    # 生成符合长度要求的账户名(变量定义在循环内,避免残留值干扰)
    $accountname = if ($name.FirstName.Length + $name.LastName.Length + 1 -le 20) {
        "$($name.FirstName).$($name.LastName)"
    } else {
        "$($name.FirstName.Substring(0,3)).$($name.LastName.Substring(0,12))"
    }

    # 检查账户是否存在,存在则记录并输出警告
    if (Get-ADUser -Filter "samaccountname -eq '$accountname'") {
        Write-Warning "The account $accountname already exists."
        $existingAccounts += $accountname
    }
}

# 若存在已有的账户,终止脚本,阻止后续创建逻辑
if ($existingAccounts.Count -gt 0) {
    exit
}

try {
    foreach ($name in $csv){
        $accountname = if ($name.FirstName.Length + $name.LastName.Length + 1 -le 20) {
            "$($name.FirstName).$($name.LastName)"
        } else {
            "$($name.FirstName.Substring(0,3)).$($name.LastName.Substring(0,12))"
        }

        New-ADUser -Name "$($name.LastName), $($name.FirstName) ($($name.emailaddress))" `
            -Path "OU=test,OU=test test,DC=test,DC=com" `
            -Surname $name.LastName `
            -GivenName $name.FirstName `
            -DisplayName "$($name.LastName), $($name.FirstName) ($($name.emailaddress))" `
            -samaccountname $accountname `
            -EmailAddress $name.emailaddress `
            -AccountPassword (ConvertTo-SecureString "password" -AsPlainText -force) `
            -PassThru `
            -ChangePasswordAtLogon $False `
            -Enabled $True 
    }
}
catch  [Microsoft.ActiveDirectory.Management.ADException] {
    if ($error[0].Exception.Message -ne "The server is unwilling to process the request") {
        Write-Warning $Error[0] 
        Write-Host $error[0].TargetObject -ForegroundColor Red 
    }
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException] {
    Write-Warning $Error[0] 
    Write-Host $Error[0].TargetObject -ForegroundColor Red
}

# 仅当模板为Sharepoint且无已存在账户时执行邮件脚本
if ($csv.Template -eq "Sharepoint" -and -not $existingAccounts) {
    Set-Location c:\email
    .\email.ps1
}

echo "`nUser Account Creation Complete" 

关键修改点说明

  • 新增$existingAccounts数组,收集所有已存在的账户,遍历完所有CSV条目后再判断是否终止脚本
  • 将账户名生成逻辑改为更简洁的if-else写法,且变量定义在循环内部,避免上一次循环的残留值干扰
  • 移除第一个循环内的exit,改为遍历完成后检查数组长度,大于0则执行exit,确保所有重复账户警告都能输出
  • 调整邮件脚本的判断条件,用-not $existingAccounts替代原有的错误信息判断,逻辑更可靠

内容的提问来源于stack exchange,提问作者InwardEdward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:50:21