Solved

VB.NET - Find computer in Active Directory and display OU

Posted on 2014-10-08
8
777 Views
Last Modified: 2014-10-13
I have some code where it first moves the computer into a different OU and then I want it to confirm the change by displaying the OU it is now in in a list view.

The problem is that it is not working!

Can someone help please?
    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        If txtFile.Text Is "" Then
            MessageBox.Show("You have not selected a file to process", "No file selected", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            ListView1.Items.Clear()
            On Error Resume Next
            lblStatusBar.Text = "Working..."
            Dim text As String = txtFile.Text
            Dim PC As String = IO.File.OpenText(text).ReadLine
            Dim objsrc As DirectoryEntry
            Dim objdest As DirectoryEntry
            Dim file As New FileInfo(text)

            Dim sB As Long = file.Length
            Dim cR As Long = 0
            ProgressBar1.Maximum = 100
            Dim reader2 As New StreamReader(text)
            Dim Counter As Integer = 0

            Do While Not reader2.EndOfStream
                PC = reader2.ReadLine
                Cursor = Cursors.WaitCursor
                cR = cR + PC.Length
                ProgressBar1.Value = (cR / sB) * 100
                Application.DoEvents()

                'Dim CurrentOUPath As New DirectoryEntry("LDAP://CN=" & PC & ",OU=Systems,OU=Computers,OU=factory,OU=area,DC=UK,DC=company,DC=com")
                Dim CurrentOUPath As New DirectoryEntry("LDAP://CN=" & PC & ",OU=PSPS,OU=Computers,OU=factory,OU=area,DC=UK,DC=company,DC=com")
                CurrentOUPath.MoveTo(New DirectoryEntry("LDAP://OU=Systems,OU=Computers,OU=factory,OU=area,DC=UK,DC=company,DC=com"))
                System.Threading.Thread.Sleep(500)

                Dim entry As DirectoryEntry = New DirectoryEntry("LDAP://DC=UK,DC=company,DC=com")
                Dim searcher As New DirectorySearcher(entry)
                searcher.Filter = ("(&(objectclass=computer)name=" & PC & "))")
                searcher.PropertiesToLoad.Add("ou")
                Dim OUresult As SearchResultCollection
                OUresult = searcher.FindAll()
                Dim result As SearchResult
                For Each result In OUresult
                    If OUresult Is Nothing Then
                        Dim lvi As New ListViewItem
                        lvi = ListView1.Items.Add(PC)
                        lvi.SubItems.Add("OU not found")
                    Else
                        Dim lvi As New ListViewItem
                        lvi = ListView1.Items.Add(PC)
                        lvi.SubItems.Add(result.Properties("ou")(0))
                    End If
                Next
                Counter += 1
                AddHandler Me.ListView1.ColumnClick, AddressOf ColumnClick

            Loop

            For Each lvi As ListViewItem In ListView1.Items
                If lvi.SubItems(2).Text = "OU not found" Then
                    lvi.UseItemStyleForSubItems = True
                    lvi.BackColor = Color.Tomato
                End If
            Next

        End If
        Cursor = Cursors.Default
        ProgressBar1.Value = 100
        lblStatusBar.Text = "Task complete"
        lblPassProcessed.Text = "Computers Processed: " & ListView1.Items.Count
    End Sub

Open in new window

0
Comment
Question by:fruitloopy
  • 4
  • 4
8 Comments
 
LVL 7

Expert Comment

by:HaiFai
ID: 40370485
Hi

Where is it failing there ?
0
 
LVL 2

Author Comment

by:fruitloopy
ID: 40370537
No errors. It just doesnt populate the 2nd column of the listview.
When I first had it with no For loop at line 39 it entered the "OU not found" which still means it isnt working.
Dim entry As DirectoryEntry = New DirectoryEntry("LDAP://DC=UK,DC=cat,DC=com")
                Dim searcher As New DirectorySearcher(entry)
                searcher.Filter = ("(&(objectclass=computer)name=" & PC & "))")
                searcher.PropertiesToLoad.Add("ou")
                Dim OUresult As SearchResultCollection
                OUresult = searcher.FindAll()
                Dim result As SearchResult
                If OUresult Is Nothing Then
                    Dim lvi As New ListViewItem
                    lvi = ListView1.Items.Add(PC)
                    lvi.SubItems.Add("OU not found")
                Else
                    Dim lvi As New ListViewItem
                    lvi = ListView1.Items.Add(PC)
                    lvi.SubItems.Add(result.Properties("ou")(0))
                End If

Open in new window

2014-10-09-13-46-03-OU-Changes--Running-
0
 
LVL 7

Expert Comment

by:HaiFai
ID: 40370558
hmm could try it something like this
change
searcher.Filter = ("(&(objectclass=computer)name=" & PC & "))")
to
searcher.Filter = "(&(ObjectClass=computer)(CN=" & PC & "))"

and you probably want to use searcher.findone istead of find.all
0
 
LVL 7

Accepted Solution

by:
HaiFai earned 500 total points
ID: 40370567
i made short example should it work like this ?
add two buttons, textbox, label, and listview

Imports System.IO
Imports System.DirectoryServices

Public Class Form1
    Dim listofpc As New List(Of String)
    Dim dirEntry As New System.DirectoryServices.DirectoryEntry
    Dim listitem As ListViewItem
    Private Sub browse_Click(sender As Object, e As EventArgs) Handles browse.Click
        OpenFileDialog1.ShowDialog()
        If Not OpenFileDialog1.FileName = "" Then
            Dim freader As New StreamReader(OpenFileDialog1.FileName)
            Do While Not freader.EndOfStream
                listofpc.Add(freader.ReadLine.ToString)
            Loop
            For Each p In listofpc
                Dim dirsearch As New DirectorySearcher()
                Dim direntry As SearchResult
                dirsearch.Filter = "(&(ObjectClass=computer)(CN=" & p & "))"
                direntry = dirsearch.FindOne
                If Not direntry Is Nothing Then
                    listitem = ListView1.Items.Add(p)
                    With listitem
                        .SubItems.Add(direntry.Path.ToString)
                    End With
                     Else
                    listitem = ListView1.Items.Add(p)
                    With listitem
                        .SubItems.Add("Computer not found")
                    End With
                End If
            Next
            ListView1.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.HeaderSize)
            ListView1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.HeaderSize)
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListView1.View = View.Details
        ListView1.Columns.Add("Name")
        ListView1.Columns.Add("OU")
        Label1.Text = "Target OU"
        TextBox1.Text = "LDAP://OU=Systems,OU=Computers,OU=factory,OU=area,DC=UK,DC=company,DC=com"

    End Sub

    Private Sub movebtn_Click(sender As Object, e As EventArgs) Handles movebtn.Click
        For Each i As ListViewItem In ListView1.SelectedItems
            'MsgBox(i.SubItems.Item(1).Text)
            Dim currentitem As New DirectoryEntry(i.SubItems.Item(1).Text)
            currentitem.MoveTo(New DirectoryEntry(TextBox1.Text))
        Next
    End Sub
End Class

Open in new window

0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 2

Author Comment

by:fruitloopy
ID: 40370713
Your code works fine for discovering the OU it is currently residing in and thats fantastic.

I have adapted (probably badly!) your code into mine and for some reason the computer isnt being moved into the new OU. Your code doesnt do it either. Would it need authenticating to the ADS?
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        If txtFile.Text Is "" Then
            MessageBox.Show("You have not selected a file to process", "No file selected", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            ListView1.Items.Clear()
            On Error Resume Next
            lblStatusBar.Text = "Working..."
            Dim text As String = txtFile.Text
            Dim PC As String = IO.File.OpenText(text).ReadLine
            Dim objsrc As DirectoryEntry
            Dim objdest As DirectoryEntry
            Dim file As New FileInfo(text)

            Dim sB As Long = file.Length
            Dim cR As Long = 0
            ProgressBar1.Maximum = 100
            Dim reader2 As New StreamReader(text)
            Dim Counter As Integer = 0

            Do While Not reader2.EndOfStream
                listofpc.Add(reader2.ReadLine.ToString)
                PC = reader2.ReadLine
                Cursor = Cursors.WaitCursor
                cR = cR + PC.Length
                ProgressBar1.Value = (cR / sB) * 100
                Application.DoEvents()

                Dim CurrentOUPath As New DirectoryEntry("LDAP://CN=" & PC & ",OU=PSPS,OU=Computers,OU=factory,OU=area,DC=UK,DC=company,DC=com")
                CurrentOUPath.MoveTo(New DirectoryEntry("LDAP://OU=Systems,OU=Computers,OU=factory,OU=area,DC=UK,DC=company,DC=com"))
                CurrentOUPath.CommitChanges()

                System.Threading.Thread.Sleep(500)

                For Each PC In listofpc
                    Dim dirsearch As New DirectorySearcher()
                    Dim direntry As SearchResult
                    dirsearch.Filter = "(&(ObjectClass=computer)(CN=" & PC & "))"
                    direntry = dirsearch.FindOne
                    If Not direntry Is Nothing Then
                        lvi = ListView1.Items.Add(PC)
                        lvi.SubItems.Add(direntry.Path.ToString)
                    Else

                        lvi = ListView1.Items.Add(PC)
                        lvi.SubItems.Add("Error")
                    End If
                Next
                Counter += 1
                AddHandler Me.ListView1.ColumnClick, AddressOf ColumnClick
            Loop

Open in new window

0
 
LVL 7

Expert Comment

by:HaiFai
ID: 40376586
Hi

Hmm thats odd ... do you get any error messages or so ?
i tested my code and it seems to move it correcly ... could it be sync issue that it will take a moment to sync all dc computers ?
my code uses your current logon dc to do things with your credentials

another thing you could check is that destination ou really exist there and is written correcly (case sensitive)
0
 
LVL 2

Author Comment

by:fruitloopy
ID: 40376680
You beat me to it! I was just about to post some new code that is now working correctly.
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        If txtFile.Text Is "" Then
            MessageBox.Show("You have not selected a file to process", "No file selected", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            ListView1.Items.Clear()
            On Error Resume Next
            lblStatusBar.Text = "Working..."
            Dim text As String = txtFile.Text
            Dim PC As String = IO.File.OpenText(text).ReadLine
            Dim file As New FileInfo(text)

            'Dim sB As Long = file.Length
            'Dim cR As Long = 0
            ProgressBar1.Maximum = 100
            Dim reader2 As New StreamReader(text)
            'Dim Counter As Integer = 0



            Do While Not reader2.EndOfStream
                PC = reader2.ReadLine
                Cursor = Cursors.WaitCursor
                'cR = cR + PC.Length
                'ProgressBar1.Value = (cR / sB) * 100
                Application.DoEvents()
                Dim CurrentOUPath As New DirectoryEntry("LDAP://CN=" & PC & "OU=oldpath,OU=Computers,OU=Factory,DC=UK,DC=com")
                CurrentOUPath.MoveTo(New DirectoryEntry("LDAP://OU=Systems,OU=Computers,OU=Factory,DC=UK,DC=com"))
            Loop

        End If
        CurrentOU()
    End Sub

    Sub CurrentOU()
        ListView1.Items.Clear()
        On Error Resume Next
        'lblStatusBar.Text = "Working..."
        Dim text As String = txtFile.Text
        Dim PC As String = IO.File.OpenText(text).ReadLine
        Dim file As New FileInfo(text)

        Dim sB As Long = file.Length
        Dim cR As Long = 0
        ProgressBar1.Maximum = 100
        Dim reader2 As New StreamReader(text)
        Dim Counter As Integer = 0

        listofpc.Add(reader2.ReadLine.ToString)
        'PC = reader2.ReadLine
        Cursor = Cursors.WaitCursor
        cR = cR + PC.Length
        ProgressBar1.Value = (cR / sB) * 100
        Application.DoEvents()

        System.Threading.Thread.Sleep(500)

        For Each PC In listofpc
            Dim dirsearch As New DirectorySearcher()
            Dim direntry As SearchResult
            dirsearch.Filter = "(&(ObjectClass=computer)(CN=" & PC & "))"
            dirsearch.SearchScope = SearchScope.Subtree
            dirsearch.PropertiesToLoad.Add("distinguishedName")
            direntry = dirsearch.FindOne
            Dim str = direntry.Properties("distinguishedName")(0).ToString
            Dim ou As String = str.Split(","c)(1)
            'MsgBox(ou)
            If Not direntry Is Nothing Then
                lvi = ListView1.Items.Add(PC)
                lvi.SubItems.Add(ou) '(direntry.Properties("distinguishedName")(0).ToString)
            Else

                lvi = ListView1.Items.Add(PC)
                lvi.SubItems.Add("Error")
            End If
        Next
        For Each lvi As ListViewItem In ListView1.Items

            If lvi.SubItems(1).Text = "Error" Then
                lvi.UseItemStyleForSubItems = True
                lvi.BackColor = Color.Tomato
            End If
        Next
        Cursor = Cursors.Default
        ProgressBar1.Value = 100
        lblStatusBar.Text = "Task complete"
        lblPassProcessed.Text = "Computers Processed: " & ListView1.Items.Count
    End Sub

Open in new window

I'm not entirely sure why it now works but it does and that's more important to me at the moment.
Thanks for your help.
0
 
LVL 2

Author Closing Comment

by:fruitloopy
ID: 40376684
Gave me exactly what I needed, thanks
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now