使用带有.Files的变量设置文件对象

时间:2016-05-23 13:57:59

标签: vbscript

我在HP Operations Manager中使用它,它使用PARAMETER部分,因此您可以在HPOM策略中定义变量。这当前适用于硬编码的一个文件,但我希望能够使用PARAMETER来设置文件名,因此脚本是通用的。

这样做是为了检查特定文件是否存在,并设置变量(Rule.Status = True),如果它比FileAge变量中指定的分钟数小。

现在我正在使用:

Set MonitorFile = MonitorFolder.Files("EDI.001")

工作正常。但是当我尝试做的时候:

Set MonitorFile = MonitorFolder.Files(FileName)

失败并出现以下错误:

  

无效的过程调用或参数。

我做错了吗?在这种情况下是否有更好的方法来使用变量?

以下是整个脚本:

'PARAMETERS START

'PARAMETER FolderName STRING DEFAULT "D:\RFInput\InBoxPO" VALUE "D:\RFInput\InBoxPO\" SESSION
Dim FolderName
FolderName = "D:\RFInput\InBoxPO\"
Session("FolderName") = FolderName

'PARAMETER FileAge INT DEFAULT "60" VALUE "1" SESSION
Dim FileAge
FileAge = 1
Session("FileAge") = FileAge

'PARAMETER FolderDisplayName STRING DEFAULT "InBoxPO" VALUE "InBoxPO" SESSION 
Dim FolderDisplayName
FolderDisplayName = "InBoxPO"
Session("FolderDisplayName") = FolderDisplayName

'PARAMETER FileName STRING DEFAULT "EDI.001" VALUE "EDI.001" SESSION
Dim FileName
FileName = "EDI.001"
Session("FileName") = FileName

'PARAMETERS END

Dim fs, MonitorFolder, MonitorFile, objShell, MinutesOld
Dim objFile, listNames
' Set constants for working with files
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objShell = CreateObject("Shell.Application")
Set fs = CreateObject("Scripting.FileSystemObject")
Set MonitorFolder = fs.GetFolder(FolderName)

Rule.Status = False

For Each objFile In MonitorFolder.Files 
    listNames = objFile.Name 
    If InStr(listNames, FileName) = 1 Then
        Set MonitorFile = MonitorFolder.Files("EDI.001")
        MinutesOld = DateDiff("n", MonitorFile.DateLastModified, Now)
        If MinutesOld > FileAge Then
            'Turn on for debugging - Wscript.Echo FileName & " is older than " & FileAge & " minutes in folder " & FolderName & "."
            Rule.Status = True
        End If
    End If
Next
Set objShell = Nothing
Set fs = Nothing
Set MonitorFolder = Nothing
'END OF SCRIPT

1 个答案:

答案 0 :(得分:1)

确实,对Files集合中的特定项目的访问似乎仅适用于字符串文字,不确定原因是什么。

您可以简化For Each循环:

For Each objFile In MonitorFolder.Files 
    If LCase(objFile.name) = LCase(FileName) Then
        Set MonitorFile = objFile
        ...
    End If
Next

如果您需要按文件名查找,则可以构建dictionary,如下所示:

Set filenames = CreateObject("Scripting.Dictionary")
For Each objFile In MonitorFolder.Files
    filenames.Add objFile.Name, objFile
Next

这将允许您按名称访问文件,如下所示:

Set MonitorFile = filenames(FileName)