首页 > 解决方案 > 无法将格式化的 Get-ADOrganizationlUnit 输出传递到脚本中的函数

问题描述

我无法将结果传递Get-ADOrganizationalUnit给脚本中的函数。

我将结果存储在一个变量中,该变量用于将 cmdlet 返回的 OU 的规范名称添加到表单上的下拉列表中。

然后,我尝试在调用时在函数中使用相同的变量,该变量将根据所选的规范名称确定 OU 的区别。

由于在表单加载时设置了变量,因此相关下拉列表将填充各种 OU,我添加了一个write-output $myVar只是为了确保在传递给函数之前没有发生任何奇怪的事情。我尝试使用$myVar全局$Global:varName变量,并尝试在调用函数时传入变量:myFunction $myVar $myVar1。如果我随后write-output $myVar在函数中使用,则没有输出,但我可以使用write-host $myVar它,它将返回一个字符串,该字符串仅包含$myVar.

我也直接在 shell 中对此进行了测试,将规范名称关联回 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因为脚本会有一个表单,我只是用它来尝试弄清楚发生了什么。

标签: powershell

解决方案


我试过你的版本,它似乎工作得很好:

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 为我显示数据,当我执行上面的函数时,我也会得到输出。唯一想到的是问题出在其他地方。


推荐阅读