让 VBScript 检查文件名中包含特定单词的文件,然后查找并删除该文件

Make VBScript check for a file with a certain word in it's file name and then find and delete that file

我想知道是否有办法让我的 vbs 脚本可以检查并删除名称中包含特定单词的任何文件。这是我目前所拥有的:

x=MsgBox ("Searching for any infected files...",64,"Search") 

DIM filesys
Set filesys = CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("C:\Documents and Settings\Name\Desktop\example.txt") Then
    WScript.Sleep 1500
    x=MsgBox ("Warning! A infected file was found!",48,"Warning") 
    filesys.DeleteFile "C:\Documents and Settings\Name\Desktop\example.txt"
    x=MsgBox ("File was deleted!",48,"File Deleted")
    WScript.Sleep 1000
    x=MsgBox ("This Computer is now clean!",64,"Hooray!") 
Else 
    WScript.Sleep 500
    x=MsgBox ("File not found! This Computer is clean!",64,"Hooray!")
End If

是否还有一种方法可以使 username/file 路径在任何计算机上都有效?我知道是

"C:\Documents and Settings\%username%\Desktop\example.txt"

在批处理中,但是在 vbscript 中有类似的东西吗?还有一种方法可以删除名称中也有 'example' 的任何扩展名的文件吗?例如:

filesys.DeleteFile "C:\Documents and Settings\Name\Desktop\example.anyextension"

非常感谢!希望您不要介意我提出的大量问题,我才刚刚开始使用 VBS/VBScript 进行编码,非常感谢您的帮助! :)

ExpandEnvironmentStrings方法returns一个环境变量的扩展值。环境变量名称,必须用%个字符括起来,不区分大小写:

Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "Current user name: " _
    & WshShell.ExpandEnvironmentStrings("%USERNAME%")
WScript.Echo "Desktop folder: " _
    & WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"

所有下一个代码片段都从链接源中原封不动地粘贴在这里。可以成为任何 VBScript 初学者的起点。在下一个巨大的脚本库中激励自己:Script resources for IT professionals.


从 MSDN 上的 Search for Files Using a Wildcard Query. Uses the Like keyword to search for all files on a computer that contain a tilde (~). However, read CIM_DataFile class 窃取:

The following VBS code sample describes how to perform a standard wildcard search on a datafile. Note that the backslash delimiters must be escaped with another backslash (\). Also, when using "CIM_DataFile.FileName" in the WHERE clause, the WMIPRVSE process will scan all directories on any available storage device. This may take some time, especially if you have mapped remote shares, and can trigger antivirus warnings.

strComputer = "." 
Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}\" & strComputer & "\root\cimv2") 

Set colFiles = objWMIService.ExecQuery _ 
    ("Select * from CIM_DataFile where FileName Like '%~%'") 

For Each objFile in colFiles 
    Wscript.Echo objFile.Name 
Next 

这是一个更智能、更快 的解决方案,带有全面的评论:How Can I Delete Specific Files in a Specific Folder?嘿,脚本专家! 博客(在十岁):

strComputer = "."

Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")

Set colFileList = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='T:\Act'} Where " _
        & "ResultClass = CIM_DataFile")

For Each objFile In colFileList
    If InStr(objFile.FileName, "current") Then
        objFile.Delete
    End If
Next

当然,与大多数 WMI 脚本一样,此脚本也可以 运行 针对远程计算机。