Powershell脚本不一致的行为

时间:2018-05-16 14:45:14

标签: powershell active-directory

我有两个基于废弃帐户的PowerShell脚本。这些脚本应该排除我们环境中的六个特定OU。第一个报告所有需要采取行动的帐户。第二个采取行动,并根据相同的标准禁用帐户。

由于我无法弄清楚的原因,禁用脚本会在多个OU中留下用户,而不会对其执行操作。任何帮助都将不胜感激。

以下是报告版本:

  import-module activedirectory

$datestring = Get-Date -f MM-dd-yyyy
$oldDate = [DateTime]::Today.AddDays(-45)
$OUDN1 = "OU=Resource accounts,OU=Domain Users,DC=placeholder,DC=org"
$OUDN2 = "OU=Service Accounts,OU=Domain Users,DC=placeholder,DC=org"
$OUDN3 = "OU=DO NOT DELETE,OU=Disabled Accounts,DC=placeholder,DC=org"
$OUDN4 = "CN=Users,DC=placeholder,DC=org"
$OUDN5 = "OU=User Templates,OU=Domain Users,DC=placeholder,DC=org"
$OUDN6 = "CN=Microsoft Exchange System Objects,DC=placeholder,DC=org"

Get-ADUser -filter {(Enabled -eq $True) -AND ((LastLogonDate -lt $olddate) -OR ((LastLogonDate -notlike "*") -AND (WhenCreated -lt $olddate)))} -Properties DisplayName,Name,LastLogonDate,Modified,info,description,sAMAccountName,WhenCreated | Where-Object {($_.DistinguishedName -notlike "*,$OUDN1") -and ($_.DistinguishedName -notlike "*,$OUDN2") -and ($_.DistinguishedName -notlike "*,$OUDN3")-and ($_.DistinguishedName -notlike "*,$OUDN4") -and ($_.DistinguishedName -notlike "*,$OUDN5") -and ($_.DistinguishedName -notlike "*,$OUDN6")} | Select sAMAccountName,Name,description,LastLogonDate,WhenCreated,Modified,DistinguishedName | Export-CSV c:\Reports\nolog45_$datestring.csv

这是行动版本:

import-module activedirectory

$disUsers = @()
$oldDate = [DateTime]::Today.AddDays(-45)
$OUDN1 = "OU=Resource accounts,OU=Domain Users,DC=placeholder,DC=org"
$OUDN2 = "OU=Service Accounts,OU=Domain Users,DC=placeholder,DC=org"
$OUDN3 = "OU=DO NOT DELETE,OU=Disabled Accounts,DC=placeholder,DC=org"
$OUDN4 = "CN=Users,DC=placeholder,DC=org"
$OUDN5 = "OU=User Templates,OU=Domain Users,DC=placeholder,DC=org"
$OUDN6 = "CN=Microsoft Exchange System Objects,DC=placeholder,DC=org"

$disUsers = Get-ADUser -filter {(Enabled -eq $True) -AND (LastLogonDate -lt $olddate)} -Properties sAMAccountName,Name,SID,Enabled,LastLogonDate,Modified,info,description,DistinguishedName | Where-Object {($_.DistinguishedName -notlike "*,$OUDN1") -and ($_.DistinguishedName -notlike "*,$OUDN2") -and ($_.DistinguishedName -notlike "*,$OUDN3")-and ($_.DistinguishedName -notlike "*,$OUDN4") -and ($_.DistinguishedName -notlike "*,$OUDN5")  -and ($_.DistinguishedName -notlike "*,$OUDN6")} 

foreach ($name in $disUsers) {
        $DistName = $name.DistinguishedName
        Disable-ADAccount -Identity $DistName -ErrorAction Continue
        }

例如,今天运行了30个帐户,报告脚本仍然启用了这些帐户。这不是权限,因为我可以手动禁用相同的帐户,没有任何问题。没有生成红色文本,没有错误输出 - 只是看似忽略了帐户。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

两个脚本中的标准不一样。

您的报告脚本具有此功能,您的操作脚本不会:

 -OR ((LastLogonDate -notlike "*") -AND (WhenCreated -lt $olddate))