internal static PowerShell NewPwshInstance()

in src/Utility/Utils.cs [44:87]


        internal static PowerShell NewPwshInstance()
        {
            if (s_iss == null)
            {
                s_iss = InitialSessionState.CreateDefault();

                if (FunctionLoader.FunctionAppRootPath != null)
                {
                    s_iss.EnvironmentVariables.Add(
                        new SessionStateVariableEntry(
                            "PSModulePath",
                            FunctionLoader.FunctionModulePath,
                            description: null));
                }

                // Setting the execution policy on macOS and Linux throws an exception so only update it on Windows
                if(Platform.IsWindows)
                {
                    // This sets the execution policy on Windows to Unrestricted which is required to run the user's function scripts on
                    // Windows client versions. This is needed if a user is testing their function locally with the func CLI.
                    s_iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
                }
            }

            var pwsh = PowerShell.Create(s_iss);
            if (s_globalVariables == null)
            {
                // Get the names of the built-in global variables
                ICollection<PSVariable> globalVars = GetGlobalVariables(pwsh);
                s_globalVariables = new HashSet<string>(globalVars.Count + 3, StringComparer.OrdinalIgnoreCase)
                {
                    // These 3 variables are not in the built-in variables in a fresh Runspace,
                    // but they show up after we evaluate the 'profile.ps1' in the global scope.
                    "PSScriptRoot", "PSCommandPath", "MyInvocation"
                };

                foreach (PSVariable var in globalVars)
                {
                    s_globalVariables.Add(var.Name);
                }
            }

            return pwsh;
        }