Powershell 电子邮件地址字段不正确,I';I’我不知道怎么纠正它

Powershell 电子邮件地址字段不正确,I';I’我不知道怎么纠正它,powershell,switch-statement,Powershell,Switch Statement,以下代码确定本地计算机的OU,并应提供OU的IT管理员的电子邮件地址。我想在另一段代码中使用电子邮件地址,但返回的输出将电子邮件字段显示为OU字段。我添加了最后一行,以查看输出结果。如何更改代码以更正此问题 # This section finds the OU of the local computer $rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE") $Domain = $root

以下代码确定本地计算机的OU,并应提供OU的IT管理员的电子邮件地址。我想在另一段代码中使用电子邮件地址,但返回的输出将电子邮件字段显示为OU字段。我添加了最后一行,以查看输出结果。如何更改代码以更正此问题

 # This section finds the OU of the local computer
$rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
$Domain = $rootDse.DefaultNamingContext
$root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Domain")
$ComputerName = $env:COMPUTERNAME
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.Filter = "(&(objectClass=computer)(name=$ComputerName))"
[System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
$dn = $result.Properties["distinguishedName"]
$ouResult = $dn.Substring($ComputerName.Length + 4)

$email = $ouResult 
 Switch ($Email)
{ 
'OU=a,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test1@domain.com' }
'OU=a,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test1@domain.com' }
'OU=b,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test2@domain.com' }
'OU=c,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test3@domain.com' }
'OU=d,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test4@domain.com' }
'OU=e,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test5@domain.com' }
'OU=f,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { 'test.test6@domain.com' } 
 Default { 'Unable to determine $Email' }
}
New-Object PSObject -Property @{"Name" = $ComputerName; "OU" = $ouResult; "Email" = $email} 

不确定我是否遗漏了其他内容,但您没有分配电子邮件地址的值,只是将其作为输出发送。你应该这样做:

# Remove this line > $email = $ouResult 
Switch ($ouResult)
{ 
    'OU=a,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { $email = 'test.test1@domain.com' }
    'OU=a,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { $email = 'test.test1@domain.com' }
    # ... trucated
    'OU=f,OU=Euro,OU=NB,OU=xxComputers,DC=xxx,DC=com' { $email = 'test.test6@domain.com' } 
     Default { '$ouResult not mapped to email address' }
}
此外,由于大多数查询都是相同的,而它只是第一个不同的OU,因此可以使用
-通配符
开关作为
开关

Switch -Wildcard ($ouResult)
{ 
    'OU=a,*' { $email = 'test.test1@domain.com' }
    'OU=a,*' { $email = 'test.test1@domain.com' }
    # ... trucated
    'OU=f,*' { $email = 'test.test6@domain.com' } 
     Default { '$ouResult not mapped to email address' }
}

很高兴知道。考虑将这个标记为答案,然后使用绿色复选标记在这个答案的左边。