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

PowerShell创建AD账户报错:无法将字符串转为SwitchParameter类型

解决PowerShell创建AD账户时的Confirm参数转换错误问题

问题原因

你的脚本调用New-ADUser时,参数哈希表$params中使用了错误的参数名ADAccountPassword,而New-ADUser的正确参数名为AccountPassword。PowerShell处理未知参数时,错误地将其与Confirm开关参数绑定,导致类型转换失败(SecureString无法转换为SwitchParameter类型),从而抛出报错。

修复步骤

  1. 修正参数名:将$params哈希表中的'ADAccountPassword'改为'AccountPassword',匹配New-ADUser的官方参数名。
  2. 移除冗余代码:创建用户时已通过AccountPassword设置密码,后续调用Set-ADAccountPassword重置密码属于冗余操作,可以删除。

修复后的关键代码片段

$params = @{
    'name'                 = $Name
    'givenName'            = $GivenName
    'sn'                   = $Surname
    'SamAccountName'       = $SamAccountName
    'UserPrincipalName'    = $UserPrincipalName
    'Path'                 = $Path
    'Enabled'              = $Enabled
    'co'                   = $Country
    'c'                    = $CountryAcronym
    'PassThru'             = $true
    'streetAddress'        = $StreetAddress
    'st'                   = $Province
    'l'                    = $City
    'postalCode'           = $PostalCode
    'AccountPassword'      = $ADAccountPassword  # 修正后的正确参数名
}

$newUser = New-ADUser @params 
Write-Host "Account '$SamAccountName' created successfully."

# 移除以下冗余代码:
# Set-ADAccountPassword -Identity $newUser -NewPassword $ADAccountPassword -Reset

return $newUser

验证说明

修正后,New-ADUser能正确识别密码参数,不会触发参数绑定错误,账户创建完成后即可正常启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:18:22