Powershell debugging event -Action code block

随声附和 提交于 2019-12-10 23:36:26

问题


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):

  1. Set your breakpoint
  2. Run your event subscription code
  3. Run the command "Read-Host" in the ISE console window, or from the prompt in the shell
  4. Wait until you know your event should have fired due to external process
  5. Hit "enter" to allow Read-Host to complete

Viola, breakpoint hit!



来源:https://stackoverflow.com/questions/11959738/powershell-debugging-event-action-code-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!