I have a requirement to copy some files and folders to a USB drive with a specific volumelabel (to take into account drive letter may change)
I am using the below to determine, and return, the drive letter; how to I then use this to copy files to that drive (and overwrite any existing files)
I only know how to use objShell.run "cmd /c copy c:\temp\file.xml X:\temp file\ /y" but obviously can't use that in this case.
Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
For Each objDrive in colDrives
Select Case objDrive.DriveType
Case 1
If objDrive.VolumeName = "MyUSB" Then '
Message = Message & "Drive letter: " & objDrive.DriveLetter & VbCrLf '
Message = Message & "Drive type: " & objDrive.DriveType & VbCrLf '
Message = Message & "Volume name: " & objDrive.VolumeName & VbCrLf & VbCrLf '
End If
End Select
Next
Give a try for this example and tell me the result :
'Show drive letters associated with each
DriveLetter = ""
ComputerName = "."
Set wmiServices = GetObject ( _
"winmgmts:{impersonationLevel=Impersonate}!//" _
& ComputerName)
' Get physical disk drive
Set wmiDiskDrives = wmiServices.ExecQuery ( "SELECT Caption, DeviceID FROM Win32_DiskDrive WHERE InterfaceType = 'USB'")
For Each wmiDiskDrive In wmiDiskDrives
' x = wmiDiskDrive.Caption & Vbtab & " " & wmiDiskDrive.DeviceID
'Use the disk drive device id to
' find associated partition
query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" & wmiDiskDrive.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Set wmiDiskPartitions = wmiServices.ExecQuery(query)
For Each wmiDiskPartition In wmiDiskPartitions
'Use partition device id to find logical disk
Set wmiLogicalDisks = wmiServices.ExecQuery ("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _
& wmiDiskPartition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition")
x = ""
For Each wmiLogicalDisk In wmiLogicalDisks
'x = x & wmiDiskDrive.Caption & " " & wmiDiskPartition.DeviceID & " = " & wmiLogicalDisk.DeviceID
'Wscript.echo x
Wscript.echo "The DriveLetter of your USB Key is = " & wmiLogicalDisk.DeviceID & "\"
DriveLetter = wmiLogicalDisk.DeviceID
Next
Next
Next
Set WS = CreateObject("WScript.Shell")
Command = "cmd /c copy c:\temp\file.xml " & DriveLetter & "\ /y"
wscript.echo Command
Result = ws.run(Command,0,False)
Or something like that :
Set Ws = CreateObject("WScript.Shell")
Set FSO=CreateObject("Scripting.FileSystemObject")
For each Drv in FSO.Drives
If Drv.DriveType=0 Then Dtype="Unknown "
If Drv.DriveType=1 Then Dtype="Removable"
If Drv.DriveType=2 Then Dtype="Fixed "
If Drv.DriveType=3 Then Dtype="Network "
If Drv.DriveType=4 Then Dtype="CD-ROM "
If Drv.DriveType=5 Then Dtype="RAM Disk "
If Drv.IsReady Then
If Drv.DriveType=1 Then
Dfree=Drv.FreeSpace
DfreeMB=FormatNumber(Drv.FreeSpace/(1024^2),0)&" MB"
DriveLetter=Drv.DriveLetter
End if
End if
Next
MsgBox "Espace Libre dans Le Flash Disk " & DriveLetter & ":\"&" est Environ de " & DfreeMB,64,"Espace Libre"
Command = "cmd /c copy c:\temp\file.xml " & DriveLetter & ":\ /y"
wscript.echo Command
Result = ws.run(Command,0,True)
Related
I am running the below vbscript on outlook 2013/2016 and having issues trying to read emails in sub folders off the Inbox. I can read the Inbox emails. . Can anyone point me in the right directions?
thanks in advance.
Function CheckMail(strMailBox,strFolder,strFolderAbbr,strDetails)
'
olFolderInbox = 6
set Session = CreateObject("Redemption.RDOSession")
'
Set objOutlook = CreateObject("Outlook.Application")
Session.MAPIOBJECT = objOutlook.Session.MAPIOBJECT
set Store = Session.Stores.GetSharedMailbox(strMailBox)
set Inbox = Store.GetDefaultFolder(olFolderInbox)
'
Wscript.Echo "MailBox: " & Store.Name & " - " & Inbox.Name
If strFolder = "" then
set SubFolder = Inbox
strFolderAbbr = strMailBox & " Inbox"
Else
'set SubFolder = Inbox.Folders(strFolder)
'
set SubFolder = Inbox.Folders.Item(strFolder)
'
strFolderAbbr = strMailBox & " Inbox\" & strFolder
Wscript.Echo " Sub Folder: " & SubFolder
End If
'
nItems = SubFolder.Items.Count
If nHowlong > 1 Then
nHowlong = Round((nItems/110)/60,0)
strTime = " Hour(s)!!"
Else
nHowlong = Round(nItems/110,0)
strTime = " Minute(s)!!"
End If
Wscript.Echo nItems & " - Emails in folder " & strFolderAbbr & " About " & nHowlong & strTime
'" - " & nItems
'
for each Msg in SubFolder.Items
nCounter = nCounter + 1
'Wscript.Echo "Item " & nCounter & "/" & nItems & vbCRLF & "EID: " & Msg.EntryID & vbCRLF & "ABOUT: " & Msg.Subject & vbCRLF & "FROM: " & Msg.SenderName & vbCRLF & "LEVEL: " & IIf(Msg.Importance=2,"High",IIf(Msg.Importance=1,"Normal","Low")) & vbCRLF & "Status: " & IIf(Msg.UnRead, "Not Read", "Read") & vbCRLF & "Received: " & Msg.ReceivedTime & vbCRLF & "Body: " & Msg.Body
'& nCounter & "/" & nItems & vbCRLF & "EID: " & Msg.EntryID & vbCRLF & "ABOUT: " & Msg.Subject & vbCRLF & "FROM: " & Msg.SenderName & vbCRLF & "LEVEL: " & IIf(Msg.Importance=2,"High",IIf(Msg.Importance=1,"Normal","Low")) & vbCRLF & "Status: " & IIf(Msg.UnRead, "Not Read", "Read") & vbCRLF & "Received: " & Msg.ReceivedTime & vbCRLF & "Body: " & Msg.Body
'
' process all emails in the box
strRecords = strRecords & "REG-" &strFolderAbbr & "~" & Msg.Subject & "~" & Msg.ReceivedTime & "~" & IIf(Msg.UnRead, "Not Read", "Read") & "~" & Msg.SenderName & "~" &IIf(Msg.Importance=2,"High",IIf(Msg.Importance=1,"Normal","Low")) & "*"
On Error Resume Next
err.clear
if Err Then
'WScript.Echo "ReceivedTime was null"
End If
On Error GoTo 0
next
CheckMail = strRecords
End Function
Function IIf(bClause, sTrue, sFalse)
If CBool(bClause) Then
IIf = sTrue
Else
IIf = sFalse
End If
End Function
I finally figured out the code that works. I would first like to thank Dmitry for all the help he gave me. But this was a stuburn issue. the following code solved the problem. Please dont ask me to explain it just plain ole luck and trail and error.
set Session = CreateObject("Redemption.RDOSession")
Set objOutlook = CreateObject("Outlook.Application")
Session.MAPIOBJECT = objOutlook.Session.MAPIOBJECT
'Set Root foldedr of the mail box of the stores
set IPMRoot = Session.Stores.Item(strMailBox).IPMRootFolder
'Set the subfolder to the inbox
If strFolder = "" then
set subFolder = IPMRoot.Folders("InBox")
strFolderAbbr = strMailBox & " Inbox"
Else
'Set subfolder to subfolder chosen
set subFolder = IPMRoot.Folders("InBox").Folders(strFolder)
strFolderAbbr = strMailBox & " Inbox\" & strFolder
End If
'
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'm using the following code to try to stop a service. I can display the service state using WScript.Echo objService.State so I know I have the right service name and that it can find it and determine its state as running or stopped but when I run this script I get an Error on Line 51: Error Not Found Code 80041002 (see screenshot)
The line of code at 51 is:
objService.StopService()
Where am I going wrong? I can stop and start this via the command line using sc.exe and am able to control other services ie Alerter but as soon as I try to control this particular service it fails.
Thanks
EDIT The full code from the script (Thanks Brandon Moretz who pointed out
that I hadn't posted the full code so
the Line number didn't mean anything &
I have changed the StartService() back
to Stop as it originally was so now you have more to go on. Sorry!)
' 1. Check that the latest backup zip exists and store its name in LBZ (LatestBackupZip)
' 2. Stop the Livecontent Service
' 3. Remove .dbx, .lck and .log files from DataFolder
' 4. restart the service
' 5. Restore the database
Dim fileNewest
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
'Set ImportFldr = fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data\Import")
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\export")
'Set DataFldr = fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data")
Set DataFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data")
For Each aFile In ImportFldr.Files
sExtension = fso.GetExtensionName(aFile.Name)
If sExtension = "log" Then
'Msgbox "The file extension is a " & sExtension
Else
'Msgbox "The file extension is a " & sExtension
If fileNewest = "" Then
Set fileNewest = aFile
Else
'If fileNewest.DateCreated < aFile.DateCreated Then
If CDate(fileNewest.DateCreated) < CDate(aFile.DateCreated) Then
Set fileNewest = aFile
End If
End If
End If
Next
Msgbox "The Newest File in the folder is " & fileNewest.Name & chr(13) & "Size: " & fileNewest.Size & " bytes" & chr(13) & "Was last modified on " & FileNewest.DateLastModified
' Change to /Data
'WScript.Echo WshShell.CurrentDirectory
WshShell.CurrentDirectory = DataFldr
'WScript.Echo WshShell.CurrentDirectory
' Stop the Livecontent service
strComputer = "."
Dim objService
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'LiveContent'")
For Each objService in colServiceList
WScript.Echo objService.State
If objService.State = "Running" Then
objService.StopService()
'Wscript.Sleep 5000
End If
Next
'Dim objShell
'Set objShell = CreateObject("WScript.Shell")
'objShell.Run "%comspec% /k c: & cd ""C:\Program Files (x86)\XyEnterprise\SDL LiveContent\"" & """"loaddb RESTORE -'Dlc.file=C:\PROGRA~2\XYENTE~1\SDLLIV~1\data\Import\" & fileNewest.Name & " -Dlc.pswd=N2kAs72z"""""
LATEST EDIT
I have taken your code and still can't get it to work. I noticed that the line:
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
was missing a \ at "winmgmts:\" which I have added and I like your check to see if there is an (x86) directory as I am testing this on a 32bit server but will move it over to a 64 when it is ready so that will work nicely.
Also this section didn't work:
If fso.FolderExists( "C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data" ) Then
Set DataFldr= fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data")
Else If fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data") Then
Set DataFldr= fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data")
End If
But did if I changed the ElseIf fso.GetFolder to fso.FolderExists
The script runs fine if I comment out Line 78
objService.StopService()
But as soon as I uncomment it I get an error:
Line: 78
Char: 9
Error: Not found
Code: 80041002
Source: SWbemObjectEx
But the Service can be found as the line: WScript.Echo objService.State Echos its state to the screen.
Really confuzzled now.
' 1. Check that the latest backup zip exists and store its name in LBZ (LatestBackupZip)
' 2. Stop the Livecontent Service
' 3. Remove .dbx, .lck and .log files from DataFolder
' 4. restart the service
' 5. Restore the database
Dim fileNewest
Dim ImportFldr
Dim DataFldr
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data\Import" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\Import")
Else
WScript.Echo "Warning: Import Directory can not be found"
End If
If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data\export" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\export")
Else
WScript.Echo "Warning: Export Directory can not be found"
End If
If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data" ) Then
Set DataFldr= fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data")
Else
WScript.Echo "Warning: Data Directory can not be found"
End If
For Each aFile In ImportFldr.Files
sExtension = fso.GetExtensionName(aFile.Name)
If sExtension = "log" Then
'Msgbox "The file extension is a " & sExtension
Else
'Msgbox "The file extension is a " & sExtension
If fileNewest = "" Then
Set fileNewest = aFile
Else
If fileNewest.DateCreated < aFile.DateCreated Then
If CDate(fileNewest.DateCreated) < CDate(aFile.DateCreated) Then
Set fileNewest = aFile
End If
End If
End If
End If
Next
'Msgbox "The Newest File in the folder is " & fileNewest.Name & chr(13) & "Size: " & fileNewest.Size & " bytes" & chr(13) & "Was last modified on " & FileNewest.DateLastModified
' Change to /Data
WScript.Echo WshShell.CurrentDirectory
WshShell.CurrentDirectory = DataFldr
WScript.Echo WshShell.CurrentDirectory
' Stop the Livecontent service
strComputer = "."
Dim objService
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'LiveContent'")
For Each objService in colServiceList
WScript.Echo objService.State
If objService.State = "Running" Then
objService.StopService()
WScript.Echo objService.State
Wscript.Sleep 5000
End If
Next
EDIT 2
After very extensive testing we have come to the conclusion that there is nothing wrong with the script, it is just that this particular service will not stop with this method.
To this end we have moved on and are now using
objShell.Run "sc start LiveContent"
And this works a treat.
Thanks to Brandon for your help.
There are a couple of minor issues:
1.) Not checking for if a folder exists for calling get folder, this is what was causing your 'Not Found' error.
2.) Non-matching If ... Then & End statements in your file loop. (I would probably choose a better editor for vbscript, programmers notepad and notepad++ are very useful.)
3.) The StartService() / StopService() mix-up I mentioned previously.
' 1. Check that the latest backup zip exists and store its name in LBZ (LatestBackupZip)
' 2. Stop the Livecontent Service
' 3. Remove .dbx, .lck and .log files from DataFolder
' 4. restart the service
' 5. Restore the database
Dim fileNewest
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim ImportFldr
If fso.FolderExists( "C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data\Import" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data\Import")
Else If fso.FolderExists( "C:\Program Files\XyEnterprise\SDL LiveContent\data\export" ) Then
Set ImportFldr = fso.GetFolder("C:\Program Files\XyEnterprise\SDL LiveContent\data\export")
End If
Dim DataFldr
If fso.FolderExists( "C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data" ) Then
Set DataFldr= fso.GetFolder("C:\Program Files (x86)\XyEnterprise\SDL LiveContent\data")
Else If fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data") Then
Set DataFldr= fso.GetFolder("C:\Program diles\XyEnterprise\SDL LiveContent\data")
End If
For Each aFile In ImportFldr.Files
sExtension = fso.GetExtensionName(aFile.Name)
If sExtension = "log" Then
'Msgbox "The file extension is a " & sExtension
Else
'Msgbox "The file extension is a " & sExtension
If fileNewest = "" Then
Set fileNewest = aFile
Else
If fileNewest.DateCreated < aFile.DateCreated Then
If CDate(fileNewest.DateCreated) < CDate(aFile.DateCreated) Then
Set fileNewest = aFile
End If
End If
End If
End If
Next
Msgbox "The Newest File in the folder is " & fileNewest.Name & chr(13) & "Size: " & fileNewest.Size & " bytes" & chr(13) & "Was last modified on " & FileNewest.DateLastModified
' Change to /Data
'WScript.Echo WshShell.CurrentDirectory
WshShell.CurrentDirectory = DataFldr
'WScript.Echo WshShell.CurrentDirectory
' Stop the Livecontent service
strComputer = "."
Dim objService
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'LiveContent'")
For Each objService in colServiceList
WScript.Echo objService.State
If objService.State = "Running" Then
objService.StopService()
'Wscript.Sleep 5000
End If
Next
'Dim objShell
'Set objShell = CreateObject("WScript.Shell")
'objShell.Run "%comspec% /k c: & cd ""C:\Program Files (x86)\XyEnterprise\SDL LiveContent\"" & """"loaddb RESTORE -'Dlc.file=C:\PROGRA~2\XYENTE~1\SDLLIV~1\data\Import\" & fileNewest.Name & " -Dlc.pswd=N2kAs72z"""""
After very extensive testing we have come to the conclusion that there is nothing wrong with the script as it starts and stops other services, it is just that this particular service will not stop with this method.
To this end we have moved on and are now using
objShell.Run "sc start LiveContent"
And this works a treat.
Thanks to Brandon for your help.
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
' *******************
I'm getting an "object required" error on line 54, the last line, when I run the following script. What is wrong?
Option Explicit
Dim cmdString, g_strHostFile, filepath, flexnetpath, importcmd, dtmToday, dtmYesterday, dtmFileDate, param1, param2, param3, i4path, objFSO, objTextStream, g_strComputer, WshShell
'Initialize global constants and variables.
Const FOR_READING = 1
g_strHostFile = "D:\dataimports\LUM_servers.txt"
i4path = "C:\IFOR\WIN\BIN\i4blt.exe"
filepath = "D:\DataImports\"
flexnetpath = "C:\Program Files (x86)\Flexnet\Manager\Admin"
importcmd = flexnetpath & "flexnet bulkimport -uadmin -padmin -f" & filepath
dtmToday = Date()
dtmYesterday = Date() - 1
dtmFileDate = Year(Date) & padDate(Month(Date)) & padDate(Day(Date))
param1 = "-r1 -e2,4 -n "
param2 = " -v 'Dassault Systemes' -b "
param3 = " -g "
WScript.Echo "i4Path: " & i4path
WScript.Echo "FilePath: " & filepath
WScript.Echo "flexnetpath: " & flexnetpath
WScript.Echo "importcmd: " & importcmd
WScript.Echo "dtmToday: " & dtmToday
WScript.Echo "dtmYesterday: " & dtmYesterday
WScript.Echo "dtmFileDate: " & dtmFileDate
'Read LUM Server Names from text file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(g_strHostFile) Then
Set objTextStream = objFSO.OpenTextFile(g_strHostFile, FOR_READING)
Else
WScript.Echo "Input file " & g_strHostFile & " not found."
WScript.Quit
End If
'Loop through list of computers and perform tasks on each.
Do Until objTextStream.AtEndOfStream
g_strComputer = objTextStream.ReadLine
WScript.Echo "Processing Server: " & g_strComputer
Set cmdString = i4path & param1 & g_strComputer & param2 & dtmYesterday & param3 & dtmToday & filepath & g_strComputer & "_" & dtmFileDate & "_lum.lrl"
WScript.Echo "Processing Command: " & cmdString
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmdString"
Loop
objTextStream.Close
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "Processing Bulk Import: " & importcmd
WshShell.Run "importcmd"
Function padDate(intNumber)
if intNumber <= 9 Then
padDate = "0" & CStr(intNumber)
Else
padDate = CStr(intNumber)
End If
End Function
Object required is raised when you have a statement like Set x = y where x is not an object type, but is instead an simple type (Integer, Double, Date, etc. ). I think the line
Set cmdString = i4path & param1 & g_strComputer & param2 & ...
is causing the error, and I think all you have to do is remove the Set statement. I think strings do not derive from Object and thus do not need the Set statement.
There are a few problems, I think.
importcmd = flexnetpath & "flexnet bulkimport -uadmin -padmin -f" & filepath
You probably need some spaces:
importcmd = flexnetpath & " flexnet bulkimport -uadmin -padmin -f " & filepath
Set is only used with objects, not strings, so it should be removed from this line:
Set cmdString = i4path & param1 & g_strComputer & param2 & dtmYesterday & param3 & dtmToday & filepath & g_strComputer & "_" & dtmFileDate & "_lum.lrl"
I am fairly sure you either mean
WshShell.Run importcmd
Or
WshShell.Run """" & importcmd & """"