我仍然是 Powershell 菜鸟,我正在尝试从 SQL Server 中自动删除在 Active Directory 中标记为禁用的登录。
到目前为止,我已经找到了这里显示的这段代码,并尝试修复它,但出现了一系列错误。有什么帮助吗?
其次,我计划当我修复此代码时,
-Instance
名称将是我希望代码循环并删除的实例列表。对此的任何想法也将不胜感激。
cls
# You need to either Select-Object -ExpandProperty or ().Property to get a list of user names (strings).
$users = (Get-DbaLogin -SqlInstance 'SERVER1.MYDOMAIN.COM' -Type 'Windows' | Where-Object { ($_.LoginType -eq 'WindowsUser') -and ($_.Name -like 'MYDOMAIN*') -and ($_.Name -notlike '$') }).Name
[System.Collections.ArrayList]$disabledUsers = @()
foreach ($user in $users)
{
# -split uses regex. You can use .NET .Split().
$samAccountName = $user.Split('\')[1] #$user.Name.Split('\')[1]
# Get-ADUser have a -Filter property. Where-Object is much more expensive.
$login = Get-ADUser -Identity $SamAccountName | Where-Object {($_.Enabled -eq $false)} | Select-Object @{name="Login"; expression={"MYDOMAIN\"+$_.SamAccountName}}
$logins += $login
# There is no need to split the user name, than join it again. If the disabled user exists, you add it to the list.
if ($adUser) {
$disabledUsers.Add($user)
}
}
# Remove-DbaLogin parameter -Login accepts a [string[]], we don't need to join, just convert our ArrayList to a string[]
Remove-DbaLogin -SqlInstance sql-dwh-dev -Login $disabledUsers.ToArray()