コード例 #1
0
 private void ReadScriptContents()
 {
     if (this._scriptContents == null)
     {
         try
         {
             using (FileStream stream = new FileStream(this._path, FileMode.Open, FileAccess.Read))
             {
                 using (StreamReader reader = new StreamReader(stream, Encoding.Default))
                 {
                     this._scriptContents   = reader.ReadToEnd();
                     this._originalEncoding = reader.CurrentEncoding;
                     if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
                     {
                         if (SystemPolicy.GetLockdownPolicy(this._path, stream.SafeFileHandle) != SystemEnforcementMode.Enforce)
                         {
                             base.DefiningLanguageMode = (PSLanguageMode)0;
                         }
                         else
                         {
                             base.DefiningLanguageMode = (PSLanguageMode)3;
                         }
                     }
                     else if (base.Context != null)
                     {
                         base.DefiningLanguageMode = new PSLanguageMode?(base.Context.LanguageMode);
                     }
                 }
             }
         }
         catch (ArgumentException exception)
         {
             ThrowCommandNotFoundException(exception);
         }
         catch (IOException exception2)
         {
             ThrowCommandNotFoundException(exception2);
         }
         catch (NotSupportedException exception3)
         {
             ThrowCommandNotFoundException(exception3);
         }
         catch (UnauthorizedAccessException exception4)
         {
             ThrowCommandNotFoundException(exception4);
         }
     }
 }
コード例 #2
0
 private void CommonInitialization()
 {
     if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
     {
         if (SystemPolicy.GetLockdownPolicy(this._path, null) != SystemEnforcementMode.Enforce)
         {
             base.DefiningLanguageMode = (PSLanguageMode)0;
         }
         else
         {
             base.DefiningLanguageMode = (PSLanguageMode)3;
         }
     }
     else
     {
         base.DefiningLanguageMode = PSLanguageMode.FullLanguage;
     }
 }
コード例 #3
0
 /// <summary>
 /// Common initialization for all constructors.
 /// </summary>
 private void CommonInitialization()
 {
     // Assume external scripts are untrusted by default (for Get-Command, etc)
     // until we've actually parsed their script block.
     if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None)
     {
         // Get the lock down policy with no handle. This only impacts command discovery,
         // as the real language mode assignment will be done when we read the script
         // contents.
         SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null);
         if (scriptSpecificPolicy != SystemEnforcementMode.Enforce)
         {
             this.DefiningLanguageMode = PSLanguageMode.FullLanguage;
         }
         else
         {
             this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage;
         }
     }
 }
コード例 #4
0
        private void ReadScriptContents()
        {
            if (_scriptContents == null)
            {
                // make sure we can actually load the script and that it's non-empty
                // before we call it.

                // Note, although we are passing ASCII as the encoding, the StreamReader
                // class still obeys the byte order marks at the beginning of the file
                // if present. If not present, then ASCII is used as the default encoding.

                try
                {
                    using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read))
                    {
                        Encoding defaultEncoding = ClrFacade.GetDefaultEncoding();
                        Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle;

                        using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding))
                        {
                            _scriptContents   = scriptReader.ReadToEnd();
                            _originalEncoding = scriptReader.CurrentEncoding;

                            // Check if this came from a trusted path. If so, set its language mode to FullLanguage.
                            if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None)
                            {
                                SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, safeFileHandle);
                                if (scriptSpecificPolicy != SystemEnforcementMode.Enforce)
                                {
                                    this.DefiningLanguageMode = PSLanguageMode.FullLanguage;
                                }
                                else
                                {
                                    this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage;
                                }
                            }
                            else
                            {
                                if (this.Context != null)
                                {
                                    this.DefiningLanguageMode = this.Context.LanguageMode;
                                }
                            }
                        }
                    }
                }
                catch (ArgumentException e)
                {
                    // This catches PSArgumentException as well.
                    ThrowCommandNotFoundException(e);
                }
                catch (IOException e)
                {
                    ThrowCommandNotFoundException(e);
                }
                catch (NotSupportedException e)
                {
                    ThrowCommandNotFoundException(e);
                }
                catch (UnauthorizedAccessException e)
                {
                    // this is unadvertised exception thrown by the StreamReader ctor when
                    // no permission to read the script file
                    ThrowCommandNotFoundException(e);
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="command"></param>
        /// <param name="sb"></param>
        /// <param name="filePath"></param>
        /// <param name="initSb"></param>
        /// <param name="argumentList"></param>
        /// <param name="inputObject"></param>
        /// <param name="psCmdlet"></param>
        /// <param name="currentLocationPath"></param>
        /// <param name="streamingHost"></param>
        public ThreadJob(
            string name,
            string command,
            ScriptBlock sb,
            string filePath,
            ScriptBlock initSb,
            object[] argumentList,
            PSObject inputObject,
            PSCmdlet psCmdlet,
            string currentLocationPath,
            PSHost streamingHost)
            : base(command, name)
        {
            _sb           = sb;
            _filePath     = filePath;
            _initSb       = initSb;
            _argumentList = argumentList;
            _input        = new PSDataCollection <object>();
            if (inputObject != null)
            {
                _input.Add(inputObject);
            }
            _output              = new PSDataCollection <PSObject>();
            _streamingHost       = streamingHost;
            _currentLocationPath = currentLocationPath;

            this.PSJobTypeName = "ThreadJob";

            // Get script block to run.
            if (!string.IsNullOrEmpty(_filePath))
            {
                _sb = GetScriptBlockFromFile(_filePath, psCmdlet);
                if (_sb == null)
                {
                    throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile);
                }
            }
            else if (_sb == null)
            {
                throw new PSArgumentNullException(Properties.Resources.NoScriptToRun);
            }

            // Create Runspace/PowerShell object and state callback.
            // The job script/command will run in a separate thread associated with the Runspace.
            var iss = InitialSessionState.CreateDefault2();

            // Determine session language mode for Windows platforms
            WarningRecord lockdownWarning = null;

            if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase))
            {
                bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce);
                if (enforceLockdown && !string.IsNullOrEmpty(_filePath))
                {
                    // If script source is a file, check to see if it is trusted by the lock down policy
                    enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce);

                    if (!enforceLockdown && (_initSb != null))
                    {
                        // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce
                        // lock down.  Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script.
                        enforceLockdown = true;
                        lockdownWarning = new WarningRecord(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Properties.Resources.CannotRunTrustedFileInFL,
                                _filePath));
                    }
                }

                iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage;
            }

            if (_streamingHost != null)
            {
                _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss);
            }
            else
            {
                _rs = RunspaceFactory.CreateRunspace(iss);
            }
            _ps          = PowerShell.Create();
            _ps.Runspace = _rs;
            _ps.InvocationStateChanged += (sender, psStateChanged) =>
            {
                var newStateInfo = psStateChanged.InvocationStateInfo;

                // Update Job state.
                switch (newStateInfo.State)
                {
                case PSInvocationState.Running:
                    SetJobState(JobState.Running);
                    break;

                case PSInvocationState.Stopped:
                    SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Failed:
                    SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Completed:
                    if (_runningInitScript)
                    {
                        // Begin running main script.
                        _runningInitScript = false;
                        RunScript();
                    }
                    else
                    {
                        SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true);
                    }
                    break;
                }
            };

            // Get any using variables.
            var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>();

            if (usingAsts != null &&
                usingAsts.FirstOrDefault() != null)
            {
                // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater
                _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet);
            }

            // Hook up data streams.
            this.Output = _output;
            this.Output.EnumeratorNeverBlocks = true;

            this.Error = _ps.Streams.Error;
            this.Error.EnumeratorNeverBlocks = true;

            this.Progress = _ps.Streams.Progress;
            this.Progress.EnumeratorNeverBlocks = true;

            this.Verbose = _ps.Streams.Verbose;
            this.Verbose.EnumeratorNeverBlocks = true;

            this.Warning = _ps.Streams.Warning;
            this.Warning.EnumeratorNeverBlocks = true;
            if (lockdownWarning != null)
            {
                this.Warning.Add(lockdownWarning);
            }

            this.Debug = _ps.Streams.Debug;
            this.Debug.EnumeratorNeverBlocks = true;

            this.Information = _ps.Streams.Information;
            this.Information.EnumeratorNeverBlocks = true;

            // Create the JobManager job definition and job specification, and add to the JobManager.
            ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name);
            Dictionary <string, object> parameterCollection = new Dictionary <string, object>();

            parameterCollection.Add("NewJob", this);
            var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection);
            var newJob           = psCmdlet.JobManager.NewJob(jobSpecification);

            System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job");
        }