Powershell-变量范围的行为异常
我有一个小脚本,可以读出一个广告组的成员,然后将他们与我拥有的一组用户进行比较 为了实现这一点,我使用了两个嵌套循环,如果条件和我面临的一个大问题是,我的Powershell-变量范围的行为异常,powershell,scope,powershell-3.0,Powershell,Scope,Powershell 3.0,我有一个小脚本,可以读出一个广告组的成员,然后将他们与我拥有的一组用户进行比较 为了实现这一点,我使用了两个嵌套循环,如果条件和我面临的一个大问题是,我的$members变量突然失去作用域和值为null 我试图将作用域设置为$Global:members或$Script:members,但没有效果 下面是我的源代码。任何建议、推动正确方向、如何解决问题和提供帮助都将受到高度赞赏。 提前谢谢 编辑:我通过管道将$members变量传输到输出字符串,这让我可以继续工作,但我仍然对发生的事情非常好奇,
$members
变量突然失去作用域和值为null
我试图将作用域设置为
$Global:members
或$Script:members
,但没有效果
下面是我的源代码。任何建议、推动正确方向、如何解决问题和提供帮助都将受到高度赞赏。提前谢谢 编辑:我通过管道将
$members
变量传输到输出字符串
,这让我可以继续工作,但我仍然对发生的事情非常好奇,因此如果有人知道发生了什么,请告诉我
foreach($group in $groups)
{
#pull the members here
$members = $group | Get-ADGroupMember | Out-String # Out-String fixed the issue
$members #this little print shows me everything is alright
#pull a needed portion of every group for further matching
if($group.Name -match "Group-AX_User_(.*)_Productive")
{
$man = $Matches[1]
}
foreach($entry in $result)
{
#each entry is a csv string, pull the first value
if($entry -match ".*,`"(.*)`"")
{
$tblMan = $Matches[1]
if($tblMan -eq $man)
{
#alrigth our group matches with the one in the csv
#everything is fine, members is not null
if($entry -match "`"(.*)`",`"")
{
#!!! All of the sudden, $members is null
#what the hell happened?
$m = $Matches[1]
if($members.Contains($m))
{
#well the current entry member is
#already in the group
$entry
}
}
}
}
}
}
您没有范围问题。问题是您的组在域中不存在。那么你就到了这一行:
$members = $group | Get-ADGroupMember
您正在将$null
分配给$members
将其管道化到输出字符串对您有效的原因是,它将一个空字符串分配到了成员中。你的逻辑恰好没有被它扼住
连你的精神检查都在骗你
$members #this little print shows me everything is alright
它可以很好地打印最后一个循环中的成员。在当前过程中,null不显示任何内容。然后您将在脚本中更深的
$members.Contains($m)
上出错。您会看到前面的输出,它会给人一种失去作用域的印象。$result从未定义过,我们也不知道$groups/$groups是如何格式化的,因此这几乎不可能帮助您进行故障排除,因为它在提供的信息中通常不起作用。