'VSCode and Powershell: How to debug and trace into code called by Register-ObjectEvent?

Am I missing something?

I can start the debug process with F5, but I cannot end it, and I cannot step through code or do normal debugging.

I assume this is due to the fact that the code is hanging off Register-ObjectEvent ?

(Watching a file system event....)

What is the method to run this code and keep the debugger attached to what is going on?

The code:

$folder_to_watch = 'C:\Users\demouser\Downloads\'
$file_name_filter = '*.aac'
# to archive .aac files
$destination = 'c:\temp\test\arc\'  
$DestinationDirMP3 = 'C:\data\personal\hinative-mp3'
$Watcher = New-Object IO.FileSystemWatcher $folder_to_watch, $file_name_filter -Property @{ 
    IncludeSubdirectories = $false
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$VLCExe = 'C:\Program Files\VideoLAN\VLC\vlc.exe' 

$onCreated = Register-ObjectEvent $Watcher -EventName Created -SourceIdentifier FileCreated -Action {
   $path = $Event.SourceEventArgs.FullPath
   $name = $Event.SourceEventArgs.Name
   $changeType = $Event.SourceEventArgs.ChangeType
   $timeStamp = $Event.TimeGenerated
   Write-Host "The file '$name' was $changeType at $timeStamp"
   Write-Host $path

   # File Checks
    while (Test-LockedFile $path) {
      Start-Sleep -Seconds .2
    }
    # Move File
    Write-Host "moving $path to $destination"
    Move-Item $path -Destination $destination -Force -Verbose
    # build the path to the archived .aac file
    $SourceFileName = Split-Path $path -Leaf
    $DestinationAACwoQuotes = Join-Path $destination $SourceFileName
    $DestinationAAC = "`"$DestinationAACwoQuotes`""
    $MP3FileName = [System.IO.Path]::ChangeExtension($SourceFileName,".mp3")
    $DestinationMP3woQuotes = Join-Path $DestinationDirMP3 $MP3FileName
    $DestinationMP3 = "`"$DestinationMP3woQuotes`""
    $VLCArgs = "-I dummy -vvv $DestinationAAC --sout=#transcode{acodec=mp3,ab=48,channels=2,samplerate=32000}:standard{access=file,mux=ts,dst=$DestinationMP3} vlc://quit"
    Write-Host "args $VLCArgs"
    Start-Process -FilePath $VLCExe -ArgumentList $VLCArgs
    

}


function Test-LockedFile {
    param ([parameter(Mandatory=$true)][string]$Path)  
    $oFile = New-Object System.IO.FileInfo $Path
    if ((Test-Path -Path $Path) -eq $false)
    {
      return $false
    }
  
    try
    {
      $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
        if ($oStream)
        {
          $oStream.Close()
        }
        $false
    }
    catch
    {
      # file is locked by a process.
      return $true
    }
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source