问题
I have script watching file creation in a specific directory. I'm using Register-ObjectEvent after creating a System.IO.FileSystemWatcher,
It works great, but if I set a break point in the -Action code block the IDE generates a:
WARNING: Breakpoint Line breakpoint on 'D:\My Stuff\Desktop\scripts\fileWatcher.ps1:15' will not be hit
this message happens right after I drop a file into the directory I'm watching and I can see my Write-Host printing out my message right after the above 'warning'.
Is this normal?
I need to add more code and could really use the debugger..
What can\should I do, so I can debug this code block?
$fsw = [System.IO.FileSystemWatcher] $path
Register-ObjectEvent -InputObject $fsw –EventName Created -SourceIdentifier DDFileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Out-File -FilePath $logFile -Append -InputObject "The file '$name' was $changeType at $timeStamp"
}
回答1:
If you trigger the event from a direct powershell command in the same ISE or console session, it actually works:
$path = (Resolve-Path '~\').Path
if(Test-Path "$path\newfile.txt"){ del "$path\newfile.txt" }
$fsw = [System.IO.FileSystemWatcher] $path
Register-ObjectEvent -InputObject $fsw –EventName Created -SourceIdentifier DDFileCreated -Action {
$name = $Event.SourceEventArgs.Name # put breakpoint here, via ISE or script
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
}
'foo' | out-file "$path\newfile.txt" # breakpoint hit
But if you simply hook up the event and wait for some external process to create a file, I see the issue you are hitting.
So if you can add some test code to directly trigger your event, go with that.
If not, read on...
It seems like you cannot enter the debugger while the shell or ISE is waiting for a new command, you can only enter while another command is executing.
Going with that theory, this is the workaround (works for me):
- Set your breakpoint
- Run your event subscription code
- Run the command "Read-Host" in the ISE console window, or from the prompt in the shell
- Wait until you know your event should have fired due to external process
- Hit "enter" to allow Read-Host to complete
Viola, breakpoint hit!
来源:https://stackoverflow.com/questions/11959738/powershell-debugging-event-action-code-block