[英]Powershell passing element of array as argument
I am a PowerShell novice and I am stuck :(. I wrote what was I thought a simple script to just add a list of users to an AD group. But unfortunately it doesn´t work. I have got the correct objectId in an array but then when I try to pass it as an argument it fails. Does anyway find a way forward? I feel it is something very simple but I have tried a lot of different things and well as it says I am stuck我是 PowerShell 新手,我被困住了 :(。我写了一个我认为的简单脚本,只是将用户列表添加到 AD 组。但不幸的是它不起作用。我在数组中获得了正确的 objectId但是当我尝试将它作为参数传递时,它失败了。无论如何找到前进的方法?我觉得这是一件非常简单的事情,但我尝试了很多不同的事情,并且它说我被卡住了
Added some clarifications below code segment在代码段下方添加了一些说明
$UsersToAdd = @(
'user@domain.com',
'user2@domain.com'
)
$ParentGroup = "DomainGroupX"
ForEach ($User in $UsersToAdd)
{
$UserId = az ad user list --upn $User --query [].objectId
$test = $UserId[1]
If ($UserId.count -le 1) { echo "$User not found" }else {
az ad group member add --group $ParentGroup --member-id $test
}
}
The problem is in this line: az ad group member add --group $ParentGroup --member-id $test问题出在这一行:az ad group member add --group $ParentGroup --member-id $test
this $test item is an array with one single ObjectId in it, something like this [ "sdjasddheiieyieyie"]这个 $test 项目是一个包含一个 ObjectId 的数组,类似于 [ "sdjasddheiieyieyie"]
But now It fails when i try to pass it whereas the below does work az ad group member add --group $ParentGroup --member-id "sdjasddheiieyieyie"但是现在当我尝试通过它时它失败了,而下面的确实有效 az ad group member add --group $ParentGroup --member-id "sdjasddheiieyieyie"
Thank you!!谢谢!!
You are making your JMESPath query more complicated than it needs to be:您正在使 JMESPath 查询比它需要的更复杂:
$UsersToAdd= 'user@domain.com','user2@domain.com'
$ParentGroup = "DomainGroupX"
Foreach ($User in $UsersToAdd) {
$UserId = az ad user list --upn $User --query [0].objectId
if ($UserId) {
az ad group member add --group $ParentGroup --member-id $UserId
} else {
"$User not found"
}
}
Indexing into the JSON array from the start avoids the unnecessary complications.从一开始就索引到 JSON 数组避免了不必要的复杂性。
Using [].objectId
returns the array structure as a string around the objectId
value.使用
[].objectId
将数组结构作为围绕objectId
值的字符串返回。 An additional problem is it formats the value you want by including a preceding space that you must consider.另一个问题是它通过包含您必须考虑的前置空格来格式化您想要的值。
$UsersToAdd= 'user@domain.com','user2@domain.com'
$ParentGroup = "DomainGroupX"
Foreach ($User in $UsersToAdd) {
$UserId = az ad user list --upn $User --query [].objectId
$UserId = $UserId[1].Trim()
if ($UserId) {
az ad group member add --group $ParentGroup --member-id $UserId
} else {
"$User not found"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.