@@ -207,6 +207,22 @@ protected async Task HandleAttachRequest(
207207 AttachRequestArguments attachParams ,
208208 RequestContext < object > requestContext )
209209 {
210+ // If there are no host processes to attach to or the user cancels selection, we get a null for the process id.
211+ // This is not an error, just a request to stop the original "attach to" request.
212+ // Testing against "undefined" is a HACK because I don't know how to make "Cancel" on quick pick loading
213+ // to cancel on the VSCode side without sending an attachRequest with processId set to "undefined".
214+ if ( string . IsNullOrEmpty ( attachParams . ProcessId ) || ( attachParams . ProcessId == "undefined" ) )
215+ {
216+ Logger . Write (
217+ LogLevel . Normal ,
218+ $ "Attach request aborted, received { attachParams . ProcessId } for processId.") ;
219+
220+ await requestContext . SendError (
221+ "User aborted attach to PowerShell host process." ) ;
222+
223+ return ;
224+ }
225+
210226 StringBuilder errorMessages = new StringBuilder ( ) ;
211227
212228 if ( attachParams . ComputerName != null )
@@ -235,7 +251,8 @@ await requestContext.SendError(
235251 }
236252 }
237253
238- if ( attachParams . ProcessId > 0 )
254+ int processId ;
255+ if ( int . TryParse ( attachParams . ProcessId , out processId ) && ( processId > 0 ) )
239256 {
240257 PowerShellVersionDetails runspaceVersion =
241258 this . editorSession . PowerShellContext . CurrentRunspace . PowerShellVersion ;
@@ -249,13 +266,13 @@ await requestContext.SendError(
249266 }
250267
251268 await this . editorSession . PowerShellContext . ExecuteScriptString (
252- $ "Enter-PSHostProcess -Id { attachParams . ProcessId } ",
269+ $ "Enter-PSHostProcess -Id { processId } ",
253270 errorMessages ) ;
254271
255272 if ( errorMessages . Length > 0 )
256273 {
257274 await requestContext . SendError (
258- $ "Could not attach to process '{ attachParams . ProcessId } '") ;
275+ $ "Could not attach to process '{ processId } '") ;
259276
260277 return ;
261278 }
@@ -272,8 +289,12 @@ await requestContext.SendError(
272289 }
273290 else
274291 {
292+ Logger . Write (
293+ LogLevel . Error ,
294+ $ "Attach request failed, '{ attachParams . ProcessId } ' is an invalid value for the processId.") ;
295+
275296 await requestContext . SendError (
276- "A positive integer must be specified for the processId field." ) ;
297+ $ "A positive integer must be specified for the processId field.") ;
277298
278299 return ;
279300 }
0 commit comments