@@ -645,6 +645,7 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
645
645
executionOptions ) ) . ConfigureAwait ( false ) ;
646
646
}
647
647
648
+ Task writeErrorsToConsoleTask = null ;
648
649
try
649
650
{
650
651
// Instruct PowerShell to send output and errors to the host
@@ -836,7 +837,8 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
836
837
if ( executionOptions . WriteErrorsToHost )
837
838
{
838
839
// 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 ) ;
840
842
}
841
843
}
842
844
catch ( Exception )
@@ -896,6 +898,10 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
896
898
if ( runspaceHandle != null )
897
899
{
898
900
runspaceHandle . Dispose ( ) ;
901
+ if ( writeErrorsToConsoleTask != null )
902
+ {
903
+ await writeErrorsToConsoleTask . ConfigureAwait ( false ) ;
904
+ }
899
905
}
900
906
901
907
this . OnExecutionStatusChanged (
@@ -1948,7 +1954,7 @@ internal void WriteOutput(
1948
1954
}
1949
1955
}
1950
1956
1951
- private void WriteExceptionToHost ( RuntimeException e )
1957
+ private Task WriteExceptionToHostAsync ( RuntimeException e )
1952
1958
{
1953
1959
var psObject = PSObject . AsPSObject ( e . ErrorRecord ) ;
1954
1960
@@ -1963,7 +1969,7 @@ private void WriteExceptionToHost(RuntimeException e)
1963
1969
psObject . Properties . Add ( note ) ;
1964
1970
}
1965
1971
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 ) ) ;
1967
1973
}
1968
1974
1969
1975
private void WriteError (
0 commit comments