获取当前登录用户 PowerShell Active Directory 的 OU

获取当前登录用户 PowerShell Active Directory 的 OU

我正在创建一个登录脚本,通过说出用户的姓名和他们所属的 OU 来欢迎用户。

代码:

    Import-Module activedirectory
    $user = (Get-WMIObject -ClassName Win32_ComputerSystem).Username
    $disName = Get-ADUser -Filter * | Select DistinguishedName
    $split = $disName.Split(',')

    $wshell = New-Object -ComObject Wscript.Shell
    $Output = $wshell.Popup("Welcome, $user", 0, "OU, $split[1]", 0x1)

错误出在$disName。当我仅输出 时$disName,我得到了以下信息:

DistinguishedName  
{}  
{}  
{} etc. 

我不确定它是否输出这个,因为我在 DC 上,或者我没有正确抓取 OU。

我的印象DistinguishedNameCN=Test User,OU=Tech,OU=DUsers

否则,我运行此代码,唯一打印出来的$split[1][1]

而且我也遇到了拆分方法错误,但我认为这是因为没有什么可拆分的。

答案1

使用现有代码,使输出框显示正确值的最简单的方法是使用“$( )”PowerShell 运算符将双引号括在变量内$output(即$($user)$($split[1]))。还使用$env:USERNAME作为 的值$user,并使用另一个从变量中Split('=')[1]解析出。OU=$split

电源外壳

Import-Module activedirectory
$user = $env:USERNAME;
$disName = (Get-ADUser $user).DistinguishedName;
$split = $disName.Split(',');

$wshell = New-Object -ComObject Wscript.Shell
$Output = $wshell.Popup("Welcome, $($user)", 0, "OU, $($split[1].Split('=')[1])", 0x1);

输出

在此处输入图片描述


额外 PowerShell

以下是一些与此任务相关的额外 PowerShell,您可能会发现它们很有帮助。我针对 Active Directory 测试了所有发布的逻辑,并确认了输出。

Get-ADUser $env:USERNAME -Properties * | Select CanonicalName, DistinguishedName | FL;
(Get-ADUser $env:USERNAME).DistinguishedName;
(Get-ADUser $env:USERNAME -Properties *).CanonicalName;
((Get-ADUser $env:USERNAME).DistinguishedName).Split(",")[1];
((Get-ADUser $env:USERNAME -Properties *).CanonicalName -split "/")[-2];

支持资源

答案2

我现在还远未达到 ADDS 环境,但您所做的比您所展示的努力更简单,并且是网络、书籍和 Youtube 上许多示例中很常见的事情。

无论如何,为什么直接使用 PowerShell?意思是,为什么不这样做(本机 cmdlet 和 .Net 命名空间)?

# $MemberOU = ((Get-ADUser -Filter {SamAccountName -like $env:USERNAME}).DistinguishedName -split ',') -match 'OU=' -replace 'OU='
$MemberOU = ('CN=Tom Smith,OU=IT,DC=SomeDomain,DC=Com' -split ',') -match 'OU=' -replace 'OU='
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("You are a member of this organizational unit: $MemberOU", "Welcome, $env:USERNAME", 'OK', 'Information')

相关内容