BAT file to map to network drive without running as admin - windows

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)

Related

vbscript output to text on wndows startup

I'm looking for vbscript that do the following tasks
Script Tasks
execute on startup of the computer,
the way is being executed is via putting it in startup folder of windows in
C:\Documents and Settings\Admin\Start Menu\Programs\Startup
if output text file is exist, write down some text and exit
if the text file is not exist then it echo out full destination
the code is as provided, any help would be appreciated
'create txt.vbs
'vbscript
Set WshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = objFSO.GetAbsolutePathName(".")
FilePath = CurrentDirectory & "\test.txt"
Existcode = objFSO.FileExists(FilePath)
' wscript.echo "FileExists code:" & Existcode
if Existcode = False then
Existcode = objFSO.FileExists(FilePath)
'for debugging
wscript.echo "file not exist" & vbCrLf _
& "FileExists code:" & Existcode
Set objFile = objFSO.CreateTextFile(FilePath,True)
strtext = "file created:" & vbCrLf & chr(34) & "New Line" & chr(34)
objFile.Write strtext & vbCrLf
objFile.Close
else
'for debugging
wscript.echo "file exist" & vbCrLf _
& "FileExists code:" & Existcode & vbCrLf & vbCrLf _
& FilePath & vbCrLf _
& CurrentDirectory & vbCrLf
end if
wscript.echo "end"
when get executed by clicking on it, either via a batch file, the script works with no errors and the output is as expected
while it's executed from startup folder by
windows, it show all echo that i set for debugging but doesn't
create the output file neither write to text in it, but also it read it as exist i'm not sure why
the vbscript cannot write text to startup folder,
however changes are the following
CurrentDirectory = objFSO.GetAbsolutePathName(".")
FilePath = CurrentDirectory & "\test.txt"
become
DesktopDirectory = WshShell.SpecialFolders("Desktop")
FilePath = DesktopDirectory & "\test.txt"

Copying files and folders to specific volume label

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)

How to start java program (from .jar) elevated only using VBScript

There is a great answer providing a batch file what will allways do it's best to run elevated and will not elevate if already elevated.
I don't want to distribute the batch file with my program though. The whole core of the answer is this VBSScript:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "[path to the batch file which will run elevated]", "ELEV", "", "runas", 1
Pretty simple. So just instead of the path to the batch file, I want to use the path to a jar file. But it doesn't seem to work:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "AutoClient.jar", "ELEV", "", "runas", 1
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw -jar AutoClient.jar", "ELEV", "", "runas", 1
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw", "ELEV", "-jar AutoClient.jar", "runas", 1
So well, how can I run the jar from the vbs file? Both files share the same directory. It's necessary that java application's working directory is that directory.
Edit:
So thanks #MCND (and this) I now know that the arguments go as follows:
path to executable to run
command line parameters sent to the program
working directory of the new process
'runas' command which invokes elevation
0 means do not show the window, 1 to show the window
And thanks to his code:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw.exe", "-jar AutoClient.jar", "", "runas", 1
I can add another error in my collection:
The documentation states that the first parameter in the call is the file to start, leaving the arguments to the second parameter. So it should be (sorry, not tested)
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw.exe", "-jar AutoClient.jar", "", "runas", 1
So far, the only way I made this work without crazy popup errors is:
' Get the script location, the directorry where it's running
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
' Args:
' path to executable to run
' command line parameters - first parameter of this file, which is the jar file name
' working directory (this doesn't work but I use it nevertheless)
' runas command which invokes elevation
' 0 means do not show the window. Normally, you show the window, but not this console window
' which just blinks and disappears anyway
UAC.ShellExecute "run-normally.bat", "SomeFile.jar, strFolder, "runas", 0
Because the working directory parameter doesn't work, I have following two lines in the bat file:
rem Used as a helper for the elevating VBS script. Runs the jar file
rem given as 1st argument as if the file was double clicked.
rem Make sure we're on our CURRENT directory
cd /d %~dp0
rem Run java, expecting the jar file to be given as the 1st argument
javaw -jar %1
I am not satisfied with this solution for cosmetic reasons. I want to display the UAC message for JRE, not windows command line:
I don't use Java but you aren't specifing full paths. You can't expect things to work reliably. Also whatever you are starting will need to have on it's right click menu Run As Administrator because the VBS code runs that menu command as if you clicked it. If it's not there you can't click it. EXE have it. So specify the correct paths to both Javaw and the jar file.
One issue is that the current directory is different depending on what technique you are using. ALWAYS specify full paths.
Here's a script that lists what verbs are available for an object (not we are not working with files but with objects). The graphical shell (explorer) is an object browser and has no idea what a file is apart from the fact it's an object of some type.
---------------------------
Windows Script Host
---------------------------
ShVerb
Lists or runs an explorer verb (right click menu) on a file or folder
ShVerb <filename> [verb]
Used without a verb it lists the verbs available for the file or folder
The program lists most verbs but only ones above the first separator
of the menu work when used this way
The Properties verb can be used. However the program has to keep running
to hold the properties dialog open. It keeps running by displaying
a message box.
---------------------------
OK
---------------------------
The script
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo(Cmd.doit)
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If

Can't stop a service using vbscript

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.

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