Powershell Menu and AD Search

I thought my script to find nested groups in AD would be even better if I could find the group and then search for it using a menu or a form.
 
Because there was a fixed number of groups marketing was looking for I went with a menu.
 
 
#### Begin Script ######
 
function get-dn($SAMName){
$root = [ADSI]''
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = '(&(objectClass=*)(cn= $SAMName*))' #<-- This is the CN or common name
$user = $searcher.findall()
if ($user.count -gt 1)
{
$count = 0
foreach($i in $user)
	{ Write-Host $count ':'$i.path
	$count = $count + 1
	}
$selection = Read-Host 'Please select item: '
return $user[$selection].path
}   else
	{  return $user[0].path
	}
}

function DrawMenu {    
	## supportfunction to the Menu function below
    param ($menuItems, $menuPosition, $menuTitel)
	$fcolor = $host.UI.RawUI.ForegroundColor
    $bcolor = $host.UI.RawUI.BackgroundColor
    $l = $menuItems.length + 1
    cls
    $menuwidth = $menuTitel.length + 4
    Write-Host '`t' -NoNewLine
    Write-Host ('*' * $menuwidth) -fore $fcolor -back $bcolor
    Write-Host '`t' -NoNewLine
    Write-Host '*' $menuTitel *' -fore $fcolor -back $bcolor
    Write-Host '`t' -NoNewLine
    Write-Host ('*' * $menuwidth) -fore $fcolor -back $bcolor
    Write-Host ''
    Write-Debug 'L: $l MenuItems: $menuItems MenuPosition: $menuposition'
    for ($i = 0; $i -le $l;$i++) {
	Write-Host '`t' -NoNewLine
	if ($i -eq $menuPosition) {
	Write-Host '$($menuItems[$i])' -fore $bcolor -back $fcolor
	} else {
	Write-Host '$($menuItems[$i])' -fore $fcolor -back $bcolor
			}    
		}
	}
 ## Generate a small 'DOS-like' menu.
 ## Choose a menuitem using up and down arrows, select by pressing ENTER
function Menu {    
    param ([array]$menuItems, $menuTitel = 'MENU')
	$vkeycode = 0
    $pos = 0
    DrawMenu $menuItems $pos $menuTitel
    While ($vkeycode -ne 13) { 
	$press = $host.ui.rawui.readkey('NoEcho,IncludeKeyDown')
	$vkeycode = $press.virtualkeycode
	Write-host '$($press.character)' -NoNewLine
	If ($vkeycode -eq 38) {$pos--}
	If ($vkeycode -eq 40) {$pos++}
	if ($pos -lt 0) {$pos = 0}
    if ($pos -ge $menuItems.length) {$pos = $menuItems.length -1}
	DrawMenu $menuItems $pos $menuTitel
		}    
		Write-Output $($menuItems[$pos])
	}
 
function get-NestedMembers ($group){
  if ($group.objectclass[1] -eq 'group') {
  write-verbose 'Group $($group.cn)' 
  $Group.member |% { 
  $de = new-object directoryservices.directoryentry('<a>LDAP://$</a>_')  
  if ($de.objectclass[1] -eq 'group') {
  get-NestedMembers $de  
  }  Else {
  $ws.cells.item($row,1) = $de.givenname.tostring()
  $ws.Cells.Item($row,2) = $de.SN.tostring()
  $ws.Cells.Item($row,3) = $de.mail.tostring()
  $row++
      }  
    }  
  } 
  Else {
    Throw '$group is not a group' 
  }  
  } 
 
Function xl($path) {
$xlSummaryAbove = 0 
$xlSortValues = $xlPinYin = 1 
$xlAscending = 1 
$xlDescending = 2
$xl = New-Object -comobject excel.application 
$xl.Visible = $true 
$wb = $xl.Workbooks.Add() 
$ws = $wb.Worksheets.Item(1) 
$row = 2
$group = New-Object directoryservices.directoryentry($path)
 $N = $group.Name.tostring()
 $N = $N.Substring(0,29)
 $ws.name = $N.tostring()
 $ws.Cells.Item(1,1) = 'First Name'
 $ws.Cells.Item(1,2) = 'Last Name'
 $ws.Cells.Item(1,3) = 'EMail Address' 
 $range = $ws.range('A1:C1')
 $range.font.bold = 'true' 
# Call the function
get-NestedMembers $group
# one-column sort --> works 
$range1 = $ws.range('A2:C2500')
$range2 = $ws.range('B2')
[void]$range1.sort($range2, $xlAscending)
[void]$range1.entireColumn.Autofit() }

$ErrorActionPreference = 'silentlycontinue' 
$crdm = ' in house marketing',' marketing','marketing support' #<-- Menu items go here
$selection = Menu $crdm 'WHAT DO YOU WANNA DO?'
$path = get-dn $selection
xl($path)
get-NestedMembers($path)
##### End Script ######
And a different version in vbScript that uses a HTA menu.
 
<html>
<head>
<title>Get Mail Group Members from AD</title>
<HTA:APPLICATION
     ID=”objADSPath-GM”
     APPLICATIONNAME=”Get Mail Group Members”
     SCROLL=”off”
     SINGLEINSTANCE=”yes”
>
</head>
<script language=”VBScript”>
Sub Window_Onload
   self.Focus()
   self.ResizeTo 900,600
End Sub
Sub RunScript
On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
xlDown = -4121
xlToRight = -4161
xlSummaryAbove = 0
xlSortValues = xlPinYin = 1
xlAscending = 1
xlDescending = 2
xlTopToBottom = 1
xlGuess = 0
xlDescending = 2
 
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.add
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Range(“A1:E1”).Font.Bold = True
iRow = 2
objWorksheet.Cells.Item(1,1) = “First Name”
objWorksheet.Cells.Item(1,2) = “Last Name”
objWorksheet.Cells.Item(1,3) = “EMail Address”
objWorksheet.range(“A1:C1”).font.bold = “true”
 Set objConnection = CreateObject(“ADODB.Connection”)
 Set objCommand = CreateObject(“ADODB.Command”)
 objConnection.Provider = “ADsDSOObject”
 objConnection.Open “Active Directory Provider”
 Set objCommand.ActiveConnection = objConnection
 objCommand.Properties(“Page Size”) = 1
 objCommand.Properties(“Searchscope”) = ADS_SCOPE_SUBTREE
If AD_Obj(0).Checked Then
        ADobj = AD_Obj(0).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(1).Checked Then
        ADobj = AD_Obj(1).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(2).Checked Then
        ADobj = AD_Obj(2).Value
     statval.value = ADobj & vbTab
    End If
  If AD_Obj(3).Checked Then
        ADobj = AD_Obj(3).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(4).Checked Then
        ADobj = AD_Obj(4).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(5).Checked Then
        ADobj = AD_Obj(5).Value
     statval.value = ADobj & vbTab
    End If 
If AD_Obj(6).Checked Then
        ADobj = AD_Obj(6).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(7).Checked Then
        ADobj = AD_Obj(7).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(8).Checked Then
        ADobj = AD_Obj(8).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(9).Checked Then
        ADobj = AD_Obj(9).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(10).Checked Then
        ADobj = AD_Obj(10).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(11).Checked Then
        ADobj = AD_Obj(11).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(12).Checked Then
        ADobj = AD_Obj(12).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(13).Checked Then
        ADobj = AD_Obj(13).Value
     statval.value = ADobj & vbTab
    End If
    If AD_Obj(14).Checked Then
        ADobj = AD_Obj(13).Value
     statval.value = ADobj & vbTab
    End If
   
If ADobj = “” Then
   Exit Sub
End If
 objCommand.CommandText = “SELECT Adspath FROM ‘LDAP://” & DNC & “‘” & _
   ” WHERE name='” & ADobj & “‘” & ” OR sAMAccountName='” & ADobj & “‘”
  
 Set objRecordSet = objCommand.Execute
 objRecordSet.MoveFirst
 If Err <> 0 Then
  If Err.Number = 3021 Then
   TxtADSPath.Value = Trim(AD_Obj.Value) & ” Not Found!!!”
  Else
   TxtADSPath.Value = Err.Number & ” ” & Err.Description
  End If
  txtou.Value = “”
  Err.Clear
  Exit Sub
 End If
 arrAD = Split(objRecordSet.Fields(“AdsPath”).Value, “,”)
 For i = 0 to Ubound(arrAD)
  If InStr(arrAD(i), “OU=”) Or InStr(arrAD(i), “LDAP://OU=”) Then
   iLength = Len(arrAD(i))
   leading = iif(InStr(arrAD(i),”LDAP://OU=”),10,3)
   OULength = iLength – leading
   OU = Right(arrAD(i), OULength)
   Exit For
  End If
 Next
 txtou.Value = OU
 TxtADSPath.Value = objRecordSet.Fields(“Adspath”).Value
 group = TxtADSPath.Value
Set objGroup = GetObject(TxtADSPath.Value)
Name = mid(objGroup.Name, instr(1,objGroup.Name,”=”) + 1 ) ‘set Worksheet name to that of the DL 
objWorksheet.Name = Left(Name, 30)
 
 For Each strUser In objGroup.Member
   Set objUser =  GetObject(“LDAP://” & strUser)
    objWorksheet.Cells(iRow,1) = objUser.GivenName
    objWorksheet.Cells(iRow,2) = objUser.SN
    objWorksheet.Cells(iRow,3) = objUser.mail
    iRow=iRow + 1
 Next
 
Set objRange = objWorksheet.UsedRange
Set objRange = objExcel.Range(“A2:B2500”)
Set objRange2 = objExcel.Range(“B2”)
    objRange.Sort objRange2,1,,,,,,,1
 objWorksheet.Cells.EntireColumn.AutoFit()
 objRecordSet.MoveNext
 
 statval.value = ADobj & VbCrLf & “All Done”
End Sub
Sub Window_onLoad
window.resizeTo 1024, 768
End Sub
Sub ExitHTA
    self.close()
End Sub
Function XL(group)
End Function
Function iif(cond,t,f)
 If cond Then
  iif = t
 Else
  iif = f
 End If
End Function
</script>
<BODY>
<body STYLE=”font:14 pt arial; color:white;
 filter:progid:DXImageTransform.Microsoft.Gradient
(GradientType=1, StartColorStr=’#000000′, EndColorStr=’#0000FF’)”>
<p align=”center”>
AD Mail Groups<p>
<!– Make sure you have the correct sAMAccountName in the value section. –>
<input type=”radio” name=”AD_Obj” value=”in house marketing”>In house marketing<br>
<input type=”radio” name=”AD_Obj” value=”Sales and Marketing Dirs and VPs”>Sales and Marketing Dirs and VPs<br>
<input type=”radio” name=”AD_Obj” value=”Marketing support”>Marketing support<br>
<input type=”radio” name=”AD_Obj” value=”In house marketing”>In house marketing<br>
<input type=”radio” name=”AD_Obj” value=”US Field Marketing”>US Field Marketing<br>
<input type=”radio” name=”AD_Obj” value=”Regional Contract Managers”>RCM Regional Contract Managers<br>
<input type=”radio” name=”AD_Obj” value=”RISA”>RISA<br>
<input type=”radio” name=”AD_Obj” value=”Corporate Sales”>Corporate Sales<br>
<input type=”radio” name=”AD_Obj” value=”Field Force Training”>Field Force Training<br>
<input type=”radio” name=”AD_Obj” value=”Field HR Generalists”>Field HR Generalists<br>
<input type=”radio” name=”AD_Obj” value=”Marketing”>Marketing<br>
<input type=”radio” name=”AD_Obj” value=”Sales and Clinical US Distlist”>Sales and Clinical US Distlist<br>
<input type=”radio” name=”AD_Obj” value=”Marketing DistList”>Marketing DistList<br>
<input type=”radio” name=”AD_Obj” value=”Entire US Sales Force”>Entire US Sales Force<br>
<input type=”radio” name=”AD_Obj” value=”Sales and Service Operations”>Sales and Service Operations<p>
<br>
<br>
<p align=”center”>
<input type=”button” value=”Get Group Members” name=”GetGM” onclick=”RunScript”><p>
<p align=”center”>
AdsPath
<input type=”text” name=”TxtADSPath” size=”145″ readonly><p>
<p align=”center”>
OU
<input type=”text” name=”txtOU” size=”20″ readonly><p>
<p align=”center”>
    <textarea rows=”2″ name=”statval” READONLY cols=”75″ style=”text-align:center”>Status Box</textarea></p>
<p align=”center”>
<input type=”BUTTON” name=”button1″ value=”Exit” onclick=self.close>
</BODY>
</html>
Advertisements

10 thoughts on “Powershell Menu and AD Search

  1. Excellent post. I was checking constantly this weblog and I am impressed! Extremely helpful info specially the remaining section 🙂 I deal with such information a lot. I was seeking this particular info for a very long time. Thank you and best of luck.

  2. Just after study a couple of of the weblog posts on your site now, and I genuinely like your way of blogging. I bookmarked it to my bookmark web-site list and will probably be checking back soon. Pls look into my internet web-site at the same time and let me know what you assume.

  3. Aw, this was a genuinely nice post. In concept I would like to put in writing like this additionally – taking time and actual effort to create an extremely fantastic article… but what can I say… I procrastinate alot and by no means appear to get one thing done.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s