Create a text file in %temp% and write content in it using vbs - vbscript

Basically, I want to create a new file and write in it in a directory on the PC, pointed to by the %TEMP% variable. However, the revised code below does not work:
Dim oFile
Dim shell
Set oShell = CreateObject("WScript.Shell")
user = oShell.ExpandEnvironmentStrings("%Temp%")
Set oFile = CreateObject("Wscript.Shell")
Set oFile = oFile.CreateTextFile("%Temp%\d.txt")
oFile.WriteLine "here is my contant"
oFile.Close
Error Message:
run time error
line no: 3
object required
Old Code
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
FileName = "%TEMP%\myfile.txt"
Set tf = fso.CreateTextFile(FileName, True)
If I use the file name "C:\myfile.txt" it works fine.
Error Message:
Path not found

In VBA, you can just use Environ("TEMP") to expand the Environment variable - if this does not work in VBScript, you may need to bind the WScript.Shell object and use the ExpandEnvironmentStrings property instead, like so:
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%TEMP%") & "\myfile.txt"
Set oShell = Nothing
Following from comments below
Here is a "fully fixed" code:
'Declare variables/objects first
Dim fso AS Object, oFile AS Object
Dim oShell AS Object, FileName AS String
'This bit turns "%TEMP%" into a real file path
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%Temp%\d.txt")
Set oShell = Nothing 'Tidy up the Objects we no longer need
'This bit creates the file
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(FileName)
oFile.WriteLine "here is my content"
oFile.Close
Set oFile = Nothing 'Tidy up the Objects we no longer need
Set fso = Nothing 'Tidy up the Objects we no longer need

you can use Environ("temp") to write to C:\Users\[username]\AppData\Local\Temp

Related

VBScript command to wait for files to be extracted before launching EXE to install program

I'm looking at having a script that decompresses a file (PDMsetup.zip) and then launch the executable that it extracts.
ZipFile="PDMsetup.zip"
ExtractTo=".\"
Set fso = CreateObject("Scripting.FileSystemObject")
sourceFile = fso.GetAbsolutePathName(ZipFile)
destFolder = fso.GetAbsolutePathName(ExtractTo)
Set objShell = CreateObject("Shell.Application")
Set FilesInZip=objShell.NameSpace(sourceFile).Items()
objShell.NameSpace(destFolder).copyHere FilesInZip, 16
Set fso = Nothing
Set objShell = Nothing
Set FilesInZip = Nothing
wscript.sleep 480000
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
strPath = strFolder & "\Startwinstall.exe"
objShell.Run strPath
I want to get rid of;
wscript.sleep 480000
and replace it with a command that tells the script wait until the extraction is done before launching startwinstall.exe
I've kept adjusting the wait time to make up for differences in PC performance with the extraction, but a command to just 'wait' until it's done would be preferential.
Delete any previous copy of the installer exe in the target folder and then wait for that file to be created. Create your objects once at the top of the script. And there's no need to set the objects to Nothing. That will happen automatically when the script ends. The edited script is below:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oWSH = CreateObject("Wscript.Shell")
Set oApp = CreateObject("Shell.Application")
MyFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
ExtractTo = ".\"
ZipFile = "PDMsetup.zip"
StartApp = ExtractTo & "Startwinstall.exe"
On Error Resume Next
oFSO.DeleteFile StartApp
On Error Goto 0
sourceFile = oFSO.GetAbsolutePathName(ZipFile)
destFolder = oFSO.GetAbsolutePathName(ExtractTo)
Set FilesInZip = oApp.NameSpace(sourceFile).Items()
oApp.NameSpace(destFolder).copyHere FilesInZip, 16
Do Until oFSO.FileExists(StartApp)
WScript.Sleep 1000
Loop
oWSH.Run StartApp
Note: I assigned a MyFolder variable, but it's not currently being used. ExtractTo = ".\" could be changed to ExtractTo = MyFolder. You could also eliminate the GetAbsolutePathName lines if you are using MyFolder with the ZipFile name. There are always many ways to do the same thing.
Note: I think the above can be done with a much briefer (probably two line) PowerShell script. Let me know if you're interested in that solution.

CreateTextFile error

I am getting a 'Permission denied' error when trying to run this VBScript after dragging another file or folder icon onto the script's icon.
I have tried running it on two Windows 10 machines and if I run it with arguments if objects at the file creation line, otherwise the scripts completes normally.
Any ideas?
Option Explicit
Dim objFSO
Dim objShell
Dim fldTest
Dim fileTest
Dim strPath
Dim txsOutput
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txsOutput = objFSO.CreateTextFile("Test.txt")
For Each strPath In WScript.Arguments
fldTest = objFSO.GetFolder(strPath)
For Each fleTest In fldTest.Files
...
Next
Next
txsOutput.Close()
Set txsOutput = Nothing
Set objFSO = Nothing
WScript.Quit

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

Getting current directory in VBScript

I'm trying to get the current directory and use it to run an application no matter where the file is put and no matter how the path is changed
Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim CurrentDirectory
CurrentDirectory = fso.GetAbsolutePathName(".")
Dim Directory
Directory = CurrentDirectory\attribute.exe
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Directory" & Chr(34), 0
Set WinScriptHost = Nothing
How do I actually set up this code so it does what I want it to do correctly?
You can use WScript.ScriptFullName which will return the full path of the executing script.
You can then use string manipulation (jscript example) :
scriptdir = WScript.ScriptFullName.substring(0,WScript.ScriptFullName.lastIndexOf(WScript.ScriptName)-1)
Or get help from FileSystemObject, (vbscript example) :
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
You can use CurrentDirectory property.
Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir = WshShell.CurrentDirectory
WshShell.Run strCurDir & "\attribute.exe", 0
Set WshShell = Nothing
Your problem is not getting the directory (fso.GetAbsolutePathName(".") resolves the current working directory just fine). Even if you wanted the script directory instead of the current working directory, you could easily determine that as Jakob Sternberg described in his answer.
What does not work in your code is building a path from the directory and your executable. This is invalid syntax:
Directory = CurrentDirectory\attribute.exe
If you want to build a path from a variable and a file name, the file name must be specified as a string (or a variable containing a string) and either concatenated with the variable directory variable:
Directory = CurrentDirectory & "\attribute.exe"
or (better) you construct the path using the BuildPath method:
Directory = fso.BuildPath(CurrentDirectory, "attribute.exe")
'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
Property Get Path()
Dim sTmp
If IsObject(Server) Then
'Classic ASP
Path = Server.MapPath("../")
ElseIf IsObject(WScript) Then
'Windows Scripting Host
Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
ElseIf IsObject(window) Then
'Internet Explorer HTML Application (HTA)
sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
End If
End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path
Your line
Directory = CurrentDirectory\attribute.exe
does not match any feature I have encountered in a vbscript instruction manual.
The following works for me, tho not sure what/where you expect "attribute.exe" to reside.
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run curDir & "\testme.bat", 1
set WinScriptHost = nothing
Use With in the code.
Try this way :
''''Way 1
currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))
''''Way 2
With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With
''''Way 3
With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With
simple:
scriptdir = replace(WScript.ScriptFullName,WScript.ScriptName,"")
The 2 simplest ways:
Replace(WScript.ScriptFullName, WScript.ScriptName, "")
Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
wscript.echo Mid(WScript.ScriptFullName,1,InStrRev(WScript.ScriptFullName, "\"))

Vbscript to navigate to multiple URLs listed in text file

I am trying to create a Vbscript to go through a text file containing different URLs and navigate to each URL using WshShell.Run. I am currently getting: "Object Required: urllist" Error.
Sorry I am new to Vbscript not sure where to go from here.
The urllist.txt is stored in the same directory.
Here is what I have so far:
dim listFile
dim WshShell
dim fName
Set fso = CreateObject("Scripting.FileSystemObject")
Set listFile = fso.OpenTextFile(urllist.txt)
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim fso
'do while not listFile.AtEndOfStream
fName = listFile.ReadLine()
Return = WshShell.Run("iexplore.exe " & fName, 1)
'loop
You missed quote-mark. Next line:
Set listFile = fso.OpenTextFile(urllist.txt)
Should be:
Set listFile = fso.OpenTextFile("urllist.txt")

Resources