Replace text within a file - vbscript

Hello I've tried a lot of researching but cant find what I need and haven't been able to successfully piece this together myself.
Each of my users have a XML file within their profile that I would like to edit. The file contains a reference to their computer name and clientname, which are out of date each time they login to a new terminal. I need to replace these with the current computername and clientname. The bit I cannot figure out how to do is how to search the XML for the computername when I only know the first few characters, then replace it.
my XML will have any entry something like this
"InstalledPrinter name="\WHBCVDI0109\LabelPrinter650 (from IGEL-00E0C533943E)"
I need to search the file and replace the WHBCVDI0109 and the IGEL-00E0C533943E with the correct entries. My script successfully gets those entries I just dont know how to find and replace them in the file.
My script looks like this:
Const ForReading = 1
Const ForWriting = 2
Set oShell = CreateObject( "WScript.Shell" )
'Get Variables
user=oShell.ExpandEnvironmentStrings("%UserName%")
appdata=oShell.ExpandEnvironmentStrings("%appdata%")
strComputerName = oshell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
'Set XML location
strfile = appdata & "\Smart Label Printer\SlpUserConfig.xml"
'Open
Set objfso = CreateObject("Scripting.FileSystemObject")
Set filetxt = objfso.OpenTextFile(strfile, ForWriting)
strTemp = "HKEY_LOCAL_MACHINE\SOFTWARE\Citrix\ICA\Session\ClientName"
WScript.Echo "client name is : " & oShell.RegRead(strTemp)
An pointers would be much appreciated.

You shouldn't use the FileSystemObject and String/RegExp operations to edit an XML file. Using the canonical tool - msxml2.domdocument - is less error prone and scales much better.
See here for an example (edit text); or here for another one (edit attribute).
If you publish (the relevant parts of) your .XML file, I'm willing to add same demo code specific for your use case here.

Related

Set/adjust file version of a rtf-file with VBscript

I created a logon script to automatically create a email signature for Outlook. This script creates the following file "C:\Users\%username%\AppData\Roaming\Microsoft\Signatures\Default_signature.rtf"
I would like to add to a versionnumber to this file so I can check if an update of this file is necessary or not. If not, exit logon script. Else update signature with a higher versionnumber.
To get a versionnumber was pretty easy to find, but I couldn't find how to set/change a versionnumber with VBscript.
Using the DSOFile.OleDocumentProperties didn't work for me. I kept getting a ActiveX-error "Can't create object". It could be that I have to register
the dsofile.dll in the system but this code has to work for every user in our company and I don't want to install this on every device before I can use this logon script.
'Code for requesting versionnumber
Set objFSO = CreateObject("Scripting.FileSystemObject")
file = "C:\Users\%username%\AppData\Roaming\Microsoft\Signatures\Default_signature.rtf"
Wscript.Echo "Version = " & objFSO.GetFileVersion(file)
I hope someone could tell me how to do this :)
As far as i know DSO is the only supported way by Microsoft to change properties of the files without rewriting them. There are some VBA scripts out there for Excel, but that does not apply in your case with RTFs.
However, might i suggest a different alternative? I have in my infrastructure a script that is placed to run at each logon and checks on a share a certain file's last modified date. If the file present on the machine is older, then it's replaced by that on the share.
Dim objFSO, strFileName
strFileName = "C:\Users\user\Desktop\Tests\fdsfsd.rtf"
Set objFSO = CreateObject( "Scripting.FileSystemObject" )
WScript.Echo objFSO.GetFile( strFileName ).DateLastModified
Set objFSO = Nothing

Grab file name from file list, if file size greater than 1MB do copy

I have been set out by the following task by one of my managers at work:
We have a database of images for all our clothing styles and colours. For each type of clothing and for each colour we have 3 images. 2 of them are low resolution images and 1 of them is a high resolution image.
We need to copy the high res image for each style and colour from the old database which is made up of sub folders into one folder therefore ignoring the folder structure.
I have come across this Visual Basic script which is quite close to what I need but requires a few tweaks, as I am not really experienced with VB scripts I was hoping I could get some help here over at SO.
What I need to script to be tweaked to is:
-The script to read image names from a list (filelist.txt) (if possible without requiring to add the path for each image to the list, just the name and the extension which is .jpg)
-The script only needs to grab images if the size is greater than 1MB.
-The script to copy the images from sub-folders without keeping the folder structure.
Any and all help will be greatly appreciated, explanations behind the tweaks and any guidance will also be kind but not required.
Here is the script that I have so far. The paths are temporary as I was playing around with the script.
Option Explicit
' The source path for the copy operation.
Const strSourceFolder = "C:\Users\Cou Rou\Desktop\Old database"
' The target path for the copy operation.
Const strTargetFolder = "C:\Users\Cou Rou\Desktop\New database"
' The list of files to copy. Should be a text file with one file on each row. No paths - just file name.
Const strFileList = "C:\Users\Cou Rou\Desktop\Old database\filelist.txt"
' Should files be overwriten if they already exist? TRUE or FALSE.
Const blnOverwrite = FALSE
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Dim objFileList
Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False)
Dim strFileToCopy, strSourceFilePath, strTargetFilePath
On Error Resume Next
Do Until objFileList.AtEndOfStream
' Read next line from file list and build filepaths
strFileToCopy = objFileList.Readline
strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy)
strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
' Copy file to specified target folder.
Err.Clear
objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite
If Err.Number = 0 Then
' File copied successfully
Else
' Error copying file
Wscript.Echo "Error " & Err.Number & " (" & Err.Description & "). Copying " & strFileToCopy
End If
Loop

File wont move to folder vbs

So im writing a script that drops a file folder then moves that file to the folder it dropped it self. Well the folder drops fine but the file wont move. Can some see whats wrong with my code? Or give me a better way to move the file. I also get no error message about trying to move the file.
Dim folder,fso,filsys,C
Set fso = CreateObject("Scripting.filesystemObject")
Set folder = fso.GetSpecialFolder(1)
Set wshshell = CreateObject("wscript.shell")
Set filesys = CreateObject("scripting.filesystemobject")
Set objfso = CreateObject("Scripting.filesystemObject")
Set c = fso.GetFile(Wscript.scriptFullname)
On Error Resume NEXT
Set objFolder = objFSO.CreateFolder("C:\55egr932ntn7mk23n124kv1053bmoss5")
If Err.Number<>0 Then
End If
WScript.Sleep 3000
C.Move ("C:\552ntn7mk23n124kv1053bmoss5\File.exe") (folder&"\File.exe")
And I have a program I use that turns the VBS into and EXE so you see the "file.exe" which really is the .VBS itself
I'm not familiar with this syntax, but the line below looks like it's expecting the folder variable to be a string.
C.Move ("C:\552ntn7mk23n124kv1053bmoss5\File.exe") (folder&"\File.exe")
Earlier in code it looks as though you're setting folder as an object.
Set folder = fso.GetSpecialFolder(1)
You might not get the error you mentioned in your comment if you convert folder to a string.
~~
Another thing to try is the following code:
Set fso = CreateObject("Scripting.filesystemObject")
Set folder = fso.GetSpecialFolder(1)
Alert (folder&"\File.exe")
(I'm not sure if it's "Alert" or "Msgbox" or something else.) That test will show you whether the file path makes sense. If you get an error on line 3 of that test, try converting folder to a string before your Alert (or Msgbox).

VB Do While only works for one iteration

I've never done anything before with VB and am trying to work out a little problem with this script. Basically the script should look for all jpgs in a folder, if the file name exists already remove it from the target folder, add the value to a table and then rename the source file so it exists in the target folder.
This script works to an extent, for example it will rename any file if the file doesn't exist already but for any files that do already exist it processes only one then then ends. I can run it multiple times to clear the rest but would rather it cleared them all in one go. I have done quite a bit of reading but can't see what is going wrong. Can anyone shed any light on this?
Public Function GetLPUFileAddress()
Dim strSourceFolder As String
Dim strFile As String
Dim strTargetFolder As String
Dim dbs As DAO.Database
Dim rstMgr As DAO.Recordset
strSourceFolder = "C:\Users\Images\LPU-HOLDING\"
strFile = Dir(strSourceFolder & "*.JPG")
strTargetFolder = "C:\Users\Images\LPU\"
Do While strFile <> ""
If Dir(strTargetFolder & strFile) <> "" Then Kill strTargetFolder & strFile
CurrentDb.Execute "INSERT INTO TBL_LPU ( File_Name, Import_Date ) VALUES ('" & strFile & "',Date())"
Name strSourceFolder & strFile As strTargetFolder & strFile
strFile = Dir
Loop
End Function
By calling the Dir() function with an appropriate filter, such as "C:\Users\Images\LPU\*.JPG", you start enumeration and get the first file name.
After that, repeatedly calling the Dir() function without any parameters, you will get all *.JPG file names, one for each call.
If you at any point call Dir() with a parameter, this will reset the current enumeration and start a new one.
You therefore can't use Dir() to check existance of a file in a folder while you're enumerating with Dir(). This resets the enumeration.
You have to either use some other way of checking existance of the file, or just try to kill it without checking, ignoring the error.

Script to download file and rename according to date on Windows Vista machine?

I need to daily run a script that will download a file from a fixed location and save it on my computer with an appropriate filename-YYYYMMDD-HHSS.ext timestamp. I need a historical record of what that file was at that particular time. I can manually check and see what the changes were, so compairson not needed.
(I was looking for an online service that would do this for me, but I think a locally running script on my machine would be good enough).
Although i do have php on my machine, i would prefer if its a pure windows builtin solution, just in case i have to (likely) adapt it to someone else's system (non-techies).
If someone has something like this and can contribute the code - help would be most appreciated!!
D
Your task can be easily scripted using Windows Script Host languages -- VBScript or JScript.
To download a file from Internet, you can use the XMLHTTP object to request the file contents from the server and then use the ADO Stream object to save it to a file on the disk.
As for the timestamp, the problem is that neither VBScript nor JScript have built-in functions that would format the date in the format you need, so you will have to write the code for doing this yourself. For example, you could split the date into parts, pad them if necessary and concatenate them back together. Or you could use the WMI SWbemDateTime object that uses the yyyymmddHHMMSS.mmmmmmsUUU date format, and simply extract the yyyymmddHHMMSS part from it.
Anyway, here's a sample script (in VBScript) that illustrates the idea. I hard-coded the original file name in the strFile variable, because I was too lazy to extract in from the URL (and also in case the URL doesn't specify the file name, like in http://www.google.com).
Dim strURL, strFile, strFolder, oFSO, dt, oHTTP, oStream
strURL = "http://www.google.com/intl/en_ALL/images/logo.gif" ''# The URL to download
strFile = "logo.jpg" ''# The file name
strFolder = "C:\Storage" ''# The folder where to save the files
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
''# If the download folder doesn't exist, create it
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
''# Generate the file name containing the date-time stamp
Set dt = CreateObject("WbemScripting.SWbemDateTime")
dt.SetVarDate Now
strFile = oFSO.GetBaseName(strFile) & "-" & Split(dt.Value, ".")(0) & "." & oFSO.GetExtensionName(strFile)
''# Download the URL
Set oHTTP = CreateObject("MSXML2.XMLHTTP")
oHTTP.open "GET", strURL, False
oHTTP.send
If oHTTP.Status <> 200 Then
''# Failed to download the file
WScript.Echo "Error " & oHTTP.Status & ": " & oHTTP.StatusText
Else
Set oStream = CreateObject("ADODB.Stream")
oStream.Type = adTypeBinary
oStream.Open
''# Write the downloaded byte stream to the target file
oStream.Write oHTTP.ResponseBody
oStream.SaveToFile oFSO.BuildPath(strFolder, strFile), adSaveCreateOverWrite
oStream.Close
End If
Feel free to ask if you need more explanation.
A version control system like Mercurial can do this for you without you having to rename the file. The script might be as simple as (get wget here and Mercurial here):
wget http://blah-blah-blah.com/filename.ext
hg commit -m "Downloaded new filename.ext"
A nice feature of this is that the commit won't happen unless the file's contents have changed.
To see the history, use hg log or TortoiseHg (a shell extension).
Build up on:
http://blog.netnerds.net/2007/01/vbscript-download-and-save-a-binary-file/
and
http://developernotes.thomaspowell.com/2008/06/vbscript-to-convert-timestamp-to.php

Resources