powershell - 无法将格式化的 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
因为脚本会有一个表单,我只是用它来尝试弄清楚发生了什么。
解决方案
我试过你的版本,它似乎工作得很好:
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 为我显示数据,当我执行上面的函数时,我也会得到输出。唯一想到的是问题出在其他地方。
推荐阅读
- java - Spring Mockito - Junit 控制器测试 - 模拟一项服务
- c# - 使用 C# 在字符串中使用双精度时如何删除尾随零?
- cldr - 为什么 CLDR 有上标两个尾随一些细分名称?
- teamcity - 在 Octopus 部署步骤之后 TeamCity 自动合并不起作用
- c# - 如何使用 WithAllProperties 等方法扩展 epplus 数据提取器
- windows - 通过bat文件执行时文件路径中的转义空格
- javascript - 仅过滤 jquery 过滤器中的特定列
- javascript - 数据在 Chart.js 折线图中未正确显示
- traversal - 在循环中运行遍历后,V8 因内存而崩溃
- java - 尝试访问 Web 的某些部分而不是重定向到登录页面时提供简单的 HTTP 401