Use a VBS to edit ini for users %appdata% folder - for-loop

I have script that edits the a line in the ini file, which sits on users %Appdata% folder i.e C:\Users\<>\AppData\Roaming.
The current script which I have only edits a file pointing to proper file location, but I would like to have script which can edit the file on every logged on users folder
I have a vbs below which look like this , but I am not able to use a variable %appdata% to edit the file under folder when the user is logged on
Const ForReading = 1
Const ForWriting = 2
Dim strUserName, CurrDir
Set objFSO = CreateObject("Scripting.FileSystemObject")
strUserName = InputBox("Please enter your email address below in the following format:" & Vbnewline & "firstname_lastname#test.com" & Vbnewline & Vbnewline & "HINT - If you are unsure, you can look up your name", "Add internet email address")
If strUserName = "" Then
Wscript.Quit
End If
Set objTextFile = objFSO.OpenTextFile("H:\appdata\Linkpoint360\LinkPointConfig.ini", ForReading)
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
intLineFinder = InStr(strNextLine, "UserEMailAddress")
If intLineFinder <> 0 Then
strNextLine = "UserEMailAddress=" & strUserName
End If
strNewFile = strNewFile & strNextLine & VbCrLf
Loop
objTextFile.Close
Set objTextFile = objFSO.OpenTextFile("H:\appdata\Linkpoint360\LinkPointConfig.ini", ForWriting)
objTextFile.WriteLine strNewFile
objTextFile.Close
I am not scripting expert, but I have tried best to find a suitable solution over the internet and I have no luck
If someone can please edit this vbs and give a proper script, that will be really appreciated
# Ansgar Wiechers, can't post the image as i don't have 10 repuataion, but here is what I get in pop box:
Script: << Location of file >>
Line: 13
Char: 1
Error: Path not found
Code: 800A004C
Scource: Microsoft VBScript runtime error
the error I get when is use %appdata% in my script.
from the above code I have just edited file location "H:\appdata...." to "%appdata%....."

FileSystemObject methods don't expand environment variables. You need to do it yourself, e.g. like this:
...
Set sh = CreateObject("WScript.Shell")
config = sh.ExpandEnvironmentStrings("%APPDATA%\Linkpoint360\LinkPointConfig.ini")
Set objTextFile = objFSO.OpenTextFile(config, ForReading)
...

You can't reliabily do this in vbscript.
However you can make a safe assumption (disregarding network and profile updating issues that I don't think will matter) that profiles are under Users folder and each user will have the same relative path to AppFolder.
The normal way of handling this problem type is to use logon scripts.

Related

VBscript, For each loop and Msgbox in the end

I´m working with VBScript that ie. displays and saves computer hardware info into txt file. My VBscript do some another stuff too ie. modifies some XML files. Now I want use opensource hardware monitoring software so I can log temps, voltages etc. while i´m running torture tests for the computer. The monitoring software is logging results in CSV format so I have first find out if CSV file exists in source folder because name is always different, and then rename it with computer name (I use inputbox to give that name and you can´t see it in code given below). Anyway I want to copy CSV file to another destination. Problem is that if CSV file is not found in source folder, then that MsgBox pop-ups as many times that there are files in the dest. folder. I know that the problem is in "For Each" loop but don´t know how can I bypass that if CSV file doesn´t exist. I want that MsgBox shows itself only once if CSV file doesn´t exists. Can anybody help me with this one?
dim fso, oshell, strProfilePath, oTFldr, fname, WshShell, txt
Set fso = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
strProfilePath = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
If fso.FolderExists(strProfilePath & "\Desktop\Tests\Software\") then
Set oTFldr = fso.getfolder(strProfilePath & "\Desktop\Tests\Software\")
Else
MsgBox "Software folder doesn´t exists!", vbExclamation + vbOKOnly
End If
For each ofile in oTFldr.Files
If UCase(fso.GetExtensionName(ofile.Name)) = "CSV" then
ofile.name = Compname & ".CSV"
fso.Copyfile strProfilePath & "\Desktop\Tests\Software\" & Compname & ".CSV", "C:\"
exit for
else
MsgBox "Didn´t find any CSV file!", vbExclamation + vbOKOnly
End If
Next
For each ofile in oTFldr.Files
If UCase(fso.GetExtensionName(ofile.Name)) = "CSV" then
ofile.name = Compname & ".CSV"
fso.Copyfile strProfilePath & "\Desktop\Tests\Software\" & Compname & ".CSV", "C:\"
exit for
'else
' MsgBox "Didn´t find any CSV file!", vbExclamation + vbOKOnly
End If
Next

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

VBScript that Opens an ini file and a Config file in notepad

I work in a hospital environment and right now im doing PC deployments. Part of the deployment requires us to view 2 files on a network drive looking for information regarding the old systems. They use specific ports and or TTY's to view information in each department.
I am trying to create a VBS file that can open 2 files in 2 different notepad windows. The first one opens up but the pcview.cfg keeps giving me an error. Im trying to link to the same location that the HBOWEM32 is pointed to. Can anyone solve? For security reasons I have taken out the exact location of the network drive. The code below prompts for a specific folder name which is the old pc name. After entering that data it opens the HBOWEM32 files fine but says it cannot find the other part. I Have manually looked inside the folder and the pcview.cfg file DOES exist. I just want a faster way of opening these rather than brute forcing through the run prompt.
Here is the code.
CONST strDir = "<Netowrk Location)"
Dim WshShell
set objShell = CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
function findFolder(strDir, strFlag)
set objFolder = objFSO.GetFolder(strDir)
for each objSubFolder in objFolder.SubFolders
if (inStr(objSubFolder.Name, strFlag)) then
findFolder = objSubFolder.Path
exit function
else
findFolder = findFolder (objSubFolder.Path, strFlag)
end if
next
end function
strFlag = inputBox("Enter Computer Name:")
strWeb = findFolder(strDir, strFlag) & "\HBOWEM32.ini"
objShell.Run strWeb
Set WshShell = CreateObject ("WScript.Shell")
WshShell.Run ("notepad.exe """ + "\\<same location as above>\Pcview.cfg""")
Use Option Explicit
Don't create variables you don't use (WshShell, objShell)
Improve your variable names (strFlag seems to be a computer name, strWeb seems to be the full specification of a file)
Don't lump different info into one variable (strWeb contains the folder path to re-use and the specific file name)
Use diagnostics output (at least while developing)
In code:
Option Explicit
...
Dim strComputer : strComputer = InputBox("Enter Computer Name:")
Dim strFolder : strFolder = findFolder(strDir, strComputer)
Dim strIniFSpec : strIniFSpec = objFSO.BuildPath(strFolder, "HBOWEM32.ini")
WScript.Echo "will run '" & strIniFSpec & "'"
objShell.Run strIniFSpec
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
Dim strCfgFSpec : strCfgFSpec = objFSO.BuildPath(strFolder, "Pcview.cfg")
Dim strCmd : strCmd = "notepad.exe """ & strCfgFSpec & """"
WScript.Echo "will run '" & strCmd & "'"
WshShell.Run strCmd
(not tested, please be carefull)

SFTP transfer file and move file to folder

This is my first post so please excuse my ignorance. I am using a vbscript to zip all .csv type files in a particular folder. After some google searches, I have found a workable vbscript to do this and have enabled a scheduled task to automate this.
What I need to do next is to transfer the zip file via sftp and then "move" that zip file into another folder. I believe the former can be achieved using pscp.exe via command line but can someone show me how to do the latter?
Basically the zipping will be done twice a day and so it will have a timestamp similar to yyyymmdd0900.zip (for 9am schedule) and yyyymmdd1800.zip (for 6pm schedule). After the transfer, I want to move (not copy) the zip file generated into another folder.
Any pointers would be greatly appreciated. Thank you all in advance.
EDIT: Here is some code I slapped together based on some Google searches. It does what I want it to do. Please excuse the "pasting" as i couldn't figure out how to format it properly. Currently, it runs the bat file after copying but I just noticed that i need to send (using PuTTY Secure Copy) the "latest" zip file before moving it to the "completed" folder. Can someone please show me how to do this?
Zipping the file and rename the zip file
My Code :
On Error Resume Next
strFilepath = "c:\files"
strDestination = "c:\files\completed\"
strExtension = "csv"
strYear = Year(Now)
strMonth = Right("0" & Month(Now), 2)
strDay = Right("0" & Day(Now), 2)
strHour = Right ("0" & Hour(Now), 2)
strMinute = Right ("0" & Minute (Now), 2)
strZip = strFilepath & "\" & strYear & strMonth & strDay & strHour & strMinute & ".zip"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFilepath)
For Each objFile in objFolder.Files
strFileExt = objFSO.GetExtensionName(objFile.Path)
If LCase(strFileExt) = LCase(strExtension) Then
ZipFile objFile.Path, strZip
End If
Next
Sub ZipFile(strFileToZip, strArchive)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strArchive) Then
Set objTxt = objFSO.CreateTextFile(strArchive)
objTxt.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
objTxt.Close
End If
Set objApp = CreateObject( "Shell.Application" )
intCount = objApp.NameSpace(strArchive).Items.Count + 1
objApp.NameSpace(strArchive).CopyHere strFileToZip
Do
WScript.Sleep 200
set objNameSpace = objApp.NameSpace(strArchive)
If Not objNameSpace is nothing Then
If objNameSpace.Items.Count = intCount Then
Exit Do
End If
End If
Loop
End Sub
>Move file to a different folder and then run a bat file to secury copy file to a FTP location
'Vars
Dim objFSO, objFileCopy, objFileDelete, dot, files, file
Dim strDestination, folder, subfolder, fileCount, strFilePath
'Strings
strDestination = "C:\Files\Completed\"
strFilePath = "C:\Files"
set objFSO = CreateObject("Scripting.fileSystemObject")
set folder = objFSO.getFolder(strFilePath)
For Each file In folder.files
Set objFileCopy = objFSO.GetFile(file)
If objFSO.GetExtensionName(file) = "zip" Then
objFSO.MoveFile objFileCopy.Path, strDestination
End If
Next
Dim shell
Set shell=createobject("wscript.shell")
Shell.run "C:\testsend.bat"
Set shell=nothing
This will move a file to the specified location.
Sub Move_File(Source_File, Destination_Folder)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile Source_File, Destination_Folder
Set fso = Nothing
End Sub
sftp client provides a means to change working directory on the host before performing any file transfers. It would be better to thus transfer the file directly to the target location.
NOTE: The above answer was a result of misunderstanding the question. I read it to mean the file had to be moved on the destination but the real operation was to move the file on the origin.
I found the following example code that moves a file after checking that it exists. Wildcards are allowed for the source parameter but then FileExists may not work. Requires vbscript 2.0 to work.
<%
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("c:\sourcefolder\anyfile.html") Then
filesys.MoveFile "c:\sourcefolder\anyfile.html", "c:\destfolder\"
End If
%>

vbscript : fso.opentextfile permission denied

In my code segment, when I script the file name, it gives me a permission denied
on the following line:
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
Here is the script
'output log info
Function OutputToLog (strToAdd)
Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
strDirectory = "c:\eNet"
strFile = "\weeklydel.bat"
'strText = "Book Another Holiday"
strText = strToAdd
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check that the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
'WScript.Echo "Just created " & strDirectory
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
'Wscript.Echo "Just created " & strDirectory & strFile
End If
set objFile = nothing
set objFolder = nothing
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 2
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
' Writes strText every time you run this VBScript
objTextFile.WriteLine(strText)
objTextFile.Close
End Function
I have assigned the vbscript domain administrator permissions. Any ideas?
thanks in advance
I don't think this has to do with File Permissions per se. It has to do with the fact that you've created the file using:
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
That creates the file...and carries a reference to that file (objFile)
Then you don't close the file before you destroy the reference
...
'Missing objFile.Close here
Set objFile = nothing
Set objFolder = nothing
...
Consequently you're destroying the reference but leaving the textstream open in memory thus locking your file.
You are then proceeding to attempt to re-open the file while the file is already "open". This is a little long winded, you've already got a reference after you've created the file - it would be easier just to write straight to that rather than destroy the reference before creating another one.
for what its worth...
I was convinced I had a permission error because of this line:
Set LogFile = LogFSO.OpenTextFile(LogFileName, ForWriting, True)
Because that's the line that the 'permission denied' error pointed to. But in fact, my permission error was a few lines further down:
WshShell.AppActivate(ScreensToRemove(i))
WshShell.SendKeys ("~")
WScript.Sleep(1000)
There was no screen with such a caption, so the SendKeys is what did not have permission.
The solution, of course, was:
If WshShell.AppActivate(ScreensToRemove(i)) = True Then
WshShell.SendKeys ("~")
WScript.Sleep(1000)
End if
Hope that might help.
Also, make sure that you don't have the file open in Excel (I had this problem with a .csv file)...
In my particular case the file which existed before and all I had to do was give permission to the Everyone user
balabaster is exactly right. You either need to close the file before reopening it a second time for writing, or using the existing open handle.

Resources