I have a script which lists local admins of all hosts in Active Directory below:

$Searcher = New-Object DirectoryServices.DirectorySearcher([ADSI]"")
$Searcher.Filter = "(objectClass=computer)"
$Computers = ($Searcher.Findall())
md C:\All_Local_Admins
Foreach ($Computer in $Computers)
write-host $Name
$members =[ADSI]"WinNT://$Name/Administrators"
$members = @($members.psbase.Invoke("Members"))
$members | foreach {$_.GetType().InvokeMember("Name", 'GetProperty',
$null, $_, $null) | out-file -append C:\All_Local_Admins\$name.txt

This script outputs HOST machine names as txt files (HOST1.txt, HOST2.txt etc)

What I want is to get a single text file whose name gets the date of the day (for example: 05082014.txt --> This file will include local admins of all hosts)

How can I manage this?

Thank you very much.


You could do this:

$fileName = (Get-Date -Format ddMMyyyy) + ".txt"
$location = "C:\All_Local_Admins\"
New-Item -ItemType file -Name $fileName -Path $location 

And replace your out-file with this:

out-file -append -FilePath (Join-Path $location $fileName)
  • 3
    Nice. You could replace $location\$fileName with (Join-Path $location $fileName) to prevent a missing trailing slash if somebody else updates the $location – Mathias R. Jessen Aug 5 '14 at 17:09
  • @MathiasR.Jessen I edited the answer. Thanks for the tip. – slybloty Aug 5 '14 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.