You need to enable JavaScript to run this app. 如何使用JSON配置文件替代splatting表为New-ADUser传递参数
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSON配置文件替代splatting表为New-ADUser传递参数

实现方案

步骤1:编写符合参数规则的JSON配置文件

JSON的顶层键名必须和New-ADUser的参数名完全匹配,值对应你要设置的参数值,示例配置ad_user_config.json如下:

{
    "Name": "张三",
    "SamAccountName": "zhangsan",
    "UserPrincipalName": "zhangsan@contoso.com",
    "GivenName": "三",
    "Surname": "张",
    "Path": "OU=Users,DC=contoso,DC=com",
    "AccountPassword": "P@ssw0rd123",
    "Enabled": true,
    "ChangePasswordAtLogon": true
}

步骤2:读取JSON并转换为可Splat的哈希表

默认ConvertFrom-Json输出的是PS自定义对象,需要手动转换为哈希表才能用于Splat传参,代码如下:

# 读取JSON文件内容并转换为对象
$userConfig = Get-Content -Path "ad_user_config.json" -Raw | ConvertFrom-Json

# 转换为哈希表
$adUserParams = @{}
foreach ($property in $userConfig.PSObject.Properties) {
    # 特殊参数处理:AccountPassword需要转安全字符串,不需要可以删这段判断
    if ($property.Name -eq "AccountPassword") {
        $adUserParams[$property.Name] = ConvertTo-SecureString $property.Value -AsPlainText -Force
        continue
    }
    $adUserParams[$property.Name] = $property.Value
}

步骤3:Splat传参调用New-ADUser

直接用转换好的哈希表调用即可,和你之前用自定义哈希表的逻辑完全一致:

New-ADUser @adUserParams

注意事项

  • JSON中不需要的参数直接删除即可,不要留值为null的键,避免给命令传无效空值
  • PowerShell参数不区分大小写,JSON的键名大小写不影响传参
  • 涉及敏感值(如密码)不建议明文存JSON,生产环境可以替换为加密存储、或运行时让用户输入的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 01:45:03