From 3a24f1d443cf68542f5da0b526f2054c0afae7a9 Mon Sep 17 00:00:00 2001 From: Andrew Schwartzmeyer Date: Fri, 17 Dec 2021 13:18:53 -0800 Subject: [PATCH] Create `$psEditor` as a constant This prevents accidental removal (and breakage of the extension) by disallowing `Remove-Variable` from removing `$psEditor`. While it's not expected anyone would do this, glob expressions may include the variable name and when piped to `Remove-Variable` resulted in a user-reported breakage. --- .../Services/Extension/ExtensionService.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs b/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs index 6e2793f55..bf164206b 100644 --- a/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs +++ b/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs @@ -104,15 +104,14 @@ internal Task InitializeAsync() // Assign the new EditorObject to be the static instance available to binary APIs EditorObject.SetAsStaticInstance(); + // This is constant so Remove-Variable cannot remove it. + PSVariable psEditor = new(PSEditorVariableName, EditorObject, ScopedItemOptions.Constant); // Register the editor object in the runspace return ExecutionService.ExecuteDelegateAsync( $"Create ${PSEditorVariableName} object", ExecutionOptions.Default, - (pwsh, cancellationToken) => - { - pwsh.Runspace.SessionStateProxy.PSVariable.Set(PSEditorVariableName, EditorObject); - }, + (pwsh, _) => pwsh.Runspace.SessionStateProxy.PSVariable.Set(psEditor), CancellationToken.None); }