使用VBScript

时间:2016-02-21 23:06:13

标签: variables batch-file vbscript

我需要使用vbscript删除一些浏览器文件。 我有简单的批处理代码,如

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"

在vbs中

Set obj = CreateObject("Scripting.FileSystemObject")
obj.DeleteFile("C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session")

问题是vbs无法识别变量%USERNAME%并且我收到错误“此目录中没有文件”。 有人能告诉我如何用这种语言编写变量目录/路径吗?

2 个答案:

答案 0 :(得分:2)

来自帮助。

返回环境变量的扩展值。

object.ExpandEnvironmentStrings(strString) 

<强> imageArguments 对象 WshShell对象。

<强> strString 字符串值,指示要扩展的环境变量的名称。

<强>说明 ExpandEnvironmentStrings方法仅扩展在PROCESS环境空间中定义的环境变量。环境变量名称,必须包含在&#34;%&#34;之间。字符,不区分大小写。

<强> imageExample 以下代码展开Windows目录环境变量并显示它:

Visual Basic脚本

set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")

如果你想在vbs中使用递归。

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

答案 1 :(得分:1)

您可以尝试:

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