Piping output from -whatif to a file


I am sure this is a beginner question here but I am unable to find anything online about it.
I am trying to disable user accounts that have not logged into the domain for over 10 days. I am able to pull a list with the following:
Search-ADAccount -AccountInactive -TimeSpan ([timespan]10d) -UsersOnly | Set-ADUser -Enabled $false -whatif | Export-Csv -Path C:\inactive_users.csv

I see the list, but would like to go through it manually to make sure accounts that are needed do not get deleted. The problem is that when I pipe it to export-csv, it creates a blank file with nothing in it even though I do see the list on the screen

Is there something I am missing? Also, how can I tell it to look in certain OU’s and not the whole domain?

Any help would be greatly appreciated.


To search a particular OU use the -SearchBase parameter to define the OU (by distinguished name)

Whatif appears to be similar to write-hoist in that it writes directly to screen.

One suggestion would be to use start/stop-transcripot round your command - the output of this will be captured

Hello Matthew,

You don’t need to use -WhatIf to get the expected result for your review. The Search-ADAccount cmdlet returns ADUser objects with the Enabled property which you can use to filter for only enabled inactive users, select the properties required in your CSV and pipe to Export-Csv.

Search-ADAccount -AccountInactive -TimeSpan ([timespan]10d) -UsersOnly |
Where-Object -FilterScript { $_.Enabled -eq $true } | Select-Object -Property SamAccountName, LastLogonDate, DistinguishedName |
Export-Csv -Path C:\enabled_inactive_users.csv -NoTypeInformation

I hope above helps.