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"
Related
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)
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
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.
I have a VB script that's being forced to run in Wow64 mode. I'd like to have it start either another script, or itself, in native 64 bit mode. Is there anyway to do that?
The initial script is being called by an explicit call to cscript.exe (not sure if this makes a difference or not)
Thanks
Apparently its pretty simple.
In Windows Vista and newer there is an alias folder at C:\Windows\Sysnative. If you call it it will not redirect to the c:\windows\SysWow64 32 bit folder but will force the native 64 bit executables to be called
http://msdn.microsoft.com/en-us/library/aa384187(VS.85).aspx
Therefore, you can run a vbscript in 64 bit mode from a vbscript running in wow64 mode by calling %windir%\Sysnative\cscript.exe and then providing the name of your script as a parameter.
However, this only works in Windows Vista or newer. There is a hotfix which can enable this Sysnative folder in Windows XP/2003
http://support.microsoft.com/kb/942589
Place the following code at the top of your script to detect if the OS is 64bit then re-run in 32bit mode
' ***************
' *** 64bit check
' ***************
' check to see if we are on 64bit OS -> re-run this script with 32bit cscript
Function RestartWithCScript32(extraargs)
Dim strCMD, iCount
strCMD = r32wShell.ExpandEnvironmentStrings("%SYSTEMROOT%") & "\SysWOW64\cscript.exe"
If NOT r32fso.FileExists(strCMD) Then strCMD = "cscript.exe" ' This probably won't work if we can't find the SysWOW64 Version
strCMD = strCMD & Chr(32) & Wscript.ScriptFullName & Chr(32)
If Wscript.Arguments.Count > 0 Then
For iCount = 0 To WScript.Arguments.Count - 1
if Instr(Wscript.Arguments(iCount), " ") = 0 Then ' add unspaced args
strCMD = strCMD & " " & Wscript.Arguments(iCount) & " "
Else
If Instr("/-\", Left(Wscript.Arguments(iCount), 1)) > 0 Then ' quote spaced args
If InStr(WScript.Arguments(iCount),"=") > 0 Then
strCMD = strCMD & " " & Left(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), "=") ) & """" & Mid(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), "=") + 1) & """ "
ElseIf Instr(WScript.Arguments(iCount),":") > 0 Then
strCMD = strCMD & " " & Left(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), ":") ) & """" & Mid(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), ":") + 1) & """ "
Else
strCMD = strCMD & " """ & Wscript.Arguments(iCount) & """ "
End If
Else
strCMD = strCMD & " """ & Wscript.Arguments(iCount) & """ "
End If
End If
Next
End If
r32wShell.Run strCMD & " " & extraargs, 0, False
End Function
Dim r32wShell, r32env1, r32env2, r32iCount
Dim r32fso
SET r32fso = CreateObject("Scripting.FileSystemObject")
Set r32wShell = WScript.CreateObject("WScript.Shell")
r32env1 = r32wShell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
If r32env1 <> "x86" Then
' we are not running in x86 mode, so run in that mode; check if we have done this already
For r32iCount = 0 To WScript.Arguments.Count - 1
r32env2 = r32env2 & WScript.Arguments(r32iCount) & VbCrLf
Next
' MsgBox "64bit (restarting) " & r32env2
If InStr(r32env2,"restart32") = 0 Then RestartWithCScript32 "restart32" Else MsgBox "Cannot find 32bit version of cscript.exe or unknown OS type " & r32env1
Set r32wShell = Nothing
WScript.Quit
Else
For r32iCount = 0 To WScript.Arguments.Count - 1
r32env2 = r32env2 & WScript.Arguments(r32iCount) & VbCrLf
Next
' MsgBox "32bit! " & r32env2
End If
'MsgBox "OS: " & r32env1 & VbCrLf & "Param: " & r32env2 & VbCrLf & "Script: " & WScript.FullName & VbCrLf & "Fullname: " & " " & Wscript.ScriptFullName
Set r32wShell = Nothing
Set r32fso = Nothing
' WScript.Quit
' *******************
' *** END 64bit check
' *******************
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