@@ -645,6 +645,7 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
645645 executionOptions ) ) . ConfigureAwait ( false ) ;
646646 }
647647
648+ Task writeErrorsToConsoleTask = null ;
648649 try
649650 {
650651 // Instruct PowerShell to send output and errors to the host
@@ -836,7 +837,8 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
836837 if ( executionOptions . WriteErrorsToHost )
837838 {
838839 // Write the error to the host
839- this . WriteExceptionToHost ( e ) ;
840+ // We must await this after the runspace handle has been released or we will deadlock
841+ writeErrorsToConsoleTask = this . WriteExceptionToHostAsync ( e ) ;
840842 }
841843 }
842844 catch ( Exception )
@@ -896,6 +898,10 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
896898 if ( runspaceHandle != null )
897899 {
898900 runspaceHandle . Dispose ( ) ;
901+ if ( writeErrorsToConsoleTask != null )
902+ {
903+ await writeErrorsToConsoleTask . ConfigureAwait ( false ) ;
904+ }
899905 }
900906
901907 this . OnExecutionStatusChanged (
@@ -1948,7 +1954,7 @@ internal void WriteOutput(
19481954 }
19491955 }
19501956
1951- private void WriteExceptionToHost ( RuntimeException e )
1957+ private Task WriteExceptionToHostAsync ( RuntimeException e )
19521958 {
19531959 var psObject = PSObject . AsPSObject ( e . ErrorRecord ) ;
19541960
@@ -1963,7 +1969,7 @@ private void WriteExceptionToHost(RuntimeException e)
19631969 psObject . Properties . Add ( note ) ;
19641970 }
19651971
1966- ExecuteCommandAsync ( new PSCommand ( ) . AddCommand ( "Microsoft.PowerShell.Core\\ Out-Default" ) . AddParameter ( "InputObject" , psObject ) ) ;
1972+ return ExecuteCommandAsync ( new PSCommand ( ) . AddCommand ( "Microsoft.PowerShell.Core\\ Out-Default" ) . AddParameter ( "InputObject" , psObject ) ) ;
19671973 }
19681974
19691975 private void WriteError (
0 commit comments