Ejemplo n.º 1
0
            VisitNodes(ArrayList nodes, NodeVisitor v)
            {
                if (nodes == null)
                {
                    return;
                }

                for (int i = 0; i < nodes.Count; ++i)
                {
                    ProgressNode node = (ProgressNode)nodes[i];
                    Dbg.Assert(node != null, "nodes should not contain null elements");

                    if (!v.Visit(node, nodes, i))
                    {
                        return;
                    }

                    if (node.Children != null)
                    {
                        VisitNodes(node.Children, v);
                    }
                }
            }
Ejemplo n.º 2
0
        FindOldestLeafmostNodeHelper(ArrayList treeToSearch, out ArrayList listWhereFound, out int indexWhereFound)
        {
            listWhereFound  = null;
            indexWhereFound = -1;

            FindOldestNodeVisitor v = new FindOldestNodeVisitor();

            NodeVisitor.VisitNodes(treeToSearch, v);

            listWhereFound  = v.ListWhereFound;
            indexWhereFound = v.IndexWhereFound;

#if DEBUG || ASSERTIONS_TRACE
            if (v.FoundNode == null)
            {
                Dbg.Assert(listWhereFound == null, "list should be null when no node found");
                Dbg.Assert(indexWhereFound == -1, "index should indicate no node found");
                Dbg.Assert(_topLevelNodes.Count == 0, "if there is no oldest node, then the tree must be empty");
                Dbg.Assert(_nodeCount == 0, "if there is no oldest node, then the tree must be empty");
            }
#endif
            return(v.FoundNode);
        }
Ejemplo n.º 3
0
        internal static Type GetElementType(Type arrayType)
        {
            Dbg.Assert(arrayType != null, "Caller should verify arrayType != null");
            Dbg.Assert(arrayType.IsArray, "Caller should verify arrayType.IsArray");

            // MOF syntax from Appendix A of DSP0004 doesn't allow expressing
            // of 1) nested arrays and 2) multi-dimensional arrays
            // (see production for "array" and how this production is used in
            //  other productions like "propertyDeclaration" or "parameter")
            if (arrayType.GetArrayRank() != 1)
            {
                return(null);
            }

            Type elementType = arrayType.GetElementType();

            if (elementType.IsArray)
            {
                return(null);
            }

            return(elementType);
        }
Ejemplo n.º 4
0
            public virtual IEnumerable <NotFoundError> GetNotFoundErrors_IfThisIsTheOnlyFilter()
            {
                switch (this.BehaviorOnNoMatch)
                {
                case BehaviorOnNoMatch.ReportErrors:
                    if (this.HadMatches)
                    {
                        return(Enumerable.Empty <NotFoundError>());
                    }
                    else
                    {
                        return(new[] { new NotFoundError() });
                    }

                case BehaviorOnNoMatch.SilentlyContinue:
                    return(Enumerable.Empty <NotFoundError>());

                case BehaviorOnNoMatch.Default:
                default:
                    Dbg.Assert(false, "BehaviorOnNoMatch.Default should be handled by derived classes");
                    return(Enumerable.Empty <NotFoundError>());
                }
            }
Ejemplo n.º 5
0
        Render(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
        {
            Dbg.Assert(strCollection != null, "strCollection should not be null");
            Dbg.Assert(indentation >= 0, "indentation is negative");
            Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records");

            switch (Style)
            {
            case RenderStyle.FullPlus:
                RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: true);
                break;

            case RenderStyle.Full:
                RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: false);
                break;

            case RenderStyle.Compact:
                RenderCompact(strCollection, indentation, maxWidth, rawUI);
                break;

            case RenderStyle.Minimal:
                RenderMinimal(strCollection, indentation, maxWidth, rawUI);
                break;

            case RenderStyle.Ansi:
                RenderAnsi(strCollection, indentation, maxWidth);
                break;

            case RenderStyle.Invisible:
                // do nothing
                break;

            default:
                Dbg.Assert(false, "unrecognized RenderStyle value");
                break;
            }
        }
Ejemplo n.º 6
0
        internal static CimJobException CreateFromAnyException(
            string jobDescription,
            CimJobContext jobContext,
            Exception inner)
        {
            Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null");
            Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
            Dbg.Assert(inner != null, "Caller should verify inner != null");

            CimException cimException = inner as CimException;

            if (cimException != null)
            {
                return(CreateFromCimException(jobDescription, jobContext, cimException));
            }

            string          message             = BuildErrorMessage(jobDescription, jobContext, inner.Message);
            CimJobException cimJobException     = new CimJobException(message, inner);
            var             containsErrorRecord = inner as IContainsErrorRecord;

            if (containsErrorRecord != null)
            {
                cimJobException.InitializeErrorRecord(
                    jobContext,
                    errorId: "CimJob_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId,
                    errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category);
            }
            else
            {
                cimJobException.InitializeErrorRecord(
                    jobContext,
                    errorId: "CimJob_" + inner.GetType().Name,
                    errorCategory: ErrorCategory.NotSpecified);
            }

            return(cimJobException);
        }
Ejemplo n.º 7
0
        private static string GetMatchConditionForEqualityOperator(string propertyName, object propertyValue)
        {
            string condition;

            // comparison of 'char' is case-sensitive in WQL (comparison of 'string' is case-insensitive)
            if (propertyValue is char)
            {
                char   c                = (char)propertyValue;
                char   lowerCase        = char.ToLowerInvariant(c);
                char   upperCase        = char.ToUpperInvariant(c);
                string lowerCaseLiteral = CimQuery.ObjectToWqlLiteral(lowerCase);
                string upperCaseLiteral = CimQuery.ObjectToWqlLiteral(upperCase);
                Dbg.Assert(!string.IsNullOrWhiteSpace(lowerCaseLiteral), "All characters are assumed to have valid WQL literals (lower)");
                Dbg.Assert(!string.IsNullOrWhiteSpace(upperCaseLiteral), "All characters are assumed to have valid WQL literals (upper)");
                condition = string.Format(
                    CultureInfo.InvariantCulture,
                    "(({0} = {1}) OR ({0} = {2}))",
                    propertyName,
                    lowerCaseLiteral,
                    upperCaseLiteral);
                return(condition);
            }

            string wqlLiteral = CimQuery.ObjectToWqlLiteral(propertyValue);

            if (string.IsNullOrWhiteSpace(wqlLiteral))
            {
                return(null);
            }

            condition = string.Format(
                CultureInfo.InvariantCulture,
                "({0} = {1})",
                propertyName,
                wqlLiteral);
            return(condition);
        }
Ejemplo n.º 8
0
        WrappedDeserializer(DataFormat dataFormat, string streamName, TextReader input)
            :
            base(dataFormat, streamName)
        {
            Dbg.Assert(input != null, "input should have a value");

            // If the data format is none - do nothing...
            if (dataFormat == DataFormat.None)
            {
                return;
            }

            textReader = input;
            _firstLine = textReader.ReadLine();
            if (String.Compare(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0)
            {
                // format should be XML

                dataFormat = DataFormat.XML;
            }

            switch (format)
            {
            case DataFormat.XML:
                _xmlReader = XmlReader.Create(textReader, new XmlReaderSettings {
                    XmlResolver = null
                });
                _xmlDeserializer = new Deserializer(_xmlReader);
                break;

            case DataFormat.Text:
            default:
                // do nothing; we'll just read from the TextReader

                break;
            }
        }
        internal CimCmdletInvocationContext(
            CimCmdletDefinitionContext cmdletDefinitionContext,
            Cmdlet cmdlet,
            string namespaceOverride)
        {
            this.CmdletDefinitionContext = cmdletDefinitionContext;
            this.NamespaceOverride = namespaceOverride;

            // Cmdlet might have a shorter lifespan than CimCmdletInvocationContext
            // - we need to extract information out of Cmdlet to extend information's lifespan

            this.CmdletInvocationInfo = cmdlet.MyInvocation;

            var runtime = cmdlet.CommandRuntime as MshCommandRuntime;
            Dbg.Assert(runtime != null, "CIM cmdlets should only be run from within PS runtime");

            this.DebugActionPreference = runtime.DebugPreference;
            WarnAboutUnsupportedActionPreferences(
                cmdlet,
                this.DebugActionPreference,
                "Debug",
                inquireMessageGetter: () => CmdletizationResources.CimCmdletAdapter_DebugInquire,
                stopMessageGetter: () => string.Empty);

            this.WarningActionPreference = runtime.WarningPreference;
            WarnAboutUnsupportedActionPreferences(
                cmdlet,
                this.WarningActionPreference,
                "WarningAction",
                inquireMessageGetter: () => CmdletizationResources.CimCmdletAdapter_WarningInquire,
                stopMessageGetter: () => CmdletizationResources.CimCmdletAdapter_WarningStop);

            this.VerboseActionPreference = runtime.VerbosePreference;
            this.ErrorActionPreference = runtime.ErrorAction;

            this.ShouldProcessOptimization = runtime.CalculatePossibleShouldProcessOptimization();
        }
Ejemplo n.º 10
0
        private void SleepAndRetry()
        {
            int tmpRandomDelay = _random.Next(0, _sleepAndRetryDelayRangeMs);
            int delay          = MinRetryDelayMs + _sleepAndRetryExtraDelayMs + tmpRandomDelay;

            _sleepAndRetryExtraDelayMs = _sleepAndRetryDelayRangeMs - tmpRandomDelay;
            if (_sleepAndRetryDelayRangeMs < MaxRetryDelayMs)
            {
                _sleepAndRetryDelayRangeMs *= 2;
            }

            string verboseMessage = string.Format(
                CultureInfo.InvariantCulture,
                CmdletizationResources.CimJob_SleepAndRetryVerboseMessage,
                this.JobContext.CmdletInvocationInfo.InvocationName,
                this.JobContext.Session.ComputerName ?? "localhost",
                delay / 1000.0);

            this.WriteVerbose(verboseMessage);

            lock (_jobStateLock)
            {
                if (_jobWasStopped)
                {
                    this.SetCompletedJobState(JobState.Stopped, null);
                }
                else
                {
                    Dbg.Assert(_sleepAndRetryTimer == null, "There should be only 1 active _sleepAndRetryTimer");
                    _sleepAndRetryTimer = new Timer(
                        state: null,
                        dueTime: delay,
                        period: Timeout.Infinite,
                        callback: SleepAndRetry_OnWakeup);
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// All calls to the Runspace to execute a command line must be done with this function, which properly synchronizes
        /// access to the running pipeline between the main thread and the break handler thread.  This synchronization is
        /// necessary so that executions can be aborted with Ctrl-C (including evaluation of the prompt and collection of
        /// command-completion candidates.
        ///
        /// On any given Executor instance, ExecuteCommand should be called at most once at a time by any one thread. It is NOT
        /// reentrant.
        /// </summary>
        /// <param name="command">
        /// The command line to be executed.  Must be non-null.
        /// </param>
        /// <param name="exceptionThrown">
        /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null.
        /// Can be tested to see if the execution was successful or not.
        /// </param>
        /// <param name="options">
        /// options to govern the execution
        /// </param>
        /// <returns>
        /// the object stream resulting from the execution.  May be null.
        /// </returns>
        internal Collection <PSObject> ExecuteCommand(string command, out Exception exceptionThrown, ExecutionOptions options)
        {
            Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value");

            // Experimental:
            // Check for implicit remoting commands that can be batched, and execute as batched if able.
            if (ExperimentalFeature.IsEnabled("PSImplicitRemotingBatching"))
            {
                var addOutputter = ((options & ExecutionOptions.AddOutputter) > 0);
                if (addOutputter &&
                    !_parent.RunspaceRef.IsRunspaceOverridden &&
                    _parent.RunspaceRef.Runspace.ExecutionContext.Modules != null &&
                    _parent.RunspaceRef.Runspace.ExecutionContext.Modules.IsImplicitRemotingModuleLoaded &&
                    Utils.TryRunAsImplicitBatch(command, _parent.RunspaceRef.Runspace))
                {
                    exceptionThrown = null;
                    return(null);
                }
            }

            Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0);

            return(ExecuteCommandHelper(tempPipeline, out exceptionThrown, options));
        }
Ejemplo n.º 12
0
        WrappedSerializer(DataFormat dataFormat, string streamName, TextWriter output)
            : base(dataFormat, streamName)
        {
            Dbg.Assert(output != null, "output should have a value");

            textWriter = output;
            switch (format)
            {
            case DataFormat.XML:
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.CheckCharacters    = false;
                settings.OmitXmlDeclaration = true;
                _xmlWriter     = XmlWriter.Create(textWriter, settings);
                _xmlSerializer = new Serializer(_xmlWriter);
                break;

            case DataFormat.Text:
            default:
                // do nothing; we'll just write to the TextWriter
                // or discard it.

                break;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Process record
        /// </summary>
        protected override void ProcessRecord()
        {
            IReadOnlyList <Runspace> results;

            if ((ParameterSetName == GetRunspaceCommand.NameParameterSet) && ((Name == null) || Name.Length == 0))
            {
                results = GetRunspaceUtils.GetAllRunspaces();
            }
            else
            {
                switch (ParameterSetName)
                {
                case GetRunspaceCommand.NameParameterSet:
                    results = GetRunspaceUtils.GetRunspacesByName(Name);
                    break;

                case GetRunspaceCommand.IdParameterSet:
                    results = GetRunspaceUtils.GetRunspacesById(Id);
                    break;

                case GetRunspaceCommand.InstanceIdParameterSet:
                    results = GetRunspaceUtils.GetRunspacesByInstanceId(InstanceId);
                    break;

                default:
                    Dbg.Assert(false, "Unknown parameter set in GetRunspaceCommand");
                    results = new List <Runspace>().AsReadOnly();
                    break;
                }
            }

            foreach (Runspace runspace in results)
            {
                WriteObject(runspace);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Take an enumeration of modules and only return those that match a specification
        /// in the given specification table, or have no corresponding entry in the specification table.
        /// </summary>
        /// <param name="modules">The modules to filter by specification match.</param>
        /// <param name="moduleSpecificationTable">The specification lookup table to filter the modules on.</param>
        /// <returns>The modules that match their corresponding table entry, or which have no table entry.</returns>
        private static IEnumerable <PSModuleInfo> FilterModulesForSpecificationMatch(
            IEnumerable <PSModuleInfo> modules,
            IDictionary <string, ModuleSpecification> moduleSpecificationTable)
        {
            Dbg.Assert(moduleSpecificationTable != null, $"Caller to verify that {nameof(moduleSpecificationTable)} is not null");
            Dbg.Assert(moduleSpecificationTable.Count != 0, $"Caller to verify that {nameof(moduleSpecificationTable)} is not empty");

            foreach (PSModuleInfo module in modules)
            {
                // No table entry means we return the module
                if (!moduleSpecificationTable.TryGetValue(module.Name, out ModuleSpecification moduleSpecification))
                {
                    yield return(module);

                    continue;
                }

                // Modules with table entries only get returned if they match them
                if (ModuleIntrinsics.IsModuleMatchingModuleSpec(module, moduleSpecification))
                {
                    yield return(module);
                }
            }
        }
Ejemplo n.º 15
0
        private void ParseHelper(string[] args)
        {
            Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null");
            bool noexitSeen = false;

            for (int i = 0; i < args.Length; ++i)
            {
                (string SwitchKey, bool ShouldBreak)switchKeyResults = GetSwitchKey(args, ref i, this, ref noexitSeen);
                if (switchKeyResults.ShouldBreak)
                {
                    break;
                }

                string switchKey = switchKeyResults.SwitchKey;

                // If version is in the commandline, don't continue to look at any other parameters
                if (MatchSwitch(switchKey, "version", "v"))
                {
                    _showVersion   = true;
                    _showBanner    = false;
                    _noInteractive = true;
                    _skipUserInit  = true;
                    _noExit        = false;
                    break;
                }

                if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?"))
                {
                    _showHelp         = true;
                    _showExtendedHelp = true;
                    _abortStartup     = true;
                }
                else if (MatchSwitch(switchKey, "login", "l"))
                {
                    // This handles -Login on Windows only, where it does nothing.
                    // On *nix, -Login is handled much earlier to improve startup performance.
                }
                else if (MatchSwitch(switchKey, "noexit", "noe"))
                {
                    _noExit    = true;
                    noexitSeen = true;
                }
                else if (MatchSwitch(switchKey, "noprofile", "nop"))
                {
                    _skipUserInit = true;
                }
                else if (MatchSwitch(switchKey, "nologo", "nol"))
                {
                    _showBanner = false;
                }
                else if (MatchSwitch(switchKey, "noninteractive", "noni"))
                {
                    _noInteractive = true;
                }
                else if (MatchSwitch(switchKey, "socketservermode", "so"))
                {
                    _socketServerMode = true;
                }
                else if (MatchSwitch(switchKey, "servermode", "s"))
                {
                    _serverMode = true;
                }
                else if (MatchSwitch(switchKey, "namedpipeservermode", "nam"))
                {
                    _namedPipeServerMode = true;
                }
                else if (MatchSwitch(switchKey, "sshservermode", "sshs"))
                {
                    _sshServerMode = true;
                }
                else if (MatchSwitch(switchKey, "interactive", "i"))
                {
                    _noInteractive = false;
                }
                else if (MatchSwitch(switchKey, "configurationname", "config"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingConfigurationNameArgument);
                        break;
                    }

                    _configurationName = args[i];
                }
                else if (MatchSwitch(switchKey, "custompipename", "cus"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingCustomPipeNameArgument);
                        break;
                    }

                    if (!Platform.IsWindows)
                    {
                        int maxNameLength = (Platform.IsLinux ? MaxPipePathLengthLinux : MaxPipePathLengthMacOS) - Path.GetTempPath().Length;
                        if (args[i].Length > maxNameLength)
                        {
                            WriteCommandLineError(
                                string.Format(
                                    CommandLineParameterParserStrings.CustomPipeNameTooLong,
                                    maxNameLength,
                                    args[i],
                                    args[i].Length));
                            break;
                        }
                    }

                    _customPipeName = args[i];
                }
                else if (MatchSwitch(switchKey, "command", "c"))
                {
                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "windowstyle", "w"))
                {
#if UNIX
                    WriteCommandLineError(
                        CommandLineParameterParserStrings.WindowStyleArgumentNotImplemented);
                    break;
#else
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingWindowStyleArgument);
                        break;
                    }

                    try
                    {
                        ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo(
                            args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture);
                        ConsoleControl.SetConsoleMode(style);
                    }
                    catch (PSInvalidCastException e)
                    {
                        WriteCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message));
                        break;
                    }
#endif
                }
                else if (MatchSwitch(switchKey, "file", "f"))
                {
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }
                }
#if DEBUG
                // this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only
                // attach to an already running process with that debugger.
                else if (MatchSwitch(switchKey, "wait", "w"))
                {
                    // This does not need to be localized: its chk only

                    ((ConsoleHostUserInterface)_hostUI).WriteToConsole("Waiting - type enter to continue:", false);
                    _hostUI.ReadLine();
                }

                // this option is useful for testing the initial InitialSessionState experience
                else if (MatchSwitch(switchKey, "iss", "iss"))
                {
                    // Just toss this option, it was processed earlier...
                }

                // this option is useful for testing the initial InitialSessionState experience
                // this is independent of the normal wait switch because configuration processing
                // happens so early in the cycle...
                else if (MatchSwitch(switchKey, "isswait", "isswait"))
                {
                    // Just toss this option, it was processed earlier...
                }

                else if (MatchSwitch(switchKey, "modules", "mod"))
                {
                    if (ConsoleHost.DefaultInitialSessionState == null)
                    {
                        WriteCommandLineError(
                            "The -module option can only be specified with the -iss option.",
                            showHelp: true,
                            showBanner: false);
                        break;
                    }

                    ++i;
                    int moduleCount = 0;
                    // Accumulate the arguments to this script...
                    while (i < args.Length)
                    {
                        string arg = args[i];

                        if (!string.IsNullOrEmpty(arg) && CharExtensions.IsDash(arg[0]))
                        {
                            break;
                        }
                        else
                        {
                            ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg });
                            moduleCount++;
                        }

                        ++i;
                    }

                    if (moduleCount < 1)
                    {
                        _hostUI.WriteErrorLine("No modules specified for -module option");
                    }
                }
#endif
                else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o"))
                {
                    ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter);
                    _outputFormatSpecified = true;
                }
                else if (MatchSwitch(switchKey, "inputformat", "in") || MatchSwitch(switchKey, "if", "if"))
                {
                    ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep"))
                {
                    ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter);
                }
                else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e"))
                {
                    _wasCommandEncoded = true;
                    if (!ParseCommand(args, ref i, noexitSeen, true))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea"))
                {
                    if (!CollectArgs(args, ref i))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "settingsfile", "settings"))
                {
                    // Parse setting file arg and write error
                    if (!TryParseSettingFileHelper(args, ++i, this))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "sta", "s"))
                {
                    if (!Platform.IsWindowsDesktop)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.STANotImplemented);
                        break;
                    }

                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = true;
                }
                else if (MatchSwitch(switchKey, "mta", "mta"))
                {
                    if (!Platform.IsWindowsDesktop)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MTANotImplemented);
                        break;
                    }

                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = false;
                }
                else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingWorkingDirectoryArgument);
                        break;
                    }

                    _workingDirectory = args[i];
                }
#if !UNIX
                else if (MatchSwitch(switchKey, "removeworkingdirectorytrailingcharacter", "removeworkingdirectorytrailingcharacter"))
                {
                    _removeWorkingDirectoryTrailingCharacter = true;
                }
#endif
                else
                {
                    // The first parameter we fail to recognize marks the beginning of the file string.

                    --i;
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }
                }
            }

            if (_showHelp)
            {
                ShowHelp();
            }

            if (_showBanner && !_showHelp)
            {
                DisplayBanner();

                if (UpdatesNotification.CanNotifyUpdates)
                {
                    UpdatesNotification.ShowUpdateNotification(_hostUI);
                }
            }

            Dbg.Assert(
                ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) ||
                (_exitCode == ConsoleHost.ExitCodeSuccess),
                "if exit code is failure, then abortstartup should be true");
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Processes records from the input pipeline.
        /// For each input file, the command retrieves its
        /// corresponding certificate.
        /// </summary>
        protected override void ProcessRecord()
        {
            //
            // this cannot happen as we have specified the Path
            // property to be a mandatory parameter
            //
            Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
                       "GetCertificateCommand: Param binder did not bind path");

            X509Certificate2 cert = null;

            foreach (string p in FilePath)
            {
                List <string> paths = new List <string>();

                // Expand wildcard characters
                if (_isLiteralPath)
                {
                    paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
                }
                else
                {
                    try
                    {
                        foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
                        {
                            paths.Add(tempPath.ProviderPath);
                        }
                    }
                    catch (ItemNotFoundException)
                    {
                        _filesNotFound.Add(p);
                    }
                }

                foreach (string resolvedPath in paths)
                {
                    string resolvedProviderPath =
                        SecurityUtils.GetFilePathOfExistingFile(this, resolvedPath);


                    if (resolvedProviderPath == null)
                    {
                        _filesNotFound.Add(p);
                    }
                    else
                    {
                        try
                        {
                            cert = GetCertFromPfxFile(resolvedProviderPath);
                        }
                        catch (CryptographicException)
                        {
                            //
                            // CryptographicException is thrown when any error
                            // occurs inside the crypto class library. It has a
                            // protected member HResult that indicates the exact
                            // error but it is not available outside the class.
                            // Thus we have to assume that the above exception
                            // was thrown because the pfx file is password
                            // protected.
                            //
                            SecureString password = null;

                            string prompt = null;
                            prompt = CertificateCommands.GetPfxCertPasswordPrompt;

                            password = SecurityUtils.PromptForSecureString(Host.UI, prompt);
                            try
                            {
                                cert = GetCertFromPfxFile(resolvedProviderPath,
                                                          password);
                            }
                            catch (CryptographicException e)
                            {
                                //
                                // since we cannot really figure out the
                                // meaning of a given CryptographicException
                                // we have to use NotSpecified category here
                                //
                                ErrorRecord er =
                                    new ErrorRecord(e,
                                                    "GetPfxCertificateUnknownCryptoError",
                                                    ErrorCategory.NotSpecified,
                                                    null);
                                WriteError(er);
                                continue;
                            }
                        }

                        WriteObject(cert);
                    }
                }
            }

            if (_filesNotFound.Count > 0)
            {
                if (_filesNotFound.Count == FilePath.Length)
                {
                    ErrorRecord er =
                        SecurityUtils.CreateFileNotFoundErrorRecord(
                            CertificateCommands.NoneOfTheFilesFound,
                            "GetPfxCertCommandNoneOfTheFilesFound");

                    ThrowTerminatingError(er);
                }
                else
                {
                    //
                    // we found some files but not others.
                    // Write error for each missing file
                    //
                    foreach (string f in _filesNotFound)
                    {
                        ErrorRecord er =
                            SecurityUtils.CreateFileNotFoundErrorRecord(
                                CertificateCommands.FileNotFound,
                                "GetPfxCertCommandFileNotFound",
                                f
                                );

                        WriteError(er);
                    }
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (ParameterSetName.Equals("Xml", StringComparison.OrdinalIgnoreCase))
            {
                foreach (XmlNode xmlNode in this.Xml)
                {
                    ProcessXmlNode(xmlNode, string.Empty);
                }
            }
            else if (
                (ParameterSetName.Equals("Path", StringComparison.OrdinalIgnoreCase) ||
                 (ParameterSetName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase))))
            {
                // If any file not resolved, execution stops. this is to make consistent with select-string.
                List <string> fullresolvedPaths = new();
                foreach (string fpath in Path)
                {
                    if (_isLiteralPath)
                    {
                        string resolvedPath = GetUnresolvedProviderPathFromPSPath(fpath);
                        fullresolvedPaths.Add(resolvedPath);
                    }
                    else
                    {
                        ProviderInfo        provider;
                        Collection <string> resolvedPaths = GetResolvedProviderPathFromPSPath(fpath, out provider);
                        if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
                        {
                            // Cannot open File error
                            string message = StringUtil.Format(UtilityCommonStrings.FileOpenError, provider.FullName);
                            InvalidOperationException e = new(message);
                            ErrorRecord er = new(e, "ProcessingFile", ErrorCategory.InvalidOperation, fpath);
                            WriteError(er);
                            continue;
                        }

                        fullresolvedPaths.AddRange(resolvedPaths);
                    }
                }

                foreach (string file in fullresolvedPaths)
                {
                    ProcessXmlFile(file);
                }
            }
            else if (ParameterSetName.Equals("Content", StringComparison.OrdinalIgnoreCase))
            {
                foreach (string xmlstring in Content)
                {
                    XmlDocument xmlDocument;
                    try
                    {
                        xmlDocument = (XmlDocument)LanguagePrimitives.ConvertTo(xmlstring, typeof(XmlDocument), CultureInfo.InvariantCulture);
                    }
                    catch (PSInvalidCastException invalidCastException)
                    {
                        this.WriteError(invalidCastException.ErrorRecord);
                        continue;
                    }

                    this.ProcessXmlNode(xmlDocument, string.Empty);
                }
            }
            else
            {
                Dbg.Assert(false, "Unrecognized parameterset");
            }
        }
Ejemplo n.º 18
0
        private void ParseHelper(string[] args)
        {
            Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null");
            bool noexitSeen = false;

            for (int i = 0; i < args.Length; ++i)
            {
                // Invariant culture used because command-line parameters are not localized.

                string switchKey = args[i].Trim().ToLowerInvariant();
                if (String.IsNullOrEmpty(switchKey))
                {
                    continue;
                }

                if (!SpecialCharacters.IsDash(switchKey[0]) && switchKey[0] != '/')
                {
                    // then its a command

                    --i;
                    ParseCommand(args, ref i, noexitSeen, false);
                    break;
                }

                // chop off the first character so that we're agnostic wrt specifying / or -
                // in front of the switch name.

                switchKey = switchKey.Substring(1);

                // chop off the second dash so we're agnostic wrt specifying - or --
                if (!String.IsNullOrEmpty(switchKey) && SpecialCharacters.IsDash(switchKey[0]))
                {
                    switchKey = switchKey.Substring(1);
                }

                if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?"))
                {
                    _showHelp     = true;
                    _abortStartup = true;
                }
                else if (MatchSwitch(switchKey, "noexit", "noe"))
                {
                    _noExit    = true;
                    noexitSeen = true;
                }
                else if (MatchSwitch(switchKey, "importsystemmodules", "imp"))
                {
                    _importSystemModules = true;
                }
                else if (MatchSwitch(switchKey, "noprofile", "nop"))
                {
                    _skipUserInit = true;
                }
                else if (MatchSwitch(switchKey, "nologo", "nol"))
                {
                    _showBanner = false;
                }
                else if (MatchSwitch(switchKey, "noninteractive", "noni"))
                {
                    _noInteractive = true;
                }
                else if (MatchSwitch(switchKey, "socketservermode", "so"))
                {
                    _socketServerMode = true;
                }
                else if (MatchSwitch(switchKey, "servermode", "s"))
                {
                    _serverMode = true;
                }
                else if (MatchSwitch(switchKey, "namedpipeservermode", "nam"))
                {
                    _namedPipeServerMode = true;
                }
                else if (MatchSwitch(switchKey, "sshservermode", "sshs"))
                {
                    _sshServerMode = true;
                }
                else if (MatchSwitch(switchKey, "configurationname", "config"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingConfigurationNameArgument);
                        break;
                    }

                    _configurationName = args[i];
                }
                else if (MatchSwitch(switchKey, "command", "c"))
                {
                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }
                }
#if !CORECLR  // windowstyle parameter not supported on NanoServer because ProcessWindowStyle does Not exist on CoreCLR
                else if (MatchSwitch(switchKey, "windowstyle", "w"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingWindowStyleArgument);
                        break;
                    }

                    try
                    {
                        ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo(
                            args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture);
                        ConsoleControl.SetConsoleMode(style);
                    }
                    catch (PSInvalidCastException e)
                    {
                        WriteCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message));
                        break;
                    }
                }
#endif
                else if (MatchSwitch(switchKey, "file", "f"))
                {
                    // Process file execution. We don't need to worry about checking -command
                    // since if -command comes before -file, -file will be treated as part
                    // of the script to evaluate. If -file comes before -command, it will
                    // treat -command as an argument to the script...

                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingFileArgument,
                            showHelp: true,
                            showBanner: true);
                        break;
                    }

                    // Don't show the startup banner unless -noexit has been specified.
                    if (!noexitSeen)
                    {
                        _showBanner = false;
                    }

                    // Process interactive input...
                    if (args[i] == "-")
                    {
                        // the arg to -file is -, which is secret code for "read the commands from stdin with prompts"

                        _explicitReadCommandsFromStdin = true;
                        _noPrompt = false;
                    }
                    else
                    {
                        // Exit on script completion unless -noexit was specified...
                        if (!noexitSeen)
                        {
                            _noExit = false;
                        }

                        // We need to get the full path to the script because it will be
                        // executed after the profiles are run and they may change the current
                        // directory.
                        string exceptionMessage = null;
                        try
                        {
                            // Normalize slashes
                            _file = args[i].Replace(StringLiterals.AlternatePathSeparator,
                                                    StringLiterals.DefaultPathSeparator);
                            _file = Path.GetFullPath(_file);
                        }
                        catch (Exception e)
                        {
                            // Catch all exceptions - we're just going to exit anyway so there's
                            // no issue of the system being destabilized.
                            exceptionMessage = e.Message;
                        }

                        if (exceptionMessage != null)
                        {
                            WriteCommandLineError(
                                string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgument, args[i], exceptionMessage),
                                showBanner: true);
                            break;
                        }

                        if (!Path.GetExtension(_file).Equals(".ps1", StringComparison.OrdinalIgnoreCase))
                        {
                            WriteCommandLineError(
                                string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, args[i]),
                                showBanner: true);
                            break;
                        }

                        if (!System.IO.File.Exists(_file))
                        {
                            WriteCommandLineError(
                                string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, args[i]),
                                showBanner: true);
                            break;
                        }

                        i++;

                        Regex  argPattern       = new Regex(@"^.\w+\:", RegexOptions.CultureInvariant);
                        string pendingParameter = null;

                        // Accumulate the arguments to this script...
                        while (i < args.Length)
                        {
                            string arg = args[i];

                            // If there was a pending parameter, add a named parameter
                            // using the pending parameter and current argument
                            if (pendingParameter != null)
                            {
                                _collectedArgs.Add(new CommandParameter(pendingParameter, arg));
                                pendingParameter = null;
                            }
                            else if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0]))
                            {
                                Match m = argPattern.Match(arg);
                                if (m.Success)
                                {
                                    int offset = arg.IndexOf(':');
                                    if (offset == arg.Length - 1)
                                    {
                                        pendingParameter = arg.TrimEnd(':');
                                    }
                                    else
                                    {
                                        _collectedArgs.Add(new CommandParameter(arg.Substring(0, offset), arg.Substring(offset + 1)));
                                    }
                                }
                                else
                                {
                                    _collectedArgs.Add(new CommandParameter(arg));
                                }
                            }
                            else
                            {
                                _collectedArgs.Add(new CommandParameter(null, arg));
                            }
                            ++i;
                        }
                    }
                    break;
                }
#if DEBUG
                // this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only
                // attach to an already running process with that debugger.
                else if (MatchSwitch(switchKey, "wait", "w"))
                {
                    // This does not need to be localized: its chk only

                    ((ConsoleHostUserInterface)_hostUI).WriteToConsole("Waiting - type enter to continue:", false);
                    _hostUI.ReadLine();
                }

                // this option is useful for testing the initial InitialSessionState experience
                else if (MatchSwitch(switchKey, "iss", "iss"))
                {
                    // Just toss this option, it was processed earlier...
                }

                // this option is useful for testing the initial InitialSessionState experience
                // this is independent of the normal wait switch because configuration processing
                // happens so early in the cycle...
                else if (MatchSwitch(switchKey, "isswait", "isswait"))
                {
                    // Just toss this option, it was processed earlier...
                }

                else if (MatchSwitch(switchKey, "modules", "mod"))
                {
                    if (ConsoleHost.DefaultInitialSessionState == null)
                    {
                        WriteCommandLineError(
                            "The -module option can only be specified with the -iss option.",
                            showHelp: true,
                            showBanner: true);
                        break;
                    }

                    ++i;
                    int moduleCount = 0;
                    // Accumulate the arguments to this script...
                    while (i < args.Length)
                    {
                        string arg = args[i];

                        if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0]))
                        {
                            break;
                        }
                        else
                        {
                            ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg });
                            moduleCount++;
                        }
                        ++i;
                    }
                    if (moduleCount < 1)
                    {
                        _hostUI.WriteErrorLine("No modules specified for -module option");
                    }
                }
#endif
                else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o"))
                {
                    ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "inputformat", "i") || MatchSwitch(switchKey, "if", "i"))
                {
                    ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep"))
                {
                    ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter);
                }
                else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e"))
                {
                    _wasCommandEncoded = true;
                    if (!ParseCommand(args, ref i, noexitSeen, true))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea"))
                {
                    if (!CollectArgs(args, ref i))
                    {
                        break;
                    }
                }
#if !CORECLR  // explicit setting of the ApartmentState Not supported on NanoServer
                else if (MatchSwitch(switchKey, "sta", "s"))
                {
                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = true;
                }
                // Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta.
                // Not deleting -sta for backward compatability reasons
                else if (MatchSwitch(switchKey, "mta", "mta"))
                {
                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = false;
                }
#endif
                else
                {
                    // The first parameter we fail to recognize marks the beginning of the command string.

                    --i;
                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }
                }
            }

            if (_showHelp)
            {
                ShowHelp();
            }

            if (_showBanner && !_showHelp)
            {
                DisplayBanner();
            }

            Dbg.Assert(
                ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) ||
                (_exitCode == ConsoleHost.ExitCodeSuccess),
                "if exit code is failure, then abortstartup should be true");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Processes records from the input pipeline.
        /// For each input object, the command gets or
        /// sets the digital signature on the object, and
        /// and exports the object.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (Content == null)
            {
                //
                // this cannot happen as we have specified the Path
                // property to be mandatory parameter
                //
                Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
                           "GetSignatureCommand: Param binder did not bind path");

                foreach (string p in FilePath)
                {
                    Collection <string> paths = new();

                    // Expand wildcard characters
                    if (_isLiteralPath)
                    {
                        paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
                    }
                    else
                    {
                        try
                        {
                            foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
                            {
                                paths.Add(tempPath.ProviderPath);
                            }
                        }
                        catch (ItemNotFoundException)
                        {
                            WriteError(
                                SecurityUtils.CreateFileNotFoundErrorRecord(
                                    SignatureCommands.FileNotFound,
                                    "SignatureCommandsBaseFileNotFound", p));
                        }
                    }

                    if (paths.Count == 0)
                    {
                        continue;
                    }

                    bool foundFile = false;

                    foreach (string path in paths)
                    {
                        if (!System.IO.Directory.Exists(path))
                        {
                            foundFile = true;

                            string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path);

                            if (resolvedFilePath == null)
                            {
                                WriteError(SecurityUtils.CreateFileNotFoundErrorRecord(
                                               SignatureCommands.FileNotFound,
                                               "SignatureCommandsBaseFileNotFound",
                                               path));
                            }
                            else
                            {
                                if ((Signature = PerformAction(resolvedFilePath)) != null)
                                {
                                    WriteObject(Signature);
                                }
                            }
                        }
                    }

                    if (!foundFile)
                    {
                        WriteError(SecurityUtils.CreateFileNotFoundErrorRecord(
                                       SignatureCommands.CannotRetrieveFromContainer,
                                       "SignatureCommandsBaseCannotRetrieveFromContainer"));
                    }
                }
            }
            else
            {
                foreach (string sourcePathOrExtension in SourcePathOrExtension)
                {
                    if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null)
                    {
                        WriteObject(Signature);
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// This method implements the BeginProcessing method for get-random command.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (SetSeed.HasValue)
            {
                Generator = new PolymorphicRandomNumberGenerator(SetSeed.Value);
            }

            if (EffectiveParameterSet == MyParameterSet.RandomNumber)
            {
                object maxOperand = ProcessOperand(Maximum);
                object minOperand = ProcessOperand(Minimum);

                if (IsInt(maxOperand) && IsInt(minOperand))
                {
                    int minValue = minOperand != null ? (int)minOperand : 0;
                    int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue;

                    if (minValue >= maxValue)
                    {
                        ThrowMinGreaterThanOrEqualMax(minValue, maxValue);
                    }

                    for (int i = 0; i < Count; i++)
                    {
                        int randomNumber = Generator.Next(minValue, maxValue);
                        Debug.Assert(minValue <= randomNumber, "lower bound <= random number");
                        Debug.Assert(randomNumber < maxValue, "random number < upper bound");

                        WriteObject(randomNumber);
                    }
                }
                else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand)))
                {
                    Int64 minValue = minOperand != null ? ((minOperand is Int64) ? (Int64)minOperand : (int)minOperand) : 0;
                    Int64 maxValue = maxOperand != null ? ((maxOperand is Int64) ? (Int64)maxOperand : (int)maxOperand) : Int64.MaxValue;

                    if (minValue >= maxValue)
                    {
                        ThrowMinGreaterThanOrEqualMax(minValue, maxValue);
                    }

                    for (int i = 0; i < Count; i++)
                    {
                        Int64 randomNumber = GetRandomInt64(minValue, maxValue);
                        Debug.Assert(minValue <= randomNumber, "lower bound <= random number");
                        Debug.Assert(randomNumber < maxValue, "random number < upper bound");

                        WriteObject(randomNumber);
                    }
                }
                else
                {
                    double minValue = (minOperand is double) ? (double)minOperand : ConvertToDouble(Minimum, 0.0);
                    double maxValue = (maxOperand is double) ? (double)maxOperand : ConvertToDouble(Maximum, double.MaxValue);

                    if (minValue >= maxValue)
                    {
                        ThrowMinGreaterThanOrEqualMax(minValue, maxValue);
                    }

                    for (int i = 0; i < Count; i++)
                    {
                        double randomNumber = GetRandomDouble(minValue, maxValue);
                        Debug.Assert(minValue <= randomNumber, "lower bound <= random number");
                        Debug.Assert(randomNumber < maxValue, "random number < upper bound");

                        WriteObject(randomNumber);
                    }
                }
            }
            else if (EffectiveParameterSet == MyParameterSet.RandomListItem)
            {
                _chosenListItems            = new List <object>();
                _numberOfProcessedListItems = 0;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Executes a pipeline in the console when we are running asnyc.
        /// </summary>
        /// <param name="tempPipeline">
        /// The pipeline to execute.
        /// </param>
        /// <param name="exceptionThrown">
        /// Any exception thrown trying to run the pipeline.
        /// </param>
        /// <param name="options">
        /// The options to use to execute the pipeline.
        /// </param>
        internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
        {
            Dbg.Assert(!_isPromptFunctionExecutor, "should not async invoke the prompt");

            exceptionThrown = null;
            Executor oldCurrent = CurrentExecutor;

            CurrentExecutor = this;

            lock (_instanceStateLock)
            {
                Dbg.Assert(_pipeline == null, "no other pipeline should exist");
                _pipeline = tempPipeline;
            }

            try
            {
                if ((options & ExecutionOptions.AddOutputter) > 0 && _parent.OutputFormat == Serialization.DataFormat.Text)
                {
                    // Tell the script command to merge it's output and error streams

                    if (tempPipeline.Commands.Count == 1)
                    {
                        tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    }

                    // then add out-default to the pipeline to render everything...
                    Command outDefault = new Command("Out-Default", /* isScript */ false, /* useLocalScope */ true);
                    tempPipeline.Commands.Add(outDefault);
                }

                tempPipeline.Output.DataReady += OutputObjectStreamHandler;
                tempPipeline.Error.DataReady  += ErrorObjectStreamHandler;
                PipelineFinishedWaitHandle pipelineWaiter = new PipelineFinishedWaitHandle(tempPipeline);

                // close the input pipeline so the command will do something
                // if we are not reading input
                if ((options & Executor.ExecutionOptions.ReadInputObjects) == 0)
                {
                    tempPipeline.Input.Close();
                }

                tempPipeline.InvokeAsync();
                if ((options & ExecutionOptions.ReadInputObjects) > 0 && Console.IsInputRedirected)
                {
                    // read input objects from stdin
                    WrappedDeserializer des = new WrappedDeserializer(_parent.InputFormat, "Input", _parent.ConsoleIn.Value);
                    while (!des.AtEnd)
                    {
                        object o = des.Deserialize();
                        if (o == null)
                        {
                            break;
                        }

                        try
                        {
                            tempPipeline.Input.Write(o);
                        }
                        catch (PipelineClosedException)
                        {
                            // This exception can occurs when input is closed. This can happen
                            // for various reasons. For ex:Command in the pipeline is invalid and
                            // command discovery throws exception which closes the pipeline and
                            // hence the Input pipe.
                            break;
                        }
                    }
                    des.End();
                }

                tempPipeline.Input.Close();

                pipelineWaiter.Wait();

                // report error if pipeline failed
                if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null)
                {
                    if (_parent.OutputFormat == Serialization.DataFormat.Text)
                    {
                        // Report the exception using normal error reporting
                        exceptionThrown = tempPipeline.PipelineStateInfo.Reason;
                    }
                    else
                    {
                        // serialize the error record
                        AsyncPipelineFailureHandler(tempPipeline.PipelineStateInfo.Reason);
                    }
                }
            }
            catch (Exception e)
            {
                exceptionThrown = e;
            }
            finally
            {
                // Once we have the results, or an exception is thrown, we throw away the pipeline.

                _parent.ui.ResetProgress();
                CurrentExecutor = oldCurrent;
                Reset();
            }
        }
Ejemplo n.º 22
0
 internal Pipeline CreatePipeline(string command, bool addToHistory)
 {
     Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value");
     return(_parent.RunspaceRef.CreatePipeline(command, addToHistory, useNestedPipelines));
 }
Ejemplo n.º 23
0
        internal static Type GetCimType(Type dotNetType)
        {
            if (dotNetType.IsArray)
            {
                return(GetCimType(GetElementType(dotNetType)).MakeArrayType());
            }

            if (dotNetType.GetTypeInfo().IsGenericType&& dotNetType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                return(GetCimType(dotNetType.GetGenericArguments()[0]));
            }

            if (LanguagePrimitives.IsCimIntrinsicScalarType(dotNetType))
            {
                return(dotNetType);
            }

            if (dotNetType == typeof(CimInstance))
            {
                return(dotNetType);
            }

            if (dotNetType == typeof(PSReference))
            {
                return(dotNetType);
            }

            Type result = CimValueConverter.GetConvertibleCimType(dotNetType);

            if (result != null)
            {
                return(result);
            }

            if (typeof(ObjectSecurity).IsAssignableFrom(dotNetType))
            {
                return(typeof(string));
            }

            if (typeof(X509Certificate2) == dotNetType)
            {
                return(typeof(byte[]));
            }

            if (typeof(X500DistinguishedName) == dotNetType)
            {
                return(typeof(byte[]));
            }

            if (typeof(PhysicalAddress) == dotNetType)
            {
                return(typeof(string));
            }

            if (typeof(IPEndPoint) == dotNetType)
            {
                return(typeof(string));
            }

            if (typeof(WildcardPattern) == dotNetType)
            {
                return(typeof(string));
            }

            if (typeof(XmlDocument) == dotNetType)
            {
                return(typeof(string));
            }

            if (typeof(PSCredential) == dotNetType)
            {
                return(typeof(string));
            }

            Dbg.Assert(false, ".NET Type that is not supported in a .NET <-> CIM conversion");
            return(null);
        }
Ejemplo n.º 24
0
        internal Collection <PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
        {
            Dbg.Assert(tempPipeline != null, "command should have a value");

            exceptionThrown = null;

            Collection <PSObject> results = null;

            if ((options & ExecutionOptions.AddOutputter) > 0)
            {
                if (tempPipeline.Commands.Count < 2)
                {
                    if (tempPipeline.Commands.Count == 1)
                    {
                        // Tell the script command to merge it's output and error streams.
                        tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    }

                    // Add Out-Default to the pipeline to render.
                    tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false));
                }
                else
                {
                    // For multiple commands/scripts we need to insert Out-Default at the end of each statement.
                    CommandCollection executeCommands = new CommandCollection();
                    foreach (var cmd in tempPipeline.Commands)
                    {
                        executeCommands.Add(cmd);

                        if (cmd.IsEndOfStatement)
                        {
                            // End of statement needs to pipe to Out-Default.
                            cmd.IsEndOfStatement = false;
                            executeCommands.Add(GetOutDefaultCommand(endOfStatement: true));
                        }
                    }

                    var lastCmd = executeCommands.Last();
                    if (!((lastCmd.CommandText != null) &&
                          (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase)))
                        )
                    {
                        // Ensure pipeline output goes to Out-Default.
                        executeCommands.Add(GetOutDefaultCommand(endOfStatement: false));
                    }

                    tempPipeline.Commands.Clear();
                    foreach (var cmd in executeCommands)
                    {
                        tempPipeline.Commands.Add(cmd);
                    }
                }
            }

            Executor oldCurrent = CurrentExecutor;

            CurrentExecutor = this;

            lock (_instanceStateLock)
            {
                Dbg.Assert(_pipeline == null, "no other pipeline should exist");
                _pipeline = tempPipeline;
            }

            try
            {
                // blocks until all results are retrieved.
                results = tempPipeline.Invoke();
            }
            catch (Exception e)
            {
                exceptionThrown = e;
            }
            finally
            {
                // Once we have the results, or an exception is thrown, we throw away the pipeline.

                _parent.ui.ResetProgress();
                CurrentExecutor = oldCurrent;
                Reset();
            }

            return(results);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Saves the current console info into a file.
        /// </summary>
        protected override void ProcessRecord()
        {
            // Get filename..
            string file = GetFileName();

            // if file is null or empty..prompt the user for filename
            if (string.IsNullOrEmpty(file))
            {
                file = PromptUserForFile();
            }

            // if file is still empty..write error and back out..
            if (string.IsNullOrEmpty(file))
            {
                PSArgumentException ae = PSTraceSource.NewArgumentException("file", ConsoleInfoErrorStrings.FileNameNotResolved);
                ThrowError(file, "FileNameNotResolved", ae, ErrorCategory.InvalidArgument);
            }

            if (WildcardPattern.ContainsWildcardCharacters(file))
            {
                ThrowError(file, "WildCardNotSupported",
                           PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ConsoleFileWildCardsNotSupported,
                                                                      file), ErrorCategory.InvalidOperation);
            }

            // Ofcourse, you cant write to a file from HKLM: etc..
            string resolvedPath = ResolveProviderAndPath(file);

            // If resolvedPath is empty just return..
            if (string.IsNullOrEmpty(resolvedPath))
            {
                return;
            }

            // Check whether the file ends with valid extension
            if (!resolvedPath.EndsWith(StringLiterals.PowerShellConsoleFileExtension,
                                       StringComparison.OrdinalIgnoreCase))
            {
                // file does not end with proper extension..create one..
                resolvedPath = resolvedPath + StringLiterals.PowerShellConsoleFileExtension;
            }

            if (!ShouldProcess(this.Path)) // should this be resolvedPath?
            {
                return;
            }

            //check if destination file exists.
            if (File.Exists(resolvedPath))
            {
                if (NoClobber)
                {
                    string message = StringUtil.Format(
                        ConsoleInfoErrorStrings.FileExistsNoClobber,
                        resolvedPath,
                        "NoClobber"); // prevents localization
                    Exception   uae         = new UnauthorizedAccessException(message);
                    ErrorRecord errorRecord = new ErrorRecord(
                        uae, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
                    // NOTE: this call will throw
                    ThrowTerminatingError(errorRecord);
                }
                // Check if the file is read-only
                System.IO.FileAttributes attrib = System.IO.File.GetAttributes(resolvedPath);
                if ((attrib & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                {
                    if (Force)
                    {
                        RemoveFileThrowIfError(resolvedPath);
                        // Note, we do not attempt to set read-only on the new file
                    }
                    else
                    {
                        ThrowError(file, "ConsoleFileReadOnly",
                                   PSTraceSource.NewArgumentException(file, ConsoleInfoErrorStrings.ConsoleFileReadOnly, resolvedPath),
                                   ErrorCategory.InvalidArgument);
                    }
                }
            }

            try
            {
                if (this.Runspace != null)
                {
                    this.Runspace.SaveAsConsoleFile(resolvedPath);
                }
                else if (InitialSessionState != null)
                {
                    this.InitialSessionState.SaveAsConsoleFile(resolvedPath);
                }
                else
                {
                    Dbg.Assert(false, "Both RunspaceConfiguration and InitialSessionState should not be null");
                    throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.CmdletNotAvailable);
                }
            }
            catch (PSArgumentException mae)
            {
                ThrowError(resolvedPath,
                           "PathNotAbsolute", mae, ErrorCategory.InvalidArgument);
            }
            catch (PSArgumentNullException mane)
            {
                ThrowError(resolvedPath,
                           "PathNull", mane, ErrorCategory.InvalidArgument);
            }
            catch (ArgumentException ae)
            {
                ThrowError(resolvedPath,
                           "InvalidCharactersInPath", ae, ErrorCategory.InvalidArgument);
            }

            // looks like saving succeeded.
            // Now try changing $console
            Exception e = null;

            try
            {
                //Update $Console variable
                Context.EngineSessionState.SetConsoleVariable();
            }
            catch (ArgumentNullException ane)
            {
                e = ane;
            }
            catch (ArgumentOutOfRangeException aor)
            {
                e = aor;
            }
            catch (ArgumentException ae)
            {
                e = ae;
            }
            catch (SessionStateUnauthorizedAccessException sue)
            {
                e = sue;
            }
            catch (SessionStateOverflowException sof)
            {
                e = sof;
            }
            catch (ProviderNotFoundException pnf)
            {
                e = pnf;
            }
            catch (System.Management.Automation.DriveNotFoundException dnfe)
            {
                e = dnfe;
            }
            catch (NotSupportedException ne)
            {
                e = ne;
            }
            catch (ProviderInvocationException pin)
            {
                e = pin;
            }

            if (e != null)
            {
                throw PSTraceSource.NewInvalidOperationException(e,
                                                                 ConsoleInfoErrorStrings.ConsoleVariableCannotBeSet, resolvedPath);
            }
        }
Ejemplo n.º 26
0
        CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
        {
            Dbg.Assert(_topLevelNodes != null, "Shouldn't need to compress if no data exists");

            int nodesCompressed = 0;

            // This algorithm potentially makes many, many passeses over the tree.  It might be possible to optimize
            // that some, but I'm not trying to be too clever just yet.

            if (
                CompressToFitHelper(
                    rawUi,
                    maxHeight,
                    maxWidth,
                    out nodesCompressed,
                    ProgressNode.RenderStyle.FullPlus,
                    ProgressNode.RenderStyle.Full))
            {
                return(0);
            }

            if (
                CompressToFitHelper(
                    rawUi,
                    maxHeight,
                    maxWidth,
                    out nodesCompressed,
                    ProgressNode.RenderStyle.Full,
                    ProgressNode.RenderStyle.Compact))
            {
                return(0);
            }

            if (
                CompressToFitHelper(
                    rawUi,
                    maxHeight,
                    maxWidth,
                    out nodesCompressed,
                    ProgressNode.RenderStyle.Compact,
                    ProgressNode.RenderStyle.Minimal))
            {
                return(0);
            }

            if (
                CompressToFitHelper(
                    rawUi,
                    maxHeight,
                    maxWidth,
                    out nodesCompressed,
                    ProgressNode.RenderStyle.Minimal,
                    ProgressNode.RenderStyle.Invisible))
            {
                // The nodes that we compressed here are now invisible.

                return(nodesCompressed);
            }

            Dbg.Assert(false, "with all nodes invisible, we should never reach this point.");

            return(0);
        }
Ejemplo n.º 27
0
        Update(Int64 sourceId, ProgressRecord record)
        {
            Dbg.Assert(record != null, "record should not be null");

            do
            {
                if (record.ParentActivityId == record.ActivityId)
                {
                    // ignore malformed records.
                    break;
                }

                ArrayList    listWhereFound  = null;
                int          indexWhereFound = -1;
                ProgressNode foundNode       =
                    FindNodeById(sourceId, record.ActivityId, out listWhereFound, out indexWhereFound);

                if (foundNode != null)
                {
                    Dbg.Assert(listWhereFound != null, "node found, but list not identified");
                    Dbg.Assert(indexWhereFound >= 0, "node found, but index not returned");

                    if (record.RecordType == ProgressRecordType.Completed)
                    {
                        RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound);
                        break;
                    }
                    if (record.ParentActivityId == foundNode.ParentActivityId)
                    {
                        // record is an update to an existing activity. Copy the record data into the found node, and
                        // reset the age of the node.

                        foundNode.Activity          = record.Activity;
                        foundNode.StatusDescription = record.StatusDescription;
                        foundNode.CurrentOperation  = record.CurrentOperation;
                        foundNode.PercentComplete   = Math.Min(record.PercentComplete, 100);
                        foundNode.SecondsRemaining  = record.SecondsRemaining;
                        foundNode.Age = 0;
                        break;
                    }
                    else
                    {
                        // The record's parent Id mismatches with that of the found node's.  We interpret
                        // this to mean that the activity represented by the record (and the found node) is
                        // being "re-parented" elsewhere. So we remove the found node and treat the record
                        // as a new activity.

                        RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound);
                    }
                }

                // At this point, the record's activity is not in the tree. So we need to add it.

                if (record.RecordType == ProgressRecordType.Completed)
                {
                    // We don't track completion records that don't correspond to activities we're not
                    // already tracking.

                    break;
                }

                ProgressNode newNode = new ProgressNode(sourceId, record);

                // If we're adding a node, and we have no more space, then we need to pick a node to evict.

                while (_nodeCount >= maxNodeCount)
                {
                    EvictNode();
                }

                if (newNode.ParentActivityId >= 0)
                {
                    ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId);
                    if (parentNode != null)
                    {
                        if (parentNode.Children == null)
                        {
                            parentNode.Children = new ArrayList();
                        }

                        AddNode(parentNode.Children, newNode);
                        break;
                    }

                    // The parent node is not in the tree. Make the new node's parent the root,
                    // and add it to the tree.  If the parent ever shows up, then the next time
                    // we receive a record for this activity, the parent id's won't match, and the
                    // activity will be properly re-parented.

                    newNode.ParentActivityId = -1;
                }

                AddNode(_topLevelNodes, newNode);
            } while (false);

            // At this point the tree is up-to-date.  Make a pass to age all of the nodes

            AgeNodesAndResetStyle();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Processes records from the input pipeline.
        /// For each input file, the command retrieves its
        /// corresponding certificate.
        /// </summary>
        protected override void ProcessRecord()
        {
            //
            // this cannot happen as we have specified the Path
            // property to be a mandatory parameter
            //
            Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
                       "GetCertificateCommand: Param binder did not bind path");

            X509Certificate2 cert = null;

            foreach (string p in FilePath)
            {
                List <string> paths = new List <string>();

                // Expand wildcard characters
                if (_isLiteralPath)
                {
                    paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
                }
                else
                {
                    try
                    {
                        foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
                        {
                            paths.Add(tempPath.ProviderPath);
                        }
                    }
                    catch (ItemNotFoundException)
                    {
                        _filesNotFound.Add(p);
                    }
                }

                foreach (string resolvedPath in paths)
                {
                    string resolvedProviderPath =
                        SecurityUtils.GetFilePathOfExistingFile(this, resolvedPath);

                    if (resolvedProviderPath == null)
                    {
                        _filesNotFound.Add(p);
                    }
                    else
                    {
                        if (Password == null && !NoPromptForPassword.IsPresent)
                        {
                            try
                            {
                                cert = GetCertFromPfxFile(resolvedProviderPath, null);
                                WriteObject(cert);
                                continue;
                            }
                            catch (CryptographicException)
                            {
                                Password = SecurityUtils.PromptForSecureString(
                                    Host.UI,
                                    CertificateCommands.GetPfxCertPasswordPrompt);
                            }
                        }

                        try
                        {
                            cert = GetCertFromPfxFile(resolvedProviderPath, Password);
                        }
                        catch (CryptographicException e)
                        {
                            ErrorRecord er =
                                new ErrorRecord(e,
                                                "GetPfxCertificateUnknownCryptoError",
                                                ErrorCategory.NotSpecified,
                                                null);
                            WriteError(er);
                            continue;
                        }

                        WriteObject(cert);
                    }
                }
            }

            if (_filesNotFound.Count > 0)
            {
                if (_filesNotFound.Count == FilePath.Length)
                {
                    ErrorRecord er =
                        SecurityUtils.CreateFileNotFoundErrorRecord(
                            CertificateCommands.NoneOfTheFilesFound,
                            "GetPfxCertCommandNoneOfTheFilesFound");

                    ThrowTerminatingError(er);
                }
                else
                {
                    //
                    // we found some files but not others.
                    // Write error for each missing file
                    //
                    foreach (string f in _filesNotFound)
                    {
                        ErrorRecord er =
                            SecurityUtils.CreateFileNotFoundErrorRecord(
                                CertificateCommands.FileNotFound,
                                "GetPfxCertCommandFileNotFound",
                                f
                                );

                        WriteError(er);
                    }
                }
            }
        }
        private void ParseHelper(string[] args)
        {
            Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null");
            bool noexitSeen = false;

            for (int i = 0; i < args.Length; ++i)
            {
                // Invariant culture used because command-line parameters are not localized.

                string switchKey = args[i].Trim().ToLowerInvariant();
                if (String.IsNullOrEmpty(switchKey))
                {
                    continue;
                }

                if (!SpecialCharacters.IsDash(switchKey[0]) && switchKey[0] != '/')
                {
                    // then its a file

                    --i;
                    ParseFile(args, ref i, noexitSeen);
                    break;
                }

                // chop off the first character so that we're agnostic wrt specifying / or -
                // in front of the switch name.
                switchKey = switchKey.Substring(1);

                // chop off the second dash so we're agnostic wrt specifying - or --
                if (!String.IsNullOrEmpty(switchKey) && SpecialCharacters.IsDash(switchKey[0]))
                {
                    switchKey = switchKey.Substring(1);
                }

                // If version is in the commandline, don't continue to look at any other parameters
                if (MatchSwitch(switchKey, "version", "v"))
                {
                    _showVersion   = true;
                    _showBanner    = false;
                    _noInteractive = true;
                    _skipUserInit  = true;
                    _noExit        = false;
                    break;
                }
                else if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?"))
                {
                    _showHelp         = true;
                    _showExtendedHelp = true;
                    _abortStartup     = true;
                }
                else if (MatchSwitch(switchKey, "noexit", "noe"))
                {
                    _noExit    = true;
                    noexitSeen = true;
                }
                else if (MatchSwitch(switchKey, "noprofile", "nop"))
                {
                    _skipUserInit = true;
                }
                else if (MatchSwitch(switchKey, "nologo", "nol"))
                {
                    _showBanner = false;
                }
                else if (MatchSwitch(switchKey, "noninteractive", "noni"))
                {
                    _noInteractive = true;
                }
                else if (MatchSwitch(switchKey, "socketservermode", "so"))
                {
                    _socketServerMode = true;
                }
                else if (MatchSwitch(switchKey, "servermode", "s"))
                {
                    _serverMode = true;
                }
                else if (MatchSwitch(switchKey, "namedpipeservermode", "nam"))
                {
                    _namedPipeServerMode = true;
                }
                else if (MatchSwitch(switchKey, "sshservermode", "sshs"))
                {
                    _sshServerMode = true;
                }
                else if (MatchSwitch(switchKey, "interactive", "i"))
                {
                    _noInteractive = false;
                }
                else if (MatchSwitch(switchKey, "configurationname", "config"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingConfigurationNameArgument);
                        break;
                    }

                    _configurationName = args[i];
                }
                else if (MatchSwitch(switchKey, "command", "c"))
                {
                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "windowstyle", "w"))
                {
#if UNIX
                    WriteCommandLineError(
                        CommandLineParameterParserStrings.WindowStyleArgumentNotImplemented);
                    break;
#else
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingWindowStyleArgument);
                        break;
                    }

                    try
                    {
                        ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo(
                            args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture);
                        ConsoleControl.SetConsoleMode(style);
                    }
                    catch (PSInvalidCastException e)
                    {
                        WriteCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message));
                        break;
                    }
#endif
                }
                else if (MatchSwitch(switchKey, "file", "f"))
                {
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }
                }
#if DEBUG
                // this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only
                // attach to an already running process with that debugger.
                else if (MatchSwitch(switchKey, "wait", "w"))
                {
                    // This does not need to be localized: its chk only

                    ((ConsoleHostUserInterface)_hostUI).WriteToConsole("Waiting - type enter to continue:", false);
                    _hostUI.ReadLine();
                }

                // this option is useful for testing the initial InitialSessionState experience
                else if (MatchSwitch(switchKey, "iss", "iss"))
                {
                    // Just toss this option, it was processed earlier...
                }

                // this option is useful for testing the initial InitialSessionState experience
                // this is independent of the normal wait switch because configuration processing
                // happens so early in the cycle...
                else if (MatchSwitch(switchKey, "isswait", "isswait"))
                {
                    // Just toss this option, it was processed earlier...
                }

                else if (MatchSwitch(switchKey, "modules", "mod"))
                {
                    if (ConsoleHost.DefaultInitialSessionState == null)
                    {
                        WriteCommandLineError(
                            "The -module option can only be specified with the -iss option.",
                            showHelp: true,
                            showBanner: false);
                        break;
                    }

                    ++i;
                    int moduleCount = 0;
                    // Accumulate the arguments to this script...
                    while (i < args.Length)
                    {
                        string arg = args[i];

                        if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0]))
                        {
                            break;
                        }
                        else
                        {
                            ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg });
                            moduleCount++;
                        }
                        ++i;
                    }
                    if (moduleCount < 1)
                    {
                        _hostUI.WriteErrorLine("No modules specified for -module option");
                    }
                }
#endif
                else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o"))
                {
                    ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "inputformat", "in") || MatchSwitch(switchKey, "if", "if"))
                {
                    ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep"))
                {
                    ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter);
                }
                else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e"))
                {
                    _wasCommandEncoded = true;
                    if (!ParseCommand(args, ref i, noexitSeen, true))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea"))
                {
                    if (!CollectArgs(args, ref i))
                    {
                        break;
                    }
                }

                else if (MatchSwitch(switchKey, "settingsfile", "settings"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingSettingsFileArgument);
                        break;
                    }
                    string configFile = null;
                    try
                    {
                        configFile = NormalizeFilePath(args[i]);
                    }
                    catch (Exception ex)
                    {
                        string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidSettingsFileArgument, args[i], ex.Message);
                        WriteCommandLineError(error);
                        break;
                    }

                    if (!System.IO.File.Exists(configFile))
                    {
                        string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.SettingsFileNotExists, configFile);
                        WriteCommandLineError(error);
                        break;
                    }
                    PowerShellConfig.Instance.SetSystemConfigFilePath(configFile);
                }
#if STAMODE
                // explicit setting of the ApartmentState Not supported on NanoServer
                else if (MatchSwitch(switchKey, "sta", "s"))
                {
                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = true;
                }
                // Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta.
                // Not deleting -sta for backward compatability reasons
                else if (MatchSwitch(switchKey, "mta", "mta"))
                {
                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = false;
                }
#endif
                else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingWorkingDirectoryArgument);
                        break;
                    }

                    _workingDirectory = args[i];
                }
                else
                {
                    // The first parameter we fail to recognize marks the beginning of the file string.

                    --i;
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }
                }
            }

            if (_showHelp)
            {
                ShowHelp();
            }

            if (_showBanner && !_showHelp)
            {
                DisplayBanner();
            }

            Dbg.Assert(
                ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) ||
                (_exitCode == ConsoleHost.ExitCodeSuccess),
                "if exit code is failure, then abortstartup should be true");
        }
Ejemplo n.º 30
0
        /// <exception cref="PSInvalidCastException">The only kind of exception this method can throw.</exception>
        internal static object ConvertFromDotNetToCim(object dotNetObject)
        {
            if (dotNetObject == null)
            {
                return(null);
            }

            PSObject psObject   = PSObject.AsPSObject(dotNetObject);
            Type     dotNetType = psObject.BaseObject.GetType();

            Dbg.Assert(
                !(dotNetType.GetTypeInfo().IsGenericType&& dotNetType.GetGenericTypeDefinition() == typeof(Nullable <>)),
                "GetType on a boxed object should never return Nullable<T>");

            if (LanguagePrimitives.IsCimIntrinsicScalarType(dotNetType))
            {
                return(psObject.BaseObject);
            }

            if (typeof(CimInstance).IsAssignableFrom(dotNetType))
            {
                return(psObject.BaseObject);
            }

            if (typeof(PSReference).IsAssignableFrom(dotNetType))
            {
                PSReference psReference = (PSReference)psObject.BaseObject;
                if (psReference.Value == null)
                {
                    return(null);
                }
                else
                {
                    PSObject innerPso = PSObject.AsPSObject(psReference.Value);
                    return(ConvertFromDotNetToCim(innerPso.BaseObject));
                }
            }

            if (dotNetType.IsArray)
            {
                Type dotNetElementType = GetElementType(dotNetType);
                if (dotNetElementType != null)
                {
                    var   dotNetArray    = (Array)psObject.BaseObject;
                    Type  cimElementType = CimValueConverter.GetCimType(dotNetElementType);
                    Array cimArray       = Array.CreateInstance(cimElementType, dotNetArray.Length);
                    for (int i = 0; i < cimArray.Length; i++)
                    {
                        object cimElement = ConvertFromDotNetToCim(dotNetArray.GetValue(i));
                        cimArray.SetValue(cimElement, i);
                    }

                    return(cimArray);
                }
            }

            Type convertibleCimType = GetConvertibleCimType(dotNetType);

            if (convertibleCimType != null)
            {
                object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, convertibleCimType, CultureInfo.InvariantCulture);
                return(cimIntrinsicValue);
            }

            if (typeof(ObjectSecurity).IsAssignableFrom(dotNetType))
            {
                string cimIntrinsicValue = Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase.GetSddl(psObject);
                return(cimIntrinsicValue);
            }

            if (typeof(X509Certificate2).IsAssignableFrom(dotNetType))
            {
                var    cert = (X509Certificate2)(psObject.BaseObject);
                byte[] cimIntrinsicValue = cert.RawData;
                return(cimIntrinsicValue);
            }

            if (typeof(X500DistinguishedName).IsAssignableFrom(dotNetType))
            {
                var    x500name          = (X500DistinguishedName)(psObject.BaseObject);
                byte[] cimIntrinsicValue = x500name.RawData;
                return(cimIntrinsicValue);
            }

            if (typeof(PhysicalAddress).IsAssignableFrom(dotNetType))
            {
                object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, typeof(string), CultureInfo.InvariantCulture);
                return(cimIntrinsicValue);
            }

            if (typeof(IPEndPoint).IsAssignableFrom(dotNetType))
            {
                object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, typeof(string), CultureInfo.InvariantCulture);
                return(cimIntrinsicValue);
            }

            if (typeof(WildcardPattern).IsAssignableFrom(dotNetType))
            {
                var wildcardPattern = (WildcardPattern)(psObject.BaseObject);
                return(wildcardPattern.ToWql());
            }

            if (typeof(XmlDocument).IsAssignableFrom(dotNetType))
            {
                var    xmlDocument       = (XmlDocument)(psObject.BaseObject);
                string cimIntrinsicValue = xmlDocument.OuterXml;
                return(cimIntrinsicValue);
            }

            // unrecognized type = throw invalid cast exception
            throw CimValueConverter.GetInvalidCastException(
                      null, /* inner exception */
                      "InvalidDotNetToCimCast",
                      dotNetObject,
                      CmdletizationResources.CimConversion_CimIntrinsicValue);
        }