tags:

views:

1178

answers:

2

Hi,

I got this Powershell script that queries users that have not changed their password for 24 hours. The query redirects the output to csv file. Below are the Powershell script and batch script:

Powershell script:

$root = [ADSI]''
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
$searcher.sizelimit = 5000

[Void]$searcher.PropertiesToLoad.Add("cn")
[Void]$searcher.PropertiesToLoad.Add("samAccountName")
[Void]$searcher.PropertiesToLoad.Add("pwdLastSet")

$users = $searcher.findall()

$UserOU = "OU=Mountain,DC=Atlanta,DC=ga"
$PWDays = (Get-Date).AddDays(-1)

$UserCount = 0
$UserPW = 0

foreach($user in $users)
    {

    if ($user.path -like "*$UserOU")
     {
     $usercount = $UserCount 

     if ([datetime]::FromFileTime(($user.properties.pwdlastset)[0]) -le $PWDays)
      {
      $UserPW = $UserPW + 1

      Write-Host $user.Properties.cn
      }
     }

    }

Batch script:

powershell.exe d:\temp\query.ps1 > D:\temp\query.csv

My question is: How do I put change the script to put header for username in the the csv output file?

The header may simple be 'Username' not necessarily Firstname and Lastname.

+1  A: 

Not sure (never have user PS) but I guess that sticking

Write-Host "Username"

before the foreach, might do the trick

Ken Egozi
+2  A: 

Any reason why you aren't using Export-Csv? You can just pipe your objects into it and it will include headers. Something along the lines of

$users | 
? { $_.Path -like "*$UserOU" } |
? { [datetime]::FromFileTime(($user.properties.pwdlastset)[0]) -le $PWDays } |
% { $_ | Add-Member -PassThru NoteProperty Username $_.Properties.cn } |
select Username |
Export-Csv D:\temp\query.csv

might work. (Hint: The pipeline is more fun than the loop :))

Joey
Thanks for the suggestion about Export-csv. I tried replacing the foreach with your code but I got "cannot index to a null array".
titanium
Actually I was just typing that without trying. It might as well not work but you might get the idea how to piece it together. The only place where there is an index is with (($user.properties.pwdlastset)[0]. Apparently that causes the error, but then should do so in your original script already.
Joey
Alternatively you can also just append the Export-Csv to your loops. I used Add-Member to add a property that can be used as header in the CSV.
Joey