internal static void CleanupGlobalVariables()

in src/Utility/Utils.cs [92:131]


        internal static void CleanupGlobalVariables(PowerShell pwsh)
        {
            List<string> varsToRemove = null;
            ICollection<PSVariable> globalVars = GetGlobalVariables(pwsh);

            foreach (PSVariable var in globalVars)
            {
                // The variable is one of the built-in global variables.
                if (s_globalVariables.Contains(var.Name)) { continue; }

                // We cannot remove a constant variable, so leave it as is.
                if (var.Options.HasFlag(ScopedItemOptions.Constant)) { continue; }

                // The variable is exposed by a module. We don't remove modules, so leave it as is.
                if (var.Module != null) { continue; }

                // The variable is not a regular PSVariable.
                // It's likely not created by the user, so leave it as is.
                if (var.GetType() != typeof(PSVariable)) { continue; }

                if (varsToRemove == null)
                {
                    // Create a list only if it's needed.
                    varsToRemove = new List<string>();
                }

                // Add the variable path.
                varsToRemove.Add($"{VariableDriveRoot}{var.Name}");
            }

            if (varsToRemove != null)
            {
                // Remove the global variable added by the function invocation.
                pwsh.Runspace.SessionStateProxy.InvokeProvider.Item.Remove(
                    varsToRemove.ToArray(),
                    recurse: true,
                    force: true,
                    literalPath: true);
            }
        }