我正在编写一个powershell脚本,它将启动一个进程,监视文件夹以进行文件更改,然后在添加/更改文件时备份该文件夹。
如果我在Powershell ISE中运行我的脚本,它运行正常,我可以监视该文件夹,它将按预期正确保存备份。
问题是我想运行一个运行powershell脚本的批处理文件。但是每当我从powershell控制台运行脚本时,或者当我运行运行脚本的批处理文件时,它都不再起作用。脚本运行并且事件已注册。当我将文件复制到监视文件夹时,我只获取更改的事件而不是创建的事件,并且不再调用doStuff函数。我不确定如何调试这个:/
以下是我的剧本。我删除了与当前实际错误相关的部分,因此我在这里使用的一些变量你不会看到已声明但是它们在那里。当更改的事件发生时,我将写主机发送到控制台但不是创建的事件(尽管如ISE中所述,我得到了两个事件,一切正常)
#unregister events, in case they weren't unregistered properly before. Just error siliently if they don't exist
Unregister-Event ConsoleStopped -ErrorAction SilentlyContinue
Unregister-Event FileCreated -ErrorAction SilentlyContinue
Unregister-Event FileChanged -ErrorAction SilentlyContinue
Unregister-Event TimerTick -ErrorAction SilentlyContinue
#start the console process
Write-Host Starting console process...
$consoleProcess = Start-Process "$consoleExe" -PassThru
#register to listen for when the console stops
Register-ObjectEvent $consoleProcess Exited -SourceIdentifier ConsoleStopped -Action {
Write-Host Console stopped
#unregister events
Unregister-Event ConsoleStopped -ErrorAction SilentlyContinue
Unregister-Event FileCreated -ErrorAction SilentlyContinue
Unregister-Event FileChanged -ErrorAction SilentlyContinue
if(!$timer.Enabled) {
Unregister-Event TimerElapsed -ErrorAction SilentlyContinue
Remove-Item $timer
}
Remove-Item $fsw
Remove-Item $consoleProcess
}
#watch all files/folders
$filter = '*.*' # You can enter a wildcard filter here.
# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'DirectoryName, FileName, LastWrite'}
#register for FileCreated event
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
write-host Created event has occurred
doStuff($Event)
}
#register for FileChanged event
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
Write-Host Change event has occurred
doStuff($Event)
}
function doStuff($event)
{
write-host doStuff has been called
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' in '$folder' was $changeType at $timeStamp" -fore green
if(!$timer.Enabled) {
Write-Host Starting save timer
Register-ObjectEvent $timer Elapsed -SourceIdentifier TimerElapsed -Action $TimerAction
$timer.Start()
Out-File "$backupDir\backup.log" -Append -Force -InputObject "A request for a backup created at $timeStamp"
}
else {
Write-Host A backup has already been request
}
}
function backupSave ()
{
Write-Host Starting backup...
$timestamp = Get-Date -Format o | foreach { $_ -replace ":", "." }
Copy-Item $folder "$backupDir\backup_$timestamp" -Recurse -Force
}
答案 0 :(得分:0)
尝试将您的功能移至脚本的开头。
即。将function doStuff($event)
和function backupSave ()
移到脚本的开头。
问题可能是因为当您从脚本调用函数时,它们还没有被定义。它适用于Powershell ISE,因为您多次运行脚本并且函数是在某个时间定义的。