【问题标题】:Check if file is not at the same folder using WMI使用 WMI 检查文件是否不在同一文件夹中
【发布时间】:2015-10-13 12:25:03
【问题描述】:

我正在使用在本地磁盘中查找指定文件的脚本。当它找到文件时,它会重命名/删除靠近指定文件的文件。 (我的意思是在同一个目录等)

示例代码:

Sub RenameFolder( oldName, newName )
    Dim filesys
    Set filesys = WScript.CreateObject("Scripting.FileSystemObject")

    If filesys.FolderExists( oldName ) Then
        filesys.MoveFolder oldName, newName
    End If
End Sub

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

Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_DataFile Where Filename = 'myfile' and Extension = 'exe'")

For Each objFile in colFiles

RenameFolder objFile.Drive & objFile.Path & "files\test",  objFile.Drive & objFile.Path & "files\test_old"

我想添加一个条件,它将检查与myfile.exe相同的目录中是否还有另一个名为otherfile.exe的文件。

如果它存在 - 不要做任何事情,否则 - 像上面的代码一样重命名指定的文件夹。

【问题讨论】:

    标签: windows vbscript wmi


    【解决方案1】:

    您正在寻找的是FileExists 方法。以下是我建议您在代码中使用它的方法:

    Sub RenameFolder( oldName, newName )
        Dim filesys
        Set filesys = WScript.CreateObject("Scripting.FileSystemObject")
    
        If filesys.FolderExists( oldName ) Then
            filesys.MoveFolder oldName, newName
        End If
    End Sub
    
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    
    Set colFiles = objWMIService.ExecQuery _
        ("Select * from CIM_DataFile Where Filename = 'myfile' and Extension = 'exe'")
    
    For Each objFile in colFiles
        If Not filesys.FileExists(objFile.Drive & objFile.Path & "otherfile.exe") Then
            'No else clause needed since we are checking if the file _doesn't_ exist.
            RenameFolder objFile.Drive & objFile.Path & "files\test",  objFile.Drive & objFile.Path & "files\test_old"
        End If
    Next
    

    编辑:将我的示例更改为直接在提问者的代码中工作。

    【讨论】:

    • 但是我的代码正在整个磁盘上寻找 myfile.exe(我不知道文件的路径是什么,直到 scirpt 找到它)。您的脚本“知道”该文件的路径。
    • 我已经修改了我的示例以专门使用您的代码。试一试@krysteksulek。
    猜你喜欢
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2016-05-04
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多