troubleshooting Question

Use Powershell to Loop Through Worksheets in an Excel Workbook

Avatar of Justin Owens
Justin OwensFlag for United States of America asked on
Microsoft ExcelPowershell
12 Comments1 Solution13095 ViewsLast Modified:
Hello, Experts!

The current code below requires an argument for worksheet name.  I would like to somehow programatically look up all the worksheet names in the workbook and then perform the WHILE below.  I have no idea how to go about doing this.

param($ExcelFile, $SaveAs, $WorkSheetNum)
$Excel = New-Object -ComObject Excel.Application
$WorkBook = $Excel.Workbooks.Open($ExcelFile)
$WorkSheet = $WorkBook.WorkSheets.Item($WorkSheetNum)
$RowNum = 2
While ($WorkSheet.Cells.Item($RowNum, 1).Text -ne "") {
    # Read the first name and last name from the sheet
    $userFullName = $WorkSheet.Cells.Item($RowNum, 1).Text
    # Divide the first namd and last name into two different variables  
    $userFirstName = $userFullName.Split()[0]
    $userLastName = $userFullName.Split()[1]
    #Here I am querying AD for a possible last name & first name match and writing it back to the spreadsheet.
    $LdapFilter = "(&(objectClass=user)(objectCategory=person)(givenName=$userFirstName)(sn=$userLastName))" 
    #Write-Host $LdapFilter
    $Results = (New-Object DirectoryServices.DirectorySearcher($LdapFilter)).FindAll()
    if ($Results.Count -eq 0)
        $WorkSheet.Cells.Item($RowNum, 3).Value2 = "Unable to find a username match."
        elseif ($Results.Count -gt 1)
        $WorkSheet.Cells.Item($RowNum, 3).Value2= "Too many matches: ($($Results.Count))"
        $WorkSheet.Cells.Item($RowNum, 3).Value2 = $Results[0].Properties["samaccountname"][0].ToString()
"Batchelor", Developer and EE Topic Advisor
Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros