Tuesday, August 12, 2008

Get or Add Local Group Members to a Remote Computer

Here are a couple of interesting Powershell scripts that can be used to automate the addition of network accounts from one or more AD domains into the local Administrators group on a networked server or computer. Script 1 will be used to add members of any trusted domain to the local Administrators group on a list of computers. In this example, I am going to add domain groups to the local Administrators group. Script 2 will be used to check group membership of the local Administrators group. The output of this script is exported to a spreadsheet to make review of the results easier.

Here is the scenario. Your manager emails you and says, 'Hey Patrick old chum, please add these domain accounts from these domains to the local administrative groups on these servers. To make sure that I keep my job I am going to use ficticious names of domains and server.

Step 1: Create a text file called "computers.txt" in the same folder as the scripts. Each line of the text file will have the name or IP address of a networked computer or server on which we want to modify the local Administrators group. Now keep in mind, this process can be set to modify any local group on the list of computers, but I've chose the Administrators group for the sake of this discussion.



Step 2: Adding the desired accounts to the Administrators groups on remote computers.

Here is the script that will be used to add the members to the local groups.
add_to_admingroups.ps1 to add
****************************************************************
#add_to_admingroup.ps1
#patrick parkison
#email: patrickparkison@bellsouth.net
#This script uses powershell to add domain accounts (user or groups) to the local administrators
#group on remote computers.
#
#Reference for working with local groups on remote servers.
#http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx

#Get the list of computers to manange.
#Iterate through the list of computers.
foreach($i in (gc .\computers.txt)){

#Write to screen for feedback.
Write-Host "Processing "$i

#Add first user/group to remote Administrators group.
$objUser = [ADSI](“WinNT://DomainA/GroupA")
$objGroup = [ADSI]("WinNT://$i/Administrators")
$objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

#Add second user/group to remote Administrators group.
$objUser = [ADSI](“WinNT://DomainB/GroupB")
$objGroup = [ADSI]("WinNT://$i/Administrators")
$objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

#Add third user/group to remote Administrators group.
$objUser = [ADSI](“WinNT://DomainC/GroupC")
$objGroup = [ADSI]("WinNT://$i/Administrators")
$objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

#Add fourth user/group to remote Administrators group.
$objUser = [ADSI](“WinNT://DomainD/GroupC")
$objGroup = [ADSI]("WinNT://$i/Administrators")
$objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

#Add more accounts as required.

}



This is pretty is a pretty simple script. There are only two key points to look at.
The iteration of the remote computers from the computers.txt file occurs here:

foreach($i in (gc .\computers.txt)){


$i becomes that value of each computer name in the text file.
The second key point is actuall connection and manipulation of the local groups. That is done here:
#Add first user/group to remote Administrators group. $objUser = [ADSI](“WinNT://DomainA/GroupA") $objGroup = [ADSI]("WinNT://$i/Administrators") $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

Notice that $i will contain the name of each remote computer. Also, Administrators could be replaced by any valid group name.

Here is how the output of the script looks when it runs.



$ Add_to_admingroup.ps1
Processing s30004w014011
Processing 10.87.52.198
$



You would get two possible errors with this script.


The first would be if the group or user account was already a member of the local group that you are updating. That error looks like this:



Exception calling "Invoke" with "2" argument(s): "Exception has been thrown by the target of an invocation."At I:\Utilities\PowerShellScripts\Local-Groups\add_to_admingroup.ps1:53 char:25+ $objGroup.PSBase.Invoke( <<<< "Add",$objUser.PSBase.Path)

The second error would be if the remote computer were not found on the network.



That takes care of the first script. Now here is a good method to check the membership of a specific group on a list of remote computers. As indicated above, the output is displayed in a spreadsheet.



The second script is called list_admin_group_members.ps1. Here is the text of the script.

list_admin_group_members.ps1
****************************************************************

#Assign account names to variables.
$group1 = "GroupName1"
$group2 = "GroupName2"
$group3 = "GroupName3"
$group4 = "GroupName4"

#Open a spreadsheet
#Region
$RowCount = 1
#http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept06/hey0908.mspx
$a = New-Object -comobject Excel.Application
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item($RowCount,1) = "Server"
$c.Cells.Item($RowCount,2) = $group1
$c.Cells.Item($RowCount,3) = $group2
$c.Cells.Item($RowCount,4) = $group3
$c.Cells.Item($RowCount,5) = $group4
$a.Range("A1:E1").Select()
$a.Selection.Font.Bold = $True
$a.Columns.AutoFit()
$a.Visible = $True

#EndRegion


foreach($i in (gc .\computers.txt)){
Write-Host "Processing server $i."
$script:RowCount += 1 #Increment row count.
$group =[ADSI]"WinNT://$i/Administrators"
$members = @($group.psbase.Invoke("Members"))
$adminGrp = $members foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
$c.Cells.Item($RowCount,1) = $i
$c.Cells.Item($RowCount,2) = ($adminGrp -contains $group1)
$c.Cells.Item($RowCount,3) = ($adminGrp -contains $group2)
$c.Cells.Item($RowCount,4) = ($adminGrp -contains $group3)
$c.Cells.Item($RowCount,5) = ($adminGrp -contains $group4)
}
$a.Range("B2").Select()
$a.ActiveWindow.FreezePanes = $True
$a.Columns.AutoFit()





Here is the part of that section that you'll want to modify:
$group1 = "GroupName1"
$group2 = "GroupName2"
$group3 = "GroupName3"
$group4 = "GroupName4"



This assigns that the actual text that you are looking for. You would change this to a real group name that exist in the domain(s) that you are searching.

There are two main sections to this script. The first section is used to setup the spreadsheet. This is pretty useful by itself. I've included the reference where I learned how to configure the spreadsheet. If you do much reporting you'll find that to be a pretty useful link.

$c.Cells.Item($RowCount,1) = "Server"
$c.Cells.Item($RowCount,2) = $group1
$c.Cells.Item($RowCount,3) = $group2
$c.Cells.Item($RowCount,4) = $group3
$c.Cells.Item($RowCount,5) = $group4


This sets up the first row of the spreadsheet, or the column header. You could added or remove the group names as required. Just add any addition groups in subsequent columns, i.e. $RowCount,X

The next three lines are used to manipulate the bold and width features of the spreadsheet. They simply make the spreadsheet more readable.

$a.Range("A1:E1").Select()
$a.Selection.Font.Bold = $True
$a.Columns.AutoFit()


The next section will iterate iterate through the text file computers.txt, and search the Administrators group on each computer.


foreach($i in (gc .\computers.txt)){

If you wanted to check the membership on a different group you would change that here.

$group =[ADSI]"WinNT://$i/Administrators"

This piece of code does the actual work of searching the remote computer for the group membership.

$group =[ADSI]"WinNT://$i/Administrators"
$members = @($group.psbase.Invoke("Members"))
$adminGrp = $members foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}

And for the output to the spreadsheet, for each cell the name of each domain account is checked against the value of $adminGrp.


If the value of $groupX is found in the contents of $adminGrp, then a True is placed into the current cell, other wise a False is placed into the current cell.

$c.Cells.Item($RowCount,2) = ($adminGrp -contains $group1)

Finally some final manipulation of the spreadsheet is done for neatness.

$a.Range("B2").Select()
$a.ActiveWindow.FreezePanes = $True
$a.Columns.AutoFit()

Here is how the output looks on the screen looks when the script is run:

$ .\list_admin_group_members.ps1
True
True
Processing server s30004w014011.
Processing server 10.87.52.198.
True
True
$

Also here is a screenshot of how the spreadsheet looks once the script has run:




That's it for this script. Please let me know if you have any questions, or issues when running this script.

Thanks
Patrick

Monday, July 28, 2008

Get-QADGroupMember

A friend of mine posed the following question to me today at work:

Do you have any script to input a security group (GG or DLG, etc) and dump/extract the members (SAMID and e-mail address) into a file (txt or csv)?

As a matter of fact I do have a script to do that, actually it is more of a one liner. Here is the text. The text in red would be replaced with whatever group you wanted:

Get-QADGroupMember grp-wism-admins select samaccountname, displayname, email Export-Csv -Path groupsearch.csv –NoTypeInformation

One caveat. For this to run you have to install the AD cmdlets from Quest Software. These are available free from Quest. These are very powerful, useful cmdlets which make working with Active Directory a breeze in Powershell.

The software download is available here:
http://www.quest.com/powershell/activeroles-server.aspx

You'll want to download and install the 32 or 64 bit version based on your hardware. You'll also want to download the PDF based Administrator's Guide. It details the install, and also gives good examples of the Quest cmdlets. Help on the Quest cmdlets is also available through standard Powershell help methods. i.e. help get-qadgroupmember -full

Let me know if you have any questions or comments.

Thanks
Patrick

Saturday, July 26, 2008

Working with ACLS

One thing I frequently do is to migrate data from one server to another. With that data migration comes lots of clean up in the form of security permissions. I've been working on a way to use Powershell to get the security perms on a folder. Here is what I have so far. It works pretty well. Currently the data written to the screen, as well as to a spreadsheet called Output.xls.

Some more areas I want to add:
1. Make the spreadsheet an option by adding a switch /excel.
2. Make the spreadsheet activity part of a function call.

Let me know if you have any quesitons, or recommendations.

Here is the script text:
***********************************************************************************

# Inputbox - Prompt for path to scan
$x = New-Object -comobject MSScriptControl.ScriptControl
$x.language = "vbscript"
$x.addcode("function getInput() getInput = inputbox(`"Enter the path to scan.`",`"Path`") end function")
$path = $x.eval("getInput")
#delete old output file.
Remove-Item .\output.xls -force Out-Null
#Open a spreadsheet
#Region
$RowCount = 1

#Nice reference for the Excel activity.
#http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept06/hey0908.mspx
$a = New-Object -comobject Excel.Application
#$a.Visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item($RowCount,1) = "Path"
$c.Cells.Item($RowCount,2) = "Owner"
$c.Cells.Item($RowCount,3) = "Account and Perm"
#EndRegion
function scanACLs($strPath )
{
$owner = ($strPath Get-Acl select owner)
$ownerTemp = $owner.Owner
#$pathTemp = $strPath.PSChildName
$strPath Get-Acl select accesstostring fl Out-File -Force -Width 200 -filepath .\temp.txt
#Combine path and perms for output.
foreach ($i in(gc .\temp.txt))
{
#Split if string contains 'AccessToString'
if ($i.contains("AccessToString"))
{
$strTemp = (($i.split(":"))[1]).trim()
Write-Host "Owner:$ownerTemp Perms:$strTemp"
$script:RowCount += 1
$c.Cells.Item($RowCount,1) = $strPath
$c.Cells.Item($RowCount,2) = $ownerTemp
$c.Cells.Item($RowCount,3) = $strTemp
}
elseif ($i.length -gt 0)
{
$strTemp = $i.trim()
Write-Host "Owner:$ownerTemp Perms:$strTemp"
$script:RowCount += 1
$c.Cells.Item($RowCount,1) = $strPath
$c.Cells.Item($RowCount,2) = $ownerTemp
$c.Cells.Item($RowCount,3) = $strTemp
}
}
}
#Main
#This will go through the folder obtained in the Message Box at the launch of the script.
#The function scanACLS is called for each child item.
foreach ($i in(dir $path sort name))
{
Write-Host "Scanning "$path"\"$i
scanACLs($path+"\"+$i)
#
}
#Save the spreadsheet and make it visible once it is loaded with all of the data from the scanning.
$b.SaveAs("$pwd\output.xls")
$a.Visible = $True

Thursday, July 24, 2008

Powershell - Get AD User Info

Frequently during my daily work I need to gather information on users that are contained in our Active Directory listing.
This script is used to quickly gather information on a users home folder, SAM account name, their email address, and the size of their home folder.

I use this a lot when I am moving users home folders from one server to another. To save time I frequently have the line that gathers home folder size remarked out with #.

The user account names that I am searching for are contained in a text file called
accounts.txt. This file is contained in the same folder as this script. The output is sent to the screen as well as a log file called output.csv.


$userArray = @("SAMID,HomeDirectory,EmailAdress,HomeFolderSize")
$allUsers = gc .\accounts.txt
$tempArray = @()
function logfile($strData)
{
Out-File -filepath output.csv -inputobject $strData -append
}
function getAccountInfo
{
$strName = $currentUser
$strFilter = "(&(objectCategory=User)(samAccountName=$strName))"
#Get User AD info
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
[string]$folder = $objUser.homeDirectory
[string]$email = $objUser.mail
[string]$samID = $objUser.sAMAccountName
[string]$folderSize= getFolderSize($objUser.homeDirectory)
#$objUser.memberOf

$result = "$samID,$folder,$email,$folderSize"
$result #This causes the output to steam out, and be piped as the return from the function.
$folderSize = $null
$fs = $null
}
function getFolderSize($strPath)
{
$fs = New-Object -comobject Scripting.FileSystemObject
#Check validity of $strPath
if ($fs.FolderExists($strPath))
{
[double]$tempSize = ($fs.GetFolder($strPath).size) / 1024 / 1024
$tempSize = '{0:N}' -f[double]$tempSize
$tempSize
}
else
{
$tempSize = "Bad folder path!"
$tempSize
}
}
$header = "SAMID,HomeDirectory,EmailAdress,HomeFolderSize"
Out-File -filepath output.csv -inputobject $header
foreach ($currentUser in $allUsers)
{
$tempOutput = getAccountInfo $currentUser
$tempOutput
$userArray += [string[]]$tempOutput
logfile($tempOutput)
}


Let me know if you have any questions about this, or if it is helpful.

Thanks
Patrick