VB Search Domain User for File - vb.net

I am putting together an old post here with this new one. My main goal is to combine these two portions so that the search does not need to be ran on each and every computer.
'Searching for all computers in the domain
Dim de As New DirectoryEntry()
de.Path = "WinNT://domain.name"
For Each d As DirectoryEntry In de.Children()
Console.WriteLine(d.Name)
Next
I can set the path as WinNT://domain.name/username...and I get a list of something, are they files? i am not sure?
Second portion of code searches the computer for the java.exe to display its version, as well as searching for any indication of a java file on that computer.
'Searching individual computer for Java Information
Dim sdkCommand As String
sdkCommand = "C:\Windows\System32\Java.exe -version 2> C:\Users\Desktop\JavaSDKInfo.txt && C:\Windows\System32\tasklist.exe /FI ""IMAGENAME eq java.exe"" >> C:\Users\Desktop\JavaSDKInfo.txt"
Shell("cmd.exe /c" & sdkCommand)
I am crazy confizzled when it comes to have each domain user run this(or to have me remotely execute it on each machine??). I have been given hints regarding dlls, etc. Any advice regarding how to go about this or what to do would be awesome!

I know its been a while so I will go ahead and list what I did as the answer.
Using replacement in the shell I am able to pull up the list of users that was written using a streamwriter. The command is then performed on each entry in that list.
Sub WriteUserFile()
Dim de As New DirectoryEntry()
de.Path = "WinNT://domain.name"
Using sw as New StreamWriter(File.Open(UserFile, FileMOde.OpenorCreate))
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
End Sub
In order to combine it I then used this next sub and the replacement command to sub in the user names. Push d allowed me to change the directory to each user (pending admin status)
Sub DoWork()
Dim sdkCommand as string = "pushd \\*\C$ && java.exe -version2>> $$$"
For each strUserName as String in strLines
Dim ReplaceCommand as String = sdkCommand.Replace("*", strUserName).Replace("$$$", "C:\InfoReadout.txt")
Shell("cmd.exe /c" & ReplaceCommand, True, -1)
End Sub

Related

Getting DNS Cache in vb.net and returning domains

What's the best way to get the DNS Cache in Visual Basic and returning recently resolved domains? I only need the domains to compare them whit a list.
Function GetDnsCache()
Dim DNSCache As New Process
DNSCache.StartInfo.FileName = "ipconfig"
DNSCache.StartInfo.Arguments = "/displaydns "
DNSCache.StartInfo.UseShellExecute = False
DNSCache.StartInfo.RedirectStandardOutput = True
DNSCache.
DNSCache.Start()
MsgBox(DNSCache.StandardOutput.ReadToEnd())
DNSCache.WaitForExit()
End Function
This is not the cleanest way of doing this and it also takes ages to parse and load.
I would do something like this. It executes ipconfig /displaydns and appends the output to a file. Then, the file is read line by line and displayed wherever you want (I've used a Listbox)
Dim Shell = CreateObject("Wscript.Shell")
Shell.run("cmd /c ipconfig /displaydns >> C:\ipconfig.txt")
Using reader As New IO.StreamReader("C:\ipconfig.txt")
While Not reader.EndOfStream
Dim currentLine As String = reader.ReadLine()
ListBox1.Items.Add(currentLine)
End While
End Using
Should you like to display the info into a MsgBox...
Dim Shell = CreateObject("Wscript.Shell")
Shell.run("cmd /c ipconfig /displaydns >> C:\ipconfig.txt")
Dim reader as As New IO.StreamReader("C:\ipconfig.txt")
MsgBox(reader.ReadToEnd.ToString, MsgBoxStyle.Information)

ASP.NET - Deleting Computer Accounts Within AD

I'm building out a decommissioning application that will allow an individual to provide an computer name and the utility will go out and purge the computer record from various locations. I'm running into a problem when attempting to delete a computer account from Active Directory. I'm impersonating a service account that only has rights to "Delete All Child Objects" within a particular OU structure. The code below works if I run it with my domain admin account; however fails with an "Access Denied" when I run it with the impersonated service account. I have verified that the permissions are correct within AD as I can launch Active Directory Users and Computers using a "runas" and providing the service account credentials and I can delete computer objects perfectly fine.
Wondering if anyone has run into this before or has a different way to code this while still utilizing my current OU permissions. My gut tells me the "DeleteTree" method is doing more then just deleting the object.
Any assistance would be appreciated.
Sub Main()
Dim strAsset As String = "computer9002"
Dim strADUsername As String = "serviceaccount#domain.com"
Dim strADPassword As String = "password"
Dim strADDomainController As String = "domaincontroller.domain.com"
Dim objDirectoryEntry As New System.DirectoryServices.DirectoryEntry
Dim objDirectorySearcher As New System.DirectoryServices.DirectorySearcher(objDirectoryEntry)
Dim Result As System.DirectoryServices.SearchResult
Dim strLDAPPath As String = ""
Try
objDirectoryEntry.Path = "LDAP://" & strADDomainController
objDirectoryEntry.Username = strADUsername
objDirectoryEntry.Password = strADPassword
objDirectorySearcher.SearchScope = DirectoryServices.SearchScope.Subtree
objDirectorySearcher.Filter = "(&(ObjectClass=Computer)(CN=" & strAsset & "))"
Dim intRecords As Integer = 0
For Each Result In objDirectorySearcher.FindAll
Console.WriteLine(Result.Path)
Diagnostics.Debug.WriteLine("DN: " & Result.Path)
Dim objComputer As System.DirectoryServices.DirectoryEntry = Result.GetDirectoryEntry()
objComputer.DeleteTree()
objComputer.CommitChanges()
intRecords += 1
Next
If intRecords = 0 Then
Console.WriteLine("No Hosts Found")
End If
Catch e As System.Exception
Console.WriteLine("RESULT: " & e.Message)
End Try
End Sub
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain, "DOMAIN", strADUsername, strADPassword)
' find a computer
Dim computerToDelete As ComputerPrincipal = ComputerPrincipal.FindByIdentity(ctx, strAsset)
If computerToDelete IsNot Nothing Then
' delete the computer, if found
computerToDelete.Delete()
End If
The new S.DS.AM makes it really easy to play around with users and groups in AD!
Delete Tree is different from delete. You're going to need the Delete Subtree permission on the child computer objects for this to work.

VB.Net: How To Display Previous Shadow Copy Versions of File Allowing User to Choose One

I'm writing an Excel file recovery program with VB.Net that tries to be a convenient place to gather and access Microsoft's recommended methods. If your interested in my probably kludgy, error filled, and lacking enough cleanup code it's here: http://pastebin.com/v4GgDteY. The basic functionality seems to work although I haven't tested graph macro table recovery yet.
It occurred to me that Vista and Windows 7 users could benefit from being offered a list of previous versions of the file within my application if the Shadow Copy Service is on and there are previous copies. How do I do this?
I looked at a lot of web pages but found no easy to crib code. One possibility I guess would be to use vssadmin via the shell but that is pretty cumbersome. I just want to display a dialogue box like the Previous Versions property sheet and allow users to pick one of the previous versions. I guess I could just display the previous version property sheet via the shell by programmatically invoking the context menu and the "Restore previous versions choice", however I also want to be able to offer the list for Vista Home Basic and Premium Users who don't have access to that tab even though apparently the previous versions still exist. Additionally if it possible I would like to offer XP users the same functionality although I'm pretty sure with XP only the System files are in the shadow copies.
I looked at MSDN on the Shadow Copy Service and went through all the pages, I also looked at AlphaVSS and AlphaFS and all the comments. I'm kind of guessing that I need to use AlphaVss and AlphFS and do the following?
Find out the list of snapshots/restore points that exist on the computer.
Mount those snapshots.
Navigate in the mounted volumes to the Excel file the user wants to recover and make a list of those paths.
With the list of paths handy, compare with some kind of diff program, the shadow copies of the files with the original.
Pull out the youngest or oldest version (I don't think it matters) of those shadow copies that differ from the recovery target.
List those versions of the files that are found to be different.
This seems cumbersome and slow, but maybe is the fastest way to do things. I just need some confirmation that is the way to go now.
I finally decided to go ahead and start coding. Please make suggestions for speeding up the code or what do with files that are found to be different from the recovery file target. Is there a simpler way to do this with AlphaVSS and AlphaFS?
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Find out the number of vss shadow snapshots (restore
'points). All shadows apparently have a linkable path
'\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy#,
'where # is a simple one, two or three digit integer.
Dim objProcess As New Process()
objProcess.StartInfo.UseShellExecute = False
objProcess.StartInfo.RedirectStandardOutput = True
objProcess.StartInfo.CreateNoWindow = True
objProcess.StartInfo.RedirectStandardError = True
objProcess.StartInfo.FileName() = "vssadmin"
objProcess.StartInfo.Arguments() = "List Shadows"
objProcess.Start()
Dim burp As String = objProcess.StandardOutput.ReadToEnd
Dim strError As String = objProcess.StandardError.ReadToEnd()
objProcess.WaitForExit()
Dim xnum As Integer = 0
Dim counterVariable As Integer = 1
' Call Regex.Matches method.
Dim matches As MatchCollection = Regex.Matches(burp, _
"HarddiskVolumeShadowCopy")
' Loop over matches.
For Each m As Match In matches
xnum = xnum + 1
'At the max xnum + 1 is the number of shadows that exist
Next
objProcess.Close()
Do
'Here we make symbolic links to all the shadows, one at a time
'and loop through until all shadows are exposed as folders in C:\.
Dim myProcess As New Process()
myProcess.StartInfo.FileName = "cmd.exe"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Dim myStreamWriter As StreamWriter = myProcess.StandardInput
myStreamWriter.WriteLine("mklink /d C:\shadow" & counterVariable _
& " \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy" _
& counterVariable & "\")
myStreamWriter.Close()
myProcess.WaitForExit()
myProcess.Close()
' Here I compare our recovery target file against the shadow copies
Dim sFile As String = PathTb.Text
Dim sFileShadowPath As String = "C:\shadow" & _
counterVariable & DelFromLeft("C:", sFile)
Dim jingle As New Process()
jingle.StartInfo.FileName = "cmd.exe"
jingle.StartInfo.UseShellExecute = False
jingle.StartInfo.RedirectStandardInput = True
jingle.StartInfo.RedirectStandardOutput = True
jingle.StartInfo.CreateNoWindow = True
jingle.Start()
Dim jingleWriter As StreamWriter = jingle.StandardInput
jingleWriter.WriteLine("fc """ & sFile & """ """ _
& sFileShadowPath & """")
jingleWriter.Close()
jingle.WaitForExit()
Dim jingleReader As StreamReader = jingle.StandardOutput
Dim JingleCompOut As String = jingleReader.ReadToEnd
jingleReader.Close()
jingle.WaitForExit()
jingle.Close()
Dim jingleBoolean As Boolean = JingleCompOut.Contains( _
"no differences encountered").ToString
If jingleBoolean = "True" Then
MsgBox(jingleBoolean)
Else
'I haven't decided what to do with the paths of
'files that are different from the recovery target.
MsgBox("No")
End If
counterVariable = counterVariable + 1
Loop Until counterVariable = xnum + 1
End Sub

Place Line from Text File in a Shell CMD. VB.net

I am assuming there is a way to have this sub in? I am assuming Do Until Loop is the way to go, I just do not know how to contruct one.
Sub Main()
'Declare Command
Dim sCommand As String
'Declare File where Users are Located
Dim strFile As String = "C:\TestDUsers.txt"
'Running from Admin Comptuer so permissions are fine
'Want to replace the ******** section with each username from text file
sCommand = "pushd \\*********\C$ && whoami.exe >> C:\File.txt"
'Load the File and perform the loop????
Using sr As New StreamReader(File.Open(strFile, FileMode.Open))
End Using
Console.WriteLine()
Console.Clear()
End Sub
Something like this if I understand your question correct:
Sub Main()
HandleJavaInfo()
End Sub
Sub HandleJavaInfo()
Dim strFile As String = "C:\Users\pseal2\Desktop\TestDUsers.txt"
Dim strCommand = "pushd \\*********\C$ && whoami.exe >> C:\Users\pseal2\Desktop\Javainfo."
Dim strLines() As String = IO.File.ReadAllLines(strFile)
For Each strUserName As String In strLines
'execute the command as shell or process
'Example using Shell (run the command whitout showing the window for the user)
Dim ThisCommand As String = strCommand.Replace("*********", strUserName)
Shell(ThisCommand, AppWinStyle.Hide)
'Example using process
Process.Start("pushd", "\\" & strUserName & "\C$ && whoami.exe >> C:\Users\pseal2\Desktop\Javainfo.")
Next
End Sub
Now, you have only told us what you want to DO, not what you want to achieve. If you tell us exactly what the goal is, then it may be some other .Net ways to do what you want, instead of shelling out to a DOS-command, and you can get more accurate answers.

Windows Service not able to access mapped folders

I have a very simple VB.net Windows Service written using VS.net 2008. The program after doing several other functions writes a log in one of the network folders. The code is as shown below: If I change the path from "Y:\Activity_Log" to "C:\Activity_Log" it is working like a charm.
What is the problem if I use Y drive which is a valid one and I am able to access it from other VB.net desktop apps. Please help.
Dim strFile As String = "Y:\Activity_Log\" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim fs As FileStream = Nothing
Dim activityfolder As String = "Y:\Activity_Log"
Dim di As System.IO.DirectoryInfo
di = New System.IO.DirectoryInfo(activityfolder)
If (Not di.Exists) Then
di.Create()
End If
If (Not File.Exists(strFile)) Then
Try
Dim sw1 As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw1.WriteLine("******************************Activity Log for " & Now.Date & "*******************")
sw1.WriteLine("-----------------------------------------------------------------------------------------------------------------")
sw1.WriteLine(Remarks & " ---" & DateTime.Now)
sw1.Close()
Catch ex As Exception
End Try
Else
Dim sw As StreamWriter
sw = AppendText(strFile)
sw.WriteLine(Remarks & " ---" & DateTime.Now)
sw.Close()
End If
Start->Control Panel->Administrative Tools->Services
Find Your service in the list, right click on the name, Properties
Click the Log On tab
Change from Local System account to 'This Account'
Use a user that has access to that share, start with your username/password to convince yourself that it works ;)
Click Ok, then restart the service.
maybe you need to run the service under a user that has access to that drive?
maybe the generic service user doesn't have access.