/// <summary>
        /// A helper method for creating an object that represents a total count
        /// of objects that the cmdlet would return without paging
        /// (this can be more than the size of the page specified in the <see cref="First"/> cmdlet parameter).
        /// </summary>
        /// <param name="totalCount">A total count of objects that the cmdlet would return without paging.</param>
        /// <param name="accuracy">
        /// accuracy of the <paramref name="totalCount"/> parameter.
        /// <c>1.0</c> means 100% accurate;
        /// <c>0.0</c> means that total count is unknown;
        /// anything in-between means that total count is estimated
        /// </param>
        /// <returns>An object that represents a total count of objects that the cmdlet would return without paging.</returns>
        public PSObject NewTotalCount(UInt64 totalCount, double accuracy)
        {
            PSObject result = new PSObject(totalCount);

            string toStringMethodBody = string.Format(
                CultureInfo.CurrentCulture,
                @"
                    $totalCount = $this.PSObject.BaseObject
                    switch ($this.Accuracy) {{
                        {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}
                        {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}
                        default          {{ '{2}' -f $totalCount }}
                    }}
                ",
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate),
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate),
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate));
            PSScriptMethod toStringMethod = new PSScriptMethod("ToString", ScriptBlock.Create(toStringMethodBody));

            result.Members.Add(toStringMethod);

            accuracy = Math.Max(0.0, Math.Min(1.0, accuracy));
            PSNoteProperty statusProperty = new PSNoteProperty("Accuracy", accuracy);

            result.Members.Add(statusProperty);

            return(result);
        }
        protected override void ProcessRecord()
        {
            if (!MyInvocation.BoundParameters.ContainsKey(nameof(ListItemText)))
            {
                ListItemText = CompletionText;
            }
            if (!MyInvocation.BoundParameters.ContainsKey(nameof(ToolTip)))
            {
                ToolTip = CompletionText;
            }
            string completionText;

            if (DoNotEscape)
            {
                completionText = CompletionText;
            }
            else
            {
                var temp = CodeGeneration.EscapeSingleQuotedStringContent(CompletionText);
                if (temp.Contains(" ") || temp.Contains("'"))
                {
                    completionText = "'" + temp + "'";
                }
                else
                {
                    completionText = temp;
                }
            }
            WriteObject(new CompletionResult(completionText, ListItemText, ResultType, ToolTip));
        }
示例#3
0
        protected override void ProcessRecord()
        {
            var jobNames = Name?
                           .Select(i => WildcardPattern.Get(i, WildcardOptions.IgnoreCase))
                           ?? new[] { WildcardPattern.Get("*", WildcardOptions.IgnoreCase) };
            var printerNames = PrinterName?
                               .Select(i => CodeGeneration.EscapeSingleQuotedStringContent(WildcardPattern.Get(i, WildcardOptions.IgnoreCase).ToWql()))
                               ?? new string[] { "%" };

            if (ParameterSetName == DefaultSet)
            {
                foreach (var sn in Session !)
                {
                    foreach (var printerName in printerNames)
                    {
                        try
                        {
                            var printers = sn.QueryInstances("root/standardcimv2", "WQL", $"select * from msft_printer where Name like '{printerName}'", _options);
                            foreach (var printer in printers)
                            {
                                var parameters = new CimMethodParametersCollection()
                                {
                                    CimMethodParameter.Create("PrinterObject", printer, CimType.Instance, CimFlags.In)
                                };
                                var methodResult = sn.InvokeMethod("root/standardcimv2", "msft_printjob", "GetByObject", parameters, _options);
                                var jobs         = (IEnumerable <CimInstance>)methodResult.OutParameters["cmdletOutput"].Value;
                                WriteObject(methodResult.OutParameters);
                                Console.WriteLine("checking jobs");
                                jobs.GetEnumerator();
                                Console.WriteLine("Got enumerator");
                                foreach (var job in jobs)
                                {
                                    Console.WriteLine("creating job");
                                    var psjob = new PSPrintJob(job);
                                    Console.WriteLine("job created");
                                    if (jobNames.Any(i => i.IsMatch(psjob.Name)))
                                    {
                                        WriteObject(psjob);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            WriteError(new ErrorRecord(e, "not good", ErrorCategory.NotSpecified, null));
                        }
                    }
                }
            }
            else if (ParameterSetName == PrinterSet)
            {
            }
        }
示例#4
0
        private DebuggerCommandResults HandlePromptCommand(PSDataCollection <PSObject> output)
        {
            // Nested debugged runspace prompt should look like:
            // [DBG]: [JobName]: PS C:\>>
            string    promptScript  = "'[DBG]: '" + " + " + "'[" + CodeGeneration.EscapeSingleQuotedStringContent(_jobName) + "]: '" + " + " + @"""PS $($executionContext.SessionState.Path.CurrentLocation)>> """;
            PSCommand promptCommand = new PSCommand();

            promptCommand.AddScript(promptScript);
            _wrappedDebugger.ProcessCommand(promptCommand, output);

            return(new DebuggerCommandResults(null, true));
        }
        /// <summary>
        /// Offers the names of types loaded into the session for argument completion.
        /// </summary>
        public IEnumerable <CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters)
        {
            var wc    = new WildcardPattern(wordToComplete?.Trim("\"'()[]".ToCharArray()) + "*", WildcardOptions.IgnoreCase);
            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(a => a.GetTypes())
                        .Where(t => t.IsPublic)
                        .Select(t => (t.FullName, t.Name))
                        .Where(n => wc.IsMatch(n.Name) || wc.IsMatch(n.FullName));

            foreach (var(FullName, Name) in types)
            {
                string safeOutput = FullName.Contains(" ") ? "'" + CodeGeneration.EscapeSingleQuotedStringContent(FullName) + "'" : FullName;
                yield return(new CompletionResult(safeOutput, FullName, CompletionResultType.Type, FullName));
            }
        }
示例#6
0
        private static List <Hashtable> InitializeSuggestions()
        {
            var suggestions = new List <Hashtable>(
                new Hashtable[]
            {
                NewSuggestion(
                    id: 1,
                    category: "Transactions",
                    matchType: SuggestionMatchType.Command,
                    rule: "^Start-Transaction",
                    suggestion: SuggestionStrings.Suggestion_StartTransaction,
                    enabled: true),
                NewSuggestion(
                    id: 2,
                    category: "Transactions",
                    matchType: SuggestionMatchType.Command,
                    rule: "^Use-Transaction",
                    suggestion: SuggestionStrings.Suggestion_UseTransaction,
                    enabled: true),
                NewSuggestion(
                    id: 3,
                    category: "General",
                    matchType: SuggestionMatchType.Dynamic,
                    rule: ScriptBlock.CreateDelayParsedScriptBlock(s_checkForCommandInCurrentDirectoryScript, isProductCode: true),
                    suggestion: ScriptBlock.CreateDelayParsedScriptBlock(s_createCommandExistsInCurrentDirectoryScript, isProductCode: true),
                    suggestionArgs: new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory) },
                    enabled: true)
            });

            if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion"))
            {
                suggestions.Add(
                    NewSuggestion(
                        id: 4,
                        category: "General",
                        matchType: SuggestionMatchType.ErrorId,
                        rule: "CommandNotFoundException",
                        suggestion: ScriptBlock.CreateDelayParsedScriptBlock(s_getFuzzyMatchedCommands, isProductCode: true),
                        suggestionArgs: new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandNotFound) },
                        enabled: true));
            }

            return(suggestions);
        }
示例#7
0
 protected static CompletionResult CreateCompletionResult(string value, bool escapeVariables = true)
 {
     if (value.Contains("'") ||
         value.Contains(" ") ||
         value.Contains(";") ||
         (escapeVariables && value.Contains("$")))
     {
         var val = CodeGeneration.EscapeSingleQuotedStringContent(value);
         if (escapeVariables)
         {
             val = CodeGeneration.EscapeVariableName(val);
         }
         return(new CompletionResult("'" + val + "'", value, CompletionResultType.ParameterValue, value));
     }
     else
     {
         return(new CompletionResult(value, value, CompletionResultType.ParameterValue, value));
     }
 }
示例#8
0
        public static string QuoteName(string name)
        {
            bool quotesNeeded = false;

            foreach (var c in name)
            {
                if (Char.IsWhiteSpace(c))
                {
                    quotesNeeded = true;
                    break;
                }
            }

            if (!quotesNeeded)
            {
                return(name);
            }

            return("'" + CodeGeneration.EscapeSingleQuotedStringContent(name) + "'");
        }