VBScript Writing to Server Text File - vbscript

I have created a VBScript which pulls the service tag, username, and computer name from a computer. What I need to do now is compile this information in a text document.
How it's set up is as follows:
We have an Active Directory Server, with a folder for login scripts. I have created a batch file to run this .vbs script, and the script works well so far. What I now need is for a file on the AD server, called "logging.txt", to be populated with the information that is created with the .vbs script.
This is the script I have so far:
'Get Dell Service Tag Info
set ProSet = GetObject("winmgmts:").InstancesOf("Win32_BIOS")
Set ProSet1 = GetObject("winmgmts:").InstancesOf("Win32_SystemEnclosure")
For each Pro in ProSet
For each Pro1 in ProSet1
ServiceTag=Pro.SerialNumber
wscript.echo ServiceTag
exit for
Next
exit for
Next
'get username and computername, could also be asked in a batch
Set oShell = WScript.CreateObject("WScript.Shell")
Set oShellEnv = oShell.Environment("Process")
sComputerName = oShellEnv("ComputerName")
sUsername = oShellEnv("username")
wscript.echo sComputerName & " " & sUsername
Thank you very much in advance!
This is what I've tried so far:
sub log (user, computer)
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile(Server.MapPath(".\logging.csv"),8,true)
f.WriteLine now & "," & user & "," & computer
f.Close:set f=Nothing
set fs=Nothing
end sub

I feel as though you're leaving something out.. this is how to write a text file in VBS.
dim filesys, filetxt, getname, path
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("c:\somefile.txt", True)
path = filesys.GetAbsolutePathName("c:\somefile.txt")
getname = filesys.GetFileName(path)
filetxt.WriteLine("Your text goes here.")
filetxt.Close
If filesys.FileExists(path) Then
Response.Write ("Your file, '" & getname & "', has been created.")
End If

It would probably be easiest to save the information to a local text file and upload it with the command line ftp utility from the batch script that calls your script rather than trying to invent another wheel and do it in vbscript.
You can list the command line options of ftp with:
ftp /?
I recommend setting up something like this:
ftp -s:control.txt
control.txt would contain something like:
open [hostname or address]
[username]
[password]
cd [remote directory name]
put logging.txt
disconnect
bye

Related

SQL Loader : Generate new log file each time

I am using SQL Loader to import data from CSV file to a database table, and it works fine. Each time I run the command sqlldr, the log file is overridden with new infos.
Is there a way to add a timestamp or something to keep the archive of those log files instead of overriding the same file and without passing the value in the command params.
.par file :
CONTROL=D:\projects\ctl\control.ctl
LOG=D:\projects\log\TRACK_MIGRATION.log
DATA=D:\projects\data\CUSTOMERS_SITES.csv
Want something like : TRACK_MIGRATION_20221229_113917.log
You must modify the startup script to remove the log parameter from the parameter file and add the log parameter to the command line.
.par file
CONTROL=D:\projects\ctl\control.ctl
DATA=D:\projects\data\CUSTOMERS_SITES.csv
command line
sqlldr user/password#DB parfile=parfile.par log=log_%date%_%time:~0,2%%time:~3,2%%time:~6,2%.log
log file
29.12.2022 20:06 1 262 log_29.12.2022_200657.log
29.12.2022 20:12 1 262 log_29.12.2022_201224.log
After a long search, found no native way to automate naming the SQL Loader log file by adding a timestamp or something.
As mentioned above, I suggest wrapping the command line in a script that will take the responsibility of renaming your log file after it gets generated, or using the log= command line param which is a bit frustrating if you are running your command often.
For my case I found that our client use VBScript for such things in the server, so I decided using it to wrap my command line.
'Running SQL Loader command line
Dim oShell
Set oShell = WScript.CreateObject("WScript.Shell")
oShell.run "sqlldr userid=" & DBLogin & "/" & DBPwd & "#" & DBName & " parfile=parfile.par"
Set oShell = Nothing
'Renaming the log file (TRACK_MIGRATION_YYYYMMDD_HHMMSS.log)
Dim FSO
Dim todayDate
todayDate = Year(Now) & Month(Now) & Day(Now) & "_" & Hour(Now) & Minute(Now) & Second(Now)
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.MoveFile "TRACK_MIGRATION.log", "TRACK_MIGRATION_" & todayDate & ".log"

File checking on Windows Startup is failing [duplicate]

This question already has answers here:
Getting current directory in VBScript
(9 answers)
Cannot get the current directory in .vbs file [duplicate]
(1 answer)
Closed 2 years ago.
I have this script that allows me to automatically backup my MySQL Database every 5 minutes using a batch file.
Dim WshShell
Dim FSO
Dim stopBackup
stopBackup = false
' Register on Windows Startup if not registered when this file is opened.
RegisterOnWindowsStartUp()
' Keep backing up the database every 5 minutes, loop will do.
Do While True
Set FSO = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("auto_backup.bat") Then ' Check if bat file for backing up the database exist.
MsgBox "Backup Message Test."
' Run the batch file which handle the auto backup of database, keep it invisible.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "auto_backup.bat" & Chr(34), 0
Set WshShell = Nothing
WScript.Sleep 300000 ' Delay loop every 5 minutes.
Else ' Stop the loop and do not proceed anymore when the bat file is not exist.
WScript.Echo "Failed to auto backup the database, this won't continue anymore."
stopBackup = true
RemoveFromRegistry() ' Unregister this file on Windows Startup since the bat file is no longer exist.
End If
If stopBackup Then ' Break the loop when stopBackup become true
Exit Do ' Break the loop here.
End If
Loop
' Remove this script from registry on Windows Startup
Function RemoveFromRegistry()
Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.RegDelete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run\autobackup_key"
End Function
' Register this script on Windows Startup only if not registered.
Function RegisterOnWindowsStartUp()
If IsRegistryExist = False Then
Set WshShell = CreateObject("WScript.Shell")
keyNameLocation = "HKCU\Software\Microsoft\Windows\CurrentVersion\Run\autobackup_key"
valueFileLocation = WScript.ScriptFullName
keyType = "REG_SZ"
WshShell.RegWrite keyNameLocation, valueFileLocation, keyType
Set WshShell = Nothing
End If
End Function
' Check if Registry Key Exist on Windows Startup.
Function IsRegistryExist()
Dim sKey, bFound
skey = "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\autobackup_key"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
on error goto 0 ' restore error trapping
end with
If bFound Then
IsRegistryExist = True
Else
IsRegistryExist = False
End If
End Function
The filename of the batch file that allows me to back up the database is auto_backup.bat and it's working fine and no problem, it's on the same directory where the script above is located.
The problem is every time the Windows Startup, it fails to check for the existence of auto_backup.bat, but when I open the script and run it, its working fine and no issue.
There might be some issue with my logic, can anybody help me fix it?
it's on the same directory where the script above is located
This is not where a relative path looks. It starts from the working directory.
The working directory of a shortcut is not necessarily the directory containing the shortcut. You should edit the shortcut properties and set the working directory you want, instead of using the default (which is often C:\Windows or C:\Users\%USERNAME%)
Or you can put an absolute path in the script, or have the script change working directory to its own directory, or have the script combine its directory and the filename to dynamically create an absolute path.
The problem is because when you register your script on Windows Startup through the registry, the script will be executed from the directory of Windows Startup when windows started.
In order to get the original working directory where you can look for the auto_backup.bat, you can combine the FileSystemObject and WScript.ScriptFullName functions to get the parent directory of the current script.
CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\auto_backup.bat"
Then the IF-ELSE condition inside your loop would be
...
Do While True
Set FSO = CreateObject("Scripting.FileSystemObject")
' (1) Add this code.
autobackup_bat_file = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\auto_backup.bat"
If fso.FileExists(autobackup_bat_file) Then ' (2) Change this line.
MsgBox "Backup Message Test."
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & autobackup_bat_file & Chr(34), 0 ' (3) Change this line.
' Continue some of your code here...
...

VBSscript error - Create shortcut to FTP with username and passowrd

I have a vbsscript that I can deploy to users that will create a shortcut to an FTP drive on the user's desktop. This script works in this form:
Set objShell=Wscript.CreateObject("Wscript.shell")
strDesktopFolder=objShell.SpecialFolders("Desktop") & "\"
Set objShortcut=objShell.CreateShortcut(strDesktopFolder & "FTP.lnk")
objShortCut.TargetPath = "ftp://ftp.website.com"
objShortCut.Description = "FTP"
objShortCut.Save
This is great, but it requires that the user type a username and password to access the folder. I really need to save the username and password before as part of the deployment and eliminate extra steps for the end-user. Therefore, I want to save the username and password as part of the vbs script when I deploy it. I have come close and can save a username and password with the following:
Set objShell=Wscript.CreateObject("Wscript.shell")
strDesktopFolder=objShell.SpecialFolders("Desktop") & "\"
Set objShortcut=objShell.CreateShortcut(strDesktopFolder & "FTP.lnk")
objShortCut.TargetPath = "ftp://user:pass#ftp.website.com"
objShortCut.Description = "FTP"
objShortCut.Save
However, the issue is that I can't save them correctly. The username format is:
user#website.com
This is the format for my ftp site. I cannot change that. This format returns an error (800A0005). I need my script to work without error like this:
Set objShell=Wscript.CreateObject("Wscript.shell")
strDesktopFolder=objShell.SpecialFolders("Desktop") & "\"
Set objShortcut=objShell.CreateShortcut(strDesktopFolder & "FTP.lnk")
objShortCut.TargetPath = "ftp://user#website.com:pass#ftp.website.com"
objShortCut.Description = "FTP"
objShortCut.Save
Thanks for any and all help!
If your username contains the # symbol, and your web browser or the windows explorer does not like it, you must substitute it with the + symbol like this :
user#website.com = user+website.com
Set objShell=Wscript.CreateObject("Wscript.shell")
strDesktopFolder=objShell.SpecialFolders("Desktop") & "\"
Set objShortcut=objShell.CreateShortcut(strDesktopFolder & "FTP.lnk")
objShortCut.TargetPath = "ftp://user+website.com:pass#ftp.website.com"
objShortCut.Description = "FTP"
objShortCut.Save

VBS WScript.Run fails after passing Exists test

In a couple of place in my code I check if the file exists (it does) then I try to Run the file as above, or get the DateLastModified, and get errors about file not found or invalid path. How can the script NOT see a file after confirming it exists?
I'm working up a .vbs script that tries to run an Access .mdb file. The WScript.Run command seems to choke on the filename, but putting a MsgBox() before that call to display the path allows Run to work properly. I don't want to display a popup.
Error is:
The directory name is invalid.
How is this possible and how can I get around it?
Here is code:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
SET ws = WScript.CreateObject("WScript.Shell")
path = Chr(34) & LocalPath & AccessFileName & Chr(34)
if (fso.FileExists(LocalPath & AccessFileName)) THEN
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run path 'This line errors
End If
Try to open your file with shell .InvokeVerb method:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
If CreateObject("Scripting.FileSystemObject").FileExists(LocalPath & AccessFileName) Then
CreateObject("Shell.Application").Namespace(LocalPath).ParseName(AccessFileName).InvokeVerb
End If
UPD: Both ActiveX WScript.Shell and Shell.Application uses native windows shell to perform a file execution.The first one launches new process via WSH core located in wscript.exe, cscript.exe, wshom.ocx, jscript.dll, vbscript.dll, ets, .Run and .Exec methods of WsShell object provides wide control on the launched process, and second one located in Shell32.dll, uses .InvokeVerb method of IShellDispatch object, called without name, runs default verb equals to the windows explorer "open" command.In case of any issues connected to WSH, explorer might still works without any proplems. If it does, that is just a work-around, I can't say what's wrong definetely without close look.
Hello the following code worked for me.
Basically this code gets a folder object and loops through all files in a folder and checks if its the one that you named. This it runs the application.
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = Wscript.CreateObject("Wscript.Shell")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set myFolder = fso.GetFolder(LocalPath)
For each myFile in myFolder.Files
If myFile.Name = AccessFileName Then
'Wscript.Echo myFile.Name
ws.Run myFolder.Path & "\" & myFile.Name
End If
Next
You can give this a shot. You probably do not need the quotes around the path, but I included it as a comment if you want to give it a shot. You just put quotes twice if you need to include a quote character in a string:
Set fso = CreateObject("Scripting.FileSystemObject")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set ws = WScript.CreateObject("WScript.Shell")
' path = """" & LocalPath & AccessFileName & """" <-- probably unnecessary
path = LocalPath & AccessFileName
If (fso.FileExists(path)) Then
Set file = fso.GetFile(path)
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run file.Path 'This line errors
End If
This does not make any sense. Having a MsgBox line is altering the behavior of the program!!!
I feel it is probably some weird invisible character somewhere which is getting activated when you comment the line.
Try retyping the If block without the MsgBox in between.

vbscript to check if a process is running, if its not then copy a file from network

I am new to VB scripting and need help on a program to do the following, Can someone please help me out. It would be great if this whole program can be embedded into one vbscript.
Write a script to check
if a process is running or not( example notepad++.exe),
if its running then dont do anything.
If the process is not running, check if a directory is present or not under C:\Program Files(x86)
Say if the directory is not there then copy the .exe file from a network shared location onto a local drive and
then perform the command line installation in silent mode.(example> notepad++.exe -ms)
You can use this example. You need to put an if check and compare with objItem.Name = "notepad.exe" and do whatever you wish to do:
sComputerName = "."
Set objWMIService = GetObject("winmgmts:\\" & sComputerName & "\root\cimv2")
sQuery = "SELECT * FROM Win32_Process"
Set objItems = objWMIService.ExecQuery(sQuery)
'iterate all item(s)
For Each objItem In objItems
WScript.Echo "Process [Name:" & objItem.Name & "]"
Next
Also note you can use WHERE statement in query:
SELECT * FROM Win32_Process WHERE Name LIKE '%notepad%'
Here you can find names of columns for query:

Resources