我无法将Get-ADOrganizationalUnit
的结果传递给脚本中的函数。
我将结果存储在一个变量中,该变量用于将cmdlet返回的OU的规范名称添加到表单的下拉列表中。
然后,我尝试在一个函数中使用相同的变量,该函数在被调用时将根据所选的规范名称来确定OU的区别。
由于在加载表单时已设置了变量,以便要在下拉菜单中填充各种OU,因此我添加了write-output $myVar
只是为了确保在传递之前没有发生任何奇怪的事情进入功能。我试图通过$myVar
使$Global:varName
成为全局变量,并且试图在调用函数myFunction $myVar $myVar1
时传递变量。如果然后在函数中使用write-output $myVar
,则没有输出,但是我可以使用write-host $myVar
,它将返回仅包含$myVar
中所有OU的专有名称的字符串。>
我也直接在外壳中对此进行了测试,并且将规范名称与OU的DN相关联也没有任何问题,但不知道我在做错什么导致它无法工作在脚本中使用时。
我正在使用它来获取下拉列表和功能的OU数据:
$userOUs = Get-ADOrganizationalUnit -SearchBase $ouRoot -Filter * -Properties CanonicalName | Where-Object {$_.Name -like '*user*'}
注意:使用$userOUs
成功填充了下拉列表。
我用一个按钮调用函数:
$myBtn.Add_Click({ myFunction $userID $userOUs})
我试图将其传递给的功能:
function myFunction($userID, $userOUs) {
Write-Output $userOUs #returns nothing
Write-Host $userOUs #returns the string containing all of the OUs' distinguished names
$selectedOU = $OUList.SelectedItem
$targetOUCanonicalName = "$domainPrefix$selectedOU" #I remove the domain name from the canonical name for display in the dropdown but add it back here
$targetOu = $userOUs | Where-Object {$_.CanonicalName -eq $targetCanonicalName} | select -ExpandProperty distinguishedName
Get-ADUser -Identity $userID | Move-ADObject -TargetPath $targetOU
}
最终,目标是能够使用$userOus
变量基于OU规范名称的下拉列表中的选择来确定OU的DN。我想尝试保持动态性,而不必在switch语句中定义所有内容。
我希望一旦朝正确的方向碰到为什么变量没有按我需要的方式传递到函数中,我就能实现。
编辑:我不打算使用write-host
或write-output
,因为脚本将具有某种形式,我只是用这种形式来试图弄清楚正在发生什么。
答案 0 :(得分:0)
我已经尝试过您的版本,并且看起来工作正常:
function myFunction($userID, $userOUs) {
Write-Output $userOUs #returns nothing
Write-Host $userOUs #returns the string containing all of the OUs' distinguished names
#$selectedOU = $OUList.SelectedItem
#$targetOUCanonicalName = "$domainPrefix$selectedOU" #I remove the domain name from the canonical name for display in the dropdown but add it back here
#$targetOu = $userOUs | Where-Object {$_.CanonicalName -eq $targetCanonicalName} | select -ExpandProperty distinguishedName
# Get-ADUser -Identity $userID | Move-ADObject -TargetPath $targetOU
}
$userOUs = Get-ADOrganizationalUnit -Filter * -Properties CanonicalName | Where-Object {$_.Name -like '*user*' }
$userOUs
myFunction -userID $UserID -userOUs $userOUs
$ UserOus为我显示数据,当我如上所述执行您的函数时,我也得到输出。唯一想到的是问题出在其他地方。