0

同僚から、次のことを行う PowerShell スクリプトを作成するように連絡がありました。

このスクリプトは、「Temp Associates」と呼ばれる AD セキュリティ グループの lastlogondate を読み取り、lastlogondate > または = = 現在の日付から 29 日後のアカウントを無効にし、無効な OU に移動します。無効にすると、説明も無効になった日付に変更されます。次に、無効になっているユーザーをリストしたレポートを作成し、当社のグローバル ヘルプデスクに電子メールで送信してください。

うまくいくはずなのにうまくいかないものをいくつかまとめました。スクリプトを実行すると、エラー メッセージは表示されず、データが入力されていないログ ファイルが生成されます。SOX 準拠を維持するために$PasswordAge = (Get-Date).adddays(-29)、現在要件を満たすアカウントがあるかどうかわからないため、テスト目的で値を操作できる必要があります。

電子メールは現在機能しており、send-mailmessage -credential パラメータで使用する PSCredential を作成する必要がありました。

私は間違いなく 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
}
4

2 に答える 2

0

直接の答えではありませんが、答えとして入れてください。

途中でチェックを実装していない場合は特に、何が間違っているのかを判断するのは非常に困難です。基本的なデバッグ戦略は、途中でいくつかの出力を追加して、スクリプトがセクションにヒットしているかどうかを確認することです。そのようなものでした:write-output "Entering Foreach"そしてwrite-output "Looping user $($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."
}
于 2014-08-08T18:18:40.253 に答える
0

のコードが実行されないことがわかりましたif。に置き換える必要があり$DisabledUsers.Count > 0ます$DisabledUsers.Count -gt 0

于 2015-03-13T13:41:17.403 に答える