2015-10-13 39 views
1

我正在使用正在本地磁盤中查找指定文件的腳本。當它找到該文件時,它會重命名/刪除接近指定文件的文件。 (我的意思是在同一個目錄等)使用WMI檢查文件是否不在相同的文件夾

示例代碼:

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另一個文件。

如果有 - 不要做任何事情,否則 - 重命名指定的文件夾,如上面的代碼。

回答

0

你在找什麼是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 

編輯:改變了我的例子直接在提問者的代碼工作。

+0

但我的代碼是在整個磁盤上尋找myfile.exe(我不知道什麼是文件的路徑,直到scirpt會發現它)。您的scirpt「知道」該文件的路徑。 – krysteksulek

+0

我修改了我的示例以專門處理您的代碼。給那一槍@krysteksulek。 –

相關問題