Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Out put file information isn't complete

$
0
0

For some reason my out file is only showing me the information gathered from the last loop and I need it to show all of the information gathered during all of the loops. The below script is what I'm using and it does work just over writes it's self and I can't get it to stop. Thanks

Import-Module ActiveDirectory
#  Instructions:
#  Change $site variable
$sites = "*","*","*"
$ou = "*","*","*"
$counter = 0
$currentdate = Get-Date

#Loop through sites
foreach ($site in $sites) {

#Loop through OUs
foreach ($o in $ou) {

#Build LDAP search paths
$ldappath = "OU=" + $o + ",OU=USERS,OU=" + $site + ",OU=*,DC=*,DC=*,DC=*,DC=*"
$staleaccountldappath = "OU=Stale Accounts,OU=USERS,OU=" + $site + ",OU=*,DC=*,DC=*,DC=*,DC=*"

#Execute LDAP Query
$staleaccounts = Get-ADUser -searchscope subtree -searchbase $ldappath -Properties lastlogondate,whencreated,description -Filter * | select samaccountname, lastlogondate, whencreated, description, distinguishedname | where { $_.lastlogondate -le (Get-Date).AddDays(-45) -and $_.whencreated -le (Get-Date).AddDays(-30)} |sort-object samaccountname

#Loop through search results.
foreach ($i in $staleaccounts) {
$counter = $counter + 1

$olddescription = $i.description
$currentsite = $site

# Build Description Variable
$accountdescription = "Account disabled due to inactivity. Last Logon: " + $i.lastlogondate

# Change User Description
Set-ADuser $i.samaccountname -Description $accountdescription$accountdescription -WhatIf

#Disable Accounts
Disable-ADAccount -Identity $i.samaccountname -whatif

#Move Accounts to stale accounts OU.
Get-ADUser $i.samaccountname | Move-ADObject -TargetPath $staleaccountldappath -WhatIf
Write-Host $i.samaccountname, " ----- " , $i.whencreated, " ----- " , $i.lastlogondate

$alist = "SamAccountName`tDescription`tLastLogonDate`twhenCreated`tdistinguishedname`t`n"        
$staleaccounts | ForEach-Object {
  $arec = $_.SamAccountName,$_.Description,$_.LastLogonDate,$_.whenCreated,$_.Distinguishedname
  $aline = ($arec -join "`t") + "`t" + "`n"
  $alist += $aline
  $alist | Out-File ("c:\Temp\NotLoggedInForLast30Days.csv") 

}
 }
  }
   }       


Viewing all articles
Browse latest Browse all 15028

Trending Articles