Reputation: 168
I am using the following Powershell from http://iislogs.com/steveschofield/2009/01/09/list-local-administrators-on-a-machine-using-powershell-adsi/ to extract the local and domain admin accounts configured in PC and servers of an internal network.
Powershell script is below:
function LogToFile ([string]$strFileName, [string]$strComputer)
{
Add-Content $strFileName $strComputer
}
$strComputer = “server1.loc.mydomain.com”
$computer = [ADSI](“WinNT://” + $strComputer + “,computer”)
$Group = $computer.psbase.children.find(“Administrators”)
$members= $Group.psbase.invoke(“Members”) | %{$_.GetType().InvokeMember(“Name”, ‘GetProperty’, $null, $_, $null)}
ForEach($user in $members)
{
Write-Host $user
$a = $strComputer + “!” + $user.ToString()
LogToFile “C:\local-admins.txt” $a
}
When executed, it produces results in the txt file in following format:
server1.loc.mydomain.com!Administrator
server1.loc.mydomain.com!JohnDoe
server1.loc.mydomain.com!Support
server1.loc.mydomain.com!Domain Administrators
Can someone help me to change the output on txt file, so the results are shown in this format:
server1.loc.mydomain.com!Administrator!JohnDoe!Support!Domain Administrators
If reported in this way, then I can easily export to csv and work with it. It'd be super cool if this can be transformed to export on CSV in desired format instead of txt.
I am a complete novice in PS, but trying to piece things together to address my needs and hope you may provide me with needed help.
Thanks.
Upvotes: 0
Views: 1784
Reputation: 174990
To change the output to have all accounts in one line, change the foreach()
loop at the bottom to just:
$a = @($strComputer;$members) -join '!'
LogToFile "C:\local-admins.txt" $a
To generate a list of servers with successive numbers in their name, use the range operator ..
:
$serverNames = foreach($number in 1..38){
'server{0}' -f $number
}
So you end up with something like:
function LogToFile ([string]$strFileName, [string]$strComputer)
{
Add-Content $strFileName $strComputer
}
foreach($ServerNumber in 1..38){
$ServerName = 'server{0}.loc.mydomain.com' -f $ServerNumber
$Computer = [ADSI]("WinNT://$ServerName,computer")
$Group = $Computer.psbase.children.Find('Administrators')
$Members= $Group.psbase.invoke('Members') |ForEach-Object { $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null) }
$Output = @($ServerName;$members) -join '!'
LogToFile 'C:\local-admins.txt' $Output
}
Upvotes: 1