注意:以下假设您的 JSON 配置文件:
- 包含一个对象,其属性名称与目标cmdlet的参数名称匹配,
New-ADUser
- 并且属性 values 仅限于字符串、数字、布尔值和嵌套对象,PowerShell 可以根据 @ 中解释的约束cast 到参数的类型987654321@.
这些约束确保该对象的哈希表表示可以按原样用于参数splatting。
如果您正在运行 PowerShell (Core) 7+,则可以利用 ConvertFrom-Json 的
-AsHashtable 参数。
# Load JSON from file 'config.json' into a [hashtable] instance.
$params = Get-Content -Raw config.json | ConvertFrom-Json -AsHashtable
# Use the hashtable for splatting.
New-ADUser @params
在 Windows PowerShell(其最新和最终版本是 5.1)中,您必须手动转换 @ 返回的 [pscustomobject] 实例 987654334@ 转至hashtable:
# Load JSON from file 'config.json' into a [pscustomobject] instance.
$paramsAux = Get-Content -Raw config.json | ConvertFrom-Json
# Convert the [pscustomobject] to a [hashtable] instance by
# making its properties (name-value pairs) hashtable entries.
$params = @{}
foreach ($prop in $paramsAux.psobject.Properties) {
$params[$prop.Name] = $prop.Value
}
# Use the hashtable for splatting.
New-ADUser @params
您在评论中提供的示例配置 JSON 表明顶部所述的先决条件不满足,并且配置的自定义转换需要 JSON 才能映射到目标 New-ADUser 参数:
-
更新:真正预期的目标 cmdlet 原来是
New-AzureADuser,其参数与下面的示例 JSON 的属性是直接匹配,因此不需要自定义转换;希望所展示的技术对确实需要自定义转换的未来读者仍然有用。
# Create a sample JSON config file.
@'
{
"GivenName": "Lili",
"SurName": "Waters",
"accountEnabled": true,
"displayName": "Lili Waters",
"mailNickname": "LiliW",
"userPrincipalName": "liliw@mailcom",
"passwordProfile": {
"forceChangePasswordNextSignIn": true,
"password": "xxyyzz"
}
}
'@ > config.json
# Load JSON from file 'config.json' into a [pscustomobject] instance.
$paramsAux = Get-Content -Raw config.json | ConvertFrom-Json
# Convert the [pscustomobject] to a [hashtable] instance by
# making its properties (name-value pairs) hashtable entries,
# applying custom transformations, as necessary.
$params = @{}
foreach ($prop in $paramsAux.psobject.Properties) {
switch ($prop.Name) {
# Map the JSON property names and values onto the appropriate
# New-ADUser parameters.
'accountEnabled' { $params['Enabled'] = $prop.Value }
'mailNickname' { $params['SamAccountName'] = $prop.Value }
'passwordProfile' {
$params['ChangePasswordAtLogon'] = $prop.Value.forceChangePasswordNextSignIn
$params['AccountPassword'] = ConvertTo-SecureString -Force -AsPlainText $prop.Value.password
}
# All other properties directly map onto New-ADUser parameters.
default { $params[$prop.Name] = $prop.Value }
}
}
# Use the hashtable for splatting.
# Note: To inspect the actual arguments being passed, use Write-Output in lieu
# of New-ADUser, or just output the hashtable, $params, by itself.
New-ADUser @params
注意:我不确定mailNickname 属性映射到什么参数;我在上面假设了-SamAccountName;根据需要进行调整。