Exemplo n.º 1
0
        /// <summary>
        /// Each Shell ( minishell ) will have its own path specified by the
        /// application base folder, which should be the same as $pshome.
        /// </summary>
        /// <returns>String representing base directory of the executing shell.</returns>
        internal string GetDefaultShellSearchPath()
        {
            string shellID = this.HelpSystem.ExecutionContext.ShellID;

            // Beginning in PowerShell 6.0.0.12, the $pshome is no longer registry specified, we search the application base instead.
            // We use executing assemblies location in case registry entry not found
            return(Utils.GetApplicationBase(shellID)
                   ?? Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName));
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// Initializes a new instance of the InformationRecord class.
        ///
        /// </summary>
        /// <param name="messageData">The object to be transmitted to the host.</param>
        /// <param name="source">The source of the message (i.e.: script path, function name, etc.)</param>
        public InformationRecord(Object messageData, string source)
        {
            this.MessageData = messageData;
            this.Source      = source;

            this.TimeGenerated   = DateTime.Now;
            this.NativeThreadId  = PsUtils.GetNativeThreadId();
            this.ManagedThreadId = (uint)System.Threading.Thread.CurrentThread.ManagedThreadId;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the InformationRecord class.
        /// </summary>
        /// <param name="messageData">The object to be transmitted to the host.</param>
        /// <param name="source">The source of the message (i.e.: script path, function name, etc.).</param>
        public InformationRecord(object messageData, string source)
        {
            this.MessageData = messageData;
            this.Source      = source;

            this.TimeGenerated   = DateTime.Now;
            this.NativeThreadId  = PsUtils.GetNativeThreadId();
            this.ManagedThreadId = (uint)Environment.CurrentManagedThreadId;
        }
        /// <summary>
        /// Get using values as dictionary for the Foreach-Object parallel cmdlet.
        /// Ignore any using expressions that are associated with inner nested Foreach-Object parallel calls,
        /// since they are only effective in the nested call scope and not the current outer scope.
        /// </summary>
        /// <param name = "scriptBlock">Scriptblock to search.</param>
        /// <param name = "isTrustedInput">True when input is trusted.</param>
        /// <param name = "context">Execution context.</param>
        /// <param name = "foreachNames">List of foreach command names and aliases.</param>
        /// <returns>Dictionary of using variable map.</returns>
        internal static Dictionary <string, object> GetUsingValuesForEachParallel(
            ScriptBlock scriptBlock,
            bool isTrustedInput,
            ExecutionContext context,
            string[] foreachNames)
        {
            // Using variables for Foreach-Object -Parallel use are restricted to be within the
            // Foreach-Object -Parallel call scope. This will filter the using variable map to variables
            // only within the current (outer) Foreach-Object -Parallel call scope.
            var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpressions(scriptBlock.Ast).ToList();
            UsingExpressionAst usingAst = null;
            var     usingValueMap       = new Dictionary <string, object>(usingAsts.Count);
            Version oldStrictVersion    = null;

            try
            {
                if (context != null)
                {
                    oldStrictVersion = context.EngineSessionState.CurrentScope.StrictModeVersion;
                    context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                }

                for (int i = 0; i < usingAsts.Count; ++i)
                {
                    usingAst = (UsingExpressionAst)usingAsts[i];
                    if (IsInForeachParallelCallingScope(usingAst, foreachNames))
                    {
                        var    value       = Compiler.GetExpressionValue(usingAst.SubExpression, isTrustedInput, context);
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst);
                        usingValueMap.TryAdd(usingAstKey, value);
                    }
                }
            }
            catch (RuntimeException rte)
            {
                if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(
                              targetObject: null,
                              exceptionType: typeof(RuntimeException),
                              errorPosition: usingAst.Extent,
                              resourceIdAndErrorId: "UsingVariableIsUndefined",
                              resourceString: AutomationExceptions.UsingVariableIsUndefined,
                              args: rte.ErrorRecord.TargetObject);
                }
            }
            finally
            {
                if (context != null)
                {
                    context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion;
                }
            }

            return(usingValueMap);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Get a temporary directory to use for the current process
        /// </summary>
        internal static string GetTemporaryDirectory()
        {
            if (_tempDirectory != null)
            {
                return(_tempDirectory);
            }

            _tempDirectory = PsUtils.GetTemporaryDirectory();
            return(_tempDirectory);
        }
Exemplo n.º 6
0
        private static void FindStaticInformation()
        {
            versionOfPowerShellLibraries = FileVersionInfo.GetVersionInfo(typeof(PSObject).Assembly.Location).FileVersion;
            currentProcess = Process.GetCurrentProcess();
            ProcessModule mainModule = PsUtils.GetMainModule(currentProcess);

            if (mainModule != null)
            {
                applicationPath = mainModule.FileName;
            }
            nameOfExe       = Path.GetFileName(applicationPath);
            hCurrentProcess = currentProcess.Handle;
            hwndMainWindow  = currentProcess.MainWindowHandle;
            applicationName = currentProcess.ProcessName;
        }
Exemplo n.º 7
0
        internal static ExecutionPolicy GetExecutionPolicy(
            string shellId,
            ExecutionPolicyScope scope)
        {
            switch (scope)
            {
            case ExecutionPolicyScope.Process:
                string environmentVariable = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference");
                return(!string.IsNullOrEmpty(environmentVariable) ? SecuritySupport.ParseExecutionPolicy(environmentVariable) : ExecutionPolicy.Undefined);

            case ExecutionPolicyScope.CurrentUser:
            case ExecutionPolicyScope.LocalMachine:
                string localPreferenceValue = SecuritySupport.GetLocalPreferenceValue(shellId, scope);
                return(!string.IsNullOrEmpty(localPreferenceValue) ? SecuritySupport.ParseExecutionPolicy(localPreferenceValue) : ExecutionPolicy.Undefined);

            case ExecutionPolicyScope.UserPolicy:
            case ExecutionPolicyScope.MachinePolicy:
                string groupPolicyValue = SecuritySupport.GetGroupPolicyValue(shellId, scope);
                if (!string.IsNullOrEmpty(groupPolicyValue))
                {
                    Process process = Process.GetCurrentProcess();
                    string  a       = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "gpscript.exe");
                    bool    flag    = false;
                    try
                    {
                        for (; process != null; process = PsUtils.GetParentProcess(process))
                        {
                            if (string.Equals(a, PsUtils.GetMainModule(process).FileName, StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    catch (Win32Exception ex)
                    {
                    }
                    if (!flag)
                    {
                        return(SecuritySupport.ParseExecutionPolicy(groupPolicyValue));
                    }
                }
                return(ExecutionPolicy.Undefined);

            default:
                return(ExecutionPolicy.Restricted);
            }
        }
Exemplo n.º 8
0
        private static bool FileSystemIsDotNetFrameworkVersionInstalled(Version requiredVersion)
        {
            string path1 = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "Microsoft.NET");

            try
            {
                string path2 = "Framework";
                if (PsUtils.GetProcessorArchitecture() != ProcessorArchitecture.X86 && requiredVersion >= new Version(2, 0))
                {
                    path2 = "Framework64";
                }
                string[] directories = Directory.GetDirectories(Path.Combine(path1, path2), string.Format((IFormatProvider)null, "v{0}.{1}*", (object)requiredVersion.Major, (object)requiredVersion.Minor));
                if (directories == null || directories.Length == 0)
                {
                    return(false);
                }
                if (requiredVersion.Build != -1 || requiredVersion.Revision != -1)
                {
                    string str = Path.Combine(directories[0], "mscorlib.dll");
                    if (File.Exists(str))
                    {
                        FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(str);
                        if (new Version(versionInfo.FileMajorPart < 0 ? 0 : versionInfo.FileMajorPart, versionInfo.FileMinorPart < 0 ? 0 : versionInfo.FileMinorPart, versionInfo.FileBuildPart < 0 ? 0 : versionInfo.FileBuildPart, versionInfo.FilePrivatePart < 0 ? 0 : versionInfo.FilePrivatePart) < requiredVersion)
                        {
                            return(false);
                        }
                    }
                }
                return(true);
            }
            catch (UnauthorizedAccessException ex)
            {
                return(false);
            }
            catch (ArgumentException ex)
            {
                return(false);
            }
            catch (PathTooLongException ex)
            {
                return(false);
            }
            catch (IOException ex)
            {
                return(false);
            }
        }
Exemplo n.º 9
0
        internal string GetDefaultShellSearchPath()
        {
            string shellPathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(this.HelpSystem.ExecutionContext.ShellID);

            if (shellPathFromRegistry == null)
            {
                return(Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName));
            }
            if (OSHelper.IsWindows)
            {
                shellPathFromRegistry = Path.GetDirectoryName(shellPathFromRegistry);
            }
            if (!Directory.Exists(shellPathFromRegistry))
            {
                shellPathFromRegistry = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
            }
            return(shellPathFromRegistry);
        }
Exemplo n.º 10
0
        /// <summary>
        ///
        /// Initializes a new instance of the InformationRecord class.
        ///
        /// </summary>
        /// <param name="messageData">The object to be transmitted to the host.</param>
        /// <param name="source">The source of the message (i.e.: script path, function name, etc.)</param>
        public InformationRecord(Object messageData, string source)
        {
            this.MessageData = messageData;
            this.Source      = source;

            this.TimeGenerated = DateTime.Now;
            this.Tags          = new List <string>();
            // domain\user on Windows, just user on Unix
#if UNIX
            this.User = Platform.Unix.UserName;
#else
            this.User = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
#endif
            this.Computer        = PsUtils.GetHostName();
            this.ProcessId       = (uint)System.Diagnostics.Process.GetCurrentProcess().Id;
            this.NativeThreadId  = PsUtils.GetNativeThreadId();
            this.ManagedThreadId = (uint)System.Threading.Thread.CurrentThread.ManagedThreadId;
        }
Exemplo n.º 11
0
        private static void FindStaticInformation()
        {
            WindowsErrorReporting.versionOfPowerShellLibraries = FileVersionInfo.GetVersionInfo(typeof(PSObject).Assembly.Location).FileVersion;
            WindowsErrorReporting.currentProcess = Process.GetCurrentProcess();
            ProcessModule mainModule = PsUtils.GetMainModule(WindowsErrorReporting.currentProcess);

            if (mainModule != null)
            {
                WindowsErrorReporting.applicationPath = mainModule.FileName;
            }
            else
            {
                WindowsErrorReporting.applicationName = "GetMainModErr";
            }
            WindowsErrorReporting.nameOfExe       = Path.GetFileName(WindowsErrorReporting.applicationPath);
            WindowsErrorReporting.hCurrentProcess = WindowsErrorReporting.currentProcess.Handle;
            WindowsErrorReporting.hwndMainWindow  = WindowsErrorReporting.currentProcess.MainWindowHandle;
            WindowsErrorReporting.applicationName = WindowsErrorReporting.currentProcess.ProcessName;
        }
        /// <exception cref="NotSupportedException">
        /// You are trying to access the MainModule property for a process that is running
        /// on a remote computer. This property is available only for processes that are
        /// running on the local computer.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The process Id is not available (or) The process has exited.
        /// </exception>
        /// <exception cref="System.ComponentModel.Win32Exception">
        ///
        /// </exception>
        private static void FindStaticInformation()
        {
            string          sma = typeof(PSObject).Assembly.Location;
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(sma);

            s_versionOfPowerShellLibraries = fvi.FileVersion;

            s_currentProcess = Process.GetCurrentProcess();
            ProcessModule mainModule = PsUtils.GetMainModule(s_currentProcess);

            if (mainModule != null)
            {
                s_applicationPath = mainModule.FileName;
            }

            s_nameOfExe       = Path.GetFileName(s_applicationPath);
            s_hCurrentProcess = s_currentProcess.Handle;
            s_hwndMainWindow  = s_currentProcess.MainWindowHandle;
            s_applicationName = s_currentProcess.ProcessName;
        }
Exemplo n.º 13
0
 private void ConstructParentId()
 {
     try
     {
         this.parentId = -1;
         Process parentProcess = PsUtils.GetParentProcess(this.OriginalProcessInstance);
         if (parentProcess != null)
         {
             this.parentId = parentProcess.Id;
         }
     }
     catch (Win32Exception)
     {
     }
     catch (InvalidOperationException)
     {
     }
     catch (ManagementException)
     {
     }
 }
Exemplo n.º 14
0
        internal string GetDefaultShellSearchPath()
        {
            string shellId          = this.HelpSystem.ExecutionContext.ShellID;
            string pathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(shellId);
            string directoryName;

            if (pathFromRegistry == null)
            {
                directoryName = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
                this.HelpSystem.LastErrors.Add(new ErrorRecord((Exception)HelpProvider.tracer.NewArgumentException("DefaultSearchPath", "HelpErrors", "RegistryPathNotFound", (object)Utils.GetRegistryConfigurationPath(shellId), (object)"\\Path", (object)directoryName), "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, (object)null));
            }
            else
            {
                directoryName = Path.GetDirectoryName(pathFromRegistry);
                if (!Directory.Exists(directoryName))
                {
                    directoryName = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
                    this.HelpSystem.LastErrors.Add(new ErrorRecord((Exception)HelpProvider.tracer.NewArgumentException("DefaultSearchPath", "HelpErrors", "RegistryPathNotFound", (object)Utils.GetRegistryConfigurationPath(shellId), (object)"\\Path", (object)"\\Path", (object)directoryName), "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, (object)null));
                }
            }
            return(directoryName);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Each Shell ( minishell ) will have its own path specified by the
        /// registry HKLM\software\microsoft\msh\1\ShellIds\&lt;ShellID&gt;\path. Every help
        /// provider should search this path for content.
        /// </summary>
        /// <returns>string representing base directory of the executing shell.</returns>
        internal string GetDefaultShellSearchPath()
        {
            string shellID     = this.HelpSystem.ExecutionContext.ShellID;
            string returnValue = CommandDiscovery.GetShellPathFromRegistry(shellID);

            if (returnValue == null)
            {
                // use executing assemblies location in case registry entry not found
                returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
            }
            else
            {
                // Get the directory path of the executing shell
                returnValue = Path.GetDirectoryName(returnValue);
                if (!Directory.Exists(returnValue))
                {
                    // use executing assemblies location in case registry entry not found
                    returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
                }
            }

            return(returnValue);
        }
Exemplo n.º 16
0
        private void ConvertCommand(CommandAst commandAst, bool isTrustedInput)
        {
            // First need command name.
            var commandName = GetCommandName(commandAst.CommandElements[0], isTrustedInput);

            var command = new Command(commandName, isScript: false, useLocalScope: _createLocalScope);

            // Handle redirections, if any (there can really be just 0 or 1).
            if (commandAst.Redirections.Count > 0)
            {
                Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported");
                Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type");

                PipelineResultTypes toType = PipelineResultTypes.Output;
                PipelineResultTypes fromType;
                switch (commandAst.Redirections[0].FromStream)
                {
                case RedirectionStream.Error:
                    fromType = PipelineResultTypes.Error;
                    break;

                case RedirectionStream.Warning:
                    fromType = PipelineResultTypes.Warning;
                    break;

                case RedirectionStream.Verbose:
                    fromType = PipelineResultTypes.Verbose;
                    break;

                case RedirectionStream.Debug:
                    fromType = PipelineResultTypes.Debug;
                    break;

                case RedirectionStream.Information:
                    fromType = PipelineResultTypes.Information;
                    break;

                case RedirectionStream.All:
                    fromType = PipelineResultTypes.All;
                    break;

                default:
                    // Default to Error->Output to be compatible with V2.
                    fromType = PipelineResultTypes.Error;
                    break;
                }

                command.MergeMyResults(fromType, toType);
            }

            _powershell.AddCommand(command);

            // Now the parameters and arguments.
            foreach (var ast in commandAst.CommandElements.Skip(1))
            {
                var exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;

                    var usingExprAst = ast as UsingExpressionAst;
                    if (usingExprAst != null)
                    {
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingExprAst);
                        object usingValue  = _usingValueMap[usingAstKey];
                        variableAst = usingExprAst.SubExpression as VariableExpressionAst;
                        if (variableAst != null && variableAst.Splatted)
                        {
                            // Support the splatting of a dictionary
                            var parameters = usingValue as System.Collections.IDictionary;
                            if (parameters != null)
                            {
                                _powershell.AddParameters(parameters);
                            }
                            else
                            {
                                // Support the splatting of an array
                                var arguments = usingValue as System.Collections.IEnumerable;
                                if (arguments != null)
                                {
                                    foreach (object argument in arguments)
                                    {
                                        _powershell.AddArgument(argument);
                                    }
                                }
                                else
                                {
                                    // Splat the object directly.
                                    _powershell.AddArgument(usingValue);
                                }
                            }
                        }
                        else
                        {
                            _powershell.AddArgument(usingValue);
                        }

                        continue;
                    }

                    variableAst = ast as VariableExpressionAst;
                    if (variableAst != null && variableAst.Splatted)
                    {
                        GetSplattedVariable(variableAst);
                    }
                    else
                    {
                        var    constantExprAst = ast as ConstantExpressionAst;
                        object argument;
                        if (constantExprAst != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)))
                        {
                            var commandArgumentText = constantExprAst.Extent.Text;
                            argument = constantExprAst.Value;
                            if (!commandArgumentText.Equals(constantExprAst.Value.ToString(), StringComparison.Ordinal))
                            {
                                // The wrapped number will actually return a PSObject which could end holding a reference to
                                // a typetable, making the object runspace specific.  We should find a better way to avoid
                                // any possibility of sharing problems, though this is unlikely to cause problems.
                                argument = ParserOps.WrappedNumber(argument, commandArgumentText);
                            }
                        }
                        else
                        {
                            if (!isTrustedInput)
                            {
                                try
                                {
                                    argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell);
                                }
                                catch (System.Exception)
                                {
                                    throw new ScriptBlockToPowerShellNotSupportedException(
                                              "CantConvertWithDynamicExpression",
                                              null,
                                              AutomationExceptions.CantConvertWithDynamicExpression,
                                              exprAst.Extent.Text);
                                }
                            }
                            else
                            {
                                argument = GetExpressionValue(exprAst, isTrustedInput);
                            }
                        }

                        _powershell.AddArgument(argument);
                    }
                }
                else
                {
                    AddParameter((CommandParameterAst)ast, isTrustedInput);
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Collect values for UsingExpressions, in the form of a dictionary and an array.
        ///  - The dictionary form is used when the remote server is PSv5 and later version for handling UsingExpression in Invoke-Command/Start-Job
        ///  - The array form is used when the remote server is PSv3 and PSv4 for handling UsingExpression in Invoke-Command.
        /// </summary>
        /// <remarks>
        /// We still keep the array-form using values because we want to avoid any breaking changes when running Invoke-Command
        /// targeting PSv3 or PSv4 remote end -- if UsingExpressions are all in the same scope, then we still pass an array of using
        /// values to the remote end; otherwise, we will handle UsingExpression as if the remote end is PSv2.
        /// </remarks>
        /// <returns>
        /// A tuple of the dictionary-form and the array-form using values.
        /// If the array-form using value is null, then there are UsingExpressions used in different scopes.
        /// </returns>
        private static Tuple <Dictionary <string, object>, object[]> GetUsingValues(Ast body, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables)
        {
            Diagnostics.Assert(context != null || variables != null, "can't retrieve variables with no context and no variables");

            var usingAsts                  = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList();
            var usingValueArray            = new object[usingAsts.Count];
            var usingValueMap              = new Dictionary <string, object>(usingAsts.Count);
            HashSet <string> usingVarNames = (variables != null && filterNonUsingVariables) ? new HashSet <string>() : null;

            // Used to check if the PSv3/PSv4 way of handling UsingExpression can continue to be used.
            bool           hasUsingExprInDifferentScope = false;
            ScriptBlockAst sbClosestToPreUsingExpr      = null;

            UsingExpressionAst usingAst         = null;
            Version            oldStrictVersion = null;

            try
            {
                if (context != null)
                {
                    oldStrictVersion = context.EngineSessionState.CurrentScope.StrictModeVersion;
                    context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                }

                for (int i = 0; i < usingAsts.Count; ++i)
                {
                    usingAst = (UsingExpressionAst)usingAsts[i];
                    object value = null;

                    // This happens only when GetUsingValues gets called outside the ScriptBlockToPowerShellConverter class
                    if (!hasUsingExprInDifferentScope && HasUsingExpressionsInDifferentScopes(usingAst, body, ref sbClosestToPreUsingExpr))
                    {
                        // If there are UsingExpressions in different scopes, the array-form using values will not be useful
                        // even if the remote end is PSv3 or PSv4, because the way we handle using expression in PSv3 and PSv4
                        // doesn't support UsingExpression in different scopes. In this case, we will set the array-form using
                        // value to be null before return.
                        //
                        // Note that this check only affect array-form using value. In PSv5, we change the way to handle UsingExpression
                        // on both client and server sides. The dictionary-form using values is used and UsingExpression in different
                        // scope is supported.
                        hasUsingExprInDifferentScope = true;
                    }

                    if (variables != null)
                    {
                        var variableAst = usingAst.SubExpression as VariableExpressionAst;
                        if (variableAst == null)
                        {
                            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                           usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text);
                        }

                        string varName = variableAst.VariablePath.UserPath;
                        if (varName != null && variables.TryGetValue(varName, out value) && usingVarNames != null)
                        {
                            usingVarNames.Add(varName);
                        }
                    }
                    else
                    {
                        value = Compiler.GetExpressionValue(usingAst.SubExpression, isTrustedInput, context);
                    }

                    // Collect UsingExpression value as an array
                    usingValueArray[i] = value;

                    // Collect UsingExpression value as a dictionary
                    string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst);
                    usingValueMap.TryAdd(usingAstKey, value);
                }
            }
            catch (RuntimeException rte)
            {
                if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                   usingAst.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, rte.ErrorRecord.TargetObject);
                }
                else if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("CantGetUsingExpressionValueWithSpecifiedVariableDictionary", StringComparison.Ordinal))
                {
                    throw;
                }
            }
            finally
            {
                if (context != null)
                {
                    context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion;
                }
            }

            if (usingVarNames != null)
            {
                string[] keys = variables.Keys.ToArray();
                foreach (string key in keys)
                {
                    if (!usingVarNames.Contains(key))
                    {
                        variables.Remove(key);
                    }
                }
            }

            if (hasUsingExprInDifferentScope)
            {
                usingValueArray = null;
            }

            return(Tuple.Create(usingValueMap, usingValueArray));
        }
Exemplo n.º 18
0
        internal static ExecutionPolicy GetExecutionPolicy(string shellId, ExecutionPolicyScope scope)
        {
            string groupPolicyValue;
            bool   flag;

            switch (scope)
            {
            case ExecutionPolicyScope.Process:
            {
                string environmentVariable = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference");
                if (string.IsNullOrEmpty(environmentVariable))
                {
                    return(ExecutionPolicy.Undefined);
                }
                return(ParseExecutionPolicy(environmentVariable));
            }

            case ExecutionPolicyScope.CurrentUser:
            case ExecutionPolicyScope.LocalMachine:
            {
                string localPreferenceValue = GetLocalPreferenceValue(shellId, scope);
                if (string.IsNullOrEmpty(localPreferenceValue))
                {
                    return(ExecutionPolicy.Undefined);
                }
                return(ParseExecutionPolicy(localPreferenceValue));
            }

            case ExecutionPolicyScope.UserPolicy:
            case ExecutionPolicyScope.MachinePolicy:
            {
                groupPolicyValue = GetGroupPolicyValue(shellId, scope);
                if (string.IsNullOrEmpty(groupPolicyValue))
                {
                    goto Label_00BA;
                }
                if (OSHelper.IsUnix)
                {
                    flag = true;
                }
                else
                {
                    Process currentProcess = Process.GetCurrentProcess();
                    string  a = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "gpscript.exe");
                    flag = false;
                    try
                    {
                        while (currentProcess != null)
                        {
                            if (string.Equals(a, PsUtils.GetMainModule(currentProcess).FileName, StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                                break;
                            }
                            currentProcess = PsUtils.GetParentProcess(currentProcess);
                        }
                    }
                    catch (Win32Exception)
                    {
                    }
                }
                break;
            }

            default:
                return(ExecutionPolicy.Restricted);
            }
            if (!flag)
            {
                return(ParseExecutionPolicy(groupPolicyValue));
            }
Label_00BA:
            return(ExecutionPolicy.Undefined);
        }
Exemplo n.º 19
0
        internal static bool IsDotNetFrameworkVersionInstalled(Version requiredVersion)
        {
            int majorVersion;
            int minorVersion;
            int minimumSpVersion;

            return(PsUtils.FrameworkRegistryInstallation.CanCheckFrameworkInstallation(requiredVersion, out majorVersion, out minorVersion, out minimumSpVersion) ? PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(majorVersion, minorVersion, minimumSpVersion) : PsUtils.FileSystemIsDotNetFrameworkVersionInstalled(requiredVersion));
        }
Exemplo n.º 20
0
        private static ConcurrentDictionary <string, CommandTypes> AnalyzeManifestModule(string modulePath, ExecutionContext context, DateTime lastWriteTime, bool etwEnabled)
        {
            ConcurrentDictionary <string, CommandTypes> result = null;

            try
            {
                var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames);
                if (moduleManifestProperties != null)
                {
                    Version version;
                    if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version))
                    {
                        var versionInManifest = LanguagePrimitives.ConvertTo <Version>(moduleManifestProperties["ModuleVersion"]);
                        if (version != versionInManifest)
                        {
                            ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath);
                            return(null);
                        }
                    }

                    result = new ConcurrentDictionary <string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase);

                    var sawWildcard  = false;
                    var hadCmdlets   = AddPsd1EntryToResult(result, moduleManifestProperties["CmdletsToExport"], CommandTypes.Cmdlet, ref sawWildcard);
                    var hadFunctions = AddPsd1EntryToResult(result, moduleManifestProperties["FunctionsToExport"], CommandTypes.Function, ref sawWildcard);
                    var hadAliases   = AddPsd1EntryToResult(result, moduleManifestProperties["AliasesToExport"], CommandTypes.Alias, ref sawWildcard);

                    var analysisSucceeded = hadCmdlets && hadFunctions && hadAliases;

                    if (!analysisSucceeded && !sawWildcard && (hadCmdlets || hadFunctions))
                    {
                        // If we're missing CmdletsToExport, that might still be OK, but only if we have a script module.
                        // Likewise, if we're missing FunctionsToExport, that might be OK, but only if we have a binary module.

                        analysisSucceeded = !CheckModulesTypesInManifestAgainstExportedCommands(moduleManifestProperties, hadCmdlets, hadFunctions, hadAliases);
                    }

                    if (analysisSucceeded)
                    {
                        var moduleCacheEntry = new ModuleCacheEntry
                        {
                            ModulePath    = modulePath,
                            LastWriteTime = lastWriteTime,
                            Commands      = result,
                            TypesAnalyzed = false,
                            Types         = new ConcurrentDictionary <string, TypeAttributes>(1, 8, StringComparer.OrdinalIgnoreCase)
                        };
                        s_cacheData.Entries[modulePath] = moduleCacheEntry;
                    }
                    else
                    {
                        result = null;
                    }
                }
            }
            catch (Exception e)
            {
                if (etwEnabled)
                {
                    CommandDiscoveryEventSource.Log.ModuleManifestAnalysisException(modulePath, e.Message);
                }
                // Ignore the errors, proceed with the usual module analysis
                ModuleIntrinsics.Tracer.WriteLine("Exception on fast-path analysis of module {0}", modulePath);
            }

            if (etwEnabled)
            {
                CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result != null);
            }

            return(result ?? AnalyzeTheOldWay(modulePath, context, lastWriteTime));
        }