[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

06/29/2009 at 06:48AM PDT, ID: 24529948
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

9.2

Enumerating User Accounts on a Remote Computer using VB.Net/WMI

Asked by msyed1 in Microsoft Visual Basic.Net, Programming User Management, Windows Management Instrumentation (WMI)

Hello,

I had asked this question earlier.  Please see  http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_24434446.html

The suggestion given in the above PAQ still doesn't work.  Basically what happens I think is that my Select query tries to bring back the User accounts from the entire domain.  What I need is for it to bring back the User accounts ONLY for the remote computer name that I pass in.  I have tried several different WHERE clauses, but nothing seems to work.  I am attaching my code below.  It is VB.Net console application.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
Option Strict Off
Imports System.Runtime.InteropServices
Imports System.IO
Imports log4net
Imports System.Configuration
Imports System
Imports System.Management
Imports System.Net.Dns
 
 
'Imports log4net
'Private Shared ReadOnly log As ILog = LogManager.GetLogger(Type.GetType(TestPage1).Name)
 
'Private Shared ReadOnly ILog log Property LogManager.GetLogger(() As =
'End Property
'  System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
 
'----------------------------------------------------------------
' Converted from C# to VB .NET using CSharpToVBConverter(1.2).
' Developed by: Kamal Patel (http://www.KamalPatel.net) 
'----------------------------------------------------------------
Module Module1
   
    Public MasterDirectory As String = ConfigurationSettings.AppSettings("MasterDirectory")
    Public SubDirectory1 As String = ConfigurationSettings.AppSettings("SubDirectory1")
    Public SubDirectory2 As String = ConfigurationSettings.AppSettings("SubDirectory2")
 
    Public objOS As ManagementObjectSearcher
    Public objCS As ManagementObjectSearcher
    Public objMgmt As ManagementObject
 
 
    'Logger instance {DEBUG,INFO,WARN,ERROR,FATAL,OFF}
    Private ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger("TaskRunnerAccountDiscovery")
 
    Sub Main()
        Dim strDomainName, TaskRunnerServer As String
        Dim strTextFileBldr As New System.Text.StringBuilder
        Dim strCSVBldr As New System.Text.StringBuilder
        Dim arlAccountList As New ArrayList
        Dim bolFoundTaskRunner As Boolean = False
        Dim bolNoInputServers As Boolean = True
 
        Try
            log.Info("Beginning Run")
            log.Info("MasterDirectory: " & MasterDirectory)
 
            Dim arlRuntimeServers As New ArrayList
            Dim arlTextFileServers As New ArrayList
            Dim arlFinalArray As New ArrayList
            Dim arlTotalServersSearched As New ArrayList
            Dim intTaskRunnerServersFound As Integer = 0
 
            Dim strEntry As String
            Dim intNumberOfServers As Integer
            Dim intCounter As Integer = 0
            Dim ss As Integer
 
            
            arlFinalArray.Add("Archtest201")
            arlFinalArray.Add("Archtest301")
 
            If arlFinalArray.Count <= 0 Or arlFinalArray Is Nothing Then
                log.Error("Error: Server arraylist is Empty! -Exiting Program!")
            Else
                intNumberOfServers = arlFinalArray.Count.ToString
                bolNoInputServers = False
                For Each strEntry In arlFinalArray
                    strDomainName = arlFinalArray.Item(intCounter)
                    intCounter = intCounter + 1
                    If intCounter < 26 Then
                        Dim bolIsAccessDenied As Boolean = False
                        arlAccountList = EnumerateLocalAccounts(strDomainName, bolIsAccessDenied)
                        'strAccountInfo = FindAccountsOnServer(strDomainName)
                        'If strAccountInfo <> "Not Available" Then
                        If bolIsAccessDenied Then
                            strTextFileBldr.Append((Trim(strDomainName)).ToString() & "Access is Denied - Unauthorized Access Exception" & vbCrLf)
                        Else
                            If arlAccountList.Count >= 1 Then
                                strTextFileBldr.Append((Trim(strDomainName)).ToString() & vbCrLf)
                                For Each ss In arlAccountList
                                    strTextFileBldr.Append(ss).ToString()
                                    strTextFileBldr.Append(",")
                                Next
                                strTextFileBldr.Append(" " & vbCrLf & vbCrLf)
                                arlTotalServersSearched.Add(strDomainName)
                                bolFoundTaskRunner = FindIfTaskRunnerIsUsed(arlAccountList, strDomainName)
                                If bolFoundTaskRunner Then
                                    intTaskRunnerServersFound += 1
                                    strCSVBldr.Append((Trim(strDomainName)).ToString & vbCrLf)
                                End If
                            End If
                        End If
                    End If
                Next
            End If
            If bolNoInputServers Then
                Exit Sub
            Else
                WriteUserAccountsInfoToOutputFile(strTextFileBldr, arlTotalServersSearched)
                WriteServerNameToOutputFile(strCSVBldr, intTaskRunnerServersFound)
            End If
        Catch ex As Exception
            Console.WriteLine("Error Occurred: " & ex.ToString)
            log.Error("Error: " & ex.Message)
        End Try
 
        'added so the DOS screen won't flash by.... remove this when running program outside of the debugger.
        Console.ReadLine()
 
    End Sub
 
   
    Public Function EnumerateLocalAccounts(ByVal machineName As String, ByRef bolIsAccessDenied As Boolean) As ArrayList
        ''''''bolIsAccessDenied is ByRef
 
        Dim arlArrayOfAccounts As New ArrayList
        Dim strAccount As String
        Dim strDomain As String
 
        'Dim strNumbers As String = "0,1,2,3,4,5,6,7,8,9"
        'Dim strSplitNumbers() As String = Split(strNumbers, ",")
        'Dim i As Integer = 0
 
        ''If this is an IP Address....bypass
        'For i = 0 To strSplitNumbers.GetUpperBound(0)
        '    If machineName.StartsWith(strSplitNumbers(i)) Then
        '        Return arlArrayOfAccounts
        '    End If
        'Next
 
 
              Try
 
            Dim pathMachine As New Management.ManagementPath("\\" & machineName & "\root\cimv2")
 
            Dim scopeRemoteMachine As New Management.ManagementScope(pathMachine)
 
            Dim queryAccounts As New Management.ObjectQuery("SELECT * FROM Win32_Account")
            'Dim queryAccounts As New Management.ObjectQuery("SELECT * FROM Win32_Account where LocalAccount=TRUE")
 
            'Dim queryAccounts As New Management.ObjectQuery("SELECT * FROM Win32_Account where LocalAccount=TRUE And Domain = '" & machineName & "'")
 
            '("Select * from Win32_Account WHERE Domain = '" & domain & "' AND Name = '" & username & "'")
 
            'Dim queryAccounts As New Management.ObjectQuery("SELECT * FROM Win32_Account where MachineName = '" & machineName & "'")
 
 
            Dim searcherAccounts As New Management.ManagementObjectSearcher(scopeRemoteMachine, queryAccounts)
 
            Dim objectAccount As Management.ManagementObject
 
            For Each objectAccount In searcherAccounts.Get
                strAccount = (objectAccount("Name"))
                arlArrayOfAccounts.Add(strAccount)
                'Debug.WriteLine(objectAccount("Name"))
            Next
 
            Return arlArrayOfAccounts
 
        Catch uae As UnauthorizedAccessException
            log.Error("Error occurred on machinename: " & machineName & " - " & uae.Message)
            bolIsAccessDenied = True
 
        Catch ex As Exception
            log.Error("Error occurred: " & ex.Message)
        End Try
 
 
           End Function
 
 
   
   
    Function FindIfTaskRunnerIsUsed(ByVal arlAccountList As ArrayList, ByVal strDomainName As String) As Boolean
        'Dim StringArray() As String
        Dim s As String
        Dim intCounter As Integer = 0
        Dim bolServerHasTaskRunner As Boolean = False
        Try
            '''''' Split the contents of sOutput using System.Environment.Newline as the delimeter.
            'StringArray = Split(sOutput, System.Environment.NewLine)
            Dim intLen As Integer = arlAccountList.Count()
            For Each s In arlAccountList
                intCounter += 1
                If arlAccountList(intCounter).ToUpper.ToString = "TASKRUNNER".ToString Then
                    bolServerHasTaskRunner = True
                    Exit For
                End If
            Next
            Return bolServerHasTaskRunner
        Catch ex As Exception
            log.Error("Error occurred: " & ex.Message)
        End Try
    End Function
 
    Public Function MergeBothArraylists(ByVal arlRuntimeServers, ByVal arlTextFileServers) As ArrayList
        'Private Function MergeArrayLists(ByVal L1 As ArrayList, ByVal L2 As ArrayList) As Hashtable
        'Dim ht As New Hashtable
        'Dim s As String
 
        'For Each s In arlRuntimeServers
        '    If Not ht.ContainsKey(s) Then
        '        ht.Add(s, s)
        '    End If
        'Next
        'For Each s In arlTextFileServers
        '    If Not ht.ContainsKey(s) Then
        '        ht.Add(s, s)
        '    End If
        'Next
        'Return ht
 
        Dim arl As New ArrayList
        Dim s As String
 
        For Each s In arlRuntimeServers
            If Not arl.Contains(s) Then
                arl.Add(s)
            End If
        Next
        For Each s In arlTextFileServers
            If Not arl.Contains(s) Then
                arl.Add(s)
            End If
        Next
        arl.Sort()
        Return arl
    End Function
 
    Public Function ReadTextFile() As ArrayList
 
        Dim TextFileLocation As String = ConfigurationSettings.AppSettings("TextFileLocation")
        Dim arlArray As New ArrayList
        Dim oFile As System.IO.File
        Dim oRead As System.IO.StreamReader
        'oRead = oFile.OpenText("C:\sample.txt")
        oRead = oFile.OpenText(TextFileLocation)
 
 
        While oRead.Peek <> -1
            arlArray.Add(oRead.ReadLine())
        End While
        oRead.Close()
 
        Return arlArray
 
    End Function
 
    Public Function WriteFile( _
    ByVal FileName As String, _
    ByVal SubDirectory As String, _
    ByVal strFileContent As String _
)
        Try
 
            Dim objReader As StreamWriter
            If Not Directory.Exists(MasterDirectory & "\" & SubDirectory) Then
                Directory.CreateDirectory(MasterDirectory & "\" & SubDirectory)
            End If
            Dim fullpath As String = MasterDirectory & "\" & SubDirectory & "\" & FileName
            objReader = New StreamWriter(fullpath)
            objReader.Write(strFileContent)
            objReader.Close()
 
        Catch Ex As Exception
            log.Error("Error: " & Ex.ToString)
        End Try
    End Function
 
    Public Function WriteServerNameToOutputFile(ByVal strStringBldr As System.Text.StringBuilder, ByVal intRows As Integer)
 
        '''''''' This function writes a unique file for each run (e.g. TaskRunnerServersMMDDYYYY HH MM AM/PM.CSV) in a directory called 'CSVFiles' within the
        '''''''' MasterDirectory.  
        ''''''''
 
        Try
            Dim output, filename As String
            output = output & "Total Number of  Servers Searched: " & intRows.ToString & vbCrLf
            output = output & strStringBldr.ToString()
            filename = "TaskRunnerServers" & Now.ToShortDateString & " " & Now.ToShortTimeString & ".txt"
            filename = filename.Replace(":", " ")
            filename = filename.Replace("/", "")
            WriteFile(filename, SubDirectory2, output)
        Catch ex As Exception
            log.Error("Error occurred: " & ex.Message)
        End Try
 
    End Function
 
    Public Function WriteUserAccountsInfoToOutputFile(ByVal strTextFileRowBldr As System.Text.StringBuilder, ByVal arlTotalServersSearched As ArrayList)
        ''''''''
        '''''''' This function writes a unique file for each run (e.g. UserAccountInfoMMDDYYYY HH MM AM/PM.CSV) in a directory called 'CSVFiles' within the
        '''''''' MasterDirectory.  
        ''''''''
        Dim strBldrToString As String = strTextFileRowBldr.ToString()
        Dim intRows As Integer = arlTotalServersSearched.Count()
 
        Try
            Dim output, filename As String
            output = output & "Total Number of  Servers that use TaskRunner Account: " & intRows.ToString & vbCrLf
            'output = output & strTextFileRowBldr.ToString()
            output = output & strBldrToString
            filename = "UserAccountInfo" & Now.ToShortDateString & " " & Now.ToShortTimeString & ".txt"
            filename = filename.Replace(":", " ")
            filename = filename.Replace("/", "")
            WriteFile(filename, SubDirectory1, output)
        Catch ex As Exception
            log.Error("Error occurred: " & ex.Message)
        End Try
    End Function
 
 
 
 
 
 
End Module
[+][-]07/01/09 12:55 PM, ID: 24757610

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: Microsoft Visual Basic.Net, Programming User Management, Windows Management Instrumentation (WMI)
Sign Up Now!
Solution Provided By: lciprianionut
Participating Experts: 2
Solution Grade: A
 
 
[+][-]06/30/09 09:06 AM, ID: 24746712

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]07/01/09 12:25 PM, ID: 24757313

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091028-EE-VQP-86 - Hierarchy / EE_QW_4_20070622