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

No comments: