0

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
  • Your users have to change their password every 24 hours? You're a mean sysadmin >:) Commented Jun 25, 2009 at 20:58

2 Answers 2

3

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 :))

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the suggestion about Export-csv. I tried replacing the foreach with your code but I got "cannot index to a null array".
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.
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.
1

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

Write-Host "Username"

before the foreach, might do the trick

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.