问题描述
使用 Splatting Hashtable 设置参数,效果很好。
我将作为 New-ADUser @param
传递给函数,在 splatting 中设置的值将在 Active Directory 中创建。但是,我的脚本将在其他地方运行。 Json 文件将由用户操作。
如何将 Json 文件而不是 Splatting 表传递给此 New-ADUser @param
函数。
感谢您的帮助。
解决方法
注意:以下假设您的 JSON 配置文件:
- 包含一个对象,其属性名称与目标 cmdlet 的参数名称相匹配,
New-ADUser
- 并且属性值仅限于字符串、数字、布尔值和PowerShell可以强制转换为参数类型的嵌套对象,基于{ {3}}。
这些约束确保该对象的哈希表表示可以按原样用于参数 this answer。
如果您正在运行splatting,则可以利用PowerShell (Core) 7+的-AsHashtable
参数。
# Load JSON from file 'config.json' into a [hashtable] instance.
$param = Get-Content -Raw config.json | ConvertFrom-Json -AsHashtable
# Use the hashtable for splatting.
New-ADUser @param
在 Windows PowerShell(其最新和最终版本为 5.1)中,您必须手动转换返回的 [pscustomobject]
实例通过ConvertFrom-Json
到ConvertFrom-Json
:
# Load JSON from file 'config.json' into a [pscustomobject] instance.
$paramAux = Get-Content -Raw config.json | ConvertFrom-Json
# Convert the [pscustomobject] to a [hashtable] instance by
# making its properties (name-value pairs) hashtable entries.
$param = @{}
foreach ($prop in $paramAux.psobject.Properties) {
$param[$prop.Name] = $prop.Value
}
# Use the hashtable for splatting.
New-ADUser @param
您在评论中提供的示例配置 JSON 表明顶部所述的先决条件不满足,并且配置的自定义转换需要 JSON 才能映射到目标 hashtable 参数:
-
更新:真正预期的目标 cmdlet 是
New-ADUser
,对于其参数,下面的示例 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.
$paramAux = 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.
$param = @{}
foreach ($prop in $paramAux.psobject.Properties) {
switch ($prop.Name) {
# Map the JSON property names and values onto the appropriate
# New-ADUser parameters.
'accountEnabled' { $param['Enabled'] = $prop.Value }
'mailNickname' { $param['SamAccountName'] = $prop.Value }
'passwordProfile' {
$param['ChangePasswordAtLogon'] = $prop.Value.forceChangePasswordNextSignIn
$param['AccountPassword'] = ConvertTo-SecureString -Force -AsPlainText $prop.Value.password
}
# All other properties directly map onto New-ADUser parameters.
default { $param[$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 @param
注意:我不确定 mailNickname
属性映射到什么参数;我在上面假设了 -SamAccountName
;根据需要调整。