更改文件A时,我需要打开文件B,然后让文件B打开文件A,而无需再次触发监视程序。我的想法是,可以使用'$ changeAction'中的if语句来执行此操作,该语句检查是否首先打开了文件B。
我想这就像:
如果(文件B已打开,则什么都不做,否则打开文件B)
如何在Powershell中编写此代码?
Function Register-Watcher {
param ($folder)
$filter = "*.xlsx"
$folder = "\\powershell\watcher\test\folder"
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
$changeAction = [scriptblock]::Create('
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file $name was $changeType at $timeStamp"
$Excel = New-Object -ComObject Excel.Application
$Excel.Workbooks.Open("\\powershell\watcher\test\folder\fileB.xlsm") #this should be the 'else' in the 'if File B is open#
')
Register-ObjectEvent $Watcher "Changed" -Action $changeAction
}
Register-Watcher "\\powershell\watcher\test\folder\fileA.xlsx"
$Change
答案 0 :(得分:0)
为此,您可以检查是否正在运行任何打开了特定文件的Excel进程。
Get-CimInstance Win32_Process -Filter "CommandLine like '%filepath.xlsx%'"
根据上述表达式的输出,您可以决定是否打开文件。