Output filename using Returned value


Its probably a simple question. I would like to retrieve a specific AD value for All AD users, and output the results to a <SamAccountName>.txt file. I also want to make sure the output is trimmed. Its probably a For-Each to cycle through all users. So for example, say i wanted to retrieve the “logonCount” for user JSmith. The manual command would be:

(Get-ADUser JSmith -Properties * | select logonCount | ft -HideTableHeaders | Out-String).trim() | Out-File Jsmith.txt

HI Joe,


You can acheive this by piping the output of the Get-ADUser cmdlt into a Select-Object command with the -Property parameter like this


Get-ADuser -filter * -properties logoncount | `
select-object -property Samaccountname,logoncount | `
ConvertTo-Csv -NoTypeInformation | `
Select-Object -Skip 1 | `
Out-File Userlogins.txt

This also strips out the header while still keeping the results as an object that gets piped from each command


Thanks for the response

In my case, i need each users count to be outputted to a separate file, saved as SamAccountName.txt and contain “just” the logon count value (e.g. 100)


No worries,

That is fairly straightforward to accomplish, just not in a one-liner

$users = Get-ADuser -filter * -properties logoncount | select-object -property Samaccountname,logoncount

foreach ($user in $users)
        $user.logoncount | out-file "$($user.Samaccountname).txt"


This time i have saved the results from the Get-ADUser cmdlet and used the Select-object cmdlet to filter the returning object so that it only contains two properties;

Logoncount and SamAccountName

I have then just looped through the object and exported the Logoncount property for each object and used the SamAccountName property to name the file.


Awesome! This is perfect. Just one last question. How do i get it to trim (slimier to the -skip 1). For example, if use this method to retrieve PasswordLastSet, then the text file has the first line empty. The results is on the second line.

That is odd, i dont know why its putting it on the second line.

It may have something to do with how the PasswordLastSet property is displayed, and because we are just writing the output of that property to a file.


Lets try doing it properly by using the New-item cmdlet.


$users = Get-ADuser -filter * -properties PasswordLastSet | select-object -property Samaccountname,PasswordLastSet

foreach ($user in $users)
       new-item -path "$($user.Samaccountname).txt" -Value $user.PasswordLastSet


That looks like it is working the way you need it.

May i ask why you need individual files with single properties?

It would be much easier to gather the data you want and output it into a single CSV with the named headers you need.

Thanks Conor! This solution seems to work well! Im testing a few scenarios.

I just needed to add “-Type file”