Delete file in variable directory with VBScript - variables

I need use vbscript to delete some browser files.
I have simple batch code like
del /q /s /f "C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session"
rd /s /q "C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session"
In vbs
Set obj = CreateObject("Scripting.FileSystemObject")
obj.DeleteFile("C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session")
Problem is that vbs doesn't recognize variable %USERNAME% and I am getting error "no file in this directory".
Could someone tell me how to write variable directory/path in this language?

From Help.
Returns an environment variable's expanded value.
object.ExpandEnvironmentStrings(strString)
imageArguments
object
WshShell object.
strString
String value indicating the name of the environment variable you want to expand.
Remarks
The ExpandEnvironmentStrings method expands environment variables defined in the PROCESS environment space only. Environment variable names, which must be enclosed between "%" characters, are not case-sensitive.
imageExample
The following code expands the Windows Directory environment variable and displays it:
Visual Basic Script
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
If you want to do it in vbs you use recursion.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
ProcessFolder "c:\users\david candy\documents"
Sub ProcessFolder(FolderPath)
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
wscript.echo thing.path
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
' wscript.echo thing.name
ProcessFolder thing.path
Next
End Sub

You can try :
Set objFSO = CreateObject("Scripting.FileSystemObject")
set WshShell = CreateObject("WScript.Shell")
UserProfile = WshShell.ExpandEnvironmentStrings("%USERPROFILE%")
Wscript.echo UserProfile
Wscript.echo UserProfile &"\AppData\Roaming\Opera Software\Opera Stable\Current Session"
AppData = WshShell.ExpandEnvironmentStrings("%AppData%")
Wscript.echo AppData
Wscript.echo AppData &"\Opera Software\Opera Stable\Current Session"
If objFSO.FolderExists(AppData &"\Opera Software\Opera Stable\Current Session") Then
objFSO.DeleteFolder AppData &"\Opera Software\Opera Stable\Current Session"
End If

Related

How to call a batchfile from VBA script

I cannot call the "test1.bat" file from this visual basic script.
The only thing that i get is "Runtime error 70, access denied". Has someone had a similar outcome or experiences.
Sub test()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "C:\Users\taischa\Desktop\test1.bat", windowStyle, waitOnReturn
End Sub
I already tried to change the .bat to .cmd file. I also tried to access the bat file through a link as admin.I can execute the Batchfile without any problem if i doubleclick the icon or call ir via cmd. I suspect the firewall to block the makro.
Maybe someone can help me.
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "test.bat"
oShell.Run strArgs, 0, false
This makes the file invisible, but execute they. You can also type:
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c test.bat"
oShell.Run strArgs, 0, false
To end the process when its get off.
If you need to start it with a window:
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c start test.bat"
oShell.Run strArgs, 0, false
first, they create a object, then, they start a function of cmd, called cmd with the paramter /c, that means: the code will stop and the cmd will close while they stop running. But, first, he will start a window with your bat file. That makes the file visible.
I hope i helped you.
Try in this simpler way, please:
Shell "C:\Users\taischa\Desktop\test1.bat", 1
If it does not work, you should take the ownership of the folder in discussion. I mean, the user account who executes the code.
Is your user account an administrator type?
Edited:
Please, test the next code and send some feedback:
Sub testCreateRunBat()
Dim FSO As Object, lngOK As Long, BT As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set BT = FSO.OpenTextFile(ThisWorkbook.Path & "\Test.bat", 2, True)
BT.Write "C:"
BT.WriteLine
BT.Write "Dir"
BT.Close
lngOK = Shell(ThisWorkbook.Path & "\Test.bat", 1)
If lngOK <> 0 Then MsgBox "Everything OK!"
End Sub

Can't run DIR from WScript Shell in VBA?

I use the following function in a lot of my VBA projects. I initially added the reference to Windows Script Host Object model to take advantage of Intellisense, but then switched to late binding so I didn't have to reference a bunch of stuff.
Private Function RunCMD(ByVal strCMD As String) As String
'Runs the provided command
Dim oShell As Object 'New WshShell
Dim cmd As Object 'WshExec
Dim x As Integer
Const WshRunning = 0
On Error GoTo wshError
x = 0
RunCMD = "Error"
Set oShell = CreateObject("Wscript.Shell")
Set cmd = oShell.Exec(strCMD)
'Debug.Print strCMD
'Stop
Do While cmd.Status = WshRunning
Sleep 100 'for 1/10th of a second
x = x + 1
If x > 1200 Then 'We've waited 2 minutes so kill it
cmd.Terminate
MsgBox "Error: Timed Out", vbCritical, "Timed Out"
End If
Loop
RunCMD = cmd.StdOut.ReadAll & cmd.StdErr.ReadAll
Set oShell = Nothing
Set cmd = Nothing
Exit Function
wshError:
On Error Resume Next
RunCMD = cmd.StdErr.ReadAll
Resume Next
End Function
It works great when you do something like
RunCMD("ping www.bing.com") or
RunCMD("winrs -r:" & strHost & " reg query hklm\system\currentcontrolset\services\cdrom /v start")
However RunCMD("Dir c:\config* /a:-d /b /d /s") fails, and cmd.StdErr.ReadAll gives an Object Variable or With Block not set error. Even a simple RunCMD("Dir") fails.
Why does DIR make the WScript shell crap out? More importantly, how can I use CMD's DIR function (not VBA's DIR function!) to get a list of files that match a search pattern?
Does it work if you preface your dir command with "cmd /c " and wrap your DOS command in double quotes, like
RunCmd("cmd /c ""DIR""")
or
RunCmd("cmd /c ""Dir c:\config* /a:-d /b /d /s""")

vbscript permission denied 800a0046 network

I made a script that copying a file to a certain location.
I add the .vbs to taskschd.msc scheduled for make a .pst backup
but I get error message
Line: 91
Char: 7
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error
<pre>
'Set the amount of pst-files you want to copy. Start counting at 0!
ReDim pst(1)
'Define the location of each pst-file to backup. Increase the counter!
pst(0) = "C:\Users\daniel.elmnas.TT\Documents\Outlook Files\de#teknotrans.se.pst"
pst(1) = "C:\Users\daniel.elmnas.TT\Documents\Outlook Files\de.pst"
'Define your backup location
BackupPath = "\\ttad-1\Gemensam\Outlook_Backup\Daniel Elmnäs"
'Keep old backups? TRUE/FALSE
KeepHistory = FALSE
'Maximum time in milliseconds for Outlook to close on its own
delay = 30000 'It is not recommended to set this below 8000
'Start Outlook again afterwards? TRUE/FALSE
start = TRUE
'===================STOP MODIFY====================================
'Close Outlook
Call CloseOutlook(delay)
'Outlook is closed, so we can start the backup
Call BackupPST(pst, BackupPath, KeepHistory)
'Open Outlook again when desired.
If start = TRUE Then
Call OpenOutlook()
End If
Sub CloseOutlook(delay)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
'If Outlook is running, let it quit on its own.
For Each Process in objWMIService.InstancesOf("Win32_Process")
If StrComp(Process.Name,"OUTLOOK.EXE",vbTextCompare) = 0 Then
Set objOutlook = CreateObject("Outlook.Application")
objOutlook.Quit
WScript.Sleep delay
Exit For
End If
Next
'Make sure Outlook is closed and otherwise force it.
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Outlook.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
Set objWMIService = Nothing
Set objOutlook = Nothing
set colProcessList = Nothing
End Sub
Sub BackupPST(pst, BackupPath, KeepHistory)
Set fso = CreateObject("Scripting.FileSystemObject")
If KeepHistory = True Then
ArchiveFolder = Year(Now) & "-" & Month(Now) & "-" & Day(Now)
BackupPath = BackupPath & ArchiveFolder & "\"
End If
If fso.FolderExists(BackupPath) = False Then
fso.CreateFolder BackupPath
End If
For Each pstPath in pst
If fso.FileExists(pstPath) Then
fso.CopyFile pstPath, BackupPath, True
End If
Next
Set fso = Nothing
End Sub
Sub OpenOutlook()
Set objShell = CreateObject("WScript.Shell")
objShell.Run "Outlook.exe"
End Sub
</pre>
Could someone help me to solve this?
Thank you in advance
Seems like you schedule the script.
You need to start the task with a user that executes the script which has rights on the PST file, as well as on the path where you store the backup. Running it with the system account won't be enough.
There are better ways to backup PST files also, I use a Ruby script to synchronise a local copy with a backup copy, is runs on PST's more than 10GB big without problem, might be a problem if you would do it with a copy like this.
You need to backup the copy on a backup medium also because when the PST has errors (and all big PST have) you copy the errors to the backup and could lose both.
Also, you do the following
BackupPath = "\\ttad-1\Gemensam\Outlook_Backup\Daniel Elmnäs"
...
BackupPath = BackupPath & ArchiveFolder & "\"
Where is the \ between the two first variables ?
EDITED: Change the permissions of the folder.
In windows explorer, navigate to the folder where the PST file is located.
In the left pane of windows explorer, right click on the folder where the PST file is located, select "Properties".
Select the "Security" tab
Click the button "Edit" to change permissions.
Click "Add"
In the object names to select box, enter "everyone" (no quotes).
Click "Check Names", everyone should become capitalized and underlined.
Click "Ok"
Select "Everyone" from the list of Groups or user names.
In the "Permissions for Everyone" list, make sure "Read & Execute, List folder contents and Read, in the allow column are checked, click "Apply"
Click Ok.
NOTE: By doing this, anyone who has access to this computer can access the folder. You might consider only adding your login to the computer to the list of Groups or usernames instead of Everyone. You may have to repeat the above steps on the PST file(s) in question.
Original Post:
I ran the script here, testing for various issues and it ran without problems. At this point I believe the issue is rights and permissions to either the source or destination folder (or the files you are backing up). By default, the user's themselves don't have access to Outlooks data files. You would need to add "read" permissions to the files in question (PST,OST, and so on) or the full folder.
In reality, just backing up the PST files isn't enough to restore an Outlook configuration; you would need all of the files.
You can Try this:
'===================================================================
'Description: VBS script to backup your pst-files.
'
'Comment: Before executing the vbs-file, set the location of outlook
' folder you want to backup and
' the backup location (this can also be a network path).
' See the URL below for more configuration instructions and
' how to create a Scheduled Task for it.
'
' Original author : Robert Sparnaaij
' Modified: Fred Kerber
' version: 1.1
' website: http://www.howto-outlook.com/downloads/backupscript.htm
' Changes:
' Changed var types; changed to backup full folder and not just pst files.
'===================================================================
'===================BEGIN MODIFY====================================
'Define the folder location of Outlook's data files.
sOutlookDataPath = "C:\Users\FKerber.CORP\AppData\Local\Microsoft\Outlook\"
'Define your backup location
sBackupPath = "E:\Outlook Backup\"
'Keep old backups? TRUE/FALSE
bKeepHistory = TRUE
'Maximum time in milliseconds for Outlook to close on its own
iDelay = 30000 'It is not recommended to set this below 8000
'Start Outlook again afterwards? TRUE/FALSE
bStart = True
'===================STOP MODIFY====================================
'Close Outlook
Call CloseOutlook(iDelay)
'Outlook is closed, so we can start the backup
Call BackupOutlook(sOutlookDataPath, sBackupPath, bKeepHistory)
'Open Outlook again when desired.
If bStart = TRUE Then
Call OpenOutlook()
End If
Sub CloseOutlook(iDelay)
Set objWMIService = GetObject("winmgmts:" &_
{impersonationLevel= impersonate}!\\.\root\cimv2")
'If Outlook is running, let it quit on its own.
For Each oProcess in objWMIService.InstancesOf("Win32_Process")
If StrComp(oProcess.Name,"OUTLOOK.EXE",vbTextCompare) = 0 Then
Set objOutlook = CreateObject("Outlook.Application")
objOutlook.Quit
WScript.Sleep delay
Exit For
End If
Next
'Make sure Outlook is closed and otherwise force it.
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Outlook.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
Set objWMIService = Nothing
Set objOutlook = Nothing
Set colProcessList = Nothing
End Sub
Sub BackupOutlook(sOutlook, sBackupPath, bKeepHistory)
Set ofso = CreateObject("Scripting.FileSystemObject")
If bKeepHistory = True Then
sArchiveFolder = Year(Now) & "-" & Month(Now) & "-" & Day(Now)
sBackupPath = sBackupPath & sArchiveFolder & "\"
Else
For Each oFile In ofso.GetFolder(sBackupPath).Files
ofso.DeleteFile oFile.Path, True
Next
End If
If ofso.FolderExists(sBackupPath) = False Then
ofso.CreateFolder sBackupPath
End If
For Each oFile In ofso.GetFolder(sOutlook).Files
If ofso.FileExists(oFile.Path) Then
ofso.CopyFile oFile.Path, sBackupPath, True
End If
Next
Set ofso = Nothing
End Sub
Sub OpenOutlook()
Set objShell = CreateObject("WScript.Shell")
objShell.Run "Outlook.exe"
End Sub
I had a similar problem trying to delete files with VBS. I assume that as with my case: The source of the problem is that the script is trying to perform some operation on a file or folder that has a Read-only Attribute. To solve this manually you could left click -> properties -> unclick the Read-Only Attribute then the file/folder should be copied by the script. To solve the problem with VBS: I make the assumption that file/folder is set to Read-Only because there is a programme currently using them.
One: we can just skip files/folders set to read-only this time and hope to get them next time the script runs. For this we first check if file/folder is read-only (I got this from here: https://social.technet.microsoft.com/Forums/ie/en-US/7382d452-1ef9-404a-8874-48d38fcfe911/vbscript-verify-if-a-file-is-readonly?forum=ITCG), if not then we perform the copy operation.
Sub BackupPST(pst, BackupPath, KeepHistory)
'........
For Each pstPath in pst
If fso.FileExists(pstPath) Then
If not (fso.GetFile(pstPath).Attributes AND 1) Then 'if item is not read-only
fso.CopyFile pstPath, BackupPath, True
End If
End If
Next
Set fso = Nothing
End SubSub
Two: At the very least this should prevent you from getting the error. But if the script never moves the files even after running a number of times then chances are that the files (you are trying to move) are always in read only and you should change Attribute of the file (you are trying to move) in your script before calling the copy function, see how to do that here: https://devblogs.microsoft.com/scripting/how-can-i-change-a-read-only-file-to-a-read-write-file/

how to unzip a attachment in outlook and save it to a foldeer using vba

currently i have an Email that comes in and my vba code will save the file to a folder, however since this code was made they now send me the file in a zip file. This of course breaks the code and i have to resend it in a non zip file to make it work. Here is a sample of what I am currently using:
If Left(objItem.Subject, 28) = "xxxxx report Toolbox" Then
For Each Atmt In objItem.Attachments
FileName = "O:\Automated Reports\toolbox.xlsx"
Atmt.SaveAsFile FileName
modify_file
Debug.Print "success CSAT file"
Open "O:\Automated Reports\toolboxDate.JW" For Output As #1
Write #1, Right(objItem.Subject, 5)
Close #1
Next Atmt
End If
As i stated before this code woks fine for just saving the file when it is not a .zip file. I need it to unzip the file and save it to the O: drive. I have tried to use some shell.application objects but i didn't quite get that to work. Thanks for any help ahead of time
'Create new blank zip.
Set Ag=Wscript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(Ag(0), 8, vbtrue)
BlankZip = "PK" & Chr(5) & Chr(6)
For x = 0 to 17
BlankZip = BlankZip & Chr(0)
Next
ts.Write BlankZip
'Unzip
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(Ag(1))
Set DestFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Msgbox "Finished"
'Zip
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set DestFldr=objShell.NameSpace(Ag(1))
Set SrcFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Msgbox "Finished"

Detecting a DLL version number using a script

I would like to write a script that can recursively scan the DLLs in a directory and generate a report of all of their version numbers.
How can I detect the version number of a DLL using a script? VBScript solutions are preferred, unless there is a better way.
You can use the FileSystemObject object to access the file system and its GetFileVersion method to obtain the file version information.
You asked for a VBScript example, so here you are:
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
PrintDLLVersions oFSO.GetFolder(WScript.Arguments.Item(0))
Sub PrintDLLVersions(Folder)
Dim oFile, oSubFolder
' Scan the DLLs in the Folder
For Each oFile In Folder.Files
If UCase(oFSO.GetExtensionName(oFile)) = "DLL" Then
WScript.Echo oFile.Path & vbTab & oFSO.GetFileVersion(oFile)
End If
Next
' Scan the Folder's subfolders
For Each oSubFolder In Folder.SubFolders
PrintDLLVersions oSubFolder
Next
End Sub
Usage:
> cscript //nologo script-file.vbs folder > out-file
e.g.:
> cscript //nologo dll-list.vbs C:\Dir > dll-list.txt
Sample output:
C:\Dir\foo.dll 1.0.0.1
C:\Dir\bar.dll 1.1.0.0
C:\Dir\SubDir\foobar.dll 4.2.0.0
...
EDIT I think this is the source I referenced
This is the script that I use, I apologize, but I don't recall from where. (So,reader, if this started as your script please step forward) It uses the FileSystemObject which can get version directly.
#echo off
setlocal
set vbs="%temp%\filever.vbs"
set file=%1
echo Set oFSO = CreateObject("Scripting.FileSystemObject") >%vbs%
echo WScript.Echo oFSO.GetFileVersion(WScript.Arguments.Item(0)) >>%vbs%
for /f "tokens=*" %%a in (
'cscript.exe //Nologo %vbs% %file%') do set filever=%%a
del %vbs%
echo Full file version of %file% is: %filever%
for /f "tokens=2 delims=. " %%a in ("%filever%") do set secondparam=%%a
set splevel=%secondparam:~0,1%
echo SP level is: %splevel%
endlocal
pause