Cant move VBScript to another directory, it says "File not found" - vbscript

Set objShell = CreateObject("Wscript.Shell")
strFile ="Lafarrel.vbs"
dim fso, fullPath
set fso = CreateObject("Scripting.FileSystemObject")
fullPath = fso.GetAbsolutePathName(strFile)
Wscript.Echo fullPath
Wscript.Sleep 1000
dim SourceLocation
dim DestinationLocation
dim FileName
SourceLocation = fullPath
DestinationLocation = """C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"""
FileName = "Lafarrel.vbs"
fso.MoveFile SourceLocation & "" & FileName, DestinationLocation & ""
Error starts at line 14
Maybe because the last line is incorrect?
Explain what I want VBScript to do:
I want this VBScript to find itself and then change to a different directory

Use Option Explicit, for everyones' sanity.
Wscript.Sleep 1000 is unnecessary.
This line has problems: DestinationLocation = """C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"""
This string-literal contains excessive double-quotes (VBScript uses double-double-quotes to escape individual double-quote chars, but strings containing only paths and filenames should not have internal delimiting quotes.
Also, %username% won't be expanded by FileSystemObject.MoveFile.
You will need to use WshShell.ExpandEnvironmentStrings first.
Also, C:\Users\%username%\AppData\Roaming\... is a poor choice of environment-variable'd-path as the Users directory might not be on C:\, and it might not even be named "Users".
Instead, you should use %APPDATA%.
obj prefixes are ugly and unnecessary.
Dim SourceLocation is redundant as it's an alias of fullPath. Ditto Dim FileName.
GetAbsolutePathName does not verify that the file actually exists: you'll get a runtime error if "Lafarrel.vbs" does not exist in the expected location when the script runs - so expect this situation and add an If guard.
So your code should look like this:
Option Explicit
Dim shell
Set shell = CreateObject( "WScript.Shell" ) ' aka WshShell
Dim fso
Set fso = CreateObject( "Scripting.FileSystemObject" )
Dim lafarrelVbsPath
lafarrelVbsPath = fso.GetAbsolutePathName( "Lafarrel.vbs" )
If fso.FileExists( lafarrelVbsPath ) Then
Dim destinationPath
destinationPath = "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\"
destinationPath = shell.ExpandEnvironmentStrings( destinationPath )
Wscript.Echo "Moving """ & lafarrelVbsPath & """ to """ & destinationPath & """..."
' When `destinationPath` ends with a slash, then "Lafarrel.vbs" won't be renamed (phew).
fso.MoveFile lafarrelVbsPath, destinationPath
Else
Wscript.Echo "Error: File not found: """ & lafarrelVbsPath & """."
End If

WScript.ScriptFullName returns the script path and filename in full.
This sample demonstrates a couple of things including a simple way to isolate the script folder (not really needed for your use case though).
If you save this exact script into your local %temp% folder, and create a folder '%temp%\temp two' (space in there) you can just run it.
Also you MUST use ExpandEnvironmentStrings method to use env vars in a string
strFileName = WScript.Scriptname
strCurrDir = Replace(WScript.ScriptFullName, WScript.Scriptname, "")
Set wshShell = CreateObject("WScript.Shell")
strDestination = wshShell.ExpandEnvironmentStrings("%temp%\temp two\") ' note the space, but no need to double-up quotes. You MUST use ExpandEnvironmentStrings method to use env vars in a string
Wscript.Echo "I am '" & strFileName & "' and I am in '" & strCurrDir & "'"
WScript.Echo "My full path and name in one is: " & WScript.ScriptFullName
' so for moving the file, no need to separate the path and filename, as 'WScript.ScriptFullName' contains all of it (dest file must NOT exist)
' no need to double-up quotes for destination path, as this is not batch and will treat the whole string as path including spaces
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile WScript.ScriptFullName, strDestination
WScript.Echo "I've now been moved to: " & strDestination

Related

Unable to find file in VBScript

The VBE encoder section works (from prior experience but this time around it cannot find the required file. The file is in the %temp% folder so there are spaces in the path but I have used the "" as can be seen in the code. The MsgBox shows the correct file and I can confirm its existence but the code fails when fso.GetFile.
This is part of a larger script that is called with the target file (full path) as the argument. The target file is previously created by the calling script.
Main script (gets called with target file):
Set fso = CreateObject("Scripting.FileSystemObject")
Set wshShell = WScript.CreateObject("WScript.Shell")
textFile = WScript.Arguments(0)
GetExtension = fso.GetExtensionName(fso.GetFileName(textFile))
If LCase(GetExtension) = "vbs" Then
Set oFilesToEncode = WScript.Arguments
Set oEncoder = CreateObject("Scripting.Encoder")
For i = 0 To oFilesToEncode.Count - 1
file = """" & Trim(oFilesToEncode(i)) & """"
MsgBox file
If fso.FileExists(Left(file, Len(file) - 3) & "vbe") Then fso.DeleteFile(Left(file, Len(file) - 3) & "vbe")
Set oFile = fso.GetFile(file)
Set oStream = oFile.OpenAsTextStream(1)
sSourceFile = oStream.ReadAll
oStream.Close
sDest = oEncoder.EncodeScriptFile(".vbs", sSourceFile, 0, "")
sFileOut = Left(file, Len(file) - 3) & "vbe"
Set oEncFile = fso.CreateTextFile(sFileOut)
oEncFile.Write sDest
oEncFile.Close
Next
End If
WScript.Quit
Section of calling script:
Do While fso.FileExists(strTempVBS) = False
Loop
strKey = "HKEY_CLASSES_ROOT\Engineers-Toolbox\Multi-Tool\Installed\Path\"
value = wshShell.RegRead( strKey )
arg = " " & strTempVBS
running = "C:\Custom\Multi-Tool\Multi-Tool.exe " & """" & arg & """"
wshShell.Run running, True
I have tried using hard coding the path to the exe to get it going, 'value' contains the path to the main script.
Do not prematurely add quotes around paths. I'm always confused why people keep doing this, because it creates more problems than it solves. Add double quotes when they're actually required, but not before.
FileSystemObject methods can handle paths with spaces without the additional double quotes. In fact, they will interpret double quotes in a path string as part of the path and throw an error, because they can't find a file with a double quote in its name (which would be invalid anyway).
Your check for the existence of a file also doesn't work, because you don't account for the quotes you added to the path string:
file = """C:\some\folder\file.vbs"""
WScript.Echo file
WScript.Echo Left(file, Len(file) - 3) & "vbe"
The output of the above code snippet is
"C:\some\folder\file.vbs"
"C:\some\folder\file.vvbe
Change this:
file = """" & Trim(oFilesToEncode(i)) & """"
into this:
file = Trim(oFilesToEncode(i))
and the problem will disappear.
Ok, the solution is to (predictably) add the quotes in the calling script, that way the VBS to VBE encoder section can remain standard.
strTEMP = wshShell.ExpandEnvironmentStrings( "%UserProfile%" ) & "\AppData\Local\Multi-Tool\"
strTempVBS = strTEMP & "observe.vbs"
strKey = "HKEY_CLASSES_ROOT\Engineers-Toolbox\Multi-Tool\Installed\Path\"
value = wshShell.RegRead( strKey ) & " "
running = value & "" & chr(34) & strTempVBS & chr(34) & ""
wshShell.Run running ,True
Interesting was how the quotes are added. This made the called script find the required file even tho the full path contained spaces.

How to change certain code inside a VBScript with another VBScript?

I have made the script FindAndReplace.vbs which simply watches a folder and finds any desired string in the filenames and replaces that string with a desired string.
Now, What I´m trying to create is a VBScript (ConfigureFindAndReplace.vbs) that will easily configure the following 3 things in the FindAndReplace.vbs code:
Browse and select which folder to watch (targetPath)
Which text string to search for in the filenames of the files inside this folder (strFind)
Which string to replace with (strReplace)
I want the script to be user friendly for users with no programming skills.
And I want the main executable script FindAndReplace.vbs to automatically be updated EVERY time the ConfigureFindAndReplace.vbs is run.
To better help you understand here is th
e link to a .zip file containing both of the above mentioned files. This is as far as I can get and I´ve been stuck for 2 days now:
https://www.dropbox.com/s/to3r3epf4ffyedb/StackOverFlow.zip?dl=0
Hope I explained it properly. If not, let me know whatever you need to know.
Thanks in advance:)
And here are the codes from the files:
ConfigureFindAndReplace.vbs:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject ("Shell.Application")
Set objTFolder = objShell.BrowseForFolder (0, "Select Target Folder", (0))
targetPath = objTFolder.Items.Item.Path
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
sScriptDir = oFSO.GetParentFolderName(WScript.ScriptFullName) & "/"
strFind = InputBox("Add string to find.","String to Find", "")
If strFind = "" Then
Wscript.Quit
End If
strReplace = InputBox("Add string to replace with.","Replace with", "")
Dim VarFind
Dim VarReplace
Dim VarPath
VarFind = strFind
VarReplace = strReplace
VarPath = targetPath
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run sScriptDir & "FindAndReplace.vbs /strfolderpath:" & VarPath
WshShell.Run sScriptDir & "FindAndReplace.vbs /strfind:" & VarPath
WshShell.Run sScriptDir & "FindAndReplace.vbs /strreplace:" & VarPath
FindAndReplace.vbs:
'Written by Terje Borchgrevink Nuis on 15.12.2014
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim strFind
Dim strReplace
Dim strFolderPath
strFolderPath = WScript.Arguments.Named("strfolderpath")
targetPath = strFolderPath
'Max number of times to replace string
strCount = 999
'Comparison type: 0 = case sensitive, 1 = case insensitive
strCompare = 1
If targetPath = "" Then
Wscript.Quit
End If
strFind = WScript.Arguments.Named("strfind")
If strFind = "" Then
Wscript.Quit
End If
strReplace = WScript.Arguments.Named("strreplace")
Set objFolder = objFSO.GetFolder(targetPath)
fileRename objFolder
Sub fileRename(folder)
Do
Wscript.sleep 10000
'Loop through the files in the folder
For Each objFile In folder.Files
filename = objFile.Name
ext = objFSO.getExtensionName(objFile)
safename = Left(filename, Len(filename) - Len(ext) - 1)
strStart = 1
safename = Replace(safename, strFind,strReplace,strStart,strCount,strCompare)
safename = trim(safename)
On Error Resume Next
'Terminate if filename stop.txt is found
If filename="STOP.txt" Then
result = MsgBox ("Are you sure you want to terminate the following VBScript?" & vbNewLine & vbNewLine & "FindAndReplace.vbs", vbOKCancel+vbSystemModal , "Terminate VBScript")
Select Case result
Case vbOK
WScript.quit
Case vbCancel
MsgBox "FindAndReplace.vbs is still running in the background.",,"Information"
End Select
End If
'Only rename if new name is different to original name
If filename <> safename & "." & ext Then
objFSO.MoveFile objFile.Path, objFile.ParentFolder.Path & "\" & safename & "." & ext
End If
If Err.Number <> 0 Then
WScript.Echo "Error renaming: " & filename.path & "Error: " & Err.Description
Err.Clear
End If
Next
Loop
End Sub
You think you want ConfigureFindAndReplace to change the other script, this is a bad idea.
You don't know it yet, but what you actually want is for FindAndReplace to read those items from a configuration file.
If the config file is well formed and easy to read, then your users can directly update the config file, so you may not even need the ConfigureFindAndReplace script.
How?
Have a text file with 3 lines
Target Folder=c:\DataFolder
String to find=a string
Replace with=Replace a string with this string
Then in FindAndReplace, before doing any work, you open this file and read in the three lines.
Split the lines on the '=' sign. The left half is the setting and the right half is the value.
Math these up to three variables in the script
If configLineLeft = "Target Folder" then REM Each of these should be case insensitive match
REM e.g. lcase(configLineLeft) = lcase("Target Folder")
TargetFolder = configLineRight
else if configLineLeft = "String to find" then
FindString = configLineRight
else if configLineLeft = "Replace with" then
ReplaceString = configLineRight
else
REM REPORT A PROBLEM TO THE USER AND EXIT
EXIT SUB
end if
You'd do the above in a while loop (while not end of file), reading each line and testing to see which setting it is.
As I can't find any VBScript in your .Zip, some general advice. If you want a not-to-be-edited script to do different things
let the script access parameters/arguments and specifying the differences by calling the script with different arguments: cscript FindAndReplace.vbs "c:\some\folder" "param" "arg"
let the script access config data (from a .txt, .ini, .xml, .json, ... file; from a database; from the registry; ...) and use the config script to set these data
use a template/placeholder file to generate (different version of) the script
I would start with the first approach.
After reading your edit:
Instead of calling your script trice with bad args:
WshShell.Run sScriptDir & "FindAndReplace.vbs /strfolderpath:" & VarPath
WshShell.Run sScriptDir & "FindAndReplace.vbs /strfind:" & VarPath
WshShell.Run sScriptDir & "FindAndReplace.vbs /strreplace:" & VarPath
execute it once with proper args:
WshShell.Run sScriptDir & "FindAndReplace.vbs /strfolderpath:" & VarPath & " /strfind:" & VarFind & "/strreplace:" & VarReplace
(untested; you need to check the names and take care of proper quoting; cf here)

How to Copy a file that was read from a list

Hello guys I have an issue or issues with my code above
I'm trying to get "sExtension" to be search in a different folder other that the one I'm using to save my script since this script will be use as a Startup Script on many computers
(It works only if I run the script in the same folder "sExtension", "ExtAssign.txt" and sComputername are otherwise it wont find the path)
This is what it should do
Read a file called "ExtAssign.txt" (There is a full list of computer names in that file) and if it find the computer name on that file then it should copy a file with the with the extension number assigned to that computer name from a file server to "C:\" Drive
For this example I'm trying to do this locally, If I can make it then I'll try it from my File Server
Set objFSO = CreateObject("Scripting.FileSystemObject")
set oFso = CreateObject("Scripting.FileSystemObject")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
set oShell = WScript.CreateObject("WScript.Shell")
set oShellEnv = oShell.Environment("Process")
Set folder = Fso.GetFolder("C:\Users\XXXXX\Desktop\Test\Extensions\")
Set wshshell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set ObjEnv = WshShell.Environment("Process")
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Scomputername = ObjEnv("COMPUTERNAME")
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objWShell = wScript.createObject("WScript.Shell")
Dim strFile
'File to scan
strFile = "C:\Users\XXXXX\Desktop\Test\Extensions\Extassign\ExtAssign.txt"
Dim strPattern
'Look for computer name in file
strPattern = scomputername
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
Dim strLine
'Read each line and store it in strLine
strLine = objFile.ReadLine
'If the line matches the computer name, save the line to ExtArray
If InStr(strLine,strPattern)>0 Then
Dim ExtArray
'Split the line and separate the extension
ExtArray = Split(strLine,"|", -1, 1)
Dim sExtension
'Save the extension to sExtension
sExtension=ExtArray(1)
End If
Loop
'If the sExtension is empty, computer was not found, send message and terminate script.
If sExtension="" Then
WScript.Echo "ERROR: Computer "& scomputername &" not found in Extension Assignment List, so no extension has been set. Avaya will not be launched. Please contact your IT department for assistance."
Else
'If the sExtension contains a number, Copy that file to C:\ and rename it to Config.xml
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
End If
at the end it if it finds the file sExtension it will rename it to Config.xml but it wont do it unless I run the script in the same folder sExtension and sComputername.
I get File not found error
Thank you in advance and Happy new year!
The culprit is most likely this line:
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
There is a trailing space after the last backslash in the path, so you're creating a path
C:\Users\XXXXX\Desktop\Test\Extensions\ 12345
^
when you actually want a path
C:\Users\XXXXX\Desktop\Test\Extensions\12345
On a more general note: why are you creating 7(!) FileSystemObject instances (replacing one of them three times on top of that)? And 3(!) WScript.Shell instances? You don't even use most of them, not to mention that you don't need the Shell object in the first place. You only use it for determining the computer name, which could be done just fine using the WScript.Network object (that you don't use at all).
Also, please don't ever use comments like this:
'Read each line and store it in strLine
strLine = objFile.ReadLine
It's quite obvious that you read each line and assign it to the variable strLine. Comments shouldn't rephrase what you're doing (the code already does that, at least when you're using speaking variable and function names), but why you're doing it, i.e. what the purpose of a particular code section is.
Your code could be reduced to something as simple as this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set net = CreateObject("WScript.Network")
computername = net.ComputerName
foldername = "C:\Users\XXXXX\Desktop\Test\Extensions"
filename = fso.BuildPath(foldername, "Extassign\ExtAssign.txt")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If InStr(line, computername) > 0 Then
arr = Split(line, "|", -1, 1)
If UBound(arr) >= 1 Then extension = arr(1)
End If
Loop
f.Close
If IsEmpty(extension) Then
WScript.Echo "ERROR: Computer "& computername &" not found in ..."
Else
fso.CopyFile fso.BuildPath(foldername, extension), "C:\Config.xml", True
End If

Creating a Zip then copying folders to it

I'm trying to create a zip file, then copy three folders into it. I get the error on line 33 char 1, error state object required, I have searched and googled but just can't seem to either understand what I'm reading or understand what I really need to search for. Anyhow, here is my code.
Option Explicit
Dim objFSO, objFolder1, objFolder2, objFolder3, FolderToZip, ziptoFile, FolderGroup
Dim ShellApp, eFile, oNewZip, strZipHeader
Dim ZipName, Folder, i, Zip, Item
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder1 = objFSO.GetFolder("C:\Windows\Temp\SMSTSLog")
Set objFolder2 = objFSO.GetFolder ("C:\Windows\System32\CCM\Logs")
Set objFolder3 = objFSO.GetFolder ("C:\Windows\SysWOW64\CCM\Logs")
'For Each efile In objFolder.Files
' If DateDiff("d",eFile.DateLastModified,Now) >= 2 Then
' objFSO.MoveFile eFile, "C:\Documents and Settings\User\Desktop\Test2\"
' End If
'Next
Wscript.Sleep 2000
Set oNewZip = objFSO.OpenTextFile("C:\win7tools\testing script.zip", 8, True)
strZipHeader = "PK" & Chr(5) & Chr(6)
For i = 0 To 17
strZipHeader = strZipHeader & Chr(0)
Next
oNewZip.Write strZipHeader
oNewZip.Close
Set oNewZip = Nothing
WScript.Sleep 5000
FolderGroup = Array(objFolder1,objFolder2,objFolder3)
FolderToZip = "FolderGroup"
ZipToFile = "C:\Win7tools\Test Script.zip"
Set ShellApp = CreateObject("Shell.Application")
Set Zip = ShellApp.NameSpace(ZipToFile)
'Set Folder = ShellApp.NameSpace(FolderToZip)
ShellApp.NameSpace(FolderGroup).CopyHere Zip.NameSpace(ZipToFile)
WScript.Sleep 10000
set ShellApp = Nothing
set FolderToZip = Nothing
set ZipToFile = Nothing
When in doubt, read the documentation:
retVal = Shell.NameSpace(
vDir
)
Parameters
vDir [in]
Type: Variant
The folder for which to create the Folder object. This can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values. Note that the constant names found in ShellSpecialFolderConstants are available in Visual Basic, but not in VBScript or JScript. In those cases, the numeric values must be used in their place.
The NameSpace method expects either a string with a path or the integer value of one of the ShellSpecialFolderConstants, not an array of Folder objects. Also you got the order wrong. The object on which you call the copyHere method is the zip file. The argument is what you want to copy to the zip file (a path string should do just fine here). Plus, the name of the zip file you create is different from the name of the zip file you try to add the folders to.
Change your code to this:
folder1 = "C:\Windows\Temp\SMSTSLog"
folder2 = "C:\Windows\System32\CCM\Logs"
folder3 = "C:\Windows\SysWOW64\CCM\Logs"
zipfile = "C:\Win7tools\Test Script.zip"
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.OpenTextFile(zipfile, 2, True).Write "PK" & Chr(5) & Chr(6) _
& String(18, Chr(0))
Set ShellApp = CreateObject("Shell.Application")
Set zip = ShellApp.NameSpace(zipfile)
zip.CopyHere folder1
zip.CopyHere folder2
zip.CopyHere folder3
WScript.Sleep 10000
WinZip has a Command Line Interface. You might have to download and install it depending on your version: http://www.winzip.com/prodpagecl.htm
The below is a test script that works for WinZip version 9.0 if it helps.
Const WinZip = "C:\Program Files\WinZip9.0\wzzip.exe" 'WinZip Version 9.0
BasePath = "C:\Path\To\Folders\"
strZipFilePath = BasePath & "Test.zip"
strArchiveMe = BasePath & "Folder_A"
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(WinZip) Then
MsgBox "WinZip (wzzip.exe) Does Not Exist"
WScript.Quit
End If
'''// For Below Command - Change "-a" TO "-mu" To Auto Delete The file After Zip Is Created
'''// For Below Command - Change "-yb" TO "-ybc" To Answer YES To all Promps and not Terminate Operation
strcommand = Chr(34) & WinZip & Chr(34) & " -a -yb " & Chr(34) & strZipFilePath & Chr(34) & " " & Chr(34) & strArchiveMe & Chr(34)
objShell.Run strcommand, 1, True
The command format is:
winzip [action] [options] [Zip Path] [Path to file/folder to zip]

How do I rename a file using VBScript?

I am trying to rename a file and was using the below code but it does not seem to work. Can someone please tell me why? What is the correct way to rename a file from VBScript?
FSO.GetFile("MyFile.txt).Name = "Hello.txt"
I am using this thread for reference: Rename files without copying in same folder
You can rename the file using FSO by moving it: MoveFile Method.
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "A.txt", "B.txt"
I see only one reason your code to not work, missed quote after file name string:
VBScript:
FSO.GetFile("MyFile.txt[missed_quote_here]).Name = "Hello.txt"
Yes you can do that.
Here I am renaming a .exe file to .txt file
rename a file
Dim objFso
Set objFso= CreateObject("Scripting.FileSystemObject")
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"
Rename filename by searching the last character of name. For example,
Original Filename: TestFile.txt_001
Begin Character need to be removed: _
Result: TestFile.txt
Option Explicit
Dim oWSH
Dim vbsInterpreter
Dim arg1 'As String
Dim arg2 'As String
Dim newFilename 'As string
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
ForceConsole()
arg1 = WScript.Arguments(0)
arg2 = WScript.Arguments(1)
WScript.StdOut.WriteLine "This is a test script."
Dim result
result = InstrRev(arg1, arg2, -1)
If result > 0 then
newFilename = Mid(arg1, 1, result - 1)
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile arg1, newFilename
WScript.StdOut.WriteLine newFilename
End If
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
From what I understand, your context is to download from ALM.
In this case, ALM saves the files under:
C:/Users/user/AppData/Local/Temp/TD_80/ALM_VERSION/random_string/Attach/artefact_type/ID
where :
ALM_VERSION is the version of your alm installation, e.g 12.53.2.0_952
artefact_type is the type of the artefact, e.g : REQ
ID is the ID of the artefact
Herebelow a code sample which connects to an instance of ALM, domain 'DEFAUT', project 'MY_PROJECT', gets all the attachments from a REQ with id 6 and saves them in c:/tmp. It's ruby code, but it's easy to transcribe to VBSctript
require 'win32ole'
require 'fileutils'
# login to ALM and domain/project
alm_server = ENV['CURRRENT_ALM_SERVER']
tdc = WIN32OLE.new('TDApiOle80.TDConnection')
tdc.InitConnectionEx(alm_server)
username, password = ENV['ALM_CREDENTIALS'].split(':')
tdc.Login(username, password)
tdc.Connect('DEFAULT', 'MY_PROJECT')
# get a handle for the Requirements
reqFact = tdc.ReqFactory
# get Requirement with ID=6
req = reqFact.item(6)
# get a handle for the attachment of REQ
att = req.Attachments
# get a handle for the list of attachements
attList = att.NewList("")
thePath= 'c:/tmp'
# for each attachment:
attList.each do |el|
clientPath = nil
# download the attachment to its default location
el.Load true, clientPath
baseName = File.basename(el.FileName)
dirName = File.dirname(el.FileName)
puts "file downloaded as : #{baseName}\n in Folder #{dirName}"
FileUtils.mkdir_p thePath
puts "now moving #{baseName} to #{thePath}"
FileUtils.mv el.FileName, thePath
end
The output:
=> file downloaded as : REQ_6_20191112_143346.png
=> in Folder C:\Users\user\AppData\Local\Temp\TD_80\12.53.2.0_952\e68ab622\Attach\REQ\6
=> now moving REQ_6_20191112_143346.png to c:/tmp
Below code absolutely worked for me to update File extension.
Ex: abc.pdf to abc.txt
Filepath = "Pls mention your Filepath"
Set objFso = CreateObject("Scripting.FileSystemObject")
'' Below line of code is to get the object for Folder where list of files are located
Set objFolder = objFso.GetFolder(Filepath)
'' Below line of code used to get the collection object to hold list of files located in the Filepath.
Set FileCollection = objFolder.Files
For Each file In FileCollection
WScript.Echo "File name ->" + file.Name
''Instr used to Return the position of the first occurrence of "." within the File name
s = InStr(1, file.Name, ".",1)
WScript.Echo s
WScript.Echo "Extn --> " + Mid(file.Name, s, Len(file.Name))
'Left(file.Name,s-1) = Used to fetch the file name without extension
' Move method is used to move the file in the Desitnation folder you mentioned
file.Move(Filepath & Left(file.Name,s-1)&".txt")
Next
Rename File using VB SCript.
Create Folder Source and Archive in D : Drive. [You can choose other drive but make change in code from D:\Source to C:\Source in case you create folder in C: Drive]
Save files in Source folder to be renamed.
Save below code and save it as .vbs e.g ChangeFileName.vbs
Run file and the file will be renamed with existing file name and current date
Option Explicit
Dim fso,sfolder,fs,f1,CFileName,strRename,NewFilename,GFileName,CFolderName,CFolderName1,Dfolder,afolder
Dim myDate
myDate =Date
Function pd(n, totalDigits)
if totalDigits > len(n) then
pd = String(totalDigits-len(n),"0") & n
else
pd = n
end if
End Function
myDate=
Pd(DAY(date()),2) & _
Pd(Month(date()),2) & _
YEAR(Date())
'MsgBox ("Create Folders 'Source' 'Destination ' and 'Archive' in D drive. Save PDF files into Source Folder ")
sfolder="D:\Source\"
'Dfolder="D:\Destination\"
afolder="D:\archive\"
Set fso= CreateObject("Scripting.FileSystemObject")
Set fs= fso.GetFolder(sfolder)
For each f1 in fs.files
CFileName=sfolder & f1.name
CFolderName1=f1.name
CFolderName=Replace(CFolderName1,"." & fso.GetExtensionName(f1.Path),"")
'Msgbox CFileName
'MsgBox CFolderName
'MsgBox myDate
GFileName=fso.GetFileName(sfolder)
'strRename="DA009B_"& CFolderName &"_20032019"
strRename= "DA009B_"& CFolderName &"_"& myDate &""
NewFilename=replace(CFileName,CFolderName,strRename)
'fso.CopyFile CFolderName1 , afolder
fso.MoveFile CFileName , NewFilename
'fso.CopyFile CFolderName, Dfolder
Next
MsgBox "File Renamed Successfully !!! "
Set fso= Nothing
Set fs=Nothing

Resources