vbscript Remove mapped drive if the drive letter and path matches - vbscript

Here is the vbscript that I have which should remove the netwrok drive if it matches the letter and the path but it does not work properly and the array shows 13 mapped drives which I only have 5 on my computer. Doesnt it suppose to check all the available mapped drives on the user's mapped computer?
Set objShell = CreateObject("Wscript.Shell")
Set objNet = WScript.CreateObject("Wscript.Network")
Set objExec = objShell.Exec("net use ")
strMaps = LCase(objExec.StdOut.ReadAll)
MapArray=split(strMaps,CHR(10))
for x=1 to ubound(MapArray)
if instr(MapArray(x),"W:") AND instr(mapArray(x),"\\path\folder$") then
objNet.RemoveNetworkDrive "W:",true,true
end if
if instr(MapArray(x),"U:") AND instr(mapArray(x),"\\path\folder$") then
objNet.RemoveNetworkDrive "U:"
end if
next

To enumerate network drives.
Set NetDrives = WScript.CreateObject("WScript.Network").EnumNetworkDrives
For X = 0 to NetDrives.Count -1 Step 2
MsgBox NetDrives(x) & " " & NetDrives(x+1)
Next
To do what you want. We don't test then do usually. We do and test what happened. Testing most things usually takes up almost the same resources as doing.
On Error Resume Next
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.RemoveNetworkDrive "Y:"
Msgbox err.description
Again anything involving files and registry (because users delete) and networks or internet (because by nature are unreliable) should use error handling.

Related

Find the owners of all the folders within a given path

I am trying to find the owners of all the folders in a given path. I have the following code:
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFolder In objFSO.GetFolder("C:\Windows").SubFolders
strpath = objFolder.Path
WScript.Echo strpath
Next
My end goal is to put the path and and owner of all the folders from the given path into a text file.
Could someone help me find the owner of a folder and be able to place this owner name into a variable. I could then use this to improve my existing code.
As JoSerra mentioned in the comments you can retrieve the owner of a file or folder via the WMI class Win32_LogicalFileSecuritySetting. The sample code from the Script Center is mostly accurate. I would, however, recommend using double quotes instead of single quotes around the path.
Single quotes (unlike double quotes) are valid characters in a path. If you invoke the statement wmi.Get("Win32_LogicalFileSecuritySetting.Path='" & path & "'") with a path containing a single quote, the call will fail with an "invalid object path" error. Thus it's better to use double quotes and escape backslashes in the path.
path = "C:\some\folder 'with' quotes"
Function Esc(str)
Esc = Replace(str, "\", "\\")
End Function
Set wmi = GetObject("winmgmts:")
Set fs = wmi.Get("Win32_LogicalFileSecuritySetting=""" & Esc(path) & """")
rc = fs.GetSecurityDescriptor(sd)
If rc = 0 Then
WScript.Echo "Owner: " & sd.Owner.Domain & "\" & sd.Owner.Name
Else
WScript.Echo "Couldn't retrieve security descriptor."
End If

scan computer for a file and output folder location

I need to take a list of computers (IP or PC name) that are all on the same domain in CSV format. Scan each computer for a specific folder name. The folder will be arcXXXof. The x's are a hash and change for each PC. If the folder is found it needs to output the folder path to a CSV and append with each computer scanned. My programming is limited and I only really know Java. Since this will be run from a server it will need local administrative privileges to run on the local machines. My manager suggested I use VBS, but I have never written in that before.
My current snag is getting an error "expected then" Here's my loop.
Sub Recurse(strFolderPath)
Dim objFolder
Set objFolder = objFSO.GetFolder(strFolderPath) 'reads Folders pulled from recursion
Dim objSubFolder
dim folderStart 'grabs the first 2 characters of the file name. Should match 'of' if correct folder
Dim folderEnd 'grabs the last 6 (test) characters of the folder name, should match arc.txt if correct
Global checkEnd
set checkEnd = "arc" 'checks for "arc" at ending
Global checkStart
set checkStart = "of" 'used to check if folder name is correct path
For Each objSubFolder in objFolder 'for every Folder scanned
'Scans the name of the Folder, objSubFolder, for an ending of “arc", and beginning of “of” (testing)
set folderName = objSubFolder.name
Set folderEnd = right(folderName, 3)
set folderStart = left(folderName, 2)
dim folderName
if folderName = testFolderName
then WScript.Echo objSubFolder
'If folderEnd = checkEnd and
'If folderStart = checkStart
'Add Folder location to array, set array to next object
'Then fLocations(i) = object.GetAbsolutePathName(objSubFolder) and i = i+1
else
End If
Next
'recursive for searching new folder
For Each objSubFolder in objFolder.Subfolders
Call Recurse(objSubFolder.Path)
Next
OK, you could use a regex to match the name. Define it up front, in your global scope:
Dim re
Set re = New RegExp
re.IgnoreCase = True
re.Pattern = "^arc\w{3}of$"
I'm using \w, which is equivalent to [a-zA-Z_0-9]. You can change this if you're expecting only digits (\d) or something else for these three chars.
Then, in your Recurse function, test the folder name against it:
For Each objSubFolder in objFolder.SubFolders
' See if this folder name matches our regex...
If re.Test(objSubFolder.Name) Then
' Match. Just display for now...
WScript.Echo objSubFolder.Path
End If
' Test its subfolders...
Recurse objSubFolder.Path
Next
Tip: Remove the On Error Resume Next from your code while you're developing or you might miss all kinds of bugs and cause all kinds of headaches.

vbScript that Checks NetworkAdapter Config and updates URL if it detects change

Ok... everyone here seems to be way more educated about this stuff than I. But I've been at this for 2 days straight and I've gone at it from all kinds directions.
Goal:
Have a script check the IP address of local pc. At some time (thinking 5 minutes) recheck the IP address again. Compare the two and if there is a change execute a command silently.
I realize that I can not just get the IP address as I'll get the entire state using winmgmts and I'm ok with that. Really it's just to keep an eye on whether or not the state changes in general. The line of code is to access a URL which will update my FreeDNS incase the IP changes. For whatever reason, none of the programs offered have been working. One even crashes .Net Framework.
Knowing that I'm an utter noob (and thank you for reading this far!) here's what my crazy broken and utterly bizarre code looks like. Any assistance would be divine and I apologize
Dim firstSet, secondSet
Set objWMIService = GetObject("winmgmts:")
Set FirstIP = objWMIService.ExecQuery("SELECT * FROM " & "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
Set firstSet = FirstIP
WScript.Sleep 3
Set objWMIService = GetObject("winmgmts:")
Set SecondIP = objWMIService.ExecQuery("SELECT * FROM " & "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
Set secondSet = SecondIP
results = StrComp(firstSet, secondSet, 1)
If Not results = True Then
updateURL = "MyURL"
Set req = CreateObject("MSXML2.XMLHTTP.6.0")
req.Open "GET", updateURL, False
req.Send
End If

How to disable SmartScreen for a specific .cmd file?

I recent made a group of .cmd files.
Called, 'Node.1.cmd' and 'Node.2.cmd', the files' purpose was supposed to open each other (in a chain-like process).
However, whenever I open one of the 2, it gives me a seriously annoying message:
Windows Protected your PC.
Windows SmartScreen prevented an unrecognized app from starting. Running this app may put your PC at risk.
I agree that this is a bit risky, but it was made for fun, not for destruction. It was just my way of showing people not to mess with my stuff. Not even did I set any LNK at my desktop to the file.
Now, to get to the point, can I exclude this file from SmartScreen while keeping it on?
Because of this, I have problems opening it with a .vbs file
To be more specific, it opens but then automatically closes with a message:
The system cannot find the path specified.
Does windows SmartScreen encrypt the file or something like that?
I scripted the following:
Titre = "What would you like to do ? RookieTEC9©"
message = "What would you like to do ?"&vbcr&vbcr&_
"1 - Launch Project Node "&vbcr&_
"2 - Launch Golden Chrome"&vbcr&_
"3 - Launch An Application"&vbcr&_
"4 - Start Windows Update"&vbcr&_
"5 - Slide2Kill"
Default ="1"
Question = InputBox(message,Titre,Default)
Select Case Question
Case 1 Run(1)
Case 2 Run(2)
Case 3 Run(3)
Case 4 Run(4)
Case 5 Run(5)
end Select
Sub Run(var)
Set WS = CreateObject("WScript.shell")
Select Case var
Case 1 WS.run("explorer.exe /e,C:\Users\Jeremi\OneDrive\Happy_files\Unsorted_Files\Project_Node.zip\Node.1.cmd")
Case 2 ProcessNotNeeded()
Case 3 LaunchApplication()
Case 4 WindowsUpdate()
Case 5 WS.run("SlideToShutDown.exe")
End select
End Sub
Sub Kill(Process)
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
Sub ProcessNotNeeded()
Titre = "Killing Process Not Needed RookieTEC9© "
message = "Type the Name of the process to be killed by this script"&vbcr&_
"Example To Kill The Internet Explorer Process You should type"&vbcr&_
"iexplore.exe"
Default ="iexplore.exe"
Question = InputBox(message,Titre,Default)
Kill(Question)
End Sub
Function CmdPrompt(sCmd)
Dim sCmdLine,oWS,nRes
set oWS = CreateObject("Wscript.Shell")
sCmdLine = "cmd /c Start " & sCmd & ""
nRes = oWS.Run(sCmdLine,0,False)
CmdPrompt = nRes
End Function
Sub LaunchApplication()
Titre = "Launching an Application"
message = "Type the Name of the process to be Lanuched by this script"&vbcr&_
"Example To Launch The Word Application You should type"&vbcr&_
"Winword.exe"
Default ="Winword.exe"
Question = InputBox(message,Titre,Default)
CmdPrompt(Question)
End Sub
Sub WindowsUpdate()
Title = "Checking for Windows updates"
Msg = "Looking for a list of updates, So be Patient Thank you !"
Wait = "70" 'waiting 70 secondes to close the popup
Set Ws = CreateObject("Wscript.Shell")
ws.Popup Msg,wait,Title,64
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
If searchResult.Updates.Count <> 0 Then 'If updates were found
'so with this loop shows how you can list the title of each update that was found.
For i = 0 To searchResult.Updates.Count - 1
Set update = searchResult.Updates.Item(i)
ws.Popup update.Title,wait,Title,64
Next
End If
Ws.Run "wuauclt.exe /reportnow /detectnow",1,False
End Sub
Sorry for the long code!
To be 100% honest, I didn't create this from scratch, I just edited it.
I am new to VBS
However, if you have any questions on HTML or CSS, I may be able to answer it.
Please keep in mind that I am a 5th grader and only started coding this school year.
THX for your time and answer.
P.S.
Also, the file was in a zip. Does that effect it?
You can unblock these CMD files, it is explained here
Once unblocked you should be able to run it from the console and from your script.
I myself scripted a very long time in vbscript but now it is obsolete. Since you have
just started to learn, I advise you to learn another scripting language like Ruby which is fun to learn or if you want to go the 'only windows' way Powershell (shiver..)

Unlock bitlocker drive with VBScript

I'm trying to script out the unlocking of a bitlocker drive using a DRA certificate. I'm attempting to use the WMI Method UnlockWithCertificateFile and I can't for the life of me figure out what i'm doing wrong or even find an example.
I know the certificate and pin work because i can manually unlock the drive using manage-bde -unlock....
when i run my script i get a return value of -2146885623 wich i've looked up to be -2146885623, "Cannot find the requested object."
i'm not sure what object its talking about.
here is the code i'm using (minus the pin)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2\Security\MicrosoftVolumeEncryption")
' Obtain an instance of the the class
' using a key property value.
Set objShare = objWMIService.Get("Win32_EncryptableVolume.DeviceID='\\?\Volume{a2965903-4af0-11e2-be65-806e6f6e6963}\'")
' Obtain an InParameters object specific
' to the method.
Set objInParam = objShare.Methods_("UnlockWithCertificateFile"). _
inParameters.SpawnInstance_()
' Add the input parameters.
objInParam.Properties_.Item("PathWithFileName") = "D:\BitLocker.pfx"
objInParam.Properties_.Item("Pin") = "PinCode
' Execute the method and obtain the return status.
' The OutParameters object in objOutParams
' is created by the provider.
Set objOutParams = objWMIService.ExecMethod("Win32_EncryptableVolume.DeviceID='\\?\Volume{a2965903-4af0-11e2-be65-806e6f6e6963}\'", "UnlockWithCertificateFile", objInParam)
' List OutParams
Wscript.Echo "Out Parameters: "
Wscript.echo "ReturnValue: " & objOutParams.ReturnValue
has anyone ever used this method or can anyone see something i may be doing wrong? also i'm using the windows 8 commandline recovery option, i'm not sure if that makes a difference because i have tested calling other methods and wmi and scripting seem to be fully implemented.

Resources