Since my post on VBScript command line parameters is by far the most popular, here’s some useful script we use to get the current directory your script is running from. This is great for referencing other files.
currentDirectory = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
WScript.Echo currentDirectory
Pretty simple one to follow, it grabs the script name (with path), finds the length, grabs the script name by itself, finds the length, subtracts and you’re left with the path. Too easy, but really useful.
Edit: This post has been very popular and there have been a few alternatives provided, here are some of them:
- Set oShell = CreateObject(”WScript.Shell”)
Set ofso = CreateObject(”Scripting.FileSystemObject”)
oShell.CurrentDirectory = oFSO.GetParentFolderName(Wscript.ScriptFullName) - set wshell = createobject(”wscript.shell”)
wscript.echo wshell.currentdirectory
‘This gives the current shell directory rather than the script’s directory – use with caution! - Replace(WScript.ScriptFullName,WScript.ScriptName,””)
Please test whichever you use!
Very good, however this is more simpler:
Set oShell = CreateObject(“WScript.Shell”)
Set ofso = CreateObject(“Scripting.FileSystemObject”)
oShell.CurrentDirectory = oFSO.GetParentFolderName(Wscript.ScriptFullName)
Set oShell = CreateObject(“WScript.Shell”)
Set ofso = CreateObject(“Scripting.FileSystemObject”)
Set oShell.CurrentDirectory = “D:\Aut\SIM”
I am getting an error
Object required: ‘oShell.CurrentDirectory’
Line (4): “Set oShell.CurrentDirectory = ofso.GetAbsolutePathName(“D:\Aut\SIM”)”.
Can u plz tell what’s the problem
Thankyou
You need to remove “Set” from the start of the line. Set is used for creating objects and you’ve created the object in the first line.
Set oShell = CreateObject(“WScript.Shell”)
Set ofso = CreateObject(“Scripting.FileSystemObject”)
oShell.CurrentDirectory = “D:\Aut\SIM”
Yes, the GetParentFolderName method is nice, but requires the FSO object in place – take your pick.
Hi,
shall I know how to make use of VBScript to get the HOME Directory
It means if I made a connection to one network,it creates some Files and Folders in MY HOME Directory
NOW I want a VBScript code to check whether these Files and Folders are Created or not
can any one help PLZ
You’ll want to use something like
oFSO.FolderExists(“c:\Folder”)
or
oFSO.FileExists(“C:\Folder\file.txt”)
Try searching for FolderExists and FileExists VBscript
HI Leereid,
Thanks for the reply but I have one issue here ie.,
What u said is for correct for searching the folders and files
But what I want to know is to know the HOME directory for the System and and send that HOME Directory to QTP(TESTING TOOL)
Here is the brief description about that
Actually there may be many users for the single system right?
Now MY Question is how to know in which users we had login into the
system.
I want to know that by using VBScript
WAITING FOR THE REPLY
YOUR’S FRIEND
Ok, a couple of things to look at:
To get the current home directory, try using environment variables.
You can get these through vbscript like:
objShell.ExpandEnvironmentStrings(“%systemdrive%”)
You can also look at all the environment variables by running a command prompt and typing “set”.
I believe the ones you want will be:
USERNAME and USERPROFILE. These will give you information on the current logged in user.
If you look in the folder at the start of USERPROFILE (usually c:\Documents and Settings in XP), there will be folders in here for all the users who have logged in.
Hope this helps.
HI,
How,to get the HOMEDIRECORY by using VBScript
For ex. say there are 3 users named siva,daya,and ramu who can login to the system.suppose the 3 users are there in c:\Documents and settings\
Now let us assume that I had loginto the system by using ramu(USER)
Now I want the VBScript code to get the output as C:\Documents and settings\ramu
can anyone help plz,it’s urgent
Set objShell = CreateObject(“WScript.Shell”)
profile_path = objShell.ExpandEnvironmentStrings(“%USERPROFILE%”)
THANKS
Can u help ME in one more issue here
BY Using VBScript,how to open any Applicatio
For EX:I AM having one WINSCP(to copy files from one system to other)
NOW I have to open that WINSCP by using vbscript
can u help plz
Also where can we find these VBScript commands.can u tell ME the url
You can do that through something like:
strCMD = “notepad.exe”
objShell.Run(strCMD,0,True)
And this will run the command “notepad.exe”
Google objShell.Run for more info
You can also use something like:
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
objFSO.CopyFile “c:\sourcefolder\anyfile.html”, “c:\destfolder\”
to do file copying with VBScript
Set objFSO = CreateObject(”Scripting.FileSystemObject”)
objFSO.CopyFile “c:\sourcefolder\anyfile.html”, “c:\destfolder\”
This will copy to the same m/c,but I want to copy that to different system
Is there any command for copying files from one m/c to another m/c
Of course, just substitute the other machine, so it might be:
objFSO.CopyFile “c:\sourcefolder\anyfile.html”, “\\OtherMachine\Files\destfolder”
You could also use robocopy (I’ve done some posts on this)
Othermachine means it’s ipaddress onlr right?
by using this can we copy files from windows to linux m/c
I’m not familiar with winscp, but Othermachine could be a name or an IP address. From what I can tell about winscp you could use either I suppose.
Hi,
do u have any idea about QTP(Testing Tool)
No, sorry
Hi,
can u show ME how to delete a particular file in vbscript
Sure, I’ve created a new post, take a look.
Where can I check that new post
or just visit
https://leereid.wordpress.com/
Hi,
Is there any way to delete a file
ie.,if the file is exists then it should be deleted otherwise it should continue with the next step
It should not show any error if the file is not there..
Is there any way to achieve this
plz it’s urgent……..
If objFSO.FileExists(“c:\temp\temp.txt”) Then
Or alternatively you can use On Error Resume Next which will continue the script if errors occur. Personally, I’d use the first option
I must thank you for your helpful blog.
A quick search via google led me to your vbscript commandline example, something far easier to achieve in comparison to Microsofts VBscript reference material.
Also I commend you for your assistance and patience extended to “REDDY SIVA SARAN”
You are a true net citizen!
Simon.
No problem. Of course I’ll listen to requests.
Hi,
can I know how to do this task in VBSCRIPT
Opening two files and comparing some test which is in one of those files
ie.,say abc and xyz files
opening the abc and xyz files
Now comparing the test which is in abc but not in xyz file
How to do this VBSCRIPT
can u tell plz
it’s urgent
There’s some information in this post – https://leereid.wordpress.com/2008/09/09/vbscript-edit-line-in-file/, try that out
hi,
is there any way to check whether any gif file is there or not in vbscript
hi,
can u tell plz how to check for a file in Temporay internet Files folder by using the VBScript
ie., The Temporay internet files folder will be in /localsettings/temporary internet files
Now by using the vbscript,how to check for a file in temporary internet files folder
plz can u help in this it’s urgent
I’ve given you most of the tools to do these tasks:
A few ways to check if a file is a certain type are:
– Look for “.gif” in the file name
– Use split and check if the last item is gif
– Use right and check if the last 4 characters are .gif
To look for a file in the temporary internet files folder, first I’m not sure why you’d need/want to, but you know how to get to the folder and how to check if a file exists
This will return the directory the script is located in, which is very useful, but that’s not always the “current directory”. I sometimes call scripts from within other scripts, and this can cause the current directory to be a different location. I’ve borrowed your technique, along with Mr Nose’s (when I have an FSO handy), to help me in those situations. But sometimes you need to know what the actual current working directory is.
The currentdirectory property of a wscript.shell object is better for returning that.
set wshell = createobject(“wscript.shell”)
wscript.echo wshell.currentdirectory
This little bit of code will return a different result depending on where the script is being called from, rather than where it is located. (Useful, fe, when trying to track down log files you are expecting to be created in the directory of the script.)
Wshell.currentdirectory is very handy too. There’s an article on Hey Scripting Guy about current directory which might help others: http://www.microsoft.com/technet/scriptcenter/resources/qanda/aug04/hey0823.mspx
This might be a little simpler…
Replace(WScript.ScriptFullName,WScript.ScriptName,””)
Im new to this so if I do this wrong i apologize….I have a question. I need a vbscript that can detect whether a file exists in a given directory. The directory I need to monitor is:
C:\PROGRAM FILES\VERITAS\NBSCRIPTS\3DR_LOGS
each day files are written to this directory, but I need to know if a file that begins with NB0001 is created in that directory…is that simple code? As you can see i have no VB background just searching the net for possible solutions – Thx for your time.
Welcome to VBScript! Absolutely you can use VBScript to do this. I’ll outline how you can do it:
– Create a folder object
– Specify your folder
– Get every file in the folder
– Check it
Here’s some code, put it into a file called “something.vbs”
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set folder = objFSO.GetFolder(“C:\PROGRAM FILES\VERITAS\NBSCRIPTS\3DR_LOGS”)
Set files = folder.Files
For each file In files
WScript.Echo file.name
If Left(file.Name,6) = “NB0001” Then
‘Do Something
End If
Next
Hi,
Can I know how to write a vbscript for searching a string in a file
Also that file name changes from time to time as the file name starts as SSLVPN-Logs-54541 followed by some number
Can u tell me how to do this
If you look at the comment above, it shows how to do the second part of your question, just change
If Left(file.Name,6) = “NB0001″ Then
to
myString = “SSLVPN-Logs-54541”
If Left(file.Name,Len(myString)) = myString Then
In the ‘Do Something part then you can get the file contents and use InStr or similar to look for your string.
Hi,
Can I get the vbscript for knowing the processes running in the system tray
I mean in windows there will be system tray right?
Now I want to know how to develop the script to know the particular process is running in the system tray or not
Try here: http://www.computerperformance.co.uk/vbscript/wmi_process.htm
Or you could google it
Hey guys, I’m trying to figure out how to run a script to install something without hardcoding a path. I have it working EXCEPT when the working directory has a space in it. Can anyone give me some vbscript code on running something in a working directory with spaces?
Any help would be greatly appreciated. I usually complete things on my own but this one has gotten the better of me.
Thanks!
Stephen
Sure, what I do for this is first, declare a variable:
Quotes = Chr(34)
Then do something like
filename = Quotes & “c:\temp\myfile.msi” & Quotes
You don’t need to declare the variable, but I do for neatness.
Hi,
I have a dought here
Say there is a string “abcxyzdef”
Now I want the output as “abc” in one variable and xyz in one variable and def in other variable
Depends what you’re trying to do.
You could use something like:
mystring = “abcxyzdef”
var1 = Left(mystring,3)
var2 = Mid(mystring,3,3)
var3 = right(mystring,3)
I must congratulate you on your patience with certain requestors – my hat off to you sir!
Thanks for the useful tip. You shouldn’t list though { set wshell = createobject(”wscript.shell”) : wscript.echo wshell.currentdirector } as an alternative, since it gives caller directory, not the script’s (as the reader who suggested it did warn about above), which could cause real damage (delete files say at wrong folder etc.) if script author doesn’t notice it and try to use that one
Hi George,
No doubt, but it depends what one is trying to do. For some people this will be exactly right.
my personal pick due to its simplicity and works with older OS versions like Win2k
Path = Replace(WScript.ScriptFullName,WScript.ScriptName,””)
wscript.echo Path
thanks 🙂
seems there is a problem with copy/paste of the quotation mark “” anyways just retyped the “” and worked like a charm.
thanks 😉
Say I have string like “I walk 10Kms, towards east and then left by 2Kms”
Now I want the addition of all the numbers preceded by Kms
What I would do is split the string, using a delimiter of Kms. This would be something like:
array = Split(string, “Kms”)
Now if you know that Kms is always preceded by a space, then the number, you could get the number by doing something like:
For Each entry in Array
numofDigits = InstrRev(entry,” “)
number = Right(entry, numofDigits)
total = toal + number
Next
This hasn’t been tested, but is pseudocode for an approach I think could work.
Thanks a Ton! of the examples you gave, I find your original much more straight forward and workable then the others. ^_^
Lee
Is there a way to copy files from unix server and place it on your local machine(Windows) through scripting?
Hello,
How to get the HOMEDIRECORY for around 20 000 users by VBScript?
Thanks
Jay
Hello,
How to get the HOMEDIRECTORY for around 20 000 users by VBScript?
Thanks
Jay
Try using an environment variable like %HOMEDRIVE% or %HOMESHARE%
I know this is an older post, but another method when WScript is not available (like when the VBScript is embedded within an app) is:
CurrentPath = CreateObject(“Scripting.FileSystemObject”).GetAbsolutePathName(“.”)
I tried but it is not working
Hello,
I’m new to scripting world can any one pls suggest me how can i call an EXE from current path and inside sub-directory . let me give you a brief idea
Mainfolder is the current directory, it can be located anywhere depends
Inside Mainfolder there are sub folders Folder1 and Folder2
i need to execute EXE which is inside Folder1 and Folder2 by passing switches
ex:
c:\Mainfolder\Folder1\setup.exe /q
c:\Mainfolder\Folder2\setup.exe /q
as i said Mainfolder can be located any where not particularly on c drive may be on share location
so,can you please help me with scripting with explained scenario..thank you
Sure, at the top of your script, have a line like:
Set objShell = CreateObject(“WScript.Shell”)
That will let you run stuff in the command shell, then in your script, run something like:
return = objShell.Run(cmd,0,True)
Return will be the value of the return code and cmd should be your command (which might be something like “c:\Mainfolder\Folder1\setup.exe /q”.
You should be careful thought if your path has spaces
[…] of visitors have been to one of just 2 articles (Sweet VBScript – command line parameters and VBScript Current Directory or Folder) I’m puzzled. These are brilliantly useful articles, but is there anything else people are […]
Thanks alot
thanks
great post
the previous comment is a classic spam one (also got the same one at my blog)
Thanks George, I had a few spam posts to clear up from the last few days
Dear Leereid,
Is there a way to find the full path of the DIRECTORY from the DIRECTORY table of an MSI
I don’t know of a straight forward way to obtain it directly from the msi but a couple of things might help.
1. Using a verbose log on a test installation should show you the values of all the properties.
2. Using Wise Package Studio, the directory table used to show the paths of all the folders.
3. You could also try using the free edito InstEd, that seems to show the path
Thank you very much for your response. Specifically, I was trying to get it out using a VBScript which is run separately, provided the installer MSI path.
The same is the case with advertised shortcuts. I cant seem to find a way to get the path of the shortcut from an MSI database (via tables maybe) using VBScript.There is somethign called componentpath which will get this. But the MSI should be installed for that. I am trying to achieve without installing.
I have dropped the same in other blogs too, but no satisfactory reply so far. I appreciate Leerid in responding to my message. And you’r blogs are just wonderful considering this one is 5 years old. 🙂
Please do let us know if you have something else. Thanks!
Running a VBScript you could open the msi and then parse through the table as much as you need to build the folder path.
Here’s some code to get the productcode, you could adjust this to get values from the Directory table
‘*** Create the WindowsInstaller object
Set WI = CreateObject(“WindowsInstaller.Installer”)
‘*** Open the msi file – 0 indicates read only
Set DB = WI.OpenDatabase(msi,0)
‘*** Select the Product Code from the property table. All valid msis have a product code
Set View = DB.OpenView(“Select `Value` From Property WHERE `Property` =’ProductCode'”)
View.Execute
Set Rec = View.Fetch
If Not Rec Is Nothing Then
GetMSIProductCode=Rec.StringData(1)
Set Rec = Nothing
End If
‘*** Set the variables to nothing
Set DB = Nothing
Set WI = Nothing
to use the variable in a command use the “&” sign. I was trying to use the profile path with another directory to change the size of the java cache setting and this is how I got it to work:
Const ForReading = 1
Const ForWriting = 2
‘get user profile
Set objShell = CreateObject(“WScript.Shell”)
profile_path = objShell.ExpandEnvironmentStrings(“%USERPROFILE%”)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objTextFile = objFSO.OpenTextFile(profile_path & “\AppData\LocalLow\Sun\Java\Deployment\deployment.properties”, ForReading)
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
intLineFinder = InStr(strNextLine, “deployment.cache.max.size”)
If intLineFinder 0 Then
strNextLine = “deployment.cache.max.size=550”
End If
strNewFile = strNewFile & strNextLine & vbCrLf
Loop
objTextFile.Close
Set objTextFile = objFSO.OpenTextFile(profile_path & “\AppData\LocalLow\Sun\Java\Deployment\deployment.properties”, ForWriting)
objTextFile.WriteLine strNewFile
objTextFile.Close
wscript.echo (“Updated cache setting”)
wscript.quit
how to change the installation directory of an exe application through the vbsript