Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Email 用于禁用非活动AD用户的Powershell脚本创建日志并发送电子邮件_Email_Powershell_Active Directory_User Inactivity - Fatal编程技术网

Email 用于禁用非活动AD用户的Powershell脚本创建日志并发送电子邮件

Email 用于禁用非活动AD用户的Powershell脚本创建日志并发送电子邮件,email,powershell,active-directory,user-inactivity,Email,Powershell,Active Directory,User Inactivity,一位同事已联系我创建PowerShell脚本,以执行以下操作: 脚本将读取名为“Temp Associates”的广告安全组的lastlogondate,禁用lastlogondate>或=当前日期后29天的帐户,并移动到禁用的OU。当它禁用时,也会将描述符更改为禁用日期。然后创建一份列出禁用用户的报告,并通过电子邮件发送到我们的全球帮助热线 我把一些东西汇编在一起,似乎它们应该有用,但却不行。当我运行脚本时,我没有收到任何错误消息,并且生成的日志文件没有填充任何数据。为了保持SOX合规性,我应

一位同事已联系我创建PowerShell脚本,以执行以下操作:

脚本将读取名为“Temp Associates”的广告安全组的lastlogondate,禁用lastlogondate>或=当前日期后29天的帐户,并移动到禁用的OU。当它禁用时,也会将描述符更改为禁用日期。然后创建一份列出禁用用户的报告,并通过电子邮件发送到我们的全球帮助热线

我把一些东西汇编在一起,似乎它们应该有用,但却不行。当我运行脚本时,我没有收到任何错误消息,并且生成的日志文件没有填充任何数据。为了保持SOX合规性,我应该能够以$PasswordAge=Get-Date.adddays-29为单位对该值进行调整,以便进行测试,因为我不确定我们目前是否有任何符合要求的帐户

电子邮件现在可以工作了,只需创建PSCredential以在send mailmessage-credential参数中使用

我绝对是PowerShell的新手,可以利用我能得到的所有帮助。任何改进现有代码或使用不同方法的建议都是受欢迎的,但如果可能的话,我想利用我已有的方法

代码如下:

#import the ActiveDirectory Module
Import-Module ActiveDirectory

#Create a variable for the date stamp in the log file
$LogDate = get-date -f yyyyMMddhhmm

#Sets the OU to do the base search for all user accounts, change for your env.
$SearchBase = "CN=Temp Associates,OU=Res Accounts,DC=our,DC=domain,DC=org"

#Create an empty array for the log file
$LogArray = @()

#Sets the number of days to disable user accounts based on lastlogontimestamp and pwdlastset.
$PasswordAge = (Get-Date).adddays(-29)

#Use ForEach to loop through all users with pwdlastset and lastlogontimestamp greater than date set. Also added users with no lastlogon date set. Disables the accounts and adds to log array.
#Add the properties you will be using to ensure they are available.
$DisabledUsers = (Get-ADUser -searchbase $SearchBase -Properties samaccountname, name, distinguishedname -filter {((lastlogondate -notlike "*") -OR (lastlogondate -le $Passwordage)) -AND (enabled -eq $True) -AND (whencreated -le $Passwordage)} )

if ($DisabledUsers -ne $null -and $DisabledUsers.Count > 0) {
    ForEach ($DisabledUser in $DisabledUsers) {

        #Sets the user objects description attribute to a date stamp. Example "11/13/2011"
        set-aduser $DisabledUser -Description ((get-date).toshortdatestring()) -whatif

        #Disabled user object. To log only add "-whatif"
        Disable-ADAccount $DisabledUser -whatif

        #Create new object for logging
        $obj = New-Object PSObject
        $obj | Add-Member -MemberType NoteProperty -Name "Name" -Value $DisabledUser.name
        $obj | Add-Member -MemberType NoteProperty -Name "samAccountName" -Value $DisabledUser.samaccountname
        $obj | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $DisabledUser.DistinguishedName
        $obj | Add-Member -MemberType NoteProperty -Name "Status" -Value 'Disabled'

        #Adds object to the log array
        $LogArray += $obj

    }

    # Move disabled users in Temp Associates group to Disabled OU 
    Search-ADAccount –AccountDisabled –UsersOnly –SearchBase “CN=Temp Associates,OU=Res Accounts,DC=our,DC=domain,DC=org”  | 
    Move-ADObject –TargetPath “OU=Disabled,DC=our,DC=domain,DC=org” -WhatIf

    #Exports log array to CSV file in the temp directory with a date and time stamp in the file name.
    $logArray | Export-Csv "C:\Temp\User_Report_$logDate.csv" -NoTypeInformation

    #Create PSCredential for use in e-mail -credential parameter
    $secpasswd = ConvertTo-SecureString "PasswordHere" -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ("UserHere", $secpasswd)

    #Send e-mail to Global Helpdesk with report generated
    $emailFrom = "smtp@address.com"
    $emailTo = "User@address.com" 
    $subject = "NA Disabled Temp Users to be deleted" 
    $smtpServer = "smtp.address.com"
    $attachment = "C:\Temp\User_Report_$logDate.csv"


    Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -SmtpServer $smtpServer -attachment $attachment -credential $mycreds
}else {
    Write-Output "No disabled users to process for $PasswordAge."

    #Create PSCredential for use in e-mail -credential parameter
    $secpasswd = ConvertTo-SecureString "PasswordHere" -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ("UserHere", $secpasswd)

    #Send e-mail to Global Helpdesk with report generated
    $emailFrom = "smtp@address.com"
    $emailTo = "User@address.com" 
    $subject = "NA Disabled Temp Users to be deleted" 
    $smtpServer = "smtp.address.com"
    $attachment = "C:\Temp\User_Report_$logDate.csv"
    Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -Body "No disabled users to process for $PasswordAge." -SmtpServer $smtpServer -credential $mycreds
}

把它作为一个答案,即使它不是一个直接的答案

很难说什么是错的,尤其是当你没有执行任何检查的时候。一个基本的调试策略是在整个过程中添加一些输出,以查看脚本是否命中了部分。这是:输入Foreach并写入输出循环用户$$DisabledUser.samaccountname以确保脚本正确执行。这将有助于确定你的呃逆在哪里

或者,我将首先查看Get ADUser查询。单独运行,确保它返回用户。如果没有,则返回预期结果

这是您的代码的修订版本,如果没有返回用户,它会进行错误检查

#import the ActiveDirectory Module
Import-Module ActiveDirectory

#Create a variable for the date stamp in the log file
$LogDate = get-date -f yyyyMMddhhmm

#Sets the OU to do the base search for all user accounts, change for your env.
$SearchBase = "CN=Temp Associates,OU=Res Accounts,DC=our,DC=domain,DC=org"

#Create an empty array for the log file
$LogArray = @()

#Sets the number of days to disable user accounts based on lastlogontimestamp and pwdlastset.
$PasswordAge = (Get-Date).adddays(-29)

#Use ForEach to loop through all users with pwdlastset and lastlogontimestamp greater than date set. Also added users with no lastlogon date set. Disables the accounts and adds to log array.
#Add the properties you will be using to ensure they are available.
$DisabledUsers = (Get-ADUser -searchbase $SearchBase -Properties samaccountname, name, distinguishedname -filter {((lastlogondate -notlike "*") -OR (lastlogondate -le $Passwordage)) -AND (enabled -eq $True) -AND (whencreated -le $Passwordage)} )

if ($DisabledUsers -ne $null -and $DisabledUsers.Count > 0) {
    ForEach ($DisabledUser in $DisabledUsers) {

        #Sets the user objects description attribute to a date stamp. Example "11/13/2011"
        set-aduser $DisabledUser -Description ((get-date).toshortdatestring()) -whatif

        #Disabled user object. To log only add "-whatif"
        Disable-ADAccount $DisabledUser -whatif

        #Create new object for logging
        $obj = New-Object PSObject
        $obj | Add-Member -MemberType NoteProperty -Name "Name" -Value $DisabledUser.name
        $obj | Add-Member -MemberType NoteProperty -Name "samAccountName" -Value $DisabledUser.samaccountname
        $obj | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $DisabledUser.DistinguishedName
        $obj | Add-Member -MemberType NoteProperty -Name "Status" -Value 'Disabled'

        #Adds object to the log array
        $LogArray += $obj

    }

    # Move disabled users in Temp Associates group to Disabled OU 
    Search-ADAccount –AccountDisabled –UsersOnly –SearchBase “CN=Temp Associates,OU=Res Accounts,DC=our,DC=domain,DC=org”  | 
    Move-ADObject –TargetPath “OU=Disabled,DC=our,DC=domain,DC=org” -WhatIf

    #Exports log array to CSV file in the temp directory with a date and time stamp in the file name.
    $logArray | Export-Csv "C:\Temp\User_Report_$logDate.csv" -NoTypeInformation

    #Send e-mail to Global Helpdesk with report generated
    $emailFrom = "sender@mail.com" 
    $emailTo = "recipient@mail.com" 
    $subject = "NA Disabled Temp Users to be deleted" 
    $smtpServer = "smtp.server.com"
    $attachment = "C:\Temp\User_Report_$logDate.csv"


    Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -SmtpServer $smtpServer -attachment $attachment
}else {
    Write-Output "No disabled users to process for $PasswordAge."
}

我发现if中的代码从未执行过。
您必须将$DisabledUsers.Count>0替换为$DisabledUsers.Count-gt 0

声音建议。我倾向于使用write verbose,它通过-verbose开关启用或禁用额外的输出。@是的,我通常也使用它,但在这样的脚本上下文中,我认为-verbose不起作用。它需要位于具有[CmdletBinding]的函数内部。但是,如果我错了,请纠正我。这会有用的。只需要添加[CmdletBinding]和一个空参数行。我想我已经发布了一个回复,感谢您的快速回复,但我没有看到它。无论如何,再次谢谢你。我已经做了您描述的更改以添加一些错误检查。我目前正在等待一个测试帐户被创建,然后我将确定它是否是功能齐全的。感谢您的详细和快速回复。因此,测试帐户已创建。我将$PasswordAge=Get-Date.adddays-29更改为$PasswordAge=Get-Date.adddays-1,但仍然没有禁用用户进行处理。我将更仔细地观察过滤器,但一切看起来都合乎逻辑。我不确定将$searchbase指定为组是否也会有问题。如果有人知道为什么即使我将$Passwordage降低到1,这也不会产生任何结果,请告诉我。欢迎提出任何建议。有人有什么想法/建议吗?我有很短的时间来研究这一点,但还没有弄清楚我的逻辑是怎么搞砸的。非常感谢您在这方面提供的所有帮助。因此,我有更多的时间来处理这一问题,看起来问题在于$searchbase要么无法正常工作,要么Get ADUser命令无法正常工作。我试图在$Searchbase中指定的容器是一个安全组。。。我开始怀疑Get ADUser是否不会与安全组合作?将继续努力解决问题,并希望找到解决办法。如往常一样,任何评论都将不胜感激。