vbscript list logged on users to terminal server - vbscript

Try to list the logged on users to a windows terminal server in a workgroup via vbscript.
I have the below but it does not seem to return the logged on users?
strComputer = "."
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colSessions = objWMI.ExecQuery _
("Select * from Win32_LogonSession Where LogonType = 10")
If colSessions.Count = 0 Then
Wscript.Echo "No interactive users found"
Else
WScript.Echo "RDP Sessions:"
For Each objSession in colSessions
Set colList = objWMI.ExecQuery("Associators of " _
& "{Win32_LogonSession.LogonId=" & objSession.LogonId & "} " _
& "Where AssocClass=Win32_LoggedOnUser Role=Dependent" )
For Each objItem in colList
WScript.Echo "Username: " & objItem.Name & " FullName: " & objItem.FullName
Next
Next
End If

You must run it as Administrator!
run CMD as administrator and run the command CSCRIPT

Other option is to check owners of explorer.exe process.
This will list you all users having open session on server.
strComputer = "."
Set colProcesses = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & strComputer & _
"\root\cimv2").ExecQuery("Select * from Win32_Process where name = 'explorer.exe'")
For Each objProcess in colProcesses
who = objProcess.GetOwner(strNameOfUser)
Wscript.Echo "Process " _
& objProcess.Name & " is owned by " _
& strNameOfUser & "."
Next
Example of result:
D:\TEMP>cscript get_explorer_owner.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
Process explorer.exe is owned by john.
Process explorer.exe is owned by peter.
Process explorer.exe is owned by bob.

Related

BAT file to map to network drive without running as admin

I'm trying to create a .bat file that will map to a network drive when it is clicked (it would be even better if it could connect automatically on login if connected to the network, otherwise do not connect)
What I have so far is:
net use P: "\\server\foldername\foldername"
Is there a way that I can create this so the users will not have to right click and run as an administrator? I would like it if they could just click the .bat file and it will map for them.
Save below in a test.bat and It'll work for you:
#echo off
net use Z: \\server\SharedFolderName password /user:domain\Username /persistent:yes
/persistent:yes flag will tell the computer to automatically reconnect this share on logon. Otherwise, you need to run the script again during each boot to map the drive.
For Example:
net use Z: \\WindowsServer123\g$ P#ssw0rd /user:Mynetdomain\Sysadmin /persistent:yes
I just figured it out! What I did was I created the batch file like I had it originally:
net use P: "\\server\foldername\foldername"
I then saved it to the desktop and right clicked the properties and checked run as administrator. I then copied the file to C:\Users\"TheUser"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Where "TheUser" was the desired user I wanted to add it to.
#echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass
net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell.
So, I think you can run powershell scripts from a .bat file, and the script is
New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"
add -persist at the end, you will create a persisted mapped network drive
New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist
for more details, refer New-PSDrive - Microsoft Docs
This .vbs code creates a .bat file with the current mapped network drives.
Then, just put the created file into the machine which you want to re-create the mappings and double-click it. It will try to create all mappings using the same drive letters (errors can occur if any letter is in use). This method also can be used as a backup of the current mappings.
Save the code bellow as a .vbs file (e.g. Mappings.vbs) and double-click it.
' ********** My Code **********
Set wshShell = CreateObject( "WScript.Shell" )
' ********** Get ComputerName
strComputer = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
' ********** Get Domain
sUserDomain = createobject("wscript.network").UserDomain
Set Connect = GetObject("winmgmts://"&strComputer)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
' ********** Current Path
sCurrentPath = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
' ********** Blank the report message
strMsg = ""
' ********** Set objects
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")
' ********** Get UserName
sUser = CreateObject("WScript.Network").UserName
' ********** Print user and computer
'strMsg = strMsg & " User: " & sUser & VbCrLf
'strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf
strMsg = strMsg & "### COPIED FROM " & strComputer & " ###" & VbCrLf& VbCrLf
strMsg = strMsg & "#echo off" & vbCrLf
For i = 0 to oDrives.Count - 1 Step 2
strMsg = strMsg & "net use " & oDrives.Item(i) & " " & oDrives.Item(i+1) & " /user:" & sUserDomain & "\" & sUser & " /persistent:yes" & VbCrLf
Next
strMsg = strMsg & ":exit" & VbCrLf
strMsg = strMsg & "#pause" & VbCrLf
' ********** write the file to disk.
strDirectory = sCurrentPath
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
' Procede
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End if
' ********** Calculate date serial for filename **********
intMonth = month(now)
if intMonth < 10 then
strThisMonth = "0" & intMonth
else
strThisMonth = intMOnth
end if
intDay = Day(now)
if intDay < 10 then
strThisDay = "0" & intDay
else
strThisDay = intDay
end if
strFilenameDateSerial = year(now) & strThisMonth & strThisDay
sFileName = strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".bat"
Set objFile = objFSO.CreateTextFile(sFileName,True)
objFile.Write strMsg & vbCrLf
' ********** Ask to view file
strFinish = "End: A .bat was generated. " & VbCrLf & "Copy the generated file (" & sFileName & ") into the machine where you want to recreate the mappings and double-click it." & VbCrLf & VbCrLf
MsgBox(strFinish)

Monitoring service with WMI

I would like to monitor some services with WMI:
1. Test if the service is running
2. If not running restart it
3. If I can't restart it send an email
Could someone help me deal with this please?
strComputer = "."
srv= " WSearch, wuauserv "
Set objWMIService = GetObject( _
"winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_Service where Name='srv'")
For Each objService in colItems
Wscript.Echo "Service Name: " & objService.Name & VBNewLine _
& "State: " & objService.State
if objService.State="Stopped" then
objService.StartService()
Wscript.Echo "Started service "
else
REM here the code for email if the service didn't start
end if
Next

Vbscript logging into ftp

I am attempting to log into ftp host and download files. I am not sure how to locate the file as it is stored in directories under the date and will change every day. this is what I have so far
Option Explicit
Dim objFSO, objMyFile, objShell, strFTPScriptFileName, strFilePut
Dim strLocalFolderName, strFTPServerName, strLoginID
Dim strPassword, strFTPServerFolder
strLocalFolderName = "c:\foldername"
strFTPServerName = "ftp.host.com"
strLoginID = "somelogin"
strPassword = "password8"
so after the password how would I log into the date file and locate so for example the file would be under
20130722/filename.ftp
The usual way to do this in VBScript is to generate an FTP script and run that with ftp.exe:
'variable definitions
...
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
remoteDir = Year(Date) & Right("0" & Month(Date), 2) & Right("0" & Day(Date), 2)
tempDir = sh.ExpandEnvironmentStrings("%TEMP%")
script = fso.BuildPath(tempDir, "download.ftp")
logfile = fso.BuildPath(tempDir, "ftp.log")
Set f = fso.OpenTextFile(script, 2, True)
f.WriteLine "open" & strFTPServerName & vbNewLine _
& "user" & strLoginID & vbNewLine _
& strPassword & vbNewLine _
& "prompt no" & vbNewLine _
& "lcd " & strLocalFolderName & vbNewLine _
& "cd " & remoteDir & vbNewLine _
& "get cs.ftp" & vbNewLine _
& "bye"
f.Close
rc=sh.Run("%COMSPEC% /c ftp -s:" & qq(script) & " >" & qq(logfile), 0, True)
WScript.Echo "FTP finished with exit code " & rc & "."
fso.DeleteFile script, True
The above should work out of the box. If you're free to install additional software, the FTP client included with ActiveXperts' Network Component might be another option.

How to check which Operating System?

How can I check OS version in a batch file or through a vbs in an Windows 2k/2k3 environment ?
You know ... Something like ... : "If winver Win2k then ... or if winver Win2k3 then ....
Run the ver command and parse the string output that it gives you.
you can use vbscript
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colOSes = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOS in colOSes
Wscript.Echo "Computer Name: " & objOS.CSName
Wscript.Echo "Caption: " & objOS.Caption 'Name
Wscript.Echo "Version: " & objOS.Version 'Version & build
Next
use the Caption to capture the string you want.
You should use ver and find.
Example:
ver | find "XP"

From cmd.exe script, how can I schedule a task to run on next boot (and never again)?

As part of a very simple cmd.exe install script, I need to run a program the next time the machine reboots. I don't want it to run after that (it's a one-shot configuration tool).
The program will actually be another cmd.exe script but any example should do since I can run cmd /c on the script itself.
What's the best way to go about doing this?
You could use the SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce key
This VB script could help. Extract:
workfile = ifile.ReadLine
strcomputer = ucase(left(workfile,instr(workfile,",")-1))
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strcomputer & "\root\default:StdRegProv")
if err.number <> 0 then
ofile.WriteLine "[" & now() & "] " & strcomputer & " will NOT run once. Failed to set runonce install with error: " & Err.Number & "/" & left(Err.Description,17)
else
sKeyPathEnv = "SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
sValueName = "Set_RunOnce"
sKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
sValueName = "SystemRoot"
oReg.GetExpandedStringValue HKLM, sKeyPath, sValueName, sSystemRoot
oReg.SetStringValue HKLM, sKeyPathEnv, "Set_RunOnce", vRunOnce
if Err.Number <> 0 then
ofile.WriteLine "[" & now() & "] " & strcomputer & " will NOT run once. Failed to set runonce install with error: " & Err.Number & "/" & left(Err.Description,17)
else
ofile.WriteLine "[" & now() & "] " & strcomputer & " will run once via runonce at next reboot. "
end if
end if

Resources