脚本停止受保护的文件,如系统文件

时间:2010-02-16 11:00:30

标签: vba vbscript

由于受保护的文件(例如系统文件“Permission Denied”),此代码会在一段时间后停止。

有没有办法修改下面的代码,以便它可以处理这些受保护的文件或绕过它们?

Set objFS=CreateObject("Scripting.FileSystemObject") 
WScript.Echo Chr(34) & "Full Path" &_ 
 Chr(34) & ","  & Chr(34) & "File Size" &_ 
 Chr(34) & ","  & Chr(34) & "File Date modified" &_ 
 Chr(34) & "," & Chr(34) & "File Date Created" &_ 
 Chr(34) & "," & Chr(34) & "File Date Accessed" & Chr(34) 
Set objArgs = WScript.Arguments 
strFolder = objArgs(0) 
Set objFolder = objFS.GetFolder(strFolder) 
Go (objFolder) 
Sub Go(objDIR) 
  If objDIR <> "\System Volume Information" Then 
    For Each eFolder in objDIR.SubFolders 
        Go eFolder 
    Next    
  End If 
    For Each strFile In objDIR.Files 
        WScript.Echo Chr(34) & strFile.Path & Chr(34) & "," &_ 
        Chr(34) & strFile.Size & Chr(34) & "," &_ 
        Chr(34) & strFile.DateLastModified & Chr(34) & "," &_ 
        Chr(34) & strFile.DateCreated & Chr(34) & "," &_ 
        Chr(34) & strFile.DateLastAccessed & Chr(34) 
    Next  
End Sub 
  

然后从命令行调用它   像这样。

c:\test> cscript //nologo myscript.vbs "c:\" > "C:\test\Output.csv"

4 个答案:

答案 0 :(得分:1)

我已经简化了你的代码(基于你的重复问题)并且没有尝试处理错误我可以看到问题:objDIR.SubFolders在其中一个子文件夹(例如\ System Volume Information)没有时失败有权查看!您需要在Folder上使用另一个方法来枚举foldernames,将它们与现有路径组合,然后捕获错误.GetFolder可能会在您没有权限时导致。 (我目前没有时间对该解决方案进行编码。)

Option Explicit

Dim objFS
Dim objArgs
Dim strFolder
Dim objFolder

Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
WScript.StdOut.WriteLine """Full Path"",""File Size""," & _
  """File Date modified"",""File Date Created""," & _
  """File Date Accessed"""
Set objArgs = WScript.Arguments
strFolder = objArgs(0)
Set objFolder = objFS.GetFolder(strFolder)
Go objFolder
Sub Go(objDIR)
  Dim strFile
  On Error Resume Next
    For Each eFolder in objDIR.SubFolders
        Go eFolder
    Next
    For Each strFile In objDIR.Files
        WScript.StdOut.WriteLine """" & strFile.Path & """,""" & _
          strFile.Size & """,""" & _
          strFile.DateLastModified & """,""" & _
          strFile.DateCreated & """,""" & _
          strFile.DateLastAccessed & """"
    Next
End Sub

答案 1 :(得分:1)

VBScript允许错误捕获,但不如VBA优雅。试试下面的脚本。

On Error Resume Next
    '[ ... code ...  ]
Dim test_result, divisor

 divisor = 1        '' No error
'divisor = 0        '' raise error #11
'divisor = "zero"   '' raise a different error

test_result = 2/divisor

If Err.Number = 11 then  ''This line must appear at the point error is raised
    MsgBox "Handled Error: " & Err.Description
ElseIf Err.Number > 0 then 
    MsgBox "Error: " & Err.Number & "  " & Err.Description
    Err.Clear   ''if you wanted to proceed clean from here
End If

MsgBox "Result: " & test_result

答案 2 :(得分:0)

确保该进程具有权限。 see

答案 3 :(得分:0)

您可以通过添加

来忽略VBScript中的脚本错误
On Error Resume Next

在您要忽略错误的代码部分之前。

恢复默认行为的语句是

On Error GoTo 0

只是一句话:VB和VBScript中的方法调用如果它们显示为单个语句,则不使用括号。因此,Go (objFolder)行应替换为Go objFolder