예제 #1
0
        /// <summary>
        /// Transforms the input data to an PSCredential.
        /// </summary>
        /// 
        /// <param name="engineIntrinsics">
        /// The engine APIs for the context under which the transformation is being
        /// made.
        /// </param>
        /// 
        /// <param name="inputData">
        /// If Null, the transformation prompts for both Username and Password
        /// If a string, the transformation uses the input for a username, and prompts 
        ///    for a Password
        /// If already an PSCredential, the transform does nothing.
        /// </param>
        /// <returns>An PSCredential object representing the inputData.</returns>
        public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
        {
            PSCredential cred = null;
            string userName = null;
            bool shouldPrompt = false;

            if ((engineIntrinsics == null) ||
               (engineIntrinsics.Host == null) ||
               (engineIntrinsics.Host.UI == null))
            {
                throw PSTraceSource.NewArgumentNullException("engineIntrinsics");
            }

            if (inputData == null)
            {
                shouldPrompt = true;
            }
            else
            {
                // Try to coerce the input as an PSCredential
                cred = LanguagePrimitives.FromObjectAs<PSCredential>(inputData);

                // Try to coerce the username from the string
                if (cred == null)
                {
                    shouldPrompt = true;
                    userName = LanguagePrimitives.FromObjectAs<string>(inputData);

                    // If we couldn't get the username (as a string,)
                    // throw an exception
                    if (userName == null)
                    {
                        throw new PSArgumentException("userName");
                    }
                }
            }

            if (shouldPrompt)
            {
                string caption = null;
                string prompt = null;


                caption = CredentialAttributeStrings.CredentialAttribute_Prompt_Caption;

                prompt = CredentialAttributeStrings.CredentialAttribute_Prompt;

                cred = engineIntrinsics.Host.UI.PromptForCredential(
                           caption,
                           prompt,
                           userName,
                           "");
            }

            return cred;
        }
예제 #2
0
 protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
 {
     string varName = arguments as string;
     if (varName != null)
     {
         if (varName.StartsWith("+", StringComparison.Ordinal))
         {
             varName = varName.Substring(1);
         }
         VariablePath silp = new VariablePath(varName);
         if (!silp.IsVariable)
         {
             throw new ValidationMetadataException(
                 "ArgumentNotValidVariableName",
                 null,
                 Metadata.ValidateVariableName, varName);
         }
     }
 }
예제 #3
0
 protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
 {
     throw new NotImplementedException();
 }
예제 #4
0
        private void Initialize(Runspace runspace, EngineIntrinsics engineIntrinsics)
        {
            _engineIntrinsics = engineIntrinsics;
            _runspace         = runspace;

            if (!_delayedOneTimeInitCompleted)
            {
                DelayedOneTimeInitialize();
                _delayedOneTimeInitCompleted = true;
            }

            _previousRender              = _initialPrevRender;
            _previousRender.bufferWidth  = _console.BufferWidth;
            _previousRender.bufferHeight = _console.BufferHeight;
            _previousRender.errorPrompt  = false;
            _buffer.Clear();
            _edits                = new List <EditItem>();
            _undoEditIndex        = 0;
            _editGroupStart       = -1;
            _current              = 0;
            _mark                 = 0;
            _emphasisStart        = -1;
            _emphasisLength       = 0;
            _tokens               = null;
            _parseErrors          = null;
            _inputAccepted        = false;
            _initialX             = _console.CursorLeft;
            _initialY             = _console.CursorTop;
            _initialForeground    = _console.ForegroundColor;
            _initialBackground    = _console.BackgroundColor;
            _statusIsErrorMessage = false;

            _initialOutputEncoding = _console.OutputEncoding;

            // Don't change the OutputEncoding if already UTF8, no console, or using raster font on Windows
            _skipOutputEncodingChange = _initialOutputEncoding == Encoding.UTF8 ||
                                        (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
                                         PlatformWindows.IsConsoleInput() &&
                                         PlatformWindows.IsUsingRasterFont());

            if (!_skipOutputEncodingChange)
            {
                _console.OutputEncoding = Encoding.UTF8;
            }

            _lastRenderTime = Stopwatch.StartNew();

            _killCommandCount            = 0;
            _yankCommandCount            = 0;
            _yankLastArgCommandCount     = 0;
            _tabCommandCount             = 0;
            _recallHistoryCommandCount   = 0;
            _anyHistoryCommandCount      = 0;
            _visualSelectionCommandCount = 0;
            _hashedHistory = null;

            if (_getNextHistoryIndex > 0)
            {
                _currentHistoryIndex = _getNextHistoryIndex;
                UpdateFromHistory(HistoryMoveCursor.ToEnd);
                _getNextHistoryIndex = 0;
                if (_searchHistoryCommandCount > 0)
                {
                    _searchHistoryPrefix = "";
                    if (Options.HistoryNoDuplicates)
                    {
                        _hashedHistory = new Dictionary <string, int>();
                    }
                }
            }
            else
            {
                _currentHistoryIndex       = _history.Count;
                _searchHistoryCommandCount = 0;
            }
            if (_previousHistoryItem != null)
            {
                _previousHistoryItem.ApproximateElapsedTime = DateTime.UtcNow - _previousHistoryItem.StartTime;
            }
        }
예제 #5
0
        private string InvokePSReadLine(CancellationToken cancellationToken)
        {
            EngineIntrinsics engineIntrinsics = _psesHost.IsRunspacePushed ? null : _engineIntrinsics;

            return(_psrlProxy.ReadLine(_psesHost.Runspace, engineIntrinsics, cancellationToken, /* lastExecutionStatus */ null));
        }
        public static IEnumerable <CommandInfo> GetReferencedCommands(ScriptBlock scriptBlock, EngineIntrinsics executionContext, PSCmdlet cmdlet)
        {
            Dictionary <CommandInfo, bool> resolvedCommandCache = new Dictionary <CommandInfo, bool>();
            Queue <PSToken>           tokenQueue = new Queue <PSToken>();
            Collection <PSParseError> errors;

            foreach (PSToken token in PSParser.Tokenize(new object[] { scriptBlock }, out errors))
            {
                tokenQueue.Enqueue(token);
            }
            if (tokenQueue.Count == 0)
            {
                yield return(null);
            }
            while (tokenQueue.Count > 0)
            {
                PSToken token = tokenQueue.Dequeue();
                if (token.Type == PSTokenType.Command)
                {
                    CommandInfo cmd = null;
                    cmd = executionContext.SessionState.InvokeCommand.GetCommand(token.Content, CommandTypes.Alias);
                    if (cmd == null)
                    {
                        cmd = executionContext.SessionState.InvokeCommand.GetCommand(token.Content, CommandTypes.Function);
                        if (cmd == null)
                        {
                            cmd = executionContext.SessionState.InvokeCommand.GetCommand(token.Content, CommandTypes.Cmdlet);
                        }
                    }
                    else
                    {
                        while (cmd != null && cmd is AliasInfo)
                        {
                            AliasInfo alias = cmd as AliasInfo;
                            if (!resolvedCommandCache.ContainsKey(alias))
                            {
                                yield return(alias);

                                resolvedCommandCache.Add(alias, true);
                            }
                            cmd = alias.ReferencedCommand;
                        }
                    }
                    if (cmd == null)
                    {
                        continue;
                    }
                    if (cmd is FunctionInfo)
                    {
                        if (!resolvedCommandCache.ContainsKey(cmd))
                        {
                            FunctionInfo func = cmd as FunctionInfo;
                            yield return(cmd);

                            foreach (PSToken t in PSParser.Tokenize(new object[] { func.ScriptBlock }, out errors))
                            {
                                tokenQueue.Enqueue(t);
                            }
                            resolvedCommandCache.Add(cmd, true);
                        }
                    }
                    else
                    {
                        if (!resolvedCommandCache.ContainsKey(cmd))
                        {
                            yield return(cmd);

                            resolvedCommandCache.Add(cmd, true);
                        }
                    }
                }
            }
        }