diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..975bce2178940eebb0f5fef977ce0c49e55499ce 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,16 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +PowerShell-master/assets/Powershell_av_colors.ico filter=lfs diff=lfs merge=lfs -text +PowerShell-master/assets/Powershell_avatar.ico filter=lfs diff=lfs merge=lfs -text +PowerShell-master/assets/Powershell_black.ico filter=lfs diff=lfs merge=lfs -text +PowerShell-master/assets/Powershell-preview.icns filter=lfs diff=lfs merge=lfs -text +PowerShell-master/assets/Powershell.icns filter=lfs diff=lfs merge=lfs -text +PowerShell-master/src/Schemas/PSMaml/developerCommand.rld filter=lfs diff=lfs merge=lfs -text +PowerShell-master/src/Schemas/PSMaml/Maml.rld filter=lfs diff=lfs merge=lfs -text +PowerShell-master/test/powershell/engine/Help/assets/Microsoft.PowerShell.Core_00000000-0000-0000-0000-000000000000_en-US_HelpContent.cab filter=lfs diff=lfs merge=lfs -text +PowerShell-master/test/powershell/engine/Help/assets/Microsoft.PowerShell.Management_eefcb906-b326-4e99-9f54-8b4bb6ef3c6d_en-US_helpcontent.cab filter=lfs diff=lfs merge=lfs -text +PowerShell-master/test/powershell/engine/Help/assets/Microsoft.PowerShell.Utility_1da87e53-152b-403e-98dc-74d7b4d63d59_en-US_helpcontent.cab filter=lfs diff=lfs merge=lfs -text +PowerShell-master/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/assets/BadCounterSamples.blg filter=lfs diff=lfs merge=lfs -text +PowerShell-master/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/assets/CounterSamples.blg filter=lfs diff=lfs merge=lfs -text +PowerShell-master/tools/terms/PowerShell-Terms-Rules.mdb filter=lfs diff=lfs merge=lfs -text diff --git a/PowerShell-master/.config/suppress.json b/PowerShell-master/.config/suppress.json new file mode 100644 index 0000000000000000000000000000000000000000..9be220b291ee19411f63aed3d98cccc9b8dbad4c --- /dev/null +++ b/PowerShell-master/.config/suppress.json @@ -0,0 +1,17 @@ +{ + "tool": "Credential Scanner", + "suppressions": [ + { + "file": "\\test\\tools\\Modules\\WebListener\\ClientCert.pfx", + "_justification": "Test certificate with private key" + }, + { + "file": "\\test\\tools\\Modules\\WebListener\\ServerCert.pfx", + "_justification": "Test certificate with private key" + }, + { + "file": "\\test\\powershell\\Modules\\Microsoft.PowerShell.Security\\certificateCommon.psm1", + "_justification": "Test certificate with private key and inline suppression isn't working" + } + ] +} diff --git a/PowerShell-master/.config/tsaoptions.json b/PowerShell-master/.config/tsaoptions.json new file mode 100644 index 0000000000000000000000000000000000000000..786ef4331a21b4f5326ff08c11c694f277017caf --- /dev/null +++ b/PowerShell-master/.config/tsaoptions.json @@ -0,0 +1,12 @@ +{ + "codebaseName": "TFSMSAzure_PowerShell", + "instanceUrl": "https://msazure.visualstudio.com", + "projectName": "One", + "areaPath": "One\\MGMT\\Compute\\Powershell\\Powershell\\PowerShell Core\\pwsh", + "notificationAliases": [ + "adityap@microsoft.com", + "dongbow@microsoft.com", + "pmeinecke@microsoft.com", + "tplunk@microsoft.com" + ] +} diff --git a/PowerShell-master/.devcontainer/Dockerfile b/PowerShell-master/.devcontainer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c849a9f78e5a355791f32625f76cdc64a9b35992 --- /dev/null +++ b/PowerShell-master/.devcontainer/Dockerfile @@ -0,0 +1,25 @@ +#------------------------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information. +#------------------------------------------------------------------------------------------------------------- + +FROM mcr.microsoft.com/powershell/test-deps:ubuntu-20.04@sha256:d1609c57d2426b9cfffa3a3ab7bda5ebc4448700f8ba8ef377692c4a70e64b8c + +# Avoid warnings by switching to noninteractive +ENV DEBIAN_FRONTEND=noninteractive + +# Configure apt and install packages +RUN apt-get update \ + && apt-get -y upgrade \ + && apt-get -y install --no-install-recommends apt-utils 2>&1 \ + # + # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed + && apt-get -y install --no-install-recommends git procps lsb-release \ + # + # Clean up + && apt-get autoremove -y \ + && apt-get clean -y \ + && rm -rf /var/lib/apt/lists/* + +# Switch back to dialog for any ad-hoc use of apt-get +ENV DEBIAN_FRONTEND=dialog diff --git a/PowerShell-master/.devcontainer/devcontainer.json b/PowerShell-master/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..eded2d1bdec5616acf4b5ecc0c6f0616b2711e20 --- /dev/null +++ b/PowerShell-master/.devcontainer/devcontainer.json @@ -0,0 +1,23 @@ +// See https://aka.ms/vscode-remote/devcontainer.json for format details. +{ + "name": ".NET Core 6.0, including pwsh (Ubuntu 18.04)", + "dockerFile": "Dockerfile", + + "workspaceMount": "source=${localWorkspaceFolder},target=/PowerShell,type=bind", + "workspaceFolder": "/PowerShell", + + // Uncomment the next line to run commands after the container is created. + "postCreateCommand": "cd src/powershell-unix && dotnet restore", + + "customizations": { + "vscode": { + "extensions": [ + "ms-azure-devops.azure-pipelines", + "ms-dotnettools.csharp", + "ms-vscode.powershell", + "DavidAnson.vscode-markdownlint", + "vitaliymaz.vscode-svg-previewer" + ] + } + } +} diff --git a/PowerShell-master/.editorconfig b/PowerShell-master/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..57d2f6c6c3e65109cd4b28f496baeda2bb7d99b7 --- /dev/null +++ b/PowerShell-master/.editorconfig @@ -0,0 +1,213 @@ +# EditorConfig is awesome: https://EditorConfig.org +# .NET coding convention settings for EditorConfig +# https://learn.microsoft.com/visualstudio/ide/editorconfig-code-style-settings-reference +# +# This file comes from dotnet repositories: +# https://github.com/dotnet/runtime/blob/master/.editorconfig +# https://github.com/dotnet/roslyn/blob/master/.editorconfig + +# Top-most EditorConfig file +root = true + +[*] +charset = utf-8 +# indent_size intentionally not specified in this section +indent_style = space +insert_final_newline = true + +# Source code +[*.{cs,ps1,psd1,psm1}] +indent_size = 4 + +# Shell scripts +[*.sh] +end_of_line = lf +indent_size = 4 + +# Xml project files +[*.{csproj,resx,ps1xml}] +indent_size = 2 + +# Data serialization +[*.{json,yaml,yml}] +indent_size = 2 + +# Markdown +[*.md] +indent_size = 2 + +# Xml files +[*.{resx,ruleset,stylecop,xml,xsd,xsl}] +indent_size = 2 + +# Xml config files +[*.{props,targets,config,nuspec}] +indent_size = 2 + +[*.tsv] +indent_style = tab + +# Dotnet code style settings: +[*.cs] +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true + +file_header_template = Copyright (c) Microsoft Corporation.\nLicensed under the MIT License. + +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion + +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Name all constant fields using PascalCase +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.required_modifiers = const + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +# Static fields should have s_ prefix +dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion +dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields +dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static +dotnet_naming_symbols.static_fields.applicable_accessibilities = private, internal, private_protected + +dotnet_naming_style.static_prefix_style.required_prefix = s_ +dotnet_naming_style.static_prefix_style.capitalization = camel_case + +# Internal and private fields should be _camelCase +dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion +dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields +dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style + +dotnet_naming_symbols.private_internal_fields.applicable_kinds = field +dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal + +dotnet_naming_style.camel_case_underscore_style.required_prefix = _ +dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case + +# Suggest more modern language features when available +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +# Background Info: https://github.com/dotnet/runtime/pull/100250 +dotnet_style_prefer_collection_expression = when_types_exactly_match +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_readonly_field = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_auto_properties = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion + +dotnet_code_quality_unused_parameters = non_public:suggestion + +# Dotnet diagnostic settings: +[*.cs] + +# CA1859: Use concrete types when possible for improved performance +# https://learn.microsoft.com/en-gb/dotnet/fundamentals/code-analysis/quality-rules/ca1859 +dotnet_diagnostic.CA1859.severity = suggestion + +# Disable SA1600 (ElementsMustBeDocumented) for test directory only +[test/**/*.cs] +dotnet_diagnostic.SA1600.severity = none + +# CSharp code style settings: +[*.cs] + +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false +csharp_prefer_braces = true:silent + +csharp_prefer_static_local_function = true:suggestion +csharp_prefer_simple_using_statement = false:none +csharp_style_prefer_switch_expression = true:suggestion +csharp_style_prefer_range_operator = false:none +csharp_style_prefer_index_operator = false:none +csharp_style_pattern_local_over_anonymous_function = false:none + +csharp_using_directive_placement = outside_namespace:suggestion + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = one_less_than_current + +# Only use var when it's obvious what the variable type is +csharp_style_var_for_built_in_types = false:none +csharp_style_var_when_type_is_apparent = false:none +csharp_style_var_elsewhere = false:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_local_functions = true:silent + +# Prefer method-like constructs to have a block body +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none + +# Prefer property-like constructs to have an expression-body +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +# Suggest more modern language features when available +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = do_not_ignore +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Newline settings +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true diff --git a/PowerShell-master/.gitattributes b/PowerShell-master/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..c9033dc798a4c1801cdb27be05f2f5978b60b879 --- /dev/null +++ b/PowerShell-master/.gitattributes @@ -0,0 +1,7 @@ +CHANGELOG.md merge=union +* text=auto +*.png binary +*.rtf binary +*.sh text eol=lf +testablescript.ps1 text eol=lf +TestFileCatalog.txt text eol=lf diff --git a/PowerShell-master/.github/CODEOWNERS b/PowerShell-master/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..14569b81924b96a53752066d80ffa32f30329f65 --- /dev/null +++ b/PowerShell-master/.github/CODEOWNERS @@ -0,0 +1,69 @@ +# https://help.github.com/articles/about-codeowners/ + +# Areas are not limited to the filters defined in this file +# First, let's start with areas with no filters or paths + +# Default +* @PowerShell/powershell-maintainers + +# Area: Performance +# @adityapatwardhan + +# Area: Security +src/System.Management.Automation/security/wldpNativeMethods.cs @TravisEz13 @seeminglyscience + +# Area: CI Build +.github/workflows @PowerShell/powershell-maintainers @jshigetomi +.github/actions @PowerShell/powershell-maintainers @jshigetomi + +# Now, areas that should have paths or filters, although we might not have them defined +# According to the docs, order here must be by precedence of the filter, with later rules overwritting +# but the feature seems to make taking a union of all the matching rules. + +# Area: Cmdlets Management +# src/Microsoft.PowerShell.Commands.Management/ @daxian-dbw @adityapatwardhan + +# Area: Utility Cmdlets +# src/Microsoft.PowerShell.Commands.Utility/ + +# Area: Console +# src/Microsoft.PowerShell.ConsoleHost/ @daxian-dbw + +# Area: DSC +# src/System.Management.Automation/DscSupport @TravisEz13 @SteveL-MSFT + +# Area: Engine +# src/System.Management.Automation/engine @daxian-dbw + +# Area: Debugging +# Must be below engine to override +# src/System.Management.Automation/engine/debugger/ + +# Area: Help +src/System.Management.Automation/help @adityapatwardhan @daxian-dbw + +# Area: Intellisense +# @daxian-dbw + +# Area: Language +src/System.Management.Automation/engine/parser @daxian-dbw @seeminglyscience + +# Area: Providers +# src/System.Management.Automation/namespaces + +# Area: Remoting +src/System.Management.Automation/engine/remoting @daxian-dbw @TravisEz13 + +# Areas: Build +# Must be last +*.config @PowerShell/powershell-maintainers @jshigetomi +*.props @PowerShell/powershell-maintainers @jshigetomi +*.yml @PowerShell/powershell-maintainers @jshigetomi +*.csproj @PowerShell/powershell-maintainers @jshigetomi +build.* @PowerShell/powershell-maintainers @jshigetomi +tools/ @PowerShell/powershell-maintainers @jshigetomi +# docker/ @PowerShell/powershell-maintainers @jshigetomi + +# Area: Compliance +tools/terms @TravisEz13 +tools/credScan @TravisEz13 diff --git a/PowerShell-master/.github/CONTRIBUTING.md b/PowerShell-master/.github/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..35eab8c9b5b8e782b0f93d9d8e3fc11182a13f7b --- /dev/null +++ b/PowerShell-master/.github/CONTRIBUTING.md @@ -0,0 +1,431 @@ +# Contributing to PowerShell + +We welcome and appreciate contributions from the community! + +There are many ways to become involved with PowerShell including: + +- [Contributing to Documentation](#contributing-to-documentation) +- [Contributing to Issues](#contributing-to-issues) +- [Contributing to Code](#contributing-to-code) + +Please read the rest of this document to ensure a smooth contribution process. + +## Contributing to Documentation + +Contributing to the docs is an excellent way to get started with the process of making open source contributions with minimal technical skill required. + +Please see the [Contributor Guide in `MicrosoftDocs/PowerShell-Docs`](https://aka.ms/PSDocsContributor). + +Learn how to [Contribute to Docs like a Microsoft Insider](https://www.youtube.com/watch?v=ZQODV8krq1Q) (by @sdwheeler) + +### Updating Documentation for an existing cmdlet + +If you made a change to an existing cmdlet and would like to update the documentation using PlatyPS, +here are the quick steps: + +1. Install +`PlatyPS` +if you don't have it - +`Install-Module PlatyPS`. +1. Clone the +[`MicrosoftDocs/PowerShell-Docs`](https://github.com/MicrosoftDocs/PowerShell-Docs) +repository if you don't already have it. +1. Start your local build of PowerShell +(with the change to the cmdlet you made). +1. Find the cmdlet's Markdown file in PowerShell Docs - usually under +`PowerShell-Docs/reference///.md` +(Ex. `PowerShell-Docs/reference/7/Microsoft.PowerShell.Utility/Select-String.md`) +1. Run +`Update-MarkdownHelp -Path ` +which will update the documentation for you. +1. Make any additional changes needed for the cmdlet to be properly documented. +1. Send a Pull Request to the PowerShell Docs repository with the changes that +`PlatyPS` +made. +1. Link your Docs PR to your original change PR. + +### Style notes for documentation related to maintaining or contributing to the PowerShell project + +* When writing Markdown documentation, use [semantic linefeeds][]. + In most cases, it means "one clause/idea per line". +* Otherwise, these issues should be treated like any other issue in this repository. + +### Spell checking documentation + +Documentation is spellchecked. We use the +[textlint](https://github.com/textlint/textlint/wiki/Collection-of-textlint-rule) command-line tool, +which can be run in interactive mode to correct typos. + +To run the spell checker, follow these steps: + +* install [Node.js](https://nodejs.org/en/) (v10 or up) +* install [textlint](https://github.com/textlint/textlint/wiki/Collection-of-textlint-rule) by + `npm install -g textlint textlint-rule-terminology` +* run `textlint --rule terminology `, + adding `--fix` will accept all the recommendations. + +If you need to add a term or disable checking part of a file see the [configuration sections of the rule](https://github.com/sapegin/textlint-rule-terminology). + +### Checking links in documentation + +Documentation is link-checked. We make use of the +`markdown-link-check` command-line tool, +which can be run to see if any links are dead. + +To run the link-checker, follow these steps: + +* install [Node.js](https://nodejs.org/en/) (v10 or up) +* install `markdown-link-check` by + `npm install -g markdown-link-check@3.8.5` +* run `find . \*.md -exec markdown-link-check {} \;` + +## Contributing to Issues + +1. Review [Issue Management][issue-management]. +1. Check if the issue you are going to file already exists in our [GitHub issues][open-issue]. +1. If you can't find your issue already, + [open a new issue](https://github.com/PowerShell/PowerShell/issues/new/choose), + making sure to follow the directions as best you can. +1. If the issue is marked as [`Up-for-Grabs`][up-for-grabs], + the PowerShell Maintainers are looking for help with the issue. +1. Issues marked as [`First-Time-Issue`][first-time-issue], + are identified as being easy and a great way to learn about this project and making + contributions. + +### Finding or creating an issue + +1. Follow the instructions in [Contributing to Issues][contribute-issues] to find or open an issue. +1. Mention in the issue that you are working on the issue and ask `@powershell/powershell` for an assignment. + +### Forks and Pull Requests + +GitHub fosters collaboration through the notion of [pull requests][using-prs]. +On GitHub, anyone can [fork][fork-a-repo] an existing repository +into their own user account, where they can make private changes to their fork. +To contribute these changes back into the original repository, +a user simply creates a pull request in order to "request" that the changes be taken "upstream". + +Additional references: + +* GitHub's guide on [forking](https://guides.github.com/activities/forking/) +* GitHub's guide on [Contributing to Open Source](https://guides.github.com/activities/contributing-to-open-source/#pull-request) +* GitHub's guide on [Understanding the GitHub Flow](https://guides.github.com/introduction/flow/) + +## Contributing to Code + +### Quick Start Checklist + +* Review the [Contributor License Agreement][CLA] requirement. +* Get familiar with the [PowerShell Repository Git Concepts](../docs/git/README.md). +* Start a [GitHub Codespace](#Dev Container) and start exploring the repository. +* Consider if what you want to do might be implementable as a [PowerShell Binary Module](https://learn.microsoft.com/powershell/scripting/developer/module/how-to-write-a-powershell-binary-module?view=powershell-7.5). + The PowerShell repository has a rigorous acceptance process due to its huge popularity and emphasis on stability and long term support, and with a binary module you can contribute to the community much more quickly. +* Pick an existing issue to work on! For instance, clarifying a confusing or unclear error message is a great starting point. + +### Intro to Git and GitHub + +1. Sign up for a [GitHub account](https://github.com/signup/free). +1. Learning Git and GitHub: + - [Git Basics](../docs/git/basics.md): install and getting started + - [Good Resources for Learning Git and GitHub][good-git-resources] +1. The PowerShell repository uses GitHub Flow as the primary branching strategy. [Learn about GitHub Flow](https://guides.github.com/introduction/flow/) + +### Code Editing + +PowerShell is primarily written in [C#](https://learn.microsoft.com/dotnet/csharp/tour-of-csharp/overview). While you can use any C# development environment you prefer, [Visual Studio Code][use-vscode-editor] is recommended. + +### Dev Container + +There is a PowerShell [Dev Container](https://code.visualstudio.com/docs/devcontainers/containers) which enables you get up and running quickly with a prepared Visual Studio Code environment with all the required prerequisites already installed. + +[GitHub Codespaces](https://github.com/features/codespaces) is the fastest way to get started. +Codespaces allows you to start a Github-hosted devcontainer from anywhere and contribute from your browser or via Visual Studio Code remoting. +All GitHub users get 15 hours per month of a 4-core codespace for free. + +To start a codespace for the PowerShell repository: + +1. Go to https://github.com/PowerShell/PowerShell +1. Click the green button on the right and choose to create a codespace + + ![alt text](Images/Codespaces.png) +1. Alternatively, just hit the comma `,` key on your keyboard which should instantly start a codespace as well. + +Once the codespace starts, you can press `ctrl+shift+b` (`cmd+shift+b` on Mac) to run the default build task. If you would like to interactivey test your changes, you can press `F5` to start debugging, add breakpoints, etc. + +[Learn more about how to get started with C# in Visual Studio Code](https://code.visualstudio.com/docs/csharp/get-started) + +### Building and Testing + +#### Building PowerShell + +[Building PowerShell](../README.md#Building-Powershell) has instructions for various platforms. + +#### Testing PowerShell + +Please see PowerShell [Testing Guidelines - Running Tests Outside of CI][running-tests-outside-of-ci] on how to test your build locally. + +### Lifecycle of a pull request + +#### Before submitting + +* If your change would fix a security vulnerability, + first follow the [vulnerability issue reporting policy][vuln-reporting], before submitting a PR. +* To avoid merge conflicts, make sure your branch is rebased on the `master` branch of this repository. +* Many code changes will require new tests, + so make sure you've added a new test if existing tests do not effectively test the code changed. +* Clean up your commit history. + Each commit should be a **single complete** change. + This discipline is important when reviewing the changes as well as when using `git bisect` and `git revert`. + +#### Pull request - Submission + +**Always create a pull request to the `master` branch of this repository**. + +![GitHub-PR.png](Images/GitHub-PR.png) + +* It's recommended to avoid a PR with too many changes. + A large PR not only stretches the review time, but also makes it much harder to spot issues. + In such case, it's better to split the PR to multiple smaller ones. + For large features, try to approach it in an incremental way, so that each PR won't be too big. +* If you're contributing in a way that changes the user or developer experience, you are expected to document those changes. + See [Contributing to documentation related to PowerShell](#contributing-to-documentation). +* Add a meaningful title of the PR describing what change you want to check in. + Don't simply put: "Fix issue #5". + Also don't directly use the issue title as the PR title. + An issue title is to briefly describe what is wrong, while a PR title is to briefly describe what is changed. + A better example is: "Add Ensure parameter to New-Item cmdlet", with "Fix #5" in the PR's body. +* When you create a pull request, + include a summary about your changes in the PR description. + The description is used to create changelogs, + so try to have the first sentence explain the benefit to end users. + If the changes are related to an existing GitHub issue, + please reference the issue in the PR description (e.g. ```Fix #11```). + See [this][closing-via-message] for more details. + +* Please use the present tense and imperative mood when describing your changes: + * Instead of "Adding support for Windows Server 2012 R2", write "Add support for Windows Server 2012 R2". + * Instead of "Fixed for server connection issue", write "Fix server connection issue". + + This form is akin to giving commands to the codebase + and is recommended by the Git SCM developers. + It is also used in the [Git commit messages](#common-engineering-practices). +* If the change is related to a specific resource, please prefix the description with the resource name: + * Instead of "New parameter 'ConnectionCredential' in New-SqlConnection", + write "New-SqlConnection: add parameter 'ConnectionCredential'". +* If your change warrants an update to user-facing documentation, + a Maintainer will add the `Documentation Needed` label to your PR and add an issue to the [PowerShell-Docs repository][PowerShell-Docs], + so that we make sure to update official documentation to reflect your contribution. + As an example, this requirement includes any changes to cmdlets (including cmdlet parameters) and features which have associated about_* topics. + While not required, we appreciate any contributors who add this label and create the issue themselves. + Even better, all contributors are free to contribute the documentation themselves. + (See [Contributing to documentation related to PowerShell](#contributing-to-documentation) for more info.) +* If your change adds a new source file, ensure the appropriate copyright and license headers is on top. + It is standard practice to have both a copyright and license notice for each source file. + * For `.cs` files use the copyright header with empty line after it: + + ```c# + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + ``` + + * For `.ps1` and `.psm1` files use the copyright header with empty line after it: + + ```powershell + # Copyright (c) Microsoft Corporation. + # Licensed under the MIT License. + + ``` + +* If your change adds a new module manifest (.psd1 file), ensure that: + + ```powershell + Author = "PowerShell" + Company = "Microsoft Corporation" + Copyright = "Copyright (c) Microsoft Corporation." + ``` + + is at the top. + +### Pull Request - Work in Progress + +* If your pull request is not ready to merge, please add the prefix `WIP:` to the beginning of the title and remove the prefix when the PR is ready. + +#### Pull Request - Automatic Checks + +* If this is your first contribution to PowerShell, + you may be asked to sign a [Contribution Licensing Agreement][CLA] (CLA) + before your changes will be accepted. +* Make sure you follow the [Common Engineering Practices](#common-engineering-practices) + and [testing guidelines](../docs/testing-guidelines/testing-guidelines.md). +* After submitting your pull request, + our [CI system (Azure DevOps Pipelines)][ci-system] + will run a suite of tests and automatically update the status of the pull request. +* Our CI contains automated spell checking and link checking for Markdown files. If there is any false-positive, + [run the spell checker command-line tool in interactive mode](#spell-checking-documentation) + to add words to the `.spelling` file. + + You could update the `.spelling` file manually in accordance with messages in the test log file, or + [run the spell checker command-line tool in interactive mode](#spell-checking-documentation) + to add the false-positive words directly. + +#### Pull Request - Workflow + +1. The PR *author* creates a pull request from a fork. +1. The *author* ensures that their pull request passes the [CI system][ci-system] build. + - If the build fails, a [Repository Maintainer][repository-maintainer] adds the `Review - waiting on author` label to the pull request. + The *author* can then continue to update the pull request until the build passes. +1. If the *author* knows whom should participate in the review, they should add them otherwise they can add the recommended *reviewers*. +1. Once the build passes, if there is not sufficient review, the *maintainer* adds the `Review - needed` label. +1. An [Area Expert][area-expert] should also review the pull request. + - If the *author* does not meet the *reviewer*'s standards, the *reviewer* makes comments. A *maintainer* then removes the `Review - needed` label and adds + the `Review - waiting on author` label. The *author* must address the comments and repeat from step 2. + - If the *author* meets the *reviewer*'s standards, the *reviewer* approves the PR. A maintainer then removes the `need review` label. +1. Once the code review is completed, a *maintainer* merges the pull request after one business day to allow for additional critical feedback. + +#### Pull Request - Roles and Responsibilities + +1. The PR *author* is responsible for moving the PR forward to get it approved. + This includes addressing feedback within a timely period and indicating feedback has been addressed by adding a comment and mentioning the specific *reviewers*. + When updating your pull request, please **create new commits** and **don't rewrite the commits history**. + This way it's very easy for the reviewers to see diff between iterations. + If you rewrite the history in the pull request, review could be much slower. + The PR is likely to be squash-merged to master by the *assignee*. +1. *Reviewers* are anyone who wants to contribute. + They are responsible for ensuring the code: addresses the issue being fixed, does not create new issues (functional, performance, reliability, or security), and implements proper design. + *Reviewers* should use the `Review changes` drop down to indicate they are done with their review. + - `Request changes` if you believe the PR merge should be blocked if your feedback is not addressed, + - `Approve` if you believe your feedback has been addressed or the code is fine as-is, it is customary (although not required) to leave a simple "Looks good to me" (or "LGTM") as the comment for approval. + - `Comment` if you are making suggestions that the *author* does not have to accept. + Early in the review, it is acceptable to provide feedback on coding formatting based on the published [Coding Guidelines][coding-guidelines], however, + after the PR has been approved, it is generally *not* recommended to focus on formatting issues unless they go against the [Coding Guidelines][coding-guidelines]. + Non-critical late feedback (after PR has been approved) can be submitted as a new issue or new pull request from the *reviewer*. +1. *Assignees* who are always *Maintainers* ensure that proper review has occurred and if they believe one approval is not sufficient, the *maintainer* is responsible to add more reviewers. + An *assignee* may also be a reviewer, but the roles are distinct. + Once the PR has been approved and the CI system is passing, the *assignee* will merge the PR after giving one business day for any critical feedback. + For more information on the PowerShell Maintainers' process, see the [documentation](../docs/maintainers). + +#### Pull Requests - Abandoned + +A pull request with the label `Review - waiting on author` for **more than two weeks** without a word from the author is considered abandoned. + +In these cases: + +1. *Assignee* will ping the author of PR to remind them of pending changes. + - If the *author* responds, it's no longer an abandoned; the pull request proceeds as normal. +1. If the *author* does not respond **within a week**: + - If the *reviewer*'s comments are very minor, merge the change, fix the code immediately, and create a new PR with the fixes addressing the minor comments. + - If the changes required to merge the pull request are significant but needed, *assignee* creates a new branch with the changes and open an issue to merge the code into the dev branch. + Mention the original pull request ID in the description of the new issue and close the abandoned pull request. + - If the changes in an abandoned pull request are no longer needed (e.g. due to refactoring of the codebase or a design change), *assignee* will simply close the pull request. + +### Making Breaking Changes + +When you make code changes, +please pay attention to these that can affect the [Public Contract][breaking-changes-contract]. +For example, changing PowerShell parameters, APIs, or protocols break the public contract. +Before making changes to the code, +first review the [breaking changes contract][breaking-changes-contract] +and follow the guidelines to keep PowerShell backward compatible. + +### Making Design Changes + +To add new features such as cmdlets or making design changes, +please follow the [PowerShell Request for Comments (RFC)][rfc-process] process. + +### Common Engineering Practices + +Other than the guidelines for [coding][coding-guidelines], +the [RFC process][rfc-process] for design, +[documentation](#contributing-to-documentation) and [testing](../docs/testing-guidelines/testing-guidelines.md) discussed above, +we encourage contributors to follow these common engineering practices: + +* Format commit messages following these guidelines: + +```text +Summarize change in 50 characters or less + +Similar to email, this is the body of the commit message, +and the above is the subject. +Always leave a single blank line between the subject and the body +so that `git log` and `git rebase` work nicely. + +The subject of the commit should use the present tense and +imperative mood, like issuing a command: + +> Makes abcd do wxyz + +The body should be a useful message explaining +why the changes were made. + +If significant alternative solutions were available, +explain why they were discarded. + +Keep in mind that the person most likely to refer to your commit message +is you in the future, so be detailed! + +As Git commit messages are most frequently viewed in the terminal, +you should wrap all lines around 72 characters. + +Using semantic line feeds (breaks that separate ideas) +is also appropriate, as is using Markdown syntax. +``` + +* These are based on Tim Pope's [guidelines](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html), + Git SCM [submitting patches](https://git.kernel.org/cgit/git/git.git/tree/Documentation/SubmittingPatches), + Brandon Rhodes' [semantic linefeeds][], + and John Gruber's [Markdown syntax](https://daringfireball.net/projects/markdown/syntax). +* Don't commit code that you didn't write. + If you find code that you think is a good fit to add to PowerShell, + file an issue and start a discussion before proceeding. +* Create and/or update tests when making code changes. +* Run tests and ensure they are passing before opening a pull request. +* All pull requests **must** pass CI systems before they can be approved. +* Avoid making big pull requests. + Before you invest a large amount of time, + file an issue and start a discussion with the community. + +### Contributor License Agreement (CLA) + +To speed up the acceptance of any contribution to any PowerShell repositories, +you should sign the Microsoft [Contributor License Agreement (CLA)](https://cla.microsoft.com/) ahead of time. +If you've already contributed to PowerShell or Microsoft repositories in the past, congratulations! +You've already completed this step. +This a one-time requirement for the PowerShell project. +Signing the CLA process is simple and can be done in less than a minute. +You don't have to do this up-front. +You can simply clone, fork, and submit your pull request as usual. +When your pull request is created, it is checked by the CLA bot. +If you have signed the CLA, the status check will be set to `passing`. Otherwise, it will stay at `pending`. +Once you sign a CLA, all your existing and future pull requests will have the status check automatically set at `passing`. + +## Code of Conduct Enforcement + +Reports of abuse will be reviewed by the [PowerShell Committee][ps-committee] and if it has been determined that violations of the +[Code of Conduct](../CODE_OF_CONDUCT.md) has occurred, then a temporary ban may be imposed. +The duration of the temporary ban will depend on the impact and/or severity of the infraction. +This can vary from 1 day, a few days, a week, and up to 30 days. +Repeat offenses may result in a permanent ban from the PowerShell org. + +[running-tests-outside-of-ci]: ../docs/testing-guidelines/testing-guidelines.md#running-tests-outside-of-ci +[issue-management]: ../docs/maintainers/issue-management.md +[vuln-reporting]: ./SECURITY.md +[using-prs]: https://help.github.com/articles/using-pull-requests/ +[fork-a-repo]: https://help.github.com/articles/fork-a-repo/ +[closing-via-message]: https://help.github.com/articles/closing-issues-via-commit-messages/ +[CLA]: #contributor-license-agreement-cla +[ci-system]: ../docs/testing-guidelines/testing-guidelines.md#ci-system +[good-git-resources]: https://help.github.com/articles/good-resources-for-learning-git-and-github/ +[contribute-issues]: #contributing-to-issues +[open-issue]: https://github.com/PowerShell/PowerShell/issues +[up-for-grabs]: https://github.com/powershell/powershell/issues?q=is%3Aopen+is%3Aissue+label%3AUp-for-Grabs +[semantic linefeeds]: https://rhodesmill.org/brandon/2012/one-sentence-per-line/ +[PowerShell-Docs]: https://github.com/powershell/powershell-docs/ +[use-vscode-editor]: https://learn.microsoft.com/dotnet/core/tutorials/with-visual-studio-code +[repository-maintainer]: ../docs/community/governance.md#repository-maintainers +[area-expert]: ../.github/CODEOWNERS +[first-time-issue]: https://github.com/powershell/powershell/issues?q=is%3Aopen+is%3Aissue+label%3AFirst-Time-Issue +[coding-guidelines]: ../docs/dev-process/coding-guidelines.md +[breaking-changes-contract]: ../docs/dev-process/breaking-change-contract.md +[rfc-process]: https://github.com/PowerShell/PowerShell-RFC +[ps-committee]: ../docs/community/governance.md#powershell-committee diff --git a/PowerShell-master/.github/ISSUE_TEMPLATE/Bug_Report.yaml b/PowerShell-master/.github/ISSUE_TEMPLATE/Bug_Report.yaml new file mode 100644 index 0000000000000000000000000000000000000000..03fcf444e880ff764427187e66ae11cbf248b06e --- /dev/null +++ b/PowerShell-master/.github/ISSUE_TEMPLATE/Bug_Report.yaml @@ -0,0 +1,75 @@ +name: Bug report 🐛 +description: Report errors or unexpected behavior 🤔 +labels: Needs-Triage +body: +- type: markdown + attributes: + value: > + For Windows PowerShell 5.1 issues, suggestions, or feature requests please use the + [Feedback Hub app](https://support.microsoft.com/windows/send-feedback-to-microsoft-with-the-feedback-hub-app-f59187f8-8739-22d6-ba93-f66612949332) + + This repository is **ONLY** for PowerShell Core 6 and PowerShell 7+ issues. +- type: checkboxes + attributes: + label: Prerequisites + options: + - label: Write a descriptive title. + required: true + - label: Make sure you are able to repro it on the [latest released version](https://github.com/PowerShell/PowerShell/releases) + required: true + - label: Search the existing issues. + required: true + - label: Refer to the [FAQ](https://github.com/PowerShell/PowerShell/blob/master/docs/FAQ.md). + required: true + - label: Refer to [Differences between Windows PowerShell 5.1 and PowerShell](https://learn.microsoft.com/powershell/scripting/whats-new/differences-from-windows-powershell). + required: true +- type: textarea + attributes: + label: Steps to reproduce + description: > + List of steps, sample code, failing test or link to a project that reproduces the behavior. + Make sure you place a stack trace inside a code (```) block to avoid linking unrelated issues. + placeholder: > + I am experiencing a problem with X. + I think Y should be happening but Z is actually happening. + validations: + required: true +- type: textarea + attributes: + label: Expected behavior + render: console + placeholder: | + PS> 2 + 2 + 4 + validations: + required: true +- type: textarea + attributes: + label: Actual behavior + render: console + placeholder: | + PS> 2 + 2 + 5 + validations: + required: true +- type: textarea + attributes: + label: Error details + description: Paste verbatim output from `Get-Error` if PowerShell return an error. + render: console + placeholder: PS> Get-Error +- type: textarea + attributes: + label: Environment data + description: Paste verbatim output from `$PSVersionTable` below. + render: powershell + placeholder: PS> $PSVersionTable + validations: + required: true +- type: textarea + attributes: + label: Visuals + description: > + Please upload images or animations that can be used to reproduce issues in the area below. + Try the [Steps Recorder](https://support.microsoft.com/en-us/windows/record-steps-to-reproduce-a-problem-46582a9b-620f-2e36-00c9-04e25d784e47) + on Windows or [Screenshot](https://support.apple.com/en-us/HT208721) on macOS. diff --git a/PowerShell-master/.github/ISSUE_TEMPLATE/Feature_Request.yaml b/PowerShell-master/.github/ISSUE_TEMPLATE/Feature_Request.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8e4cec3c4d47a27d7e712539a31e4da7edda2ef --- /dev/null +++ b/PowerShell-master/.github/ISSUE_TEMPLATE/Feature_Request.yaml @@ -0,0 +1,20 @@ +name: Feature Request / Idea 🚀 +description: Suggest a new feature or improvement (this does not mean you have to implement it) +labels: [Issue-Enhancement, Needs-Triage] +body: +- type: textarea + attributes: + label: Summary of the new feature / enhancement + description: > + A clear and concise description of what the problem is that the + new feature would solve. Try formulating it in user story style + (if applicable). + placeholder: "'As a user I want X so that Y...' with X being the being the action and Y being the value of the action." + validations: + required: true +- type: textarea + attributes: + label: Proposed technical implementation details (optional) + placeholder: > + A clear and concise description of what you want to happen. + Consider providing an example PowerShell experience with expected result. diff --git a/PowerShell-master/.github/ISSUE_TEMPLATE/Microsoft_Update_Issue.yaml b/PowerShell-master/.github/ISSUE_TEMPLATE/Microsoft_Update_Issue.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce3de7ae84804410ae80774de74611e18be86f39 --- /dev/null +++ b/PowerShell-master/.github/ISSUE_TEMPLATE/Microsoft_Update_Issue.yaml @@ -0,0 +1,87 @@ +name: Microsoft Update issue report 🐛 +description: Report issue installing a PowerShell 7 Update or fresh install through Microsoft Update 🤔 +labels: Needs-Triage +assignees: + - TravisEz13 +body: +- type: markdown + attributes: + value: > + For Windows PowerShell 5.1 issues, suggestions, or feature requests please use the + [Feedback Hub app](https://support.microsoft.com/windows/send-feedback-to-microsoft-with-the-feedback-hub-app-f59187f8-8739-22d6-ba93-f66612949332) + + This repository is **ONLY** for PowerShell Core 6 and PowerShell 7+ issues. +- type: checkboxes + attributes: + label: Prerequisites + options: + - label: Write a descriptive title. + required: true + - label: Make sure you are able to repro it on the [latest released version](https://github.com/PowerShell/PowerShell/releases) + required: true + - label: Search the existing issues. + required: true + - label: Refer to the [FAQ](https://github.com/PowerShell/PowerShell/blob/master/docs/FAQ.md). + required: true + - label: Refer to [Differences between Windows PowerShell 5.1 and PowerShell](https://learn.microsoft.com/powershell/scripting/whats-new/differences-from-windows-powershell). + required: true +- type: textarea + attributes: + label: Steps to reproduce + description: > + List of steps, sample code, failing test or link to a project that reproduces the behavior. + Make sure you place a stack trace inside a code (```) block to avoid linking unrelated issues. + placeholder: > + I am experiencing a problem with X. + I think Y should be happening but Z is actually happening. + validations: + required: true +- type: textarea + attributes: + label: Expected behavior + render: console + placeholder: | + PS> 2 + 2 + 4 + validations: + required: true +- type: textarea + attributes: + label: Actual behavior + render: console + placeholder: | + PS> 2 + 2 + 5 + validations: + required: true +- type: textarea + attributes: + label: Environment data + description: Paste verbatim output from `$PSVersionTable` below. + render: powershell + placeholder: PS> $PSVersionTable + validations: + required: true +- type: textarea + attributes: + label: OS Data + description: Paste verbatim output from `(Get-CimInstance Win32_OperatingSystem) | Select-Object -Property Version, Caption` below. + render: powershell + placeholder: PS> (Get-CimInstance Win32_OperatingSystem) | Select-Object -Property Version, Caption + validations: + required: true +- type: textarea + attributes: + label: Windows update log + description: Please run `Get-WindowsUpdateLog` and upload the resulting file to this issue. + render: markdown + placeholder: PS> Get-WindowsUpdateLog + validations: + required: true +- type: textarea + attributes: + label: Visuals + description: > + Please upload images or animations that can be used to reproduce issues in the area below. + Try the [Steps Recorder](https://support.microsoft.com/en-us/windows/record-steps-to-reproduce-a-problem-46582a9b-620f-2e36-00c9-04e25d784e47) + on Windows or [Screenshot](https://support.apple.com/en-us/HT208721) on macOS. diff --git a/PowerShell-master/.github/ISSUE_TEMPLATE/Release_Process.yaml b/PowerShell-master/.github/ISSUE_TEMPLATE/Release_Process.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e8d6282db14a39428b43c7e8fad0f814d36b90a --- /dev/null +++ b/PowerShell-master/.github/ISSUE_TEMPLATE/Release_Process.yaml @@ -0,0 +1,41 @@ +name: Release Process +description: Maintainers Only - Release Process +title: "Release Process for v7.x.x" +labels: [Issue-Meta, Needs-Triage] +body: +- type: markdown + attributes: + value: > + This template is for maintainers to create an issues to track the release process. + Please **only** use this template if you are a maintainer. +- type: textarea + attributes: + label: Checklist + value: | + - [ ] Verify that [`PowerShell-Native`](https://github.com/PowerShell/PowerShell-Native) has been updated / released as needed. + - [ ] Check for `PowerShellGet` and `PackageManagement` release plans. + - [ ] Start process to sync Azure DevOps artifacts feed such as modules and NuGet packages. + - [ ] Create a private branch named `release/v6.x.x` in Azure DevOps repository. + All release related changes should happen in this branch. + - [ ] Prepare packages + - [ ] Kick off coordinated build. + - [ ] Kick off Release pipeline. + - *These tasks are orchestrated by the release pipeline, but here as status to the community.* + - [ ] Prepare packages + - [ ] Sign the RPM package. + - [ ] Install and verify the packages. + - [ ] Trigger the docker staging builds (signing must be done). + - [ ] Create the release tag and push the tag to `PowerShell/PowerShell` repository. + - [ ] Run tests on all supported Linux distributions and publish results. + - [ ] Update documentation, and scripts. + - [ ] Update [CHANGELOG.md](../../CHANGELOG.md) with the finalized change log draft. + - [ ] Stage a PR to master to update other documents and + scripts to use the new package names, links, and `metadata.json`. + - [ ] For preview releases, + merge the release branch to GitHub `master` with a merge commit. + - [ ] For non-preview releases, + make sure all changes are either already in master or have a PR open. + - [ ] Delete the release branch. + - [ ] Trigger the Docker image release. + - [ ] Retain builds. + - [ ] Update https://github.com/dotnet/dotnet-docker/tree/master/3.0/sdk with new version and SHA hashes for global tool. NOTE: this link is broken! diff --git a/PowerShell-master/.github/ISSUE_TEMPLATE/WG_member_request.yaml b/PowerShell-master/.github/ISSUE_TEMPLATE/WG_member_request.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d7f0e9ba53f979a2e84f8a38e12150770652a22 --- /dev/null +++ b/PowerShell-master/.github/ISSUE_TEMPLATE/WG_member_request.yaml @@ -0,0 +1,66 @@ +name: Working Group Member Request +description: Request membership to serve on a PowerShell Working Group +title: Working Group Member Request +labels: [WG-NeedsReview, WG-Cmdlets, WG-Engine, WG-Interactive-Console, WG-Remoting, Needs-Triage] +body: +- type: markdown + attributes: + value: | + ## Thank you for your interest in joining a PowerShell Working Group. + + ### Please complete the following public form to request membership to a PowerShell Working Group. + + > [!NOTE] + > Not all Working Groups are accepting new members at this time. +- type : dropdown + id : request_type + validations: + required: true + attributes: + label: Name of Working Group you are requesting to join? + description: >- + Please select the name of the working group you are requesting to join. (Select one) + options: + - "Cmdlets and Modules" + - "Engine" + - "Interactive UX" + - "Remoting" +- type: dropdown + id: time + validations: + required: true + attributes: + label: Can you provide at least 1 hour per week to the Working Group? Note that time commitments will vary per Working Group and decided by its members. + description: >- + Please select Yes or No. + options: + - "Yes" + - "No" +- type: markdown + attributes: + value: | + ## ⚠️ This form is public. Do not provide any private or proprietary information. ⚠️ +- type: textarea + attributes: + label: Why do you want to join this working group? + description: Please provide a brief description of why you want to join this working group. + placeholder: > + I want to join this working group because... + validations: + required: true +- type: textarea + attributes: + label: What skills do you bring to this working group? + description: Please provide a brief description of what skills you bring to this working group. + placeholder: > + I bring the following skills to this working group... + validations: + required: true +- type: textarea + attributes: + label: Public links to articles, code, or other resources that demonstrate your skills. + description: Please provide public links to articles, code, or other resources that demonstrate your skills. + placeholder: > + I have the following public links to articles, code, or other resources that demonstrate my skills... + validations: + required: true diff --git a/PowerShell-master/.github/ISSUE_TEMPLATE/config.yml b/PowerShell-master/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..973921cb24acc3ea8cd000de942462d51d9e55d2 --- /dev/null +++ b/PowerShell-master/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Windows PowerShell + url: https://support.microsoft.com/windows/send-feedback-to-microsoft-with-the-feedback-hub-app-f59187f8-8739-22d6-ba93-f66612949332 + about: Windows PowerShell issues or suggestions. + - name: Support + url: https://github.com/PowerShell/PowerShell/blob/master/.github/SUPPORT.md + about: PowerShell Support Questions/Help + - name: Documentation Issue + url: https://github.com/MicrosoftDocs/PowerShell-Docs/issues/new/choose + about: Please open issues on documentation for PowerShell here. diff --git a/PowerShell-master/.github/Images/Codespaces.png b/PowerShell-master/.github/Images/Codespaces.png new file mode 100644 index 0000000000000000000000000000000000000000..4ee8fcc824476ffcbd61a8787d6d97fec0004956 Binary files /dev/null and b/PowerShell-master/.github/Images/Codespaces.png differ diff --git a/PowerShell-master/.github/Images/GitHub-PR.png b/PowerShell-master/.github/Images/GitHub-PR.png new file mode 100644 index 0000000000000000000000000000000000000000..222d314c945321ccccba834704b84115ed4d5c00 Binary files /dev/null and b/PowerShell-master/.github/Images/GitHub-PR.png differ diff --git a/PowerShell-master/.github/PULL_REQUEST_TEMPLATE.md b/PowerShell-master/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..27089847987e5b99e08d0b824067e569a4a653fc --- /dev/null +++ b/PowerShell-master/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,31 @@ + + +# PR Summary + + + +## PR Context + + + +## PR Checklist + +- [ ] [PR has a meaningful title](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission) + - Use the present tense and imperative mood when describing your changes +- [ ] [Summarized changes](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission) +- [ ] [Make sure all `.h`, `.cpp`, `.cs`, `.ps1` and `.psm1` files have the correct copyright header](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission) +- [ ] This PR is ready to merge. If this PR is a work in progress, please open this as a [Draft Pull Request and mark it as Ready to Review when it is ready to merge](https://docs.github.com/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests). +- **[Breaking changes](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#making-breaking-changes)** + - [ ] None + - **OR** + - [ ] [Experimental feature(s) needed](https://github.com/MicrosoftDocs/PowerShell-Docs/blob/main/reference/7.5/Microsoft.PowerShell.Core/About/about_Experimental_Features.md) + - [ ] Experimental feature name(s): +- **User-facing changes** + - [ ] Not Applicable + - **OR** + - [ ] [Documentation needed](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission) + - [ ] Issue filed: +- **Testing - New and feature** + - [ ] N/A or can only be tested interactively + - **OR** + - [ ] [Make sure you've added a new test if existing tests do not effectively test the code changed](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#before-submitting) diff --git a/PowerShell-master/.github/SECURITY.md b/PowerShell-master/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..797f700385155f71ac2b2f05f08ea5f0f201cd17 --- /dev/null +++ b/PowerShell-master/.github/SECURITY.md @@ -0,0 +1,39 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin) and [PowerShell](https://github.com/PowerShell). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). + +You should receive a response within 24 hours. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd). + + diff --git a/PowerShell-master/.github/SUPPORT.md b/PowerShell-master/.github/SUPPORT.md new file mode 100644 index 0000000000000000000000000000000000000000..6acedb28d27bea0770901771606bc40d2aa2c2bb --- /dev/null +++ b/PowerShell-master/.github/SUPPORT.md @@ -0,0 +1,13 @@ +# PowerShell Support + +If you have any problems, please consult the [known issues][], developer [FAQ][], and [GitHub issues][]. +If you do not see your problem captured, please file a [new issue][] and follow the provided template. +Also make sure to see the [Official Support Policy][]. +If you know how to fix the issue, feel free to send a pull request our way. (The [Contribution Guides][] apply to that pull request, you may want to give it a read!) + +[Official Support Policy]: https://learn.microsoft.com/powershell/scripting/powershell-support-lifecycle +[FAQ]: https://github.com/PowerShell/PowerShell/tree/master/docs/FAQ.md +[Contribution Guides]: https://github.com/PowerShell/PowerShell/tree/master/.github/CONTRIBUTING.md +[known issues]: https://learn.microsoft.com/powershell/scripting/whats-new/differences-from-windows-powershell +[GitHub issues]: https://github.com/PowerShell/PowerShell/issues +[new issue]: https://github.com/PowerShell/PowerShell/issues/new/choose diff --git a/PowerShell-master/.github/action-filters.yml b/PowerShell-master/.github/action-filters.yml new file mode 100644 index 0000000000000000000000000000000000000000..9a61bc1947bc5efc0b545bdf7bb2e08886af6cd6 --- /dev/null +++ b/PowerShell-master/.github/action-filters.yml @@ -0,0 +1,23 @@ +github: &github + - .github/actions/** + - .github/workflows/**-ci.yml +tools: &tools + - tools/buildCommon/** + - tools/ci.psm1 +props: &props + - '**.props' +tests: &tests + - test/powershell/** + - test/tools/** + - test/xUnit/** +mainSource: &mainSource + - src/** +buildModule: &buildModule + - build.psm1 +source: + - *github + - *tools + - *props + - *buildModule + - *mainSource + - *tests diff --git a/PowerShell-master/.github/actions/build/ci/action.yml b/PowerShell-master/.github/actions/build/ci/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..65331fb3185b641e57540f04ac58be0861f6d93c --- /dev/null +++ b/PowerShell-master/.github/actions/build/ci/action.yml @@ -0,0 +1,40 @@ +name: CI Build +description: 'Builds PowerShell' +runs: + using: composite + steps: + - name: Capture Environment + if: success() || failure() + run: |- + Import-Module .\tools\ci.psm1 + Show-Environment + shell: pwsh + - name: Set Build Name for Non-PR + if: github.event_name != 'PullRequest' + run: Write-Host "##vso[build.updatebuildnumber]$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))" + shell: pwsh + - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 + with: + global-json-file: ./global.json + - name: Bootstrap + if: success() + run: |- + Write-Verbose -Verbose "Running Bootstrap..." + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + Write-Verbose -Verbose "Start Sync-PSTags" + Sync-PSTags -AddRemoteIfMissing + Write-Verbose -Verbose "End Sync-PSTags" + shell: pwsh + - name: Build + if: success() + run: |- + Write-Verbose -Verbose "Running Build..." + Import-Module .\tools\ci.psm1 + Invoke-CIBuild + shell: pwsh + - name: Upload build artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: build + path: ${{ runner.workspace }}/build diff --git a/PowerShell-master/.github/actions/infrastructure/get-changed-files/README.md b/PowerShell-master/.github/actions/infrastructure/get-changed-files/README.md new file mode 100644 index 0000000000000000000000000000000000000000..277b28c0674346f0a5ad889b209181c050c85e87 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/get-changed-files/README.md @@ -0,0 +1,122 @@ +# Get Changed Files Action + +A reusable composite action that retrieves the list of files changed in a pull request or push event. + +## Features + +- Supports both `pull_request` and `push` events +- Optional filtering by file pattern +- Returns files as JSON array for easy consumption +- Filters out deleted files (only returns added, modified, or renamed files) +- Handles up to 100 changed files per request + +## Usage + +### Basic Usage (Pull Requests Only) + +```yaml +- name: Get changed files + id: changed-files + uses: "./.github/actions/infrastructure/get-changed-files" + +- name: Process files + run: | + echo "Changed files: ${{ steps.changed-files.outputs.files }}" + echo "Count: ${{ steps.changed-files.outputs.count }}" +``` + +### With Filtering + +```yaml +# Get only markdown files +- name: Get changed markdown files + id: changed-md + uses: "./.github/actions/infrastructure/get-changed-files" + with: + filter: '*.md' + +# Get only GitHub workflow/action files +- name: Get changed GitHub files + id: changed-github + uses: "./.github/actions/infrastructure/get-changed-files" + with: + filter: '.github/' +``` + +### Support Both PR and Push Events + +```yaml +- name: Get changed files + id: changed-files + uses: "./.github/actions/infrastructure/get-changed-files" + with: + event-types: 'pull_request,push' +``` + +## Inputs + +| Name | Description | Required | Default | +|------|-------------|----------|---------| +| `filter` | Optional filter pattern (e.g., `*.md` for markdown files, `.github/` for GitHub files) | No | `''` | +| `event-types` | Comma-separated list of event types to support (`pull_request`, `push`) | No | `pull_request` | + +## Outputs + +| Name | Description | +|------|-------------| +| `files` | JSON array of changed file paths | +| `count` | Number of changed files | + +## Filter Patterns + +The action supports simple filter patterns: + +- **Extension matching**: Use `*.ext` to match files with a specific extension + - Example: `*.md` matches all markdown files + - Example: `*.yml` matches all YAML files + +- **Path prefix matching**: Use a path prefix to match files in a directory + - Example: `.github/` matches all files in the `.github` directory + - Example: `tools/` matches all files in the `tools` directory + +## Example: Processing Changed Files + +```yaml +- name: Get changed files + id: changed-files + uses: "./.github/actions/infrastructure/get-changed-files" + +- name: Process each file + shell: pwsh + env: + CHANGED_FILES: ${{ steps.changed-files.outputs.files }} + run: | + $changedFilesJson = $env:CHANGED_FILES + $changedFiles = $changedFilesJson | ConvertFrom-Json + + foreach ($file in $changedFiles) { + Write-Host "Processing: $file" + # Your processing logic here + } +``` + +## Limitations + +- Simple filter patterns only (no complex glob or regex patterns) + +## Pagination + +The action automatically handles pagination to fetch **all** changed files in a PR, regardless of how many files were changed: + +- Fetches files in batches of 100 per page +- Continues fetching until all files are retrieved +- Logs a note when pagination occurs, showing the total file count +- **No file limit** - all changed files will be processed, even in very large PRs + +This ensures that critical workflows (such as merge conflict checking, link validation, etc.) don't miss files due to pagination limits. + +## Related Actions + +- **markdownlinks**: Uses this pattern to get changed markdown files +- **merge-conflict-checker**: Uses this pattern to get changed files for conflict detection +- **path-filters**: Similar functionality but with more complex filtering logic diff --git a/PowerShell-master/.github/actions/infrastructure/get-changed-files/action.yml b/PowerShell-master/.github/actions/infrastructure/get-changed-files/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..51631cfe141bdee2b4e6274d0e51384624ecae13 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/get-changed-files/action.yml @@ -0,0 +1,117 @@ +name: 'Get Changed Files' +description: 'Gets the list of files changed in a pull request or push event' +inputs: + filter: + description: 'Optional filter pattern (e.g., "*.md" for markdown files, ".github/" for GitHub files)' + required: false + default: '' + event-types: + description: 'Comma-separated list of event types to support (pull_request, push)' + required: false + default: 'pull_request' +outputs: + files: + description: 'JSON array of changed file paths' + value: ${{ steps.get-files.outputs.files }} + count: + description: 'Number of changed files' + value: ${{ steps.get-files.outputs.count }} +runs: + using: 'composite' + steps: + - name: Get changed files + id: get-files + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + with: + script: | + const eventTypes = '${{ inputs.event-types }}'.split(',').map(t => t.trim()); + const filter = '${{ inputs.filter }}'; + let changedFiles = []; + + if (eventTypes.includes('pull_request') && context.eventName === 'pull_request') { + console.log(`Getting files changed in PR #${context.payload.pull_request.number}`); + + // Fetch all files changed in the PR with pagination + let allFiles = []; + let page = 1; + let fetchedCount; + + do { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + per_page: 100, + page: page + }); + + allFiles = allFiles.concat(files); + fetchedCount = files.length; + page++; + } while (fetchedCount === 100); + + if (allFiles.length >= 100) { + console.log(`Note: This PR has ${allFiles.length} changed files. All files fetched using pagination.`); + } + + changedFiles = allFiles + .filter(file => file.status === 'added' || file.status === 'modified' || file.status === 'renamed') + .map(file => file.filename); + + } else if (eventTypes.includes('push') && context.eventName === 'push') { + console.log(`Getting files changed in push to ${context.ref}`); + + const { data: comparison } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: context.payload.before, + head: context.payload.after, + }); + + changedFiles = comparison.files + .filter(file => file.status === 'added' || file.status === 'modified' || file.status === 'renamed') + .map(file => file.filename); + + } else { + core.setFailed(`Unsupported event type: ${context.eventName}. Supported types: ${eventTypes.join(', ')}`); + return; + } + + // Apply filter if provided + if (filter) { + const filterLower = filter.toLowerCase(); + const beforeFilter = changedFiles.length; + changedFiles = changedFiles.filter(file => { + const fileLower = file.toLowerCase(); + // Support simple patterns like "*.md" or ".github/" + if (filterLower.startsWith('*.')) { + const ext = filterLower.substring(1); + return fileLower.endsWith(ext); + } else { + return fileLower.startsWith(filterLower); + } + }); + console.log(`Filter '${filter}' applied: ${beforeFilter} → ${changedFiles.length} files`); + } + + // Calculate simple hash for verification + const crypto = require('crypto'); + const filesJson = JSON.stringify(changedFiles.sort()); + const hash = crypto.createHash('sha256').update(filesJson).digest('hex').substring(0, 8); + + // Log changed files in a collapsible group + core.startGroup(`Changed Files (${changedFiles.length} total, hash: ${hash})`); + if (changedFiles.length > 0) { + changedFiles.forEach(file => console.log(` - ${file}`)); + } else { + console.log(' (no files changed)'); + } + core.endGroup(); + + console.log(`Found ${changedFiles.length} changed files`); + core.setOutput('files', JSON.stringify(changedFiles)); + core.setOutput('count', changedFiles.length); + +branding: + icon: 'file-text' + color: 'blue' diff --git a/PowerShell-master/.github/actions/infrastructure/markdownlinks/Parse-MarkdownLink.ps1 b/PowerShell-master/.github/actions/infrastructure/markdownlinks/Parse-MarkdownLink.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..a56d696eb6ec935dbb9fedd8ec0ae50fa28e431c --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/markdownlinks/Parse-MarkdownLink.ps1 @@ -0,0 +1,182 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +#requires -version 7 +# Markdig is always available in PowerShell 7 +<# +.SYNOPSIS + Parse CHANGELOG files using Markdig to extract links. + +.DESCRIPTION + This script uses Markdig.Markdown.Parse to parse all markdown files in the CHANGELOG directory + and extract different types of links (inline links, reference links, etc.). + +.PARAMETER ChangelogPath + Path to the CHANGELOG directory. Defaults to ./CHANGELOG + +.PARAMETER LinkType + Filter by link type: All, Inline, Reference, AutoLink. Defaults to All. + +.EXAMPLE + .\Parse-MarkdownLink.ps1 + +.EXAMPLE + .\Parse-MarkdownLink.ps1 -LinkType Reference +#> + +param( + [string]$ChangelogPath = "./CHANGELOG", + [ValidateSet("All", "Inline", "Reference", "AutoLink")] + [string]$LinkType = "All" +) + +Write-Verbose "Using built-in Markdig functionality to parse markdown files" + +function Get-LinksFromMarkdownAst { + param( + [Parameter(Mandatory)] + [object]$Node, + [Parameter(Mandatory)] + [string]$FileName, + [System.Collections.ArrayList]$Links + ) + + if ($null -eq $Links) { + return + } + + # Check if current node is a link + if ($Node -is [Markdig.Syntax.Inlines.LinkInline]) { + $linkInfo = [PSCustomObject]@{ + Path = $FileName + Line = $Node.Line + 1 # Convert to 1-based line numbering + Column = $Node.Column + 1 # Convert to 1-based column numbering + Url = $Node.Url ?? "" + Text = $Node.FirstChild?.ToString() ?? "" + Type = "Inline" + IsImage = $Node.IsImage + } + [void]$Links.Add($linkInfo) + } + elseif ($Node -is [Markdig.Syntax.Inlines.AutolinkInline]) { + $linkInfo = [PSCustomObject]@{ + Path = $FileName + Line = $Node.Line + 1 + Column = $Node.Column + 1 + Url = $Node.Url ?? "" + Text = $Node.Url ?? "" + Type = "AutoLink" + IsImage = $false + } + [void]$Links.Add($linkInfo) + } + elseif ($Node -is [Markdig.Syntax.LinkReferenceDefinitionGroup]) { + foreach ($refDef in $Node) { + $linkInfo = [PSCustomObject]@{ + Path = $FileName + Line = $refDef.Line + 1 + Column = $refDef.Column + 1 + Url = $refDef.Url ?? "" + Text = $refDef.Label ?? "" + Type = "Reference" + IsImage = $false + } + [void]$Links.Add($linkInfo) + } + } + elseif ($Node -is [Markdig.Syntax.LinkReferenceDefinition]) { + $linkInfo = [PSCustomObject]@{ + Path = $FileName + Line = $Node.Line + 1 + Column = $Node.Column + 1 + Url = $Node.Url ?? "" + Text = $Node.Label ?? "" + Type = "Reference" + IsImage = $false + } + [void]$Links.Add($linkInfo) + } + + # For MarkdownDocument (root), iterate through all blocks + if ($Node -is [Markdig.Syntax.MarkdownDocument]) { + foreach ($block in $Node) { + Get-LinksFromMarkdownAst -Node $block -FileName $FileName -Links $Links + } + } + # For block containers, iterate through children + elseif ($Node -is [Markdig.Syntax.ContainerBlock]) { + foreach ($child in $Node) { + Get-LinksFromMarkdownAst -Node $child -FileName $FileName -Links $Links + } + } + # For leaf blocks with inlines, process the inline content + elseif ($Node -is [Markdig.Syntax.LeafBlock] -and $Node.Inline) { + Get-LinksFromMarkdownAst -Node $Node.Inline -FileName $FileName -Links $Links + } + # For inline containers, process all child inlines + elseif ($Node -is [Markdig.Syntax.Inlines.ContainerInline]) { + $child = $Node.FirstChild + while ($child) { + Get-LinksFromMarkdownAst -Node $child -FileName $FileName -Links $Links + $child = $child.NextSibling + } + } + # For other inline elements that might have children + elseif ($Node.PSObject.Properties.Name -contains "FirstChild" -and $Node.FirstChild) { + $child = $Node.FirstChild + while ($child) { + Get-LinksFromMarkdownAst -Node $child -FileName $FileName -Links $Links + $child = $child.NextSibling + } + } +} + +function Parse-ChangelogFiles { + param( + [string]$Path + ) + + if (-not (Test-Path $Path)) { + Write-Error "CHANGELOG directory not found: $Path" + return + } + + $markdownFiles = Get-ChildItem -Path $Path -Filter "*.md" -File + + if ($markdownFiles.Count -eq 0) { + Write-Warning "No markdown files found in $Path" + return + } + + $allLinks = [System.Collections.ArrayList]::new() + + foreach ($file in $markdownFiles) { + Write-Verbose "Processing file: $($file.Name)" + + try { + $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8 + + # Parse the markdown content using Markdig + $document = [Markdig.Markdown]::Parse($content, [Markdig.MarkdownPipelineBuilder]::new()) + + # Extract links from the AST + Get-LinksFromMarkdownAst -Node $document -FileName $file.FullName -Links $allLinks + + } catch { + Write-Warning "Error processing file $($file.Name): $($_.Exception.Message)" + } + } + + # Filter by link type if specified + if ($LinkType -ne "All") { + $allLinks = $allLinks | Where-Object { $_.Type -eq $LinkType } + } + + return $allLinks +} + +# Main execution +$links = Parse-ChangelogFiles -Path $ChangelogPath + +# Output PowerShell objects +$links diff --git a/PowerShell-master/.github/actions/infrastructure/markdownlinks/README.md b/PowerShell-master/.github/actions/infrastructure/markdownlinks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e566ec2bcc3be36061b087c28ac4a1e4243e6f33 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/markdownlinks/README.md @@ -0,0 +1,177 @@ +# Verify Markdown Links Action + +A GitHub composite action that verifies all links in markdown files using PowerShell and Markdig. + +## Features + +- ✅ Parses markdown files using Markdig (built into PowerShell 7) +- ✅ Extracts all link types: inline links, reference links, and autolinks +- ✅ Verifies HTTP/HTTPS links with configurable timeouts and retries +- ✅ Validates local file references +- ✅ Supports excluding specific URL patterns +- ✅ Provides detailed error reporting with file locations +- ✅ Outputs metrics for CI/CD integration + +## Usage + +### Basic Usage + +```yaml +- name: Verify Markdown Links + uses: ./.github/actions/infrastructure/markdownlinks + with: + path: './CHANGELOG' +``` + +### Advanced Usage + +```yaml +- name: Verify Markdown Links + uses: ./.github/actions/infrastructure/markdownlinks + with: + path: './docs' + fail-on-error: 'true' + timeout: 30 + max-retries: 2 + exclude-patterns: '*.example.com/*,*://localhost/*' +``` + +### With Outputs + +```yaml +- name: Verify Markdown Links + id: verify-links + uses: ./.github/actions/infrastructure/markdownlinks + with: + path: './CHANGELOG' + fail-on-error: 'false' + +- name: Display Results + run: | + echo "Total links: ${{ steps.verify-links.outputs.total-links }}" + echo "Passed: ${{ steps.verify-links.outputs.passed-links }}" + echo "Failed: ${{ steps.verify-links.outputs.failed-links }}" + echo "Skipped: ${{ steps.verify-links.outputs.skipped-links }}" +``` + +## Inputs + +| Input | Description | Required | Default | +|-------|-------------|----------|---------| +| `path` | Path to the directory containing markdown files to verify | No | `./CHANGELOG` | +| `exclude-patterns` | Comma-separated list of URL patterns to exclude from verification | No | `''` | +| `fail-on-error` | Whether to fail the action if any links are broken | No | `true` | +| `timeout` | Timeout in seconds for HTTP requests | No | `30` | +| `max-retries` | Maximum number of retries for failed requests | No | `2` | + +## Outputs + +| Output | Description | +|--------|-------------| +| `total-links` | Total number of unique links checked | +| `passed-links` | Number of links that passed verification | +| `failed-links` | Number of links that failed verification | +| `skipped-links` | Number of links that were skipped | + +## Excluded Link Types + +The action automatically skips the following link types: + +- **Anchor links** (`#section-name`) - Would require full markdown parsing +- **Email links** (`mailto:user@example.com`) - Cannot be verified without sending email + +## GitHub Workflow Test + +This section provides a workflow example and instructions for testing the link verification action. + +### Testing the Workflow + +To test that the workflow properly detects broken links: + +1. Make change to this file (e.g., this README.md file already contains one in the [Broken Link Test](#broken-link-test) section) +1. The workflow will run and should fail, reporting the broken link(s) +1. Revert your change to this file +1. Push again to verify the workflow passes + +### Example Workflow Configuration + +```yaml +name: Verify Links + +on: + push: + branches: [ main ] + paths: + - '**/*.md' + pull_request: + branches: [ main ] + paths: + - '**/*.md' + schedule: + # Run weekly to catch external link rot + - cron: '0 0 * * 0' + +jobs: + verify-links: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Verify CHANGELOG Links + uses: ./.github/actions/infrastructure/markdownlinks + with: + path: './CHANGELOG' + fail-on-error: 'true' + + - name: Verify Documentation Links + uses: ./.github/actions/infrastructure/markdownlinks + with: + path: './docs' + fail-on-error: 'false' + exclude-patterns: '*.internal.example.com/*' +``` + +## How It Works + +1. **Parse Markdown**: Uses `Parse-MarkdownLink.ps1` to extract all links from markdown files using Markdig +2. **Deduplicate**: Groups links by URL to avoid checking the same link multiple times +3. **Verify Links**: + - HTTP/HTTPS links: Makes HEAD/GET requests with configurable timeout and retries + - Local file references: Checks if the file exists relative to the markdown file + - Excluded patterns: Skips links matching the exclude patterns +4. **Report Results**: Displays detailed results with file locations for failed links +5. **Set Outputs**: Provides metrics for downstream steps + +## Error Output Example + +``` +✗ FAILED: https://example.com/broken-link - HTTP 404 + Found in: /path/to/file.md:42:15 + Found in: /path/to/other.md:100:20 + +Link Verification Summary +============================================================ +Total URLs checked: 150 +Passed: 145 +Failed: 2 +Skipped: 3 + +Failed Links: + • https://example.com/broken-link + Error: HTTP 404 + Occurrences: 2 +``` + +## Requirements + +- PowerShell 7+ (includes Markdig) +- Runs on: `ubuntu-latest`, `windows-latest`, `macos-latest` + +## Broken Link Test + +- [Broken Link](https://github.com/PowerShell/PowerShell/wiki/NonExistentPage404) + +## License + +Same as the PowerShell repository. diff --git a/PowerShell-master/.github/actions/infrastructure/markdownlinks/Verify-MarkdownLinks.ps1 b/PowerShell-master/.github/actions/infrastructure/markdownlinks/Verify-MarkdownLinks.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..f50ab1590b9ba0969f92b65908e7dd0094599875 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/markdownlinks/Verify-MarkdownLinks.ps1 @@ -0,0 +1,317 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +#Requires -Version 7.0 + +<# +.SYNOPSIS + Verify all links in markdown files. + +.DESCRIPTION + This script parses markdown files to extract links and verifies their accessibility. + It supports HTTP/HTTPS links and local file references. + +.PARAMETER Path + Path to the directory containing markdown files. Defaults to current directory. + +.PARAMETER File + Array of specific markdown files to verify. If provided, Path parameter is ignored. + +.PARAMETER TimeoutSec + Timeout in seconds for HTTP requests. Defaults to 30. + +.PARAMETER MaximumRetryCount + Maximum number of retries for failed requests. Defaults to 2. + +.PARAMETER RetryIntervalSec + Interval in seconds between retry attempts. Defaults to 2. + +.EXAMPLE + .\Verify-MarkdownLinks.ps1 -Path ./CHANGELOG + +.EXAMPLE + .\Verify-MarkdownLinks.ps1 -Path ./docs -FailOnError + +.EXAMPLE + .\Verify-MarkdownLinks.ps1 -File @('CHANGELOG/7.5.md', 'README.md') +#> + +param( + [Parameter(ParameterSetName = 'ByPath', Mandatory)] + [string]$Path = "Q:\src\git\powershell\docs\git", + [Parameter(ParameterSetName = 'ByFile', Mandatory)] + [string[]]$File = @(), + [int]$TimeoutSec = 30, + [int]$MaximumRetryCount = 2, + [int]$RetryIntervalSec = 2 +) + +$ErrorActionPreference = 'Stop' + +# Get the script directory +$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path + +# Determine what to process: specific files or directory +if ($File.Count -gt 0) { + Write-Host "Extracting links from $($File.Count) specified markdown file(s)" -ForegroundColor Cyan + + # Process each file individually + $allLinks = @() + $parseScriptPath = Join-Path $scriptDir "Parse-MarkdownLink.ps1" + + foreach ($filePath in $File) { + if (Test-Path $filePath) { + Write-Verbose "Processing: $filePath" + $fileLinks = & $parseScriptPath -ChangelogPath $filePath + $allLinks += $fileLinks + } + else { + Write-Warning "File not found: $filePath" + } + } +} +else { + Write-Host "Extracting links from markdown files in: $Path" -ForegroundColor Cyan + + # Get all links from markdown files using the Parse-ChangelogLinks script + $parseScriptPath = Join-Path $scriptDir "Parse-MarkdownLink.ps1" + $allLinks = & $parseScriptPath -ChangelogPath $Path +} + +if ($allLinks.Count -eq 0) { + Write-Host "No links found in markdown files." -ForegroundColor Yellow + exit 0 +} + +Write-Host "Found $($allLinks.Count) links to verify" -ForegroundColor Green + +# Group links by URL to avoid duplicate checks +$uniqueLinks = $allLinks | Group-Object -Property Url + +Write-Host "Unique URLs to verify: $($uniqueLinks.Count)" -ForegroundColor Cyan + +$results = @{ + Total = $uniqueLinks.Count + Passed = 0 + Failed = 0 + Skipped = 0 + Errors = [System.Collections.ArrayList]::new() +} + +function Test-HttpLink { + param( + [string]$Url + ) + + try { + # Try HEAD request first (faster, doesn't download content) + $response = Invoke-WebRequest -Uri $Url ` + -Method Head ` + -TimeoutSec $TimeoutSec ` + -MaximumRetryCount $MaximumRetryCount ` + -RetryIntervalSec $RetryIntervalSec ` + -UserAgent "Mozilla/5.0 (compatible; GitHubActions/1.0; +https://github.com/PowerShell/PowerShell)" ` + -SkipHttpErrorCheck + + # If HEAD fails with 404 or 405, retry with GET (some servers don't support HEAD) + if ($response.StatusCode -eq 404 -or $response.StatusCode -eq 405) { + Write-Verbose "HEAD request failed with $($response.StatusCode), retrying with GET for: $Url" + $response = Invoke-WebRequest -Uri $Url ` + -Method Get ` + -TimeoutSec $TimeoutSec ` + -MaximumRetryCount $MaximumRetryCount ` + -RetryIntervalSec $RetryIntervalSec ` + -UserAgent "Mozilla/5.0 (compatible; GitHubActions/1.0; +https://github.com)" ` + -SkipHttpErrorCheck + } + + if ($response.StatusCode -ge 200 -and $response.StatusCode -lt 400) { + return @{ Success = $true; StatusCode = $response.StatusCode } + } + else { + return @{ Success = $false; StatusCode = $response.StatusCode; Error = "HTTP $($response.StatusCode)" } + } + } + catch { + return @{ Success = $false; StatusCode = 0; Error = $_.Exception.Message } + } +} + +function Test-LocalLink { + param( + [string]$Url, + [string]$BasePath + ) + + # Strip query parameters (e.g., ?sanitize=true) and anchors (e.g., #section) + $cleanUrl = $Url -replace '\?.*$', '' -replace '#.*$', '' + + # Handle relative paths + $targetPath = Join-Path $BasePath $cleanUrl + + if (Test-Path $targetPath) { + return @{ Success = $true } + } + else { + return @{ Success = $false; Error = "File not found: $targetPath" } + } +} + +# Verify each unique link +$progressCount = 0 +foreach ($linkGroup in $uniqueLinks) { + $progressCount++ + $url = $linkGroup.Name + $occurrences = $linkGroup.Group + Write-Verbose -Verbose "[$progressCount/$($uniqueLinks.Count)] Checking: $url" + + # Determine link type and verify + $verifyResult = $null + if ($url -match '^https?://') { + $verifyResult = Test-HttpLink -Url $url + } + elseif ($url -match '^#') { + Write-Verbose -Verbose "Skipping anchor link: $url" + $results.Skipped++ + continue + } + elseif ($url -match '^mailto:') { + Write-Verbose -Verbose "Skipping mailto link: $url" + $results.Skipped++ + continue + } + else { + $basePath = Split-Path -Parent $occurrences[0].Path + $verifyResult = Test-LocalLink -Url $url -BasePath $basePath + } + if ($verifyResult.Success) { + Write-Host "✓ OK: $url" -ForegroundColor Green + $results.Passed++ + } + else { + $errorMsg = if ($verifyResult.StatusCode) { + "HTTP $($verifyResult.StatusCode)" + } + else { + $verifyResult.Error + } + + # Determine if this status code should be ignored or treated as failure + # Ignore: 401 (Unauthorized), 403 (Forbidden), 429 (Too Many Requests - already retried) + # Fail: 404 (Not Found), 410 (Gone), 406 (Not Acceptable) - these indicate broken links + $shouldIgnore = $false + $ignoreReason = "" + + switch ($verifyResult.StatusCode) { + 401 { + $shouldIgnore = $true + $ignoreReason = "authentication required" + } + 403 { + $shouldIgnore = $true + $ignoreReason = "access forbidden" + } + 429 { + $shouldIgnore = $true + $ignoreReason = "rate limited (already retried)" + } + } + + if ($shouldIgnore) { + Write-Host "⊘ IGNORED: $url - $errorMsg ($ignoreReason)" -ForegroundColor Yellow + Write-Verbose -Verbose "Ignored error details for $url - Status: $($verifyResult.StatusCode) - $ignoreReason" + foreach ($occurrence in $occurrences) { + Write-Verbose -Verbose " Found in: $($occurrence.Path):$($occurrence.Line):$($occurrence.Column)" + } + $results.Skipped++ + } + else { + Write-Host "✗ FAILED: $url - $errorMsg" -ForegroundColor Red + foreach ($occurrence in $occurrences) { + Write-Host " Found in: $($occurrence.Path):$($occurrence.Line):$($occurrence.Column)" -ForegroundColor DarkGray + } + $results.Failed++ + [void]$results.Errors.Add(@{ + Url = $url + Error = $errorMsg + Occurrences = $occurrences + }) + } + } + } + +# Print summary +Write-Host "`n" + ("=" * 60) -ForegroundColor Cyan +Write-Host "Link Verification Summary" -ForegroundColor Cyan +Write-Host ("=" * 60) -ForegroundColor Cyan +Write-Host "Total URLs checked: $($results.Total)" -ForegroundColor White +Write-Host "Passed: $($results.Passed)" -ForegroundColor Green +Write-Host "Failed: $($results.Failed)" -ForegroundColor $(if ($results.Failed -gt 0) { "Red" } else { "Green" }) +Write-Host "Skipped: $($results.Skipped)" -ForegroundColor Gray + +if ($results.Failed -gt 0) { + Write-Host "`nFailed Links:" -ForegroundColor Red + foreach ($failedLink in $results.Errors) { + Write-Host " • $($failedLink.Url)" -ForegroundColor Red + Write-Host " Error: $($failedLink.Error)" -ForegroundColor DarkGray + Write-Host " Occurrences: $($failedLink.Occurrences.Count)" -ForegroundColor DarkGray + } + + Write-Host "`n❌ Link verification failed!" -ForegroundColor Red + exit 1 +} +else { + Write-Host "`n✅ All links verified successfully!" -ForegroundColor Green +} + +# Write to GitHub Actions step summary if running in a workflow +if ($env:GITHUB_STEP_SUMMARY) { + $summaryContent = @" + +# Markdown Link Verification Results + +## Summary +- **Total URLs checked:** $($results.Total) +- **Passed:** ✅ $($results.Passed) +- **Failed:** $(if ($results.Failed -gt 0) { "❌" } else { "✅" }) $($results.Failed) +- **Skipped:** $($results.Skipped) + +"@ + + if ($results.Failed -gt 0) { + $summaryContent += @" + +## Failed Links + +| URL | Error | Occurrences | +|-----|-------|-------------| + +"@ + foreach ($failedLink in $results.Errors) { + $summaryContent += "| $($failedLink.Url) | $($failedLink.Error) | $($failedLink.Occurrences.Count) |`n" + } + + $summaryContent += @" + +
+Click to see all failed link locations + +"@ + foreach ($failedLink in $results.Errors) { + $summaryContent += "`n### $($failedLink.Url)`n" + $summaryContent += "**Error:** $($failedLink.Error)`n`n" + foreach ($occurrence in $failedLink.Occurrences) { + $summaryContent += "- `$($occurrence.Path):$($occurrence.Line):$($occurrence.Column)`n" + } + } + $summaryContent += "`n
`n" + } + else { + $summaryContent += "`n## ✅ All links verified successfully!`n" + } + + Write-Verbose -Verbose "Writing `n $summaryContent `n to ${env:GITHUB_STEP_SUMMARY}" + $summaryContent | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append + Write-Verbose -Verbose "Summary written to GitHub Actions step summary" +} + diff --git a/PowerShell-master/.github/actions/infrastructure/markdownlinks/action.yml b/PowerShell-master/.github/actions/infrastructure/markdownlinks/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..de2952252d49d733fa80b334939f540ab0c21cf3 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/markdownlinks/action.yml @@ -0,0 +1,110 @@ +name: 'Verify Markdown Links' +description: 'Verify all links in markdown files using PowerShell and Markdig' +author: 'PowerShell Team' + +inputs: + timeout-sec: + description: 'Timeout in seconds for HTTP requests' + required: false + default: '30' + maximum-retry-count: + description: 'Maximum number of retries for failed requests' + required: false + default: '2' + +outputs: + total-links: + description: 'Total number of unique links checked' + value: ${{ steps.verify.outputs.total }} + passed-links: + description: 'Number of links that passed verification' + value: ${{ steps.verify.outputs.passed }} + failed-links: + description: 'Number of links that failed verification' + value: ${{ steps.verify.outputs.failed }} + skipped-links: + description: 'Number of links that were skipped' + value: ${{ steps.verify.outputs.skipped }} + +runs: + using: 'composite' + steps: + - name: Get changed markdown files + id: changed-files + uses: "./.github/actions/infrastructure/get-changed-files" + with: + filter: '*.md' + event-types: 'pull_request,push' + + - name: Verify markdown links + id: verify + shell: pwsh + env: + CHANGED_FILES_JSON: ${{ steps.changed-files.outputs.files }} + run: | + Write-Host "Starting markdown link verification..." -ForegroundColor Cyan + + # Get changed markdown files from environment variable (secure against injection) + $changedFilesJson = $env:CHANGED_FILES_JSON + $changedFiles = $changedFilesJson | ConvertFrom-Json + + if ($changedFiles.Count -eq 0) { + Write-Host "No markdown files changed, skipping verification" -ForegroundColor Yellow + "total=0" >> $env:GITHUB_OUTPUT + "passed=0" >> $env:GITHUB_OUTPUT + "failed=0" >> $env:GITHUB_OUTPUT + "skipped=0" >> $env:GITHUB_OUTPUT + exit 0 + } + + Write-Host "Changed markdown files: $($changedFiles.Count)" -ForegroundColor Cyan + $changedFiles | ForEach-Object { Write-Host " - $_" -ForegroundColor Gray } + + # Build parameters for each file + $params = @{ + File = $changedFiles + TimeoutSec = [int]'${{ inputs.timeout-sec }}' + MaximumRetryCount = [int]'${{ inputs.maximum-retry-count }}' + } + + # Run the verification script + $scriptPath = Join-Path '${{ github.action_path }}' 'Verify-MarkdownLinks.ps1' + + # Capture output and parse results + $output = & $scriptPath @params 2>&1 | Tee-Object -Variable capturedOutput + + # Try to extract metrics from output + $totalLinks = 0 + $passedLinks = 0 + $failedLinks = 0 + $skippedLinks = 0 + + foreach ($line in $capturedOutput) { + if ($line -match 'Total URLs checked: (\d+)') { + $totalLinks = $Matches[1] + } + elseif ($line -match 'Passed: (\d+)') { + $passedLinks = $Matches[1] + } + elseif ($line -match 'Failed: (\d+)') { + $failedLinks = $Matches[1] + } + elseif ($line -match 'Skipped: (\d+)') { + $skippedLinks = $Matches[1] + } + } + + # Set outputs + "total=$totalLinks" >> $env:GITHUB_OUTPUT + "passed=$passedLinks" >> $env:GITHUB_OUTPUT + "failed=$failedLinks" >> $env:GITHUB_OUTPUT + "skipped=$skippedLinks" >> $env:GITHUB_OUTPUT + + Write-Host "Action completed" -ForegroundColor Cyan + + # Exit with the same code as the verification script + exit $LASTEXITCODE + +branding: + icon: 'link' + color: 'blue' diff --git a/PowerShell-master/.github/actions/infrastructure/merge-conflict-checker/README.md b/PowerShell-master/.github/actions/infrastructure/merge-conflict-checker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b53d6f999647329756e71e2bca5c4315c250ad29 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/merge-conflict-checker/README.md @@ -0,0 +1,86 @@ +# Merge Conflict Checker + +This composite GitHub Action checks for Git merge conflict markers in files changed in pull requests. + +## Purpose + +Automatically detects leftover merge conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) in pull request files to prevent them from being merged into the codebase. + +## Usage + +### In a Workflow + +```yaml +- name: Check for merge conflict markers + uses: "./.github/actions/infrastructure/merge-conflict-checker" +``` + +### Complete Example + +```yaml +jobs: + merge_conflict_check: + name: Check for Merge Conflict Markers + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' + permissions: + pull-requests: read + contents: read + steps: + - name: checkout + uses: actions/checkout@v5 + + - name: Check for merge conflict markers + uses: "./.github/actions/infrastructure/merge-conflict-checker" +``` + +## How It Works + +1. **File Detection**: Uses GitHub's API to get the list of files changed in the pull request +2. **Marker Scanning**: Reads each changed file and searches for the following markers: + - `<<<<<<<` (conflict start marker) + - `=======` (conflict separator) + - `>>>>>>>` (conflict end marker) +3. **Result Reporting**: + - If markers are found, the action fails and lists all affected files + - If no markers are found, the action succeeds + +## Outputs + +- `files-checked`: Number of files that were checked +- `conflicts-found`: Number of files containing merge conflict markers + +## Behavior + +- **Event Support**: Only works with `pull_request` events +- **File Handling**: + - Checks only files that were added, modified, or renamed + - Skips deleted files + - **Filters out `*.cs` files** (C# files are excluded from merge conflict checking) + - Skips binary/unreadable files + - Skips directories +- **Empty File List**: Gracefully handles cases where no files need checking (e.g., PRs that only delete files) + +## Example Output + +When conflict markers are detected: + +``` +❌ Merge conflict markers detected in the following files: + - src/example.cs + Markers found: <<<<<<<, =======, >>>>>>> + - README.md + Markers found: <<<<<<<, =======, >>>>>>> + +Please resolve these conflicts before merging. +``` + +When no markers are found: + +``` +✅ No merge conflict markers found +``` + +## Integration + +This action is integrated into the `linux-ci.yml` workflow and runs automatically on all pull requests to ensure code quality before merging. diff --git a/PowerShell-master/.github/actions/infrastructure/merge-conflict-checker/action.yml b/PowerShell-master/.github/actions/infrastructure/merge-conflict-checker/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..41c7d2ad941174a232039184de2dda214af03ed7 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/merge-conflict-checker/action.yml @@ -0,0 +1,37 @@ +name: 'Check for Merge Conflict Markers' +description: 'Checks for Git merge conflict markers in changed files for pull requests' +author: 'PowerShell Team' + +outputs: + files-checked: + description: 'Number of files checked for merge conflict markers' + value: ${{ steps.check.outputs.files-checked }} + conflicts-found: + description: 'Number of files with merge conflict markers' + value: ${{ steps.check.outputs.conflicts-found }} + +runs: + using: 'composite' + steps: + - name: Get changed files + id: changed-files + uses: "./.github/actions/infrastructure/get-changed-files" + + - name: Check for merge conflict markers + id: check + shell: pwsh + env: + CHANGED_FILES_JSON: ${{ steps.changed-files.outputs.files }} + run: | + # Get changed files from environment variable (secure against injection) + $changedFilesJson = $env:CHANGED_FILES_JSON + # Ensure we always have an array (ConvertFrom-Json returns null for empty JSON arrays) + $changedFiles = @($changedFilesJson | ConvertFrom-Json) + + # Import ci.psm1 and run the check + Import-Module "$env:GITHUB_WORKSPACE/tools/ci.psm1" -Force + Test-MergeConflictMarker -File $changedFiles -WorkspacePath $env:GITHUB_WORKSPACE + +branding: + icon: 'alert-triangle' + color: 'red' diff --git a/PowerShell-master/.github/actions/infrastructure/path-filters/action.yml b/PowerShell-master/.github/actions/infrastructure/path-filters/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..af23540256da53253201ec56dd63f9df9d4f1449 --- /dev/null +++ b/PowerShell-master/.github/actions/infrastructure/path-filters/action.yml @@ -0,0 +1,137 @@ +name: Path Filters +description: 'Path Filters' +inputs: + GITHUB_TOKEN: + description: 'GitHub token' + required: true +outputs: + source: + description: 'Source code changes (composite of all changes)' + value: ${{ steps.filter.outputs.source }} + githubChanged: + description: 'GitHub workflow changes' + value: ${{ steps.filter.outputs.githubChanged }} + toolsChanged: + description: 'Tools changes' + value: ${{ steps.filter.outputs.toolsChanged }} + propsChanged: + description: 'Props changes' + value: ${{ steps.filter.outputs.propsChanged }} + testsChanged: + description: 'Tests changes' + value: ${{ steps.filter.outputs.testsChanged }} + mainSourceChanged: + description: 'Main source code changes (any changes in src/)' + value: ${{ steps.filter.outputs.mainSourceChanged }} + buildModuleChanged: + description: 'Build module changes' + value: ${{ steps.filter.outputs.buildModuleChanged }} + packagingChanged: + description: 'Packaging related changes' + value: ${{ steps.filter.outputs.packagingChanged }} +runs: + using: composite + steps: + - name: Get changed files + id: get-files + if: github.event_name == 'pull_request' + uses: "./.github/actions/infrastructure/get-changed-files" + + - name: Check if GitHubWorkflowChanges is present + id: filter + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + FILES_JSON: ${{ steps.get-files.outputs.files }} + with: + github-token: ${{ inputs.GITHUB_TOKEN }} + script: | + console.log(`Event Name: ${context.eventName}`); + + // Just say everything changed if this is not a PR + if (context.eventName !== 'pull_request') { + console.log('Not a pull request, setting all outputs to true'); + core.setOutput('toolsChanged', true); + core.setOutput('githubChanged', true); + core.setOutput('propsChanged', true); + core.setOutput('testsChanged', true); + core.setOutput('mainSourceChanged', true); + core.setOutput('buildModuleChanged', true); + core.setOutput('source', true); + return; + } + + // Get files from environment variable (secure against injection) + const files = JSON.parse(process.env.FILES_JSON || '[]'); + + // Calculate hash for verification (matches get-changed-files action) + const crypto = require('crypto'); + const filesJson = JSON.stringify(files.sort()); + const hash = crypto.createHash('sha256').update(filesJson).digest('hex').substring(0, 8); + console.log(`Received ${files.length} files (hash: ${hash})`); + + // Analyze changes with detailed logging + core.startGroup('Path Filter Analysis'); + + const actionsChanged = files.some(file => file.startsWith('.github/actions')); + console.log(`✓ Actions changed: ${actionsChanged}`); + + const workflowsChanged = files.some(file => file.startsWith('.github/workflows')); + console.log(`✓ Workflows changed: ${workflowsChanged}`); + + const githubChanged = actionsChanged || workflowsChanged; + console.log(`→ GitHub changed (actions OR workflows): ${githubChanged}`); + + const toolsCiPsm1Changed = files.some(file => file === 'tools/ci.psm1'); + console.log(`✓ tools/ci.psm1 changed: ${toolsCiPsm1Changed}`); + + const toolsBuildCommonChanged = files.some(file => file.startsWith('tools/buildCommon/')); + console.log(`✓ tools/buildCommon/ changed: ${toolsBuildCommonChanged}`); + + const toolsChanged = toolsCiPsm1Changed || toolsBuildCommonChanged; + console.log(`→ Tools changed: ${toolsChanged}`); + + const propsChanged = files.some(file => file.endsWith('.props')); + console.log(`✓ Props files changed: ${propsChanged}`); + + const testsChanged = files.some(file => file.startsWith('test/powershell/') || file.startsWith('test/tools/') || file.startsWith('test/xUnit/')); + console.log(`✓ Tests changed: ${testsChanged}`); + + const mainSourceChanged = files.some(file => file.startsWith('src/')); + console.log(`✓ Main source (src/) changed: ${mainSourceChanged}`); + + const buildModuleChanged = files.some(file => file === 'build.psm1'); + console.log(`✓ build.psm1 changed: ${buildModuleChanged}`); + + const globalConfigChanged = files.some(file => file === '.globalconfig' || file === 'nuget.config' || file === 'global.json'); + console.log(`✓ Global config changed: ${globalConfigChanged}`); + + const packagingChanged = files.some(file => + file === '.github/workflows/windows-ci.yml' || + file === '.github/workflows/linux-ci.yml' || + file.startsWith('assets/wix/') || + file === 'PowerShell.Common.props' || + file.match(/^src\/.*\.csproj$/) || + file.startsWith('test/packaging/windows/') || + file.startsWith('test/packaging/linux/') || + file.startsWith('tools/packaging/') || + file.startsWith('tools/wix/') + ) || + buildModuleChanged || + globalConfigChanged || + toolsCiPsm1Changed; + console.log(`→ Packaging changed: ${packagingChanged}`); + + const source = mainSourceChanged || toolsChanged || githubChanged || propsChanged || testsChanged || globalConfigChanged; + console.log(`→ Source (composite): ${source}`); + + core.endGroup(); + + core.setOutput('toolsChanged', toolsChanged); + core.setOutput('githubChanged', githubChanged); + core.setOutput('propsChanged', propsChanged); + core.setOutput('testsChanged', testsChanged); + core.setOutput('mainSourceChanged', mainSourceChanged); + core.setOutput('buildModuleChanged', buildModuleChanged); + core.setOutput('globalConfigChanged', globalConfigChanged); + core.setOutput('packagingChanged', packagingChanged); + core.setOutput('source', source); diff --git a/PowerShell-master/.github/actions/test/linux-packaging/action.yml b/PowerShell-master/.github/actions/test/linux-packaging/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..ce37a38c8b737598818e2ac4f23711a6109dd733 --- /dev/null +++ b/PowerShell-master/.github/actions/test/linux-packaging/action.yml @@ -0,0 +1,69 @@ +name: linux_packaging +description: 'Linux packaging for PowerShell' + +runs: + using: composite + steps: + - name: Capture Environment + if: success() || failure() + run: |- + Import-Module ./tools/ci.psm1 + Show-Environment + shell: pwsh + + - uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5.2.0 + with: + global-json-file: ./global.json + + - name: Bootstrap + run: |- + Import-Module ./build.psm1 + Start-PSBootstrap -Scenario Package + Import-Module ./tools/ci.psm1 + Invoke-CIInstall -SkipUser + shell: pwsh + + - name: Build and Package + run: |- + Import-Module ./tools/ci.psm1 + $releaseTag = Get-ReleaseTag + Start-PSBuild -Configuration 'Release' -ReleaseTag $releaseTag + Invoke-CIFinish + shell: pwsh + + - name: Install Pester + run: |- + Import-Module ./tools/ci.psm1 + Install-CIPester + shell: pwsh + + - name: Validate Package Names + run: |- + # Run Pester tests to validate package names + Import-Module Pester -Force + $testResults = Invoke-Pester -Path ./test/packaging/linux/package-validation.tests.ps1 -PassThru + if ($testResults.FailedCount -gt 0) { + throw "Package validation tests failed" + } + shell: pwsh + + - name: Upload deb packages + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: packages-deb + path: ${{ runner.workspace }}/packages/*.deb + if-no-files-found: ignore + + - name: Upload rpm packages + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: packages-rpm + path: ${{ runner.workspace }}/packages/*.rpm + if-no-files-found: ignore + + - name: Upload tar.gz packages + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: packages-tar + path: ${{ runner.workspace }}/packages/*.tar.gz + if-no-files-found: ignore diff --git a/PowerShell-master/.github/actions/test/nix/action.yml b/PowerShell-master/.github/actions/test/nix/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..ab30e0d9ce6a729df6960b4c010b4890caa7781f --- /dev/null +++ b/PowerShell-master/.github/actions/test/nix/action.yml @@ -0,0 +1,158 @@ +name: nix_test +description: 'Test PowerShell on non-Windows platforms' + +inputs: + purpose: + required: false + default: '' + type: string + tagSet: + required: false + default: CI + type: string + ctrfFolder: + required: false + default: ctrf + type: string + GITHUB_TOKEN: + description: 'GitHub token for API authentication' + required: true + +runs: + using: composite + steps: + - name: Capture Environment + if: success() || failure() + run: |- + Import-Module ./tools/ci.psm1 + Show-Environment + shell: pwsh + + - name: Download Build Artifacts + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + path: "${{ github.workspace }}" + + - name: Capture Artifacts Directory + continue-on-error: true + run: |- + Import-Module ./build.psm1 + Write-LogGroupStart -Title 'Artifacts Directory' + Get-ChildItem "${{ github.workspace }}/build/*" -Recurse + Write-LogGroupEnd -Title 'Artifacts Directory' + shell: pwsh + + - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 + with: + global-json-file: ./global.json + + - name: Set Package Name by Platform + id: set_package_name + shell: pwsh + run: |- + Import-Module ./.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 + $platform = $env:RUNNER_OS + Write-Host "Runner platform: $platform" + if ($platform -eq 'Linux') { + $packageName = 'DSC-*-x86_64-linux.tar.gz' + } elseif ($platform -eq 'macOS') { + $packageName = 'DSC-*-x86_64-apple-darwin.tar.gz' + } else { + throw "Unsupported platform: $platform" + } + + Set-GWVariable -Name "DSC_PACKAGE_NAME" -Value $packageName + + - name: Get Latest DSC Package Version + shell: pwsh + run: |- + Import-Module ./.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 + $headers = @{ + Authorization = "Bearer ${{ inputs.GITHUB_TOKEN }}" + } + $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/PowerShell/Dsc/releases" -Headers $headers + $latestRelease = $releases | Where-Object { $v = $_.name.trim("v"); $semVer = [System.Management.Automation.SemanticVersion]::new($v); if ($semVer.Major -eq 3 -and $semVer.Minor -ge 2) { $_ } } | Select-Object -First 1 + $latestVersion = $latestRelease.tag_name.TrimStart("v") + Write-Host "Latest DSC Version: $latestVersion" + + $packageName = "$env:DSC_PACKAGE_NAME" + + Write-Host "Package Name: $packageName" + + $downloadUrl = $latestRelease.assets | Where-Object { $_.name -like "*$packageName*" } | Select-Object -First 1 | Select-Object -ExpandProperty browser_download_url + Write-Host "Download URL: $downloadUrl" + + $tempPath = Get-GWTempPath + + Invoke-RestMethod -Uri $downloadUrl -OutFile "$tempPath/DSC.tar.gz" -Verbose -Headers $headers + New-Item -ItemType Directory -Path "$tempPath/DSC" -Force -Verbose + tar xvf "$tempPath/DSC.tar.gz" -C "$tempPath/DSC" + $dscRoot = "$tempPath/DSC" + Write-Host "DSC Root: $dscRoot" + Set-GWVariable -Name "DSC_ROOT" -Value $dscRoot + + - name: Bootstrap + shell: pwsh + run: |- + Import-Module ./build.psm1 + Write-LogGroupStart -Title 'Bootstrap' + Import-Module ./tools/ci.psm1 + Invoke-CIInstall -SkipUser + Write-LogGroupEnd -Title 'Bootstrap' + + - name: Extract Files + uses: actions/github-script@e69ef5462fd455e02edcaf4dd7708eda96b9eda0 # v7.0.0 + env: + DESTINATION_FOLDER: "${{ github.workspace }}/bins" + ARCHIVE_FILE_PATTERNS: "${{ github.workspace }}/build/build.zip" + with: + script: |- + const fs = require('fs').promises + const path = require('path') + const target = path.resolve(process.env.DESTINATION_FOLDER) + const patterns = process.env.ARCHIVE_FILE_PATTERNS + const globber = await glob.create(patterns) + await io.mkdirP(path.dirname(target)) + for await (const file of globber.globGenerator()) { + if ((await fs.lstat(file)).isDirectory()) continue + await exec.exec(`7z x ${file} -o${target} -aoa`) + } + + - name: Fix permissions + continue-on-error: true + run: |- + find "${{ github.workspace }}/bins" -type d -exec chmod +rwx {} \; + find "${{ github.workspace }}/bins" -type f -exec chmod +rw {} \; + shell: bash + + - name: Capture Extracted Build ZIP + continue-on-error: true + run: |- + Import-Module ./build.psm1 + Write-LogGroupStart -Title 'Extracted Build ZIP' + Get-ChildItem "${{ github.workspace }}/bins/*" -Recurse -ErrorAction SilentlyContinue + Write-LogGroupEnd -Title 'Extracted Build ZIP' + shell: pwsh + + - name: Test + if: success() + run: |- + Import-Module ./tools/ci.psm1 + Restore-PSOptions -PSOptionsPath '${{ github.workspace }}/build/psoptions.json' + $options = (Get-PSOptions) + $rootPath = '${{ github.workspace }}/bins' + $originalRootPath = Split-Path -path $options.Output + $path = Join-Path -path $rootPath -ChildPath (split-path -leaf -path $originalRootPath) + $pwshPath = Join-Path -path $path -ChildPath 'pwsh' + chmod a+x $pwshPath + $options.Output = $pwshPath + Set-PSOptions $options + Invoke-CITest -Purpose '${{ inputs.purpose }}' -TagSet '${{ inputs.tagSet }}' -TitlePrefix '${{ inputs.buildName }}' -OutputFormat NUnitXml + shell: pwsh + + - name: Convert, Publish, and Upload Pester Test Results + uses: "./.github/actions/test/process-pester-results" + with: + name: "${{ inputs.purpose }}-${{ inputs.tagSet }}" + testResultsFolder: "${{ runner.workspace }}/testResults" + ctrfFolder: "${{ inputs.ctrfFolder }}" diff --git a/PowerShell-master/.github/actions/test/process-pester-results/action.yml b/PowerShell-master/.github/actions/test/process-pester-results/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..44f2037626fb49e5ef247213ea6e5e249e93c447 --- /dev/null +++ b/PowerShell-master/.github/actions/test/process-pester-results/action.yml @@ -0,0 +1,27 @@ +name: process-pester-test-results +description: 'Process Pester test results' + +inputs: + name: + required: true + default: '' + type: string + testResultsFolder: + required: false + default: "${{ runner.workspace }}/testResults" + type: string + +runs: + using: composite + steps: + - name: Log Summary + run: |- + & "$env:GITHUB_ACTION_PATH/process-pester-results.ps1" -Name '${{ inputs.name }}' -TestResultsFolder '${{ inputs.testResultsFolder }}' + shell: pwsh + + - name: Upload testResults artifact + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: junit-pester-${{ inputs.name }} + path: ${{ runner.workspace }}/testResults diff --git a/PowerShell-master/.github/actions/test/process-pester-results/process-pester-results.ps1 b/PowerShell-master/.github/actions/test/process-pester-results/process-pester-results.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..5804bec9a943769b29c6e0bed44431434869e923 --- /dev/null +++ b/PowerShell-master/.github/actions/test/process-pester-results/process-pester-results.ps1 @@ -0,0 +1,124 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [parameter(Mandatory)] + [string]$Name, + [parameter(Mandatory)] + [string]$TestResultsFolder +) + +Import-Module "$PSScriptRoot/../../../../build.psm1" + +if (-not $env:GITHUB_STEP_SUMMARY) { + Write-Error "GITHUB_STEP_SUMMARY is not set. Ensure this workflow is running in a GitHub Actions environment." + exit 1 +} + +$testCaseCount = 0 +$testErrorCount = 0 +$testFailureCount = 0 +$testNotRunCount = 0 +$testInconclusiveCount = 0 +$testIgnoredCount = 0 +$testSkippedCount = 0 +$testInvalidCount = 0 + +# Process test results and generate annotations for failures +Get-ChildItem -Path "${TestResultsFolder}/*.xml" -Recurse | ForEach-Object { + $results = [xml] (get-content $_.FullName) + + $testCaseCount += [int]$results.'test-results'.total + $testErrorCount += [int]$results.'test-results'.errors + $testFailureCount += [int]$results.'test-results'.failures + $testNotRunCount += [int]$results.'test-results'.'not-run' + $testInconclusiveCount += [int]$results.'test-results'.inconclusive + $testIgnoredCount += [int]$results.'test-results'.ignored + $testSkippedCount += [int]$results.'test-results'.skipped + $testInvalidCount += [int]$results.'test-results'.invalid + + # Generate GitHub Actions annotations for test failures + # Select failed test cases + if ("System.Xml.XmlDocumentXPathExtensions" -as [Type]) { + $failures = [System.Xml.XmlDocumentXPathExtensions]::SelectNodes($results.'test-results', './/test-case[@result = "Failure"]') + } + else { + $failures = $results.SelectNodes('.//test-case[@result = "Failure"]') + } + + foreach ($testfail in $failures) { + $description = $testfail.description + $testName = $testfail.name + $message = $testfail.failure.message + $stack_trace = $testfail.failure.'stack-trace' + + # Parse stack trace to get file and line info + $fileInfo = Get-PesterFailureFileInfo -StackTraceString $stack_trace + + if ($fileInfo.File) { + # Convert absolute path to relative path for GitHub Actions + $filePath = $fileInfo.File + + # GitHub Actions expects paths relative to the workspace root + if ($env:GITHUB_WORKSPACE) { + $workspacePath = $env:GITHUB_WORKSPACE + if ($filePath.StartsWith($workspacePath)) { + $filePath = $filePath.Substring($workspacePath.Length).TrimStart('/', '\') + # Normalize to forward slashes for consistency + $filePath = $filePath -replace '\\', '/' + } + } + + # Create annotation title + $annotationTitle = "Test Failure: $description / $testName" + + # Build the annotation message + $annotationMessage = $message -replace "`n", "%0A" -replace "`r" + + # Build and output the workflow command + $workflowCommand = "::error file=$filePath" + if ($fileInfo.Line) { + $workflowCommand += ",line=$($fileInfo.Line)" + } + $workflowCommand += ",title=$annotationTitle::$annotationMessage" + + Write-Host $workflowCommand + + # Output a link to the test run + if ($env:GITHUB_SERVER_URL -and $env:GITHUB_REPOSITORY -and $env:GITHUB_RUN_ID) { + $logUrl = "$($env:GITHUB_SERVER_URL)/$($env:GITHUB_REPOSITORY)/actions/runs/$($env:GITHUB_RUN_ID)" + Write-Host "Test logs: $logUrl" + } + } + } +} + +@" + +# Summary of $Name + +- Total Tests: $testCaseCount +- Total Errors: $testErrorCount +- Total Failures: $testFailureCount +- Total Not Run: $testNotRunCount +- Total Inconclusive: $testInconclusiveCount +- Total Ignored: $testIgnoredCount +- Total Skipped: $testSkippedCount +- Total Invalid: $testInvalidCount + +"@ | Out-File -FilePath $ENV:GITHUB_STEP_SUMMARY -Append + +Write-Log "Summary written to $ENV:GITHUB_STEP_SUMMARY" + +Write-LogGroupStart -Title 'Test Results' +Get-Content $ENV:GITHUB_STEP_SUMMARY +Write-LogGroupEnd -Title 'Test Results' + +if ($testErrorCount -gt 0 -or $testFailureCount -gt 0) { + Write-Error "There were $testErrorCount/$testFailureCount errors/failures in the test results." + exit 1 +} +if ($testCaseCount -eq 0) { + Write-Error "No test cases were run." + exit 1 +} diff --git a/PowerShell-master/.github/actions/test/windows/action.yml b/PowerShell-master/.github/actions/test/windows/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..ddc5da4d664dfd754e3b92412bf204c1041e4abf --- /dev/null +++ b/PowerShell-master/.github/actions/test/windows/action.yml @@ -0,0 +1,107 @@ +name: windows_test +description: 'Test PowerShell on Windows' + +inputs: + purpose: + required: false + default: '' + type: string + tagSet: + required: false + default: CI + type: string + ctrfFolder: + required: false + default: ctrf + type: string + GITHUB_TOKEN: + description: 'GitHub token for API authentication' + required: true + +runs: + using: composite + steps: + - name: Capture Environment + if: success() || failure() + run: |- + Import-Module ./tools/ci.psm1 + Show-Environment + shell: pwsh + + - name: Download Build Artifacts + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + path: "${{ github.workspace }}" + + - name: Capture Artifacts Directory + continue-on-error: true + run: |- + Import-Module ./build.psm1 + Write-LogGroupStart -Title 'Artifacts Directory' + Get-ChildItem "${{ github.workspace }}/build/*" -Recurse + Write-LogGroupEnd -Title 'Artifacts Directory' + shell: pwsh + + - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 + with: + global-json-file: .\global.json + + - name: Get Latest DSC Package Version + shell: pwsh + run: |- + Import-Module .\.github\workflows\GHWorkflowHelper\GHWorkflowHelper.psm1 + $headers = @{ + Authorization = "Bearer ${{ inputs.GITHUB_TOKEN }}" + } + $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/PowerShell/Dsc/releases" -Headers $headers + $latestRelease = $releases | Where-Object { $v = $_.name.trim("v"); $semVer = [System.Management.Automation.SemanticVersion]::new($v); if ($semVer.Major -eq 3 -and $semVer.Minor -ge 2) { $_ } } | Select-Object -First 1 + $latestVersion = $latestRelease.tag_name.TrimStart("v") + Write-Host "Latest DSC Version: $latestVersion" + + $downloadUrl = $latestRelease.assets | Where-Object { $_.name -like "DSC-*-x86_64-pc-windows-msvc.zip" } | Select-Object -First 1 | Select-Object -ExpandProperty browser_download_url + Write-Host "Download URL: $downloadUrl" + $tempPath = Get-GWTempPath + Invoke-RestMethod -Uri $downloadUrl -OutFile "$tempPath\DSC.zip" -Headers $headers + + $null = New-Item -ItemType Directory -Path "$tempPath\DSC" -Force + Expand-Archive -Path "$tempPath\DSC.zip" -DestinationPath "$tempPath\DSC" -Force + $dscRoot = "$tempPath\DSC" + Write-Host "DSC Root: $dscRoot" + Set-GWVariable -Name "DSC_ROOT" -Value $dscRoot + + - name: Bootstrap + shell: powershell + run: |- + Import-Module ./build.psm1 + Write-LogGroupStart -Title 'Bootstrap' + Write-Host "Old Path:" + Write-Host $env:Path + $dotnetPath = Join-Path $env:SystemDrive 'Program Files\dotnet' + $paths = $env:Path -split ";" | Where-Object { -not $_.StartsWith($dotnetPath) } + $env:Path = $paths -join ";" + Write-Host "New Path:" + Write-Host $env:Path + # Bootstrap + Import-Module .\tools\ci.psm1 + Invoke-CIInstall + Write-LogGroupEnd -Title 'Bootstrap' + + - name: Test + if: success() + run: |- + Import-Module .\build.psm1 -force + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '${{ github.workspace }}\build\psoptions.json' + $options = (Get-PSOptions) + $path = split-path -path $options.Output + $rootPath = split-Path -path $path + Expand-Archive -Path '${{ github.workspace }}\build\build.zip' -DestinationPath $rootPath -Force + Invoke-CITest -Purpose '${{ inputs.purpose }}' -TagSet '${{ inputs.tagSet }}' -OutputFormat NUnitXml + shell: pwsh + + - name: Convert, Publish, and Upload Pester Test Results + uses: "./.github/actions/test/process-pester-results" + with: + name: "${{ inputs.purpose }}-${{ inputs.tagSet }}" + testResultsFolder: ${{ runner.workspace }}\testResults + ctrfFolder: "${{ inputs.ctrfFolder }}" diff --git a/PowerShell-master/.github/agents/SplitADOPipelines.agent.md b/PowerShell-master/.github/agents/SplitADOPipelines.agent.md new file mode 100644 index 0000000000000000000000000000000000000000..8322f473e7b2de19b93ef003baa96c4957efb950 --- /dev/null +++ b/PowerShell-master/.github/agents/SplitADOPipelines.agent.md @@ -0,0 +1,164 @@ +--- +name: SplitADOPipelines +description: This agent will implement and restructure the repository's existing ADO pipelines into Official and NonOfficial pipelines. +tools: ['vscode', 'execute', 'read', 'agent', 'edit', 'search', 'todo'] +--- + +This agent will implement and restructure the repository's existing ADO pipelines into Official and NonOfficial pipelines. + +A repository will have under the ./pipelines directory a series of yaml files that define the ADO pipelines for the repository. + +First confirm if the pipelines are using a toggle switch for Official and NonOfficial. This will look something like this + +```yaml +parameters: + - name: templateFile + value: ${{ iif ( parameters.OfficialBuild, 'v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates', 'v2/OneBranch.NonOfficial.CrossPlat.yml@onebranchTemplates' ) }} +``` + +Followed by: + +```yaml +extends: + template: ${{ variables.templateFile }} +``` + +This is an indicator that this work needs to be done. This toggle switch is no longer allowed and the templates need to be hard coded. + +## Refactoring Steps + +### Step 1: Extract Shared Templates + +For each pipeline file that uses the toggle switch pattern (e.g., `PowerShell-Packages.yml`): + +1. Create a `./pipelines/templates` directory if it doesn't exist +2. Extract the **variables section** into `./pipelines/templates/PowerShell-Packages-Variables.yml` +3. Extract the **stages section** into `./pipelines/templates/PowerShell-Packages-Stages.yml` + +**IMPORTANT**: Only extract the `variables:` and `stages:` sections. All other sections (parameters, resources, extends, etc.) remain in the pipeline files. + +### Step 2: Create Official Pipeline (In-Place Refactoring) + +The original toggle-based file becomes the Official pipeline: + +1. **Keep the file in its original location** (e.g., `./pipelines/PowerShell-Packages.yml` stays where it is) +2. Remove the toggle switch parameter (`templateFile` parameter) +3. Hard-code the Official template reference: + ```yaml + extends: + template: v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates + ``` +4. Replace the `variables:` section with a template reference: + ```yaml + variables: + - template: templates/PowerShell-Packages-Variables.yml + ``` +5. Replace the `stages:` section with a template reference: + ```yaml + stages: + - template: templates/PowerShell-Packages-Stages.yml + ``` + +### Step 3: Create NonOfficial Pipeline + +1. Create `./pipelines/NonOfficial` directory if it doesn't exist +2. Create the NonOfficial pipeline file (e.g., `./pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml`) +3. Copy the structure from the refactored Official pipeline +4. Hard-code the NonOfficial template reference: + ```yaml + extends: + template: v2/OneBranch.NonOfficial.CrossPlat.yml@onebranchTemplates + ``` +5. Reference the same shared templates: + ```yaml + variables: + - template: ../templates/PowerShell-Packages-Variables.yml + + stages: + - template: ../templates/PowerShell-Packages-Stages.yml + ``` + +**Note**: The NonOfficial pipeline uses `../templates/` because it's one directory deeper than the Official pipeline. + +### Step 4: Link NonOfficial Pipelines to NonOfficial Dependencies + +After creating NonOfficial pipelines, ensure they consume artifacts from other **NonOfficial** pipelines, not Official ones. + +1. **Check the `resources:` section** in each NonOfficial pipeline for `pipelines:` dependencies +2. **Identify Official pipeline references** that need to be changed to NonOfficial +3. **Update the `source:` field** to point to the NonOfficial version + +**Example Problem:** NonOfficial pipeline pointing to Official dependency +```yaml +resources: + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated Binaries-Official' # ❌ Wrong - Official! +``` + +**Solution:** Update to NonOfficial dependency +```yaml +resources: + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated Binaries-NonOfficial' # ✅ Correct - NonOfficial! +``` + +**IMPORTANT**: The `source:` field must match the **exact ADO pipeline definition name** as it appears in Azure DevOps, not necessarily the file name. + +### Step 5: Configure Release Environment Parameters (NonAzure Only) + +**This step only applies if the pipeline uses `category: NonAzure` in the release configuration.** + +If you detect this pattern in the original pipeline: + +```yaml +extends: + template: v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates # or NonOfficial + parameters: + release: + category: NonAzure +``` + +Then you must configure the `ob_release_environment` parameter when referencing the stages template. + +#### Official Pipeline Configuration + +In the Official pipeline (e.g., `./pipelines/PowerShell-Packages.yml`): + +```yaml +stages: + - template: templates/PowerShell-Packages-Stages.yml + parameters: + ob_release_environment: Production +``` + +#### NonOfficial Pipeline Configuration + +In the NonOfficial pipeline (e.g., `./pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml`): + +```yaml +stages: + - template: ../templates/PowerShell-Packages-Stages.yml + parameters: + ob_release_environment: Test +``` + +#### Update Stages Template to Accept Parameter + +The extracted stages template (e.g., `./pipelines/templates/PowerShell-Packages-Stages.yml`) must declare the parameter at the top: + +```yaml +parameters: + - name: ob_release_environment + type: string + +stages: + # ... rest of stages configuration using ${{ parameters.ob_release_environment }} +``` + +**IMPORTANT**: +- Only configure this for pipelines with `category: NonAzure` +- Official pipelines always use `ob_release_environment: Production` +- NonOfficial pipelines always use `ob_release_environment: Test` +- The stages template must accept this parameter and use it in the appropriate stage configurations diff --git a/PowerShell-master/.github/chatmodes/cherry-pick-commits.chatmode.md b/PowerShell-master/.github/chatmodes/cherry-pick-commits.chatmode.md new file mode 100644 index 0000000000000000000000000000000000000000..826ab11d56cf61da1f569a458b18c01c1cf12258 --- /dev/null +++ b/PowerShell-master/.github/chatmodes/cherry-pick-commits.chatmode.md @@ -0,0 +1,78 @@ +# Cherry-Pick Commits Between Branches + +Cherry-pick recent commits from a source branch to a target branch without switching branches. + +## Instructions for Copilot + +1. **Confirm branches with the user** + - Ask the user to confirm the source and target branches + - If different branches are needed, update the configuration + +2. **Identify unique commits** + - Run: `git log .. --oneline --reverse` + - **IMPORTANT**: The commit count may be misleading if branches diverged from different base commits + - Compare the LAST few commits from each branch to identify actual missing commits: + - `git log --oneline -10` + - `git log --oneline -10` + - Look for commits with the same message but different SHAs (rebased commits) + - Show the user ONLY the truly missing commits (usually just the most recent ones) + +3. **Confirm with user before proceeding** + - If the commit count seems unusually high (e.g., 400+), STOP and verify semantically + - Ask: "I found X commits to cherry-pick. Shall I proceed?" + - If there are many commits, warn that this may take time + +4. **Execute the cherry-pick** + - Ensure the target branch is checked out first + - Run: `git cherry-pick ` for single commits + - Or: `git cherry-pick ` for multiple commits + - Apply commits in chronological order (oldest first) + +5. **Handle any issues** + - If conflicts occur, pause and ask user for guidance + - If empty commits occur, automatically skip with `git cherry-pick --skip` + +6. **Verify and report results** + - Run: `git log - --oneline` + - Show the user the newly applied commits + - Confirm the branch is now ahead by X commits + +## Key Git Commands + +```bash +# Find unique commits (may show full divergence if branches were rebased) +git log .. --oneline --reverse + +# Compare recent commits on each branch (more reliable for rebased branches) +git log --oneline -10 +git log --oneline -10 + +# Cherry-pick specific commits (when target is checked out) +git cherry-pick +git cherry-pick + +# Skip empty commits +git cherry-pick --skip + +# Verify result +git log - --oneline +``` + +## Common Scenarios + +- **Empty commits**: Automatically skip with `git cherry-pick --skip` +- **Conflicts**: Stop, show files with conflicts, ask user to resolve +- **Many commits**: Warn user and confirm before proceeding +- **Already applied**: These will result in empty commits that should be skipped +- **Diverged branches**: If branches diverged (rebased), `git log` may show the entire history difference + - The actual missing commits are usually only the most recent ones + - Compare commit messages from recent history on both branches + - Cherry-pick only commits that are semantically missing + +## Workflow Style + +Use an interactive, step-by-step approach: +- Show output from each command +- Ask for confirmation before major actions +- Provide clear status updates +- Handle errors gracefully with user guidance diff --git a/PowerShell-master/.github/dependabot.yml b/PowerShell-master/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..45d2e8fe928c0142901259ab7e4f47de197a824f --- /dev/null +++ b/PowerShell-master/.github/dependabot.yml @@ -0,0 +1,32 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + labels: + - "CL-BuildPackaging" + + - package-ecosystem: "github-actions" + directory: "/" + target-branch: "release/*" + schedule: + interval: "daily" + labels: + - "CL-BuildPackaging" + + - package-ecosystem: "docker" + directory: / + schedule: + interval: daily + labels: + - "CL-BuildPackaging" + + - package-ecosystem: "docker" + directory: "/" + target-branch: "release/*" + schedule: + interval: daily + labels: + - "CL-BuildPackaging" diff --git a/PowerShell-master/.github/instructions/build-and-packaging-steps.instructions.md b/PowerShell-master/.github/instructions/build-and-packaging-steps.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..934b15395930c6b52d03aac12a6972c068f7994e --- /dev/null +++ b/PowerShell-master/.github/instructions/build-and-packaging-steps.instructions.md @@ -0,0 +1,127 @@ +--- +applyTo: + - ".github/actions/**/*.yml" + - ".github/workflows/**/*.yml" +--- + +# Build and Packaging Steps Pattern + +## Important Rule + +**Build and packaging must run in the same step OR you must save and restore PSOptions between steps.** + +## Why This Matters + +When `Start-PSBuild` runs, it creates PSOptions that contain build configuration details (runtime, configuration, output path, etc.). The packaging functions like `Start-PSPackage` and `Invoke-CIFinish` rely on these PSOptions to know where the build output is located and how it was built. + +GitHub Actions steps run in separate PowerShell sessions. This means PSOptions from one step are not available in the next step. + +## Pattern 1: Combined Build and Package (Recommended) + +Run build and packaging in the same step to keep PSOptions in memory: + +```yaml +- name: Build and Package + run: |- + Import-Module ./tools/ci.psm1 + $releaseTag = Get-ReleaseTag + Start-PSBuild -Configuration 'Release' -ReleaseTag $releaseTag + Invoke-CIFinish + shell: pwsh +``` + +**Benefits:** +- Simpler code +- No need for intermediate files +- PSOptions automatically available to packaging + +## Pattern 2: Separate Steps with Save/Restore + +If you must separate build and packaging into different steps: + +```yaml +- name: Build PowerShell + run: |- + Import-Module ./tools/ci.psm1 + $releaseTag = Get-ReleaseTag + Start-PSBuild -Configuration 'Release' -ReleaseTag $releaseTag + Save-PSOptions -PSOptionsPath "${{ runner.workspace }}/psoptions.json" + shell: pwsh + +- name: Create Packages + run: |- + Import-Module ./tools/ci.psm1 + Restore-PSOptions -PSOptionsPath "${{ runner.workspace }}/psoptions.json" + Invoke-CIFinish + shell: pwsh +``` + +**When to use:** +- When you need to run other steps between build and packaging +- When build and packaging require different permissions or environments + +## Common Mistakes + +### ❌ Incorrect: Separate steps without save/restore + +```yaml +- name: Build PowerShell + run: |- + Start-PSBuild -Configuration 'Release' + shell: pwsh + +- name: Create Packages + run: |- + Invoke-CIFinish # ❌ FAILS: PSOptions not available + shell: pwsh +``` + +### ❌ Incorrect: Using artifacts without PSOptions + +```yaml +- name: Download Build Artifacts + uses: actions/download-artifact@v4 + with: + name: build + +- name: Create Packages + run: |- + Invoke-CIFinish # ❌ FAILS: PSOptions not restored + shell: pwsh +``` + +## Related Functions + +- `Start-PSBuild` - Builds PowerShell and sets PSOptions +- `Save-PSOptions` - Saves PSOptions to a JSON file +- `Restore-PSOptions` - Loads PSOptions from a JSON file +- `Get-PSOptions` - Gets current PSOptions +- `Set-PSOptions` - Sets PSOptions +- `Start-PSPackage` - Creates packages (requires PSOptions) +- `Invoke-CIFinish` - Calls packaging (requires PSOptions on Linux/macOS) + +## Examples + +### Linux Packaging Action + +```yaml +- name: Build and Package + run: |- + Import-Module ./tools/ci.psm1 + $releaseTag = Get-ReleaseTag + Start-PSBuild -Configuration 'Release' -ReleaseTag $releaseTag + Invoke-CIFinish + shell: pwsh +``` + +### Windows Packaging Workflow + +```yaml +- name: Build and Package + run: | + Import-Module .\tools\ci.psm1 + Invoke-CIFinish -Runtime ${{ matrix.runtimePrefix }}-${{ matrix.architecture }} -channel ${{ matrix.channel }} + shell: pwsh +``` + +Note: `Invoke-CIFinish` for Windows includes both build and packaging in its logic when `Stage` contains 'Build'. diff --git a/PowerShell-master/.github/instructions/build-checkout-prerequisites.instructions.md b/PowerShell-master/.github/instructions/build-checkout-prerequisites.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..717aa6faa36e4a60b28cd228ff3af884647b4f83 --- /dev/null +++ b/PowerShell-master/.github/instructions/build-checkout-prerequisites.instructions.md @@ -0,0 +1,148 @@ +--- +applyTo: + - ".github/**/*.yml" + - ".github/**/*.yaml" +--- + +# Build and Checkout Prerequisites for PowerShell CI + +This document describes the checkout and build prerequisites used in PowerShell's CI workflows. It is intended for GitHub Copilot sessions working with the build system. + +## Overview + +The PowerShell repository uses a standardized build process across Linux, Windows, and macOS CI workflows. Understanding the checkout configuration and the `Sync-PSTags` operation is crucial for working with the build system. + +## Checkout Configuration + +### Fetch Depth + +All CI workflows that build or test PowerShell use `fetch-depth: 1000` in the checkout step: + +```yaml +- name: checkout + uses: actions/checkout@v5 + with: + fetch-depth: 1000 +``` + +**Why 1000 commits?** +- The build system needs access to Git history to determine version information +- `Sync-PSTags` requires sufficient history to fetch and work with tags +- 1000 commits provides a reasonable balance between clone speed and having enough history for version calculation +- Shallow clones (fetch-depth: 1) would break versioning logic + +**Exceptions:** +- The `changes` job uses default fetch depth (no explicit `fetch-depth`) since it only needs to detect file changes +- The `analyze` job (CodeQL) uses `fetch-depth: '0'` (full history) for comprehensive security analysis +- Linux packaging uses `fetch-depth: 0` to ensure all tags are available for package version metadata + +### Workflows Using fetch-depth: 1000 + +- **Linux CI** (`.github/workflows/linux-ci.yml`): All build and test jobs +- **Windows CI** (`.github/workflows/windows-ci.yml`): All build and test jobs +- **macOS CI** (`.github/workflows/macos-ci.yml`): All build and test jobs + +## Sync-PSTags Operation + +### What is Sync-PSTags? + +`Sync-PSTags` is a PowerShell function defined in `build.psm1` that ensures Git tags from the upstream PowerShell repository are synchronized to the local clone. + +### Location + +- **Function Definition**: `build.psm1` (line 36-76) +- **Called From**: + - `.github/actions/build/ci/action.yml` (Bootstrap step, line 24) + - `tools/ci.psm1` (Invoke-CIInstall function, line 146) + +### How It Works + +```powershell +Sync-PSTags -AddRemoteIfMissing +``` + +The function: +1. Searches for a Git remote pointing to the official PowerShell repository: + - `https://github.com/PowerShell/PowerShell` + - `git@github.com:PowerShell/PowerShell` + +2. If no upstream remote exists and `-AddRemoteIfMissing` is specified: + - Adds a remote named `upstream` pointing to `https://github.com/PowerShell/PowerShell.git` + +3. Fetches all tags from the upstream remote: + ```bash + git fetch --tags --quiet upstream + ``` + +4. Sets `$script:tagsUpToDate = $true` to indicate tags are synchronized + +### Why Sync-PSTags is Required + +Tags are critical for: +- **Version Calculation**: `Get-PSVersion` uses `git describe --abbrev=0` to find the latest tag +- **Build Numbering**: CI builds use tag-based versioning for artifacts +- **Changelog Generation**: Release notes are generated based on tags +- **Package Metadata**: Package versions are derived from Git tags + +Without synchronized tags: +- Version detection would fail or return incorrect versions +- Builds might have inconsistent version numbers +- The build process would error when trying to determine the version + +### Bootstrap Step in CI Action + +The `.github/actions/build/ci/action.yml` includes this in the Bootstrap step: + +```yaml +- name: Bootstrap + if: success() + run: |- + Write-Verbose -Verbose "Running Bootstrap..." + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + Write-Verbose -Verbose "Start Sync-PSTags" + Sync-PSTags -AddRemoteIfMissing + Write-Verbose -Verbose "End Sync-PSTags" + shell: pwsh +``` + +**Note**: `Sync-PSTags` is called twice: +1. Once by `Invoke-CIInstall` (in `tools/ci.psm1`) +2. Explicitly again in the Bootstrap step + +This redundancy ensures tags are available even if the first call encounters issues. + +## Best Practices for Copilot Sessions + +When working with the PowerShell CI system: + +1. **Always use `fetch-depth: 1000` or greater** when checking out code for build or test operations +2. **Understand that `Sync-PSTags` requires network access** to fetch tags from the upstream repository +3. **Don't modify the fetch-depth without understanding the impact** on version calculation +4. **If adding new CI workflows**, follow the existing pattern: + - Use `fetch-depth: 1000` for build/test jobs + - Call `Sync-PSTags -AddRemoteIfMissing` during bootstrap + - Ensure the upstream remote is properly configured + +5. **For local development**, developers should: + - Have the upstream remote configured + - Run `Sync-PSTags -AddRemoteIfMissing` before building + - Or use `Start-PSBuild` which handles this automatically + +## Related Files + +- `.github/actions/build/ci/action.yml` - Main CI build action +- `.github/workflows/linux-ci.yml` - Linux CI workflow +- `.github/workflows/windows-ci.yml` - Windows CI workflow +- `.github/workflows/macos-ci.yml` - macOS CI workflow +- `build.psm1` - Contains Sync-PSTags function definition +- `tools/ci.psm1` - CI-specific build functions that call Sync-PSTags + +## Summary + +The PowerShell CI system depends on: +1. **Adequate Git history** (fetch-depth: 1000) for version calculation +2. **Synchronized Git tags** via `Sync-PSTags` for accurate versioning +3. **Upstream remote access** to fetch official repository tags + +These prerequisites ensure consistent, accurate build versioning across all CI platforms. diff --git a/PowerShell-master/.github/instructions/build-configuration-guide.instructions.md b/PowerShell-master/.github/instructions/build-configuration-guide.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..d0384f4f307fa7d59302797292d4e01576bf424a --- /dev/null +++ b/PowerShell-master/.github/instructions/build-configuration-guide.instructions.md @@ -0,0 +1,150 @@ +--- +applyTo: + - "build.psm1" + - "tools/ci.psm1" + - ".github/**/*.yml" + - ".github/**/*.yaml" + - ".pipelines/**/*.yml" +--- + +# Build Configuration Guide + +## Choosing the Right Configuration + +### For Testing + +**Use: Default (Debug)** + +```yaml +- name: Build for Testing + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Start-PSBuild +``` + +**Why Debug:** +- Includes debugging symbols +- Better error messages +- Faster build times +- Suitable for xUnit and Pester tests + +**Do NOT use:** +- `-Configuration 'Release'` (unnecessary for tests) +- `-ReleaseTag` (not needed for tests) +- `-CI` (unless you specifically need Pester module) + +### For Release/Packaging + +**Use: Release with version tag and public NuGet feeds** + +```yaml +- name: Build for Release + shell: pwsh + run: | + Import-Module ./build.psm1 + Import-Module ./tools/ci.psm1 + Switch-PSNugetConfig -Source Public + $releaseTag = Get-ReleaseTag + Start-PSBuild -Configuration 'Release' -ReleaseTag $releaseTag +``` + +**Why Release:** +- Optimized binaries +- No debug symbols (smaller size) +- Production-ready + +**Why Switch-PSNugetConfig -Source Public:** +- Switches NuGet package sources to public feeds (nuget.org and public Azure DevOps feeds) +- Required for CI/CD environments that don't have access to private feeds +- Uses publicly available packages instead of Microsoft internal feeds + +### For Code Coverage + +**Use: CodeCoverage configuration** + +```yaml +- name: Build with Coverage + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Start-PSBuild -Configuration 'CodeCoverage' +``` + +## Platform Considerations + +### All Platforms + +Same commands work across Linux, Windows, and macOS: + +```yaml +strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] +runs-on: ${{ matrix.os }} +steps: + - name: Build PowerShell + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Start-PSBuild +``` + +### Output Locations + +**Linux/macOS:** +``` +src/powershell-unix/bin/Debug///publish/ +``` + +**Windows:** +``` +src/powershell-win-core/bin/Debug///publish/ +``` + +## Best Practices + +1. Use default configuration for testing +2. Avoid redundant parameters +3. Match configuration to purpose +4. Use `-CI` only when needed +5. Always specify `-ReleaseTag` for release or packaging builds +6. Use `Switch-PSNugetConfig -Source Public` in CI/CD for release builds + +## NuGet Feed Configuration + +### Switch-PSNugetConfig + +The `Switch-PSNugetConfig` function in `build.psm1` manages NuGet package source configuration. + +**Available Sources:** + +- **Public**: Uses public feeds (nuget.org and public Azure DevOps feeds) + - Required for: CI/CD environments, public builds, packaging + - Does not require authentication + +- **Private**: Uses internal PowerShell team feeds + - Required for: Internal development with preview packages + - Requires authentication credentials + +- **NuGetOnly**: Uses only nuget.org + - Required for: Minimal dependency scenarios + +**Usage:** + +```powershell +# Switch to public feeds (most common for CI/CD) +Switch-PSNugetConfig -Source Public + +# Switch to private feeds with authentication +Switch-PSNugetConfig -Source Private -UserName $userName -ClearTextPAT $pat + +# Switch to nuget.org only +Switch-PSNugetConfig -Source NuGetOnly +``` + +**When to Use:** + +- **Always use `-Source Public`** before building in CI/CD workflows +- Use before any build that will create packages for distribution +- Use in forks or environments without access to Microsoft internal feeds diff --git a/PowerShell-master/.github/instructions/code-review-branch-strategy.instructions.md b/PowerShell-master/.github/instructions/code-review-branch-strategy.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..191a677b912a54cca29b250bf7dc66fa05fe9cbb --- /dev/null +++ b/PowerShell-master/.github/instructions/code-review-branch-strategy.instructions.md @@ -0,0 +1,230 @@ +--- +applyTo: "**/*" +--- + +# Code Review Branch Strategy Guide + +This guide helps GitHub Copilot provide appropriate feedback when reviewing code changes, particularly distinguishing between issues that should be fixed in the current branch versus the default branch. + +## Purpose + +When reviewing pull requests, especially those targeting release branches, it's important to identify whether an issue should be fixed in: +- **The current PR/branch** - Release-specific fixes or backports +- **The default branch first** - General bugs that exist in the main codebase + +## Branch Types and Fix Strategy + +### Release Branches (e.g., `release/v7.5`, `release/v7.4`) + +**Purpose:** Contain release-specific changes and critical backports + +**Should contain:** +- Release-specific configuration changes +- Critical bug fixes that are backported from the default branch +- Release packaging/versioning adjustments + +**Should NOT contain:** +- New general bug fixes that haven't been fixed in the default branch +- Refactoring or improvements that apply to the main codebase +- Workarounds for issues that exist in the default branch + +### Default/Main Branch (e.g., `master`, `main`) + +**Purpose:** Primary development branch for all ongoing work + +**Should contain:** +- All general bug fixes +- New features and improvements +- Refactoring and code quality improvements +- Fixes that will later be backported to release branches + +## Identifying Issues That Belong in the Default Branch + +When reviewing a PR targeting a release branch, look for these indicators that suggest the fix should be in the default branch first: + +### 1. The Root Cause Exists in Default Branch + +If the underlying issue exists in the default branch's code, it should be fixed there first. + +**Example:** +```yaml +# PR changes this in release/v7.5: +- $metadata = Get-Content "$repoRoot/tools/metadata.json" -Raw | ConvertFrom-Json ++ $metadata = Get-Content "$(Build.SourcesDirectory)/PowerShell/tools/metadata.json" -Raw | ConvertFrom-Json +``` + +**Analysis:** If `$repoRoot` is undefined because the template doesn't include its dependencies in BOTH the release branch AND the default branch, the fix should address the root cause in the default branch first. + +### 2. The Fix is a Workaround Rather Than a Proper Solution + +If the change introduces a workaround (hardcoded paths, special cases) rather than fixing the underlying design issue, it likely belongs in the default branch as a proper fix. + +**Example:** +- Using hardcoded paths instead of fixing variable initialization +- Adding special cases instead of fixing the logic +- Duplicating code instead of fixing shared dependencies + +### 3. The Issue Affects General Functionality + +If the issue affects general functionality not specific to a release, it should be fixed in the default branch. + +**Example:** +- Template dependencies that affect all pipelines +- Shared utility functions +- Common configuration issues + +## Providing Code Review Feedback + +### For Issues in the Current Branch + +When an issue is specific to the current branch or is a legitimate fix for the branch being targeted, **use the default code review feedback format** without any special branch-strategy commentary. + +### For Issues That Belong in the Default Branch + +1. **Provide the code review feedback** +2. **Explain why it should be fixed in the default branch** +3. **Provide an issue template** in markdown format + +**Example:** + +```markdown +The `channelSelection.yml` template relies on `$repoRoot` being set by `SetVersionVariables.yml`, but doesn't declare this dependency. This issue exists in both the release branch and the default branch. + +**This should be fixed in the default branch first**, then backported if needed. The proper fix is to ensure template dependencies are correctly declared, rather than using hardcoded paths as a workaround. + +--- + +**Suggested Issue for Default Branch:** + +### Issue Title +`channelSelection.yml` template missing dependency on `SetVersionVariables.yml` + +### Description +The `channelSelection.yml` template uses the `$repoRoot` variable but doesn't ensure it's set beforehand by including `SetVersionVariables.yml`. + +**Current State:** +- `channelSelection.yml` expects `$repoRoot` to be available +- Not all pipelines that use `channelSelection.yml` include `SetVersionVariables.yml` first +- This creates an implicit dependency that's not enforced + +**Expected State:** +Either: +1. `channelSelection.yml` should include `SetVersionVariables.yml` as a dependency, OR +2. `channelSelection.yml` should be refactored to not depend on `$repoRoot`, OR +3. Pipelines using `channelSelection.yml` should explicitly include `SetVersionVariables.yml` first + +**Files Affected:** +- `.pipelines/templates/channelSelection.yml` +- `.pipelines/templates/package-create-msix.yml` +- `.pipelines/templates/release-SetTagAndChangelog.yml` + +**Priority:** Medium +**Labels:** `Issue-Bug`, `Area-Build`, `Area-Pipeline` +``` + +## Issue Template Format + +When creating an issue template for the default branch, use this structure: + +```markdown +### Issue Title +[Clear, concise description of the problem] + +### Description +[Detailed explanation of the issue] + +**Current State:** +- [What's happening now] +- [Why it's problematic] + +**Expected State:** +- [What should happen] +- [Proposed solution(s)] + +**Files Affected:** +- [List of files] + +**Priority:** [Low/Medium/High/Critical] +**Labels:** [Suggested labels like `Issue-Bug`, `Area-*`] + +**Additional Context:** +[Any additional information, links to related issues, etc.] +``` + +## Common Scenarios + +### Scenario 1: Template Dependency Issues + +**Indicators:** +- Missing template includes +- Undefined variables from other templates +- Assumptions about pipeline execution order + +**Action:** Suggest fixing template dependencies in the default branch. + +### Scenario 2: Hardcoded Values + +**Indicators:** +- Hardcoded paths replacing variables +- Environment-specific values in shared code +- Magic strings or numbers + +**Action:** Suggest proper variable/parameter usage in the default branch. + +### Scenario 3: Logic Errors + +**Indicators:** +- Incorrect conditional logic +- Missing error handling +- Race conditions + +**Action:** Suggest fixing the logic in the default branch unless it's release-specific. + +### Scenario 4: Legitimate Release Branch Fixes + +**Indicators:** +- Version-specific configuration +- Release packaging changes +- Backport of already-fixed default branch issue + +**Action:** Provide normal code review feedback for the current PR. + +## Best Practices + +1. **Always check if the issue exists in the default branch** before suggesting a release-branch-only fix +2. **Prefer fixing root causes over workarounds** +3. **Provide clear rationale** for why a fix belongs in the default branch +4. **Include actionable issue templates** so users can easily create issues +5. **Be helpful, not blocking** - provide the feedback even if you can't enforce where it's fixed + +## Examples of Good vs. Bad Approaches + +### ❌ Bad: Workaround in Release Branch Only + +```yaml +# In release/v7.5 only +- pwsh: | + $metadata = Get-Content "$(Build.SourcesDirectory)/PowerShell/tools/metadata.json" -Raw +``` + +**Why bad:** Hardcodes path to work around missing `$repoRoot`, doesn't fix the default branch. + +### ✅ Good: Fix in Default Branch, Then Backport + +```yaml +# In default branch first +- template: SetVersionVariables.yml@self # Ensures $repoRoot is set +- template: channelSelection.yml@self # Now can use $repoRoot +``` + +**Why good:** Fixes the root cause by ensuring dependencies are declared, then backport to release if needed. + +## When in Doubt + +If you're unsure whether an issue should be fixed in the current branch or the default branch, ask yourself: + +1. Does this issue exist in the default branch? +2. Is this a workaround or a proper fix? +3. Will other branches/releases benefit from this fix? + +If the answer to any of these is "yes," suggest fixing it in the default branch first. diff --git a/PowerShell-master/.github/instructions/instruction-file-format.instructions.md b/PowerShell-master/.github/instructions/instruction-file-format.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..7c4e0bdd13dcb72bc1fa9d60408fcb53ebfbbb20 --- /dev/null +++ b/PowerShell-master/.github/instructions/instruction-file-format.instructions.md @@ -0,0 +1,220 @@ +--- +applyTo: + - ".github/instructions/**/*.instructions.md" +--- + +# Instruction File Format Guide + +This document describes the format and guidelines for creating custom instruction files for GitHub Copilot in the PowerShell repository. + +## File Naming Convention + +All instruction files must use the `.instructions.md` suffix: +- ✅ Correct: `build-checkout-prerequisites.instructions.md` +- ✅ Correct: `start-psbuild-basics.instructions.md` +- ❌ Incorrect: `build-guide.md` +- ❌ Incorrect: `instructions.md` + +## Required Frontmatter + +Every instruction file must start with YAML frontmatter containing an `applyTo` section: + +```yaml +--- +applyTo: + - "path/to/files/**/*.ext" + - "specific-file.ext" +--- +``` + +### applyTo Patterns + +Specify which files or directories these instructions apply to: + +**For workflow files:** +```yaml +applyTo: + - ".github/**/*.yml" + - ".github/**/*.yaml" +``` + +**For build scripts:** +```yaml +applyTo: + - "build.psm1" + - "tools/ci.psm1" +``` + +**For multiple contexts:** +```yaml +applyTo: + - "build.psm1" + - "tools/**/*.psm1" + - ".github/**/*.yml" +``` + +## Content Structure + +### 1. Clear Title + +Use a descriptive H1 heading after the frontmatter: + +```markdown +# Build Configuration Guide +``` + +### 2. Purpose or Overview + +Start with a brief explanation of what the instructions cover: + +```markdown +## Purpose + +This guide explains how to configure PowerShell builds for different scenarios. +``` + +### 3. Actionable Content + +Provide clear, actionable guidance: + +**✅ Good - Specific and actionable:** +```markdown +## Default Usage + +Use `Start-PSBuild` with no parameters for testing: + +```powershell +Import-Module ./tools/ci.psm1 +Start-PSBuild +``` +``` + +**❌ Bad - Vague and unclear:** +```markdown +## Usage + +You can use Start-PSBuild to build stuff. +``` + +### 4. Code Examples + +Include working code examples with proper syntax highlighting: + +```markdown +```yaml +- name: Build PowerShell + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Start-PSBuild +``` +``` + +### 5. Context and Rationale + +Explain why things are done a certain way: + +```markdown +**Why fetch-depth: 1000?** +- The build system needs Git history for version calculation +- Shallow clones would break versioning logic +``` + +## Best Practices + +### Be Concise + +- Focus on essential information +- Remove redundant explanations +- Use bullet points for lists + +### Be Specific + +- Provide exact commands and parameters +- Include file paths and line numbers when relevant +- Show concrete examples, not abstract concepts + +### Avoid Duplication + +- Don't repeat information from other instruction files +- Reference other files when appropriate +- Keep each file focused on one topic + +### Use Proper Formatting + +**Headers:** +- Use H1 (`#`) for the main title +- Use H2 (`##`) for major sections +- Use H3 (`###`) for subsections + +**Code blocks:** +- Always specify the language: ` ```yaml `, ` ```powershell `, ` ```bash ` +- Keep examples short and focused +- Test examples before including them + +**Lists:** +- Use `-` for unordered lists +- Use `1.` for ordered lists +- Keep list items concise + +## Example Structure + +```markdown +--- +applyTo: + - "relevant/files/**/*.ext" +--- + +# Title of Instructions + +Brief description of what these instructions cover. + +## Section 1 + +Content with examples. + +```language +code example +``` + +## Section 2 + +More specific guidance. + +### Subsection + +Detailed information when needed. + +## Best Practices + +- Actionable tip 1 +- Actionable tip 2 +``` + +## Maintaining Instructions + +### When to Create a New File + +Create a new instruction file when: +- Covering a distinct topic not addressed elsewhere +- The content is substantial enough to warrant its own file +- The `applyTo` scope is different from existing files + +### When to Update an Existing File + +Update an existing file when: +- Information is outdated +- New best practices emerge +- Examples need correction + +### When to Merge or Delete + +Merge or delete files when: +- Content is duplicated across multiple files +- A file is too small to be useful standalone +- Information is no longer relevant + +## Reference + +For more details, see: +- [GitHub Copilot Custom Instructions Documentation](https://docs.github.com/en/copilot/how-tos/configure-custom-instructions/add-repository-instructions) diff --git a/PowerShell-master/.github/instructions/log-grouping-guidelines.instructions.md b/PowerShell-master/.github/instructions/log-grouping-guidelines.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..ff845db4e4bd6ce378ddedce80c0482b9c10ba91 --- /dev/null +++ b/PowerShell-master/.github/instructions/log-grouping-guidelines.instructions.md @@ -0,0 +1,181 @@ +--- +applyTo: + - "build.psm1" + - "tools/ci.psm1" + - ".github/**/*.yml" + - ".github/**/*.yaml" +--- + +# Log Grouping Guidelines for GitHub Actions + +## Purpose + +Guidelines for using `Write-LogGroupStart` and `Write-LogGroupEnd` to create collapsible log sections in GitHub Actions CI/CD runs. + +## Key Principles + +### 1. Groups Cannot Be Nested + +GitHub Actions does not support nested groups. Only use one level of grouping. + +**❌ Don't:** +```powershell +Write-LogGroupStart -Title "Outer Group" +Write-LogGroupStart -Title "Inner Group" +# ... operations ... +Write-LogGroupEnd -Title "Inner Group" +Write-LogGroupEnd -Title "Outer Group" +``` + +**✅ Do:** +```powershell +Write-LogGroupStart -Title "Operation A" +# ... operations ... +Write-LogGroupEnd -Title "Operation A" + +Write-LogGroupStart -Title "Operation B" +# ... operations ... +Write-LogGroupEnd -Title "Operation B" +``` + +### 2. Groups Should Be Substantial + +Only create groups for operations that generate substantial output (5+ lines). Small groups add clutter without benefit. + +**❌ Don't:** +```powershell +Write-LogGroupStart -Title "Generate Resource Files" +Write-Log -message "Run ResGen" +Start-ResGen +Write-LogGroupEnd -Title "Generate Resource Files" +``` + +**✅ Do:** +```powershell +Write-Log -message "Run ResGen (generating C# bindings for resx files)" +Start-ResGen +``` + +### 3. Groups Should Represent Independent Operations + +Each group should be a logically independent operation that users might want to expand/collapse separately. + +**✅ Good examples:** +- Install Native Dependencies +- Install .NET SDK +- Build PowerShell +- Restore NuGet Packages + +**❌ Bad examples:** +- Individual project restores (too granular) +- Small code generation steps (too small) +- Sub-steps of a larger operation (would require nesting) + +### 4. One Group Per Iteration Is Excessive + +Avoid putting log groups inside loops where each iteration creates a separate group. This would probably cause nesting. + +**❌ Don't:** +```powershell +$projects | ForEach-Object { + Write-LogGroupStart -Title "Restore Project: $_" + dotnet restore $_ + Write-LogGroupEnd -Title "Restore Project: $_" +} +``` + +**✅ Do:** +```powershell +Write-LogGroupStart -Title "Restore All Projects" +$projects | ForEach-Object { + Write-Log -message "Restoring $_" + dotnet restore $_ +} +Write-LogGroupEnd -Title "Restore All Projects" +``` + +## Usage Pattern + +```powershell +Write-LogGroupStart -Title "Descriptive Operation Name" +try { + # ... operation code ... + Write-Log -message "Status updates" +} +finally { + # Ensure group is always closed +} +Write-LogGroupEnd -Title "Descriptive Operation Name" +``` + +## When to Use Log Groups + +Use log groups for: +- Major build phases (bootstrap, restore, build, test, package) +- Installation operations (dependencies, SDKs, tools) +- Operations that produce 5+ lines of output +- Operations where users might want to collapse verbose output + +Don't use log groups for: +- Single-line operations +- Code that's already inside another group +- Loop iterations with minimal output per iteration +- Diagnostic or debug output that should always be visible + +## Examples from build.psm1 + +### Good Usage + +```powershell +function Start-PSBootstrap { + # Multiple independent operations, each with substantial output + Write-LogGroupStart -Title "Install Native Dependencies" + # ... apt-get/yum/brew install commands ... + Write-LogGroupEnd -Title "Install Native Dependencies" + + Write-LogGroupStart -Title "Install .NET SDK" + # ... dotnet installation ... + Write-LogGroupEnd -Title "Install .NET SDK" +} +``` + +### Avoid + +```powershell +# Too small - just 2-3 lines +Write-LogGroupStart -Title "Generate Resource Files (ResGen)" +Write-Log -message "Run ResGen" +Start-ResGen +Write-LogGroupEnd -Title "Generate Resource Files (ResGen)" +``` + +## GitHub Actions Syntax + +These functions emit GitHub Actions workflow commands: +- `Write-LogGroupStart` → `::group::Title` +- `Write-LogGroupEnd` → `::endgroup::` + +In the GitHub Actions UI, this renders as collapsible sections with the specified title. + +## Testing + +Test log grouping locally: +```powershell +$env:GITHUB_ACTIONS = 'true' +Import-Module ./build.psm1 +Write-LogGroupStart -Title "Test" +Write-Log -Message "Content" +Write-LogGroupEnd -Title "Test" +``` + +Output should show: +``` +::group::Test +Content +::endgroup:: +``` + +## References + +- [GitHub Actions: Grouping log lines](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#grouping-log-lines) +- `build.psm1`: `Write-LogGroupStart` and `Write-LogGroupEnd` function definitions diff --git a/PowerShell-master/.github/instructions/onebranch-condition-syntax.instructions.md b/PowerShell-master/.github/instructions/onebranch-condition-syntax.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..19bf331d9c328e911651d0d1d9704895aeafbe3d --- /dev/null +++ b/PowerShell-master/.github/instructions/onebranch-condition-syntax.instructions.md @@ -0,0 +1,223 @@ +--- +applyTo: ".pipelines/**/*.{yml,yaml}" +--- + +# OneBranch Pipeline Condition Syntax + +## Overview +Azure Pipelines (OneBranch) uses specific syntax for referencing variables and parameters in condition expressions. Using the wrong syntax will cause conditions to fail silently or behave unexpectedly. + +## Variable Reference Patterns + +### In Condition Expressions + +**✅ Correct Pattern:** +```yaml +condition: eq(variables['VariableName'], 'value') +condition: or(eq(variables['VAR1'], 'true'), eq(variables['VAR2'], 'true')) +condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) +``` + +**❌ Incorrect Patterns:** +```yaml +# Don't use $(VAR) string expansion in conditions +condition: eq('$(VariableName)', 'value') + +# Don't use direct variable references +condition: eq($VariableName, 'value') +``` + +### In Script Content (pwsh, bash, etc.) + +**✅ Correct Pattern:** +```yaml +- pwsh: | + $value = '$(VariableName)' + Write-Host "Value: $(VariableName)" +``` + +### In Input Fields + +**✅ Correct Pattern:** +```yaml +inputs: + serviceEndpoint: '$(ServiceEndpoint)' + sbConfigPath: '$(SBConfigPath)' +``` + +## Parameter References + +### Template Parameters (Compile-Time) + +**✅ Correct Pattern:** +```yaml +parameters: + - name: OfficialBuild + type: boolean + default: false + +steps: + - task: SomeTask@1 + condition: eq('${{ parameters.OfficialBuild }}', 'true') +``` + +Note: Parameters use `${{ parameters.Name }}` because they're evaluated at template compile-time. + +### Runtime Variables (Execution-Time) + +**✅ Correct Pattern:** +```yaml +steps: + - pwsh: | + Write-Host "##vso[task.setvariable variable=MyVar]somevalue" + displayName: Set Variable + + - task: SomeTask@1 + condition: eq(variables['MyVar'], 'somevalue') +``` + +## Common Scenarios + +### Scenario 1: Check if Variable Equals Value + +```yaml +- task: DoSomething@1 + condition: eq(variables['PREVIEW'], 'true') +``` + +### Scenario 2: Multiple Variable Conditions (OR) + +```yaml +- task: DoSomething@1 + condition: or(eq(variables['STABLE'], 'true'), eq(variables['LTS'], 'true')) +``` + +### Scenario 3: Multiple Variable Conditions (AND) + +```yaml +- task: DoSomething@1 + condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) +``` + +### Scenario 4: Complex Conditions + +```yaml +- task: DoSomething@1 + condition: and( + succeededOrFailed(), + ne(variables['UseAzDevOpsFeed'], ''), + eq(variables['Build.SourceBranch'], 'refs/heads/master') + ) +``` + +### Scenario 5: Built-in Variables + +```yaml +- task: CodeQL3000Init@0 + condition: eq(variables['Build.SourceBranch'], 'refs/heads/master') + +- step: finalize + condition: eq(variables['Agent.JobStatus'], 'SucceededWithIssues') +``` + +### Scenario 6: Parameter vs Variable + +```yaml +parameters: + - name: OfficialBuild + type: boolean + +steps: + # Parameter condition (compile-time) + - task: SignFiles@1 + condition: eq('${{ parameters.OfficialBuild }}', 'true') + + # Variable condition (runtime) + - task: PublishArtifact@1 + condition: eq(variables['PUBLISH_ENABLED'], 'true') +``` + +## Why This Matters + +**String Expansion `$(VAR)` in Conditions:** +- When you use `'$(VAR)'` in a condition, Azure Pipelines attempts to expand it as a string +- If the variable is undefined or empty, it becomes an empty string `''` +- The condition `eq('', 'true')` will always be false +- This makes debugging difficult because there's no error message + +**Variables Array Syntax `variables['VAR']`:** +- This is the proper way to reference runtime variables in conditions +- Azure Pipelines correctly evaluates the variable's value +- Undefined variables are handled properly by the condition evaluator +- This is the standard pattern used throughout Azure Pipelines + +## Reference Examples + +Working examples can be found in: +- `.pipelines/templates/linux.yml` - Build.SourceBranch conditions +- `.pipelines/templates/windows-hosted-build.yml` - Architecture conditions +- `.pipelines/templates/compliance/apiscan.yml` - CODEQL_ENABLED conditions +- `.pipelines/templates/insert-nuget-config-azfeed.yml` - Complex AND/OR conditions + +## Quick Reference Table + +| Context | Syntax | Example | +|---------|--------|---------| +| Condition expression | `variables['Name']` | `condition: eq(variables['PREVIEW'], 'true')` | +| Script content | `$(Name)` | `pwsh: Write-Host "$(PREVIEW)"` | +| Task input | `$(Name)` | `inputs: path: '$(Build.SourcesDirectory)'` | +| Template parameter | `${{ parameters.Name }}` | `condition: eq('${{ parameters.Official }}', 'true')` | + +## Troubleshooting + +### Condition Always False +If your condition is always evaluating to false: +1. Check if you're using `'$(VAR)'` instead of `variables['VAR']` +2. Verify the variable is actually set (add a debug step to print the variable) +3. Check the variable value is exactly what you expect (case-sensitive) + +### Variable Not Found +If you get errors about variables not being found: +1. Ensure the variable is set before the condition is evaluated +2. Check that the variable name is spelled correctly +3. Verify the variable is in scope (job vs. stage vs. pipeline level) + +## Best Practices + +1. **Always use `variables['Name']` in conditions** - This is the correct Azure Pipelines pattern +2. **Use `$(Name)` for string expansion** in scripts and inputs +3. **Use `${{ parameters.Name }}` for template parameters** (compile-time) +4. **Add debug steps** to verify variable values when troubleshooting conditions +5. **Follow existing patterns** in the repository - grep for `condition:` to see examples + +## Common Mistakes + +❌ **Mistake 1: String expansion in condition** +```yaml +condition: eq('$(PREVIEW)', 'true') # WRONG +``` + +✅ **Fix:** +```yaml +condition: eq(variables['PREVIEW'], 'true') # CORRECT +``` + +❌ **Mistake 2: Missing quotes around parameter** +```yaml +condition: eq(${{ parameters.Official }}, true) # WRONG +``` + +✅ **Fix:** +```yaml +condition: eq('${{ parameters.Official }}', 'true') # CORRECT +``` + +❌ **Mistake 3: Mixing syntax** +```yaml +condition: or(eq('$(STABLE)', 'true'), eq(variables['LTS'], 'true')) # INCONSISTENT +``` + +✅ **Fix:** +```yaml +condition: or(eq(variables['STABLE'], 'true'), eq(variables['LTS'], 'true')) # CORRECT +``` diff --git a/PowerShell-master/.github/instructions/onebranch-restore-phase-pattern.instructions.md b/PowerShell-master/.github/instructions/onebranch-restore-phase-pattern.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..0945bb47c0beb059607d807e5afb4de90ecc257b --- /dev/null +++ b/PowerShell-master/.github/instructions/onebranch-restore-phase-pattern.instructions.md @@ -0,0 +1,83 @@ +--- +applyTo: ".pipelines/**/*.{yml,yaml}" +--- + +# OneBranch Restore Phase Pattern + +## Overview +When steps need to run in the OneBranch restore phase (before the main build phase), the `ob_restore_phase` environment variable must be set in the `env:` block of **each individual step**. + +## Pattern + +### ✅ Correct (Working Pattern) +```yaml +parameters: +- name: "ob_restore_phase" + type: boolean + default: true # or false if you don't want restore phase + +steps: +- powershell: | + # script content + displayName: 'Step Name' + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} +``` + +The key is to: +1. Define `ob_restore_phase` as a **boolean** parameter +2. Set `ob_restore_phase: ${{ parameters.ob_restore_phase }}` directly in each step's `env:` block +3. Pass `true` to run in restore phase, `false` to run in normal build phase + +### ❌ Incorrect (Does Not Work) +```yaml +steps: +- powershell: | + # script content + displayName: 'Step Name' + ${{ if eq(parameters.useRestorePhase, 'yes') }}: + env: + ob_restore_phase: true +``` + +Using conditionals at the same indentation level as `env:` causes only the first step to execute in restore phase. + +## Parameters + +Templates using this pattern should accept an `ob_restore_phase` boolean parameter: + +```yaml +parameters: +- name: "ob_restore_phase" + type: boolean + default: true # Set to true to run in restore phase by default +``` + +## Reference Examples + +Working examples of this pattern can be found in: +- `.pipelines/templates/insert-nuget-config-azfeed.yml` - Demonstrates the correct pattern +- `.pipelines/templates/SetVersionVariables.yml` - Updated to use this pattern + +## Why This Matters + +The restore phase in OneBranch pipelines runs before signing and other build operations. Steps that need to: +- Set environment variables for the entire build +- Configure authentication +- Prepare the repository structure + +Must run in the restore phase to be available when subsequent stages execute. + +## Common Use Cases + +- Setting `REPOROOT` variable +- Configuring NuGet feeds with authentication +- Setting version variables +- Repository preparation and validation + +## Troubleshooting + +If only the first step in your template is running in restore phase: +1. Check that `env:` block exists for **each step** +2. Verify the conditional `${{ if ... }}:` is **inside** the `env:` block +3. Confirm indentation is correct (conditional is indented under `env:`) diff --git a/PowerShell-master/.github/instructions/onebranch-signing-configuration.instructions.md b/PowerShell-master/.github/instructions/onebranch-signing-configuration.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..747fcaffdd635601bf7f50c67cda8965bc743379 --- /dev/null +++ b/PowerShell-master/.github/instructions/onebranch-signing-configuration.instructions.md @@ -0,0 +1,195 @@ +--- +applyTo: + - ".pipelines/**/*.yml" + - ".pipelines/**/*.yaml" +--- + +# OneBranch Signing Configuration + +This guide explains how to configure OneBranch signing variables in Azure Pipeline jobs, particularly when signing is not required. + +## Purpose + +OneBranch pipelines include signing infrastructure by default. For build-only jobs where signing happens in a separate stage, you should disable signing setup to improve performance and avoid unnecessary overhead. + +## Disable Signing for Build-Only Jobs + +When a job does not perform signing (e.g., it only builds artifacts that will be signed in a later stage), disable both signing setup and code sign validation: + +```yaml +variables: + - name: ob_signing_setup_enabled + value: false # Disable signing setup - this is a build-only stage + - name: ob_sdl_codeSignValidation_enabled + value: false # Skip signing validation in build-only stage +``` + +### Why Disable These Variables? + +**`ob_signing_setup_enabled: false`** +- Prevents OneBranch from setting up the signing infrastructure +- Reduces job startup time +- Avoids unnecessary credential validation +- Only disable when the job will NOT sign any artifacts + +**`ob_sdl_codeSignValidation_enabled: false`** +- Skips validation that checks if files are properly signed +- Appropriate for build stages where artifacts are unsigned +- Must be enabled in signing/release stages to validate signatures + +## Common Patterns + +### Build-Only Job (No Signing) + +```yaml +jobs: +- job: build_artifacts + variables: + - name: ob_signing_setup_enabled + value: false + - name: ob_sdl_codeSignValidation_enabled + value: false + steps: + - checkout: self + - pwsh: | + # Build unsigned artifacts + Start-PSBuild +``` + +### Signing Job + +```yaml +jobs: +- job: sign_artifacts + variables: + - name: ob_signing_setup_enabled + value: true + - name: ob_sdl_codeSignValidation_enabled + value: true + steps: + - checkout: self + env: + ob_restore_phase: true # Steps before first signing operation + - pwsh: | + # Prepare artifacts for signing + env: + ob_restore_phase: true # Steps before first signing operation + - task: onebranch.pipeline.signing@1 + displayName: 'Sign artifacts' + # Signing step runs in build phase (no ob_restore_phase) + - pwsh: | + # Post-signing validation + # Post-signing steps run in build phase (no ob_restore_phase) +``` + +## Restore Phase Usage with Signing + +**The restore phase (`ob_restore_phase: true`) should only be used in jobs that perform signing operations.** It separates preparation steps from the actual signing and build steps. + +### When to Use Restore Phase + +Use `ob_restore_phase: true` **only** in jobs where `ob_signing_setup_enabled: true`: + +```yaml +jobs: +- job: sign_artifacts + variables: + - name: ob_signing_setup_enabled + value: true # Signing enabled + steps: + # Steps BEFORE first signing operation: use restore phase + - checkout: self + env: + ob_restore_phase: true + - template: prepare-for-signing.yml + parameters: + ob_restore_phase: true + + # SIGNING STEP: runs in build phase (no ob_restore_phase) + - task: onebranch.pipeline.signing@1 + displayName: 'Sign artifacts' + + # Steps AFTER signing: run in build phase (no ob_restore_phase) + - pwsh: | + # Validation or packaging +``` + +### When NOT to Use Restore Phase + +**Do not use restore phase in build-only jobs** where `ob_signing_setup_enabled: false`: + +```yaml +jobs: +- job: build_artifacts + variables: + - name: ob_signing_setup_enabled + value: false # No signing + - name: ob_sdl_codeSignValidation_enabled + value: false + steps: + - checkout: self + # NO ob_restore_phase - not needed without signing + - pwsh: | + Start-PSBuild +``` + +**Why?** The restore phase is part of OneBranch's signing infrastructure. Using it without signing enabled adds unnecessary overhead without benefit. + +## Related Variables + +Other OneBranch signing-related variables: + +- `ob_sdl_binskim_enabled`: Controls BinSkim security analysis (can be false in build-only, true in signing stages) + +## Best Practices + +1. **Separate build and signing stages**: Build artifacts in one job, sign in another +2. **Disable signing in build stages**: Improves performance and clarifies intent +3. **Only use restore phase with signing**: The restore phase should only be used in jobs where signing is enabled (`ob_signing_setup_enabled: true`) +4. **Restore phase before first signing step**: All steps before the first signing operation should use `ob_restore_phase: true` +5. **Always validate after signing**: Enable validation in signing stages to catch issues +6. **Document the reason**: Add comments explaining why signing is disabled or why restore phase is used + +## Example: Split Build and Sign Pipeline + +```yaml +stages: + - stage: Build + jobs: + - job: build_windows + variables: + - name: ob_signing_setup_enabled + value: false # Build-only, no signing + - name: ob_sdl_codeSignValidation_enabled + value: false # Artifacts are unsigned + steps: + - template: templates/build-unsigned.yml + + - stage: Sign + dependsOn: Build + jobs: + - job: sign_windows + variables: + - name: ob_signing_setup_enabled + value: true # Enable signing infrastructure + - name: ob_sdl_codeSignValidation_enabled + value: true # Validate signatures + steps: + - template: templates/sign-artifacts.yml +``` + +## Troubleshooting + +**Job fails with signing-related errors but signing is disabled:** +- Verify `ob_signing_setup_enabled: false` is set in variables +- Check that no template is overriding the setting +- Ensure `ob_sdl_codeSignValidation_enabled: false` is also set + +**Signed artifacts fail validation:** +- Confirm `ob_sdl_codeSignValidation_enabled: true` in signing job +- Verify signing actually occurred +- Check certificate configuration + +## Reference + +- PowerShell signing templates: `.pipelines/templates/packaging/windows/sign.yml` diff --git a/PowerShell-master/.github/instructions/pester-set-itresult-pattern.instructions.md b/PowerShell-master/.github/instructions/pester-set-itresult-pattern.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..33a73ca081d634e96eb161616651b3da9693d35e --- /dev/null +++ b/PowerShell-master/.github/instructions/pester-set-itresult-pattern.instructions.md @@ -0,0 +1,198 @@ +--- +applyTo: + - "**/*.Tests.ps1" +--- + +# Pester Set-ItResult Pattern for Pending and Skipped Tests + +## Purpose + +This instruction explains when and how to use `Set-ItResult` in Pester tests to mark tests as Pending or Skipped dynamically within test execution. + +## When to Use Set-ItResult + +Use `Set-ItResult` when you need to conditionally mark a test as Pending or Skipped based on runtime conditions that can't be determined at test definition time. + +### Pending vs Skipped + +**Pending**: Use for tests that should be enabled but temporarily can't run due to: +- Intermittent external service failures (network, APIs) +- Known bugs being fixed +- Missing features being implemented +- Environmental issues that are being resolved + +**Skipped**: Use for tests that aren't applicable to the current environment: +- Platform-specific tests running on wrong platform +- Tests requiring specific hardware/configuration not present +- Tests requiring elevated permissions when not available +- Feature-specific tests when feature is disabled + +## Pattern + +### Basic Usage + +```powershell +It "Test description" { + if ($shouldBePending) { + Set-ItResult -Pending -Because "Explanation of why test is pending" + return + } + + if ($shouldBeSkipped) { + Set-ItResult -Skipped -Because "Explanation of why test is skipped" + return + } + + # Test code here +} +``` + +### Important: Always Return After Set-ItResult + +After calling `Set-ItResult`, you **must** return from the test to prevent further execution: + +```powershell +It "Test that checks environment" { + if ($env:SKIP_TESTS -eq 'true') { + Set-ItResult -Skipped -Because "SKIP_TESTS environment variable is set" + return # This is required! + } + + # Test assertions + $result | Should -Be $expected +} +``` + +**Why?** Without `return`, the test continues executing and may fail with errors unrelated to the pending/skipped condition. + +## Examples from the Codebase + +### Example 1: Pending for Intermittent Network Issues + +```powershell +It "Validate Update-Help for module" { + if ($markAsPending) { + Set-ItResult -Pending -Because "Update-Help from the web has intermittent connectivity issues. See issues #2807 and #6541." + return + } + + Update-Help -Module $moduleName -Force + # validation code... +} +``` + +### Example 2: Skipped for Missing Environment + +```powershell +It "Test requires CI environment" { + if (-not $env:CI) { + Set-ItResult -Skipped -Because "Test requires CI environment to safely install Pester" + return + } + + Install-CIPester -ErrorAction Stop +} +``` + +### Example 3: Pending for Platform-Specific Issue + +```powershell +It "Clear-Host works correctly" { + if ($IsARM64) { + Set-ItResult -Pending -Because "ARM64 runs in non-interactively mode and Clear-Host does not work." + return + } + + & { Clear-Host; 'hi' } | Should -BeExactly 'hi' +} +``` + +### Example 4: Skipped for Missing Feature + +```powershell +It "Test ACR authentication" { + if ($env:ACRTESTS -ne 'true') { + Set-ItResult -Skipped -Because "The tests require the ACRTESTS environment variable to be set to 'true' for ACR authentication." + return + } + + $psgetModuleInfo = Find-PSResource -Name $ACRTestModule -Repository $ACRRepositoryName + # test assertions... +} +``` + +## Alternative: Static -Skip and -Pending Parameters + +For conditions that can be determined at test definition time, use the static parameters instead: + +```powershell +# Static skip - condition known at definition time +It "Windows-only test" -Skip:(-not $IsWindows) { + # test code +} + +# Static pending - always pending +It "Test for feature being implemented" -Pending { + # test code that will fail until feature is done +} +``` + +**Use Set-ItResult when**: +- Condition depends on runtime state +- Condition is determined inside a helper function +- Need to check multiple conditions sequentially + +**Use static parameters when**: +- Condition is known at test definition +- Condition doesn't change during test run +- Want Pester to show the condition in test discovery + +## Best Practices + +1. **Always include -Because parameter** with a clear explanation +2. **Always return after Set-ItResult** to prevent further execution +3. **Reference issues or documentation** when relevant (e.g., "See issue #1234") +4. **Be specific in the reason** - explain what's wrong and what's needed +5. **Use Pending sparingly** - it indicates a problem that should be fixed +6. **Prefer Skipped over Pending** when test truly isn't applicable + +## Common Mistakes + +### ❌ Mistake 1: Forgetting to Return + +```powershell +It "Test" { + if ($condition) { + Set-ItResult -Pending -Because "Reason" + # Missing return - test code will still execute! + } + $value | Should -Be $expected # This runs and fails +} +``` + +### ❌ Mistake 2: Vague Reason + +```powershell +Set-ItResult -Pending -Because "Doesn't work" # Too vague +``` + +### ✅ Correct: + +```powershell +It "Test" { + if ($condition) { + Set-ItResult -Pending -Because "Update-Help has intermittent network timeouts. See issue #2807." + return + } + $value | Should -Be $expected +} +``` + +## See Also + +- [Pester Documentation: Set-ItResult](https://pester.dev/docs/commands/Set-ItResult) +- [Pester Documentation: It](https://pester.dev/docs/commands/It) +- Examples in the codebase: + - `test/powershell/Host/ConsoleHost.Tests.ps1` + - `test/infrastructure/ciModule.Tests.ps1` + - `tools/packaging/releaseTests/sbom.tests.ps1` diff --git a/PowerShell-master/.github/instructions/pester-test-status-and-working-meaning.instructions.md b/PowerShell-master/.github/instructions/pester-test-status-and-working-meaning.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..d2b28a05f183293296d8b8b97b6b542b366fe97e --- /dev/null +++ b/PowerShell-master/.github/instructions/pester-test-status-and-working-meaning.instructions.md @@ -0,0 +1,299 @@ +--- +applyTo: "**/*.Tests.ps1" +--- + +# Pester Test Status Meanings and Working Tests + +## Purpose + +This guide clarifies Pester test outcomes and what it means for a test to be "working" - which requires both **passing** AND **actually validating functionality**. + +## Test Statuses in Pester + +### Passed ✓ +**Status Code**: `Passed` +**Exit Result**: Test ran successfully, all assertions passed + +**What it means**: +- Test executed without errors +- All `Should` statements evaluated to true +- Test setup and teardown completed without issues +- Test is **validating** the intended functionality + +**What it does NOT mean**: +- The feature is working (assertions could be wrong) +- The test is meaningful (could be testing wrong thing) +- The test exercises all code paths + +### Failed ✗ +**Status Code**: `Failed` +**Exit Result**: Test ran but assertions failed + +**What it means**: +- Test executed but an assertion returned false +- Expected value did not match actual value +- Test detected a problem with the functionality + +**Examples**: +``` +Expected $true but got $false +Expected 5 items but got 3 +Expected no error but got: Cannot find parameter +``` + +### Error ⚠ +**Status Code**: `Error` +**Exit Result**: Test crashed with an exception + +**What it means**: +- Test failed to complete +- An exception was thrown during test execution +- Could be in test setup, test body, or test cleanup +- Often indicates environmental issue, not code functional issue + +**Examples**: +``` +Cannot bind argument to parameter 'Path' because it is null +File not found: C:\expected\config.json +Access denied writing to registry +``` + +### Pending ⏳ +**Status Code**: `Pending` +**Exit Result**: Test ran but never completed assertions + +**What it means**: +- Test was explicitly marked as not ready to run +- `Set-ItResult -Pending` was called +- Used to indicate: known bugs, missing features, environmental issues + +**When to use Pending**: +- Test for feature in development +- Test disabled due to known bug (issue #1234) +- Test disabled due to intermittent failures being fixed +- Platform-specific issues being resolved + +**⚠️ WARNING**: Pending tests are NOT validating functionality. They hide problems. + +### Skipped ⊘ +**Status Code**: `Skipped` +**Exit Result**: Test did not run (detected at start) + +**What it means**: +- Test was intentionally not executed +- `-Skip` parameter or `It -Skip:$condition` was used +- Environment doesn't support this test + +**When to use Skip**: +- Test not applicable to current platform (Windows-only test on Linux) +- Test requires feature that's not available (admin privileges) +- Test requires specific configuration not present + +**Difference from Pending**: +- **Skip**: "This test shouldn't run here" (known upfront) +- **Pending**: "This test should eventually run but can't now" + +### Ignored ✛ +**Status Code**: `Ignored` +**Exit Result**: Test marked as not applicable + +**What it means**: +- Test has `[Ignore("reason")]` attribute +- Test is permanently disabled in this location +- Not the same as Skipped (which is conditional) + +**When to use Ignore**: +- Test for deprecated feature +- Test for bug that won't be fixed +- Test moved to different test file + +--- + +## What Does "Working" Actually Mean? + +A test is **working** when it meets BOTH criteria: + +### 1. **Test Status is PASSED** ✓ +```powershell +It "Test name" { + # Test executes + # All assertions pass + # Returns Passed status +} +``` + +### 2. **Test Actually Validates Functionality** +```powershell +# ✓ GOOD: Tests actual functionality +It "Get-Item returns files from directory" -Tags @('Unit') { + $testDir = New-Item -ItemType Directory -Force + New-Item -Path $testDir -Name "file.txt" -ItemType File | Out-Null + + $result = Get-Item -Path "$testDir\file.txt" + + $result.Name | Should -Be "file.txt" + $result | Should -Exist + + Remove-Item $testDir -Recurse -Force +} + +# ✗ BAD: Returns Passed but doesn't validate functionality +It "Get-Item returns files from directory" -Tags @('Unit') { + $result = Get-Item -Path somepath # May not exist, may not actually test + $result | Should -Not -BeNullOrEmpty # Too vague +} + +# ✗ BAD: Test marked Pending - validation is hidden +It "Get-Item returns files from directory" -Tags @('Unit') { + Set-ItResult -Pending -Because "File system not working" + return + # No validation happens at all +} +``` + +--- + +## The Problem with Pending Tests + +### Why Pending Tests Hide Problems + +```powershell +# BAD: Test marked Pending - looks like "working" status but validation is skipped +It "Download help from web" { + Set-ItResult -Pending -Because "Web connectivity issues" + return + + # This code never runs: + Update-Help -Module PackageManagement -Force -ErrorAction Stop + Get-Help Get-Package | Should -Not -BeNullOrEmpty +} +``` + +**Result**: +- ✗ Feature is broken (Update-Help fails) +- ✓ Test shows "Pending" (looks acceptable) +- ✗ Problem is hidden and never fixed + +### The Right Approach + +**Option A: Fix the root cause** +```powershell +It "Download help from web" { + # Use local assets that are guaranteed to work + Update-Help -Module PackageManagement -SourcePath ./assets -Force -ErrorAction Stop + + Get-Help Get-Package | Should -Not -BeNullOrEmpty +} +``` + +**Option B: Gracefully skip when unavailable** +```powershell +It "Download help from web" -Skip:$(-not $hasInternet) { + Update-Help -Module PackageManagement -Force -ErrorAction Stop + Get-Help Get-Package | Should -Not -BeNullOrEmpty +} +``` + +**Option C: Add retry logic for intermittent issues** +```powershell +It "Download help from web" { + $maxRetries = 3 + $attempt = 0 + + while ($attempt -lt $maxRetries) { + try { + Update-Help -Module PackageManagement -Force -ErrorAction Stop + break + } + catch { + $attempt++ + if ($attempt -ge $maxRetries) { throw } + Start-Sleep -Seconds 2 + } + } + + Get-Help Get-Package | Should -Not -BeNullOrEmpty +} +``` + +--- + +## Test Status Summary Table + +| Status | Passed? | Validates? | Counts as "Working"? | Use When | +|--------|---------|------------|----------------------|----------| +| **Passed** | ✓ | ✓ | **YES** | Feature is working and test proves it | +| **Failed** | ✗ | ✓ | NO | Feature is broken or test has wrong expectation | +| **Error** | ✗ | ✗ | NO | Test infrastructure broken, can't validate | +| **Pending** | - | ✗ | **NO** ⚠️ | Temporary - test should eventually pass | +| **Skipped** | - | ✗ | NO | Test not applicable to this environment | +| **Ignored** | - | ✗ | NO | Test permanently disabled | + +--- + +## Recommended Patterns + +### Pattern 1: Resilient Test with Fallback +```powershell +It "Feature works with web or local source" { + $useLocal = $false + + try { + Update-Help -Module Package -Force -ErrorAction Stop + } + catch { + $useLocal = $true + Update-Help -Module Package -SourcePath ./assets -Force -ErrorAction Stop + } + + # Validate functionality regardless of source + Get-Help Get-Package | Should -Not -BeNullOrEmpty +} +``` + +### Pattern 2: Conditional Skip with Clear Reason +```powershell +Describe "Update-Help from Web" -Skip $(-not (Test-InternetConnectivity)) { + It "Downloads help successfully" { + Update-Help -Module PackageManagement -Force -ErrorAction Stop + Get-Help Get-Package | Should -Not -BeNullOrEmpty + } +} +``` + +### Pattern 3: Separate Suites by Dependency +```powershell +Describe "Help Content Tests - Web" { + # Tests that require internet - can be skipped if unavailable + It "Downloads from web" { ... } +} + +Describe "Help Content Tests - Local" { + # Tests with local assets - should always pass + It "Loads from local assets" { + Update-Help -Module Package -SourcePath ./assets -Force + Get-Help Get-Package | Should -Not -BeNullOrEmpty + } +} +``` + +--- + +## Checklist: Is Your Test "Working"? + +- [ ] Test status is **Passed** (not Pending, not Skipped, not Failed) +- [ ] Test actually **executes** the feature being tested +- [ ] Test has **specific assertions** (not just `Should -Not -BeNullOrEmpty`) +- [ ] Test includes **cleanup** (removes temp files, restores state) +- [ ] Test can run **multiple times** without side effects +- [ ] Test failure **indicates a real problem** (not flaky assertions) +- [ ] Test success **proves the feature works** (not just "didn't crash") + +If any of these is false, your test may be passing but not "working" properly. + +--- + +## See Also + +- [Pester Documentation](https://pester.dev/) +- [Set-ItResult Documentation](https://pester.dev/docs/commands/Set-ItResult) diff --git a/PowerShell-master/.github/instructions/powershell-automatic-variables.instructions.md b/PowerShell-master/.github/instructions/powershell-automatic-variables.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..5015847f41ff9aaeec5e36de290fb957595f95c7 --- /dev/null +++ b/PowerShell-master/.github/instructions/powershell-automatic-variables.instructions.md @@ -0,0 +1,159 @@ +--- +applyTo: + - "**/*.ps1" + - "**/*.psm1" +--- + +# PowerShell Automatic Variables - Naming Guidelines + +## Purpose + +This instruction provides guidelines for avoiding conflicts with PowerShell's automatic variables when writing PowerShell scripts and modules. + +## What Are Automatic Variables? + +PowerShell has built-in automatic variables that are created and maintained by PowerShell itself. Assigning values to these variables can cause unexpected behavior and side effects. + +## Common Automatic Variables to Avoid + +### Critical Variables (Never Use) + +- **`$matches`** - Contains the results of regular expression matches. Overwriting this can break regex operations. +- **`$_`** - Represents the current object in the pipeline. Only use within pipeline blocks. +- **`$PSItem`** - Alias for `$_`. Same rules apply. +- **`$args`** - Contains an array of undeclared parameters. Don't use as a regular variable. +- **`$input`** - Contains an enumerator of all input passed to a function. Don't reassign. +- **`$LastExitCode`** - Exit code of the last native command. Don't overwrite unless intentional. +- **`$?`** - Success status of the last command. Don't use as a variable name. +- **`$$`** - Last token in the last line received by the session. Don't use. +- **`$^`** - First token in the last line received by the session. Don't use. + +### Context Variables (Use with Caution) + +- **`$Error`** - Array of error objects. Don't replace, but can modify (e.g., `$Error.Clear()`). +- **`$PSBoundParameters`** - Parameters passed to the current function. Read-only. +- **`$MyInvocation`** - Information about the current command. Read-only. +- **`$PSCmdlet`** - Cmdlet object for advanced functions. Read-only. + +### Other Common Automatic Variables + +- `$true`, `$false`, `$null` - Boolean and null constants +- `$HOME`, `$PSHome`, `$PWD` - Path-related variables +- `$PID` - Process ID of the current PowerShell session +- `$Host` - Host application object +- `$PSVersionTable` - PowerShell version information + +For a complete list, see: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_automatic_variables + +## Best Practices + +### ❌ Bad - Using Automatic Variable Names + +```powershell +# Bad: $matches is an automatic variable used for regex capture groups +$matches = Select-String -Path $file -Pattern $pattern + +# Bad: $args is an automatic variable for undeclared parameters +$args = Get-ChildItem + +# Bad: $input is an automatic variable for pipeline input +$input = Read-Host "Enter value" +``` + +### ✅ Good - Using Descriptive Alternative Names + +```powershell +# Good: Use descriptive names that avoid conflicts +$matchedLines = Select-String -Path $file -Pattern $pattern + +# Good: Use specific names for arguments +$arguments = Get-ChildItem + +# Good: Use specific names for user input +$userInput = Read-Host "Enter value" +``` + +## Naming Alternatives + +When you encounter a situation where you might use an automatic variable name, use these alternatives: + +| Avoid | Use Instead | +|-------|-------------| +| `$matches` | `$matchedLines`, `$matchResults`, `$regexMatches` | +| `$args` | `$arguments`, `$parameters`, `$commandArgs` | +| `$input` | `$userInput`, `$inputValue`, `$inputData` | +| `$_` (outside pipeline) | Use a named parameter or explicit variable | +| `$Error` (reassignment) | Don't reassign; use `$Error.Clear()` if needed | + +## How to Check + +### PSScriptAnalyzer Rule + +PSScriptAnalyzer has a built-in rule that detects assignments to automatic variables: + +```powershell +# This will trigger PSAvoidAssignmentToAutomaticVariable +$matches = Get-Something +``` + +**Rule ID**: PSAvoidAssignmentToAutomaticVariable + +### Manual Review + +When writing PowerShell code, always: +1. Avoid variable names that match PowerShell keywords or automatic variables +2. Use descriptive, specific names that clearly indicate the variable's purpose +3. Run PSScriptAnalyzer on your code before committing +4. Review code for variable naming during PR reviews + +## Examples from the Codebase + +### Example 1: Regex Matching + +```powershell +# ❌ Bad - Overwrites automatic $matches variable +$matches = [regex]::Matches($content, $pattern) + +# ✅ Good - Uses descriptive name +$regexMatches = [regex]::Matches($content, $pattern) +``` + +### Example 2: Select-String Results + +```powershell +# ❌ Bad - Conflicts with automatic $matches +$matches = Select-String -Path $file -Pattern $pattern + +# ✅ Good - Clear and specific +$matchedLines = Select-String -Path $file -Pattern $pattern +``` + +### Example 3: Collecting Arguments + +```powershell +# ❌ Bad - Conflicts with automatic $args +function Process-Items { + $args = $MyItems + # ... process items +} + +# ✅ Good - Descriptive parameter name +function Process-Items { + [CmdletBinding()] + param( + [Parameter(ValueFromRemainingArguments)] + [string[]]$Items + ) + # ... process items +} +``` + +## References + +- [PowerShell Automatic Variables Documentation](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_automatic_variables) +- [PSScriptAnalyzer Rules](https://github.com/PowerShell/PSScriptAnalyzer/blob/master/docs/Rules/README.md) +- [PowerShell Best Practices](https://learn.microsoft.com/powershell/scripting/developer/cmdlet/strongly-encouraged-development-guidelines) + +## Summary + +**Key Takeaway**: Always use descriptive, specific variable names that clearly indicate their purpose and avoid conflicts with PowerShell's automatic variables. When in doubt, choose a longer, more descriptive name over a short one that might conflict. diff --git a/PowerShell-master/.github/instructions/powershell-module-organization.instructions.md b/PowerShell-master/.github/instructions/powershell-module-organization.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..9cdba06c3640e2da06bba9a546ff2eaeec8c9a10 --- /dev/null +++ b/PowerShell-master/.github/instructions/powershell-module-organization.instructions.md @@ -0,0 +1,201 @@ +--- +applyTo: + - "tools/ci.psm1" + - "build.psm1" + - "tools/packaging/**/*.psm1" + - ".github/**/*.yml" + - ".github/**/*.yaml" +--- + +# Guidelines for PowerShell Code Organization + +## When to Move Code from YAML to PowerShell Modules + +PowerShell code in GitHub Actions YAML files should be kept minimal. Move code to a module when: + +### Size Threshold +- **More than ~30 lines** of PowerShell in a YAML file step +- **Any use of .NET types** like `[regex]`, `[System.IO.Path]`, etc. +- **Complex logic** requiring multiple nested loops or conditionals +- **Reusable functionality** that might be needed elsewhere + +### Indicators to Move Code +1. Using .NET type accelerators (`[regex]`, `[PSCustomObject]`, etc.) +2. Complex string manipulation or parsing +3. File system operations beyond basic reads/writes +4. Logic that would benefit from unit testing +5. Code that's difficult to read/maintain in YAML format + +## Which Module to Use + +### ci.psm1 (`tools/ci.psm1`) +**Purpose**: CI/CD-specific operations and workflows + +**Use for**: +- Build orchestration (invoking builds, tests, packaging) +- CI environment setup and configuration +- Test execution and result processing +- Artifact handling and publishing +- CI-specific validations and checks +- Environment variable management for CI + +**Examples**: +- `Invoke-CIBuild` - Orchestrates build process +- `Invoke-CITest` - Runs Pester tests +- `Test-MergeConflictMarker` - Validates files for conflicts +- `Set-BuildVariable` - Manages CI variables + +**When NOT to use**: +- Core build operations (use build.psm1) +- Package creation logic (use packaging.psm1) +- Platform-specific build steps + +### build.psm1 (`build.psm1`) +**Purpose**: Core build operations and utilities + +**Use for**: +- Compiling source code +- Resource generation +- Build configuration management +- Core build utilities (New-PSOptions, Get-PSOutput, etc.) +- Bootstrap operations +- Cross-platform build helpers + +**Examples**: +- `Start-PSBuild` - Main build function +- `Start-PSBootstrap` - Bootstrap dependencies +- `New-PSOptions` - Create build configuration +- `Start-ResGen` - Generate resources + +**When NOT to use**: +- CI workflow orchestration (use ci.psm1) +- Package creation (use packaging.psm1) +- Test execution + +### packaging.psm1 (`tools/packaging/packaging.psm1`) +**Purpose**: Package creation and distribution + +**Use for**: +- Creating distribution packages (MSI, RPM, DEB, etc.) +- Package-specific metadata generation +- Package signing operations +- Platform-specific packaging logic + +**Examples**: +- `Start-PSPackage` - Create packages +- `New-MSIXPackage` - Create Windows MSIX +- `New-DotnetSdkContainerFxdPackage` - Create container packages + +**When NOT to use**: +- Building binaries (use build.psm1) +- Running tests (use ci.psm1) +- General utilities + +## Best Practices + +### Keep YAML Minimal +```yaml +# ❌ Bad - too much logic in YAML +- name: Check files + shell: pwsh + run: | + $files = Get-ChildItem -Recurse + foreach ($file in $files) { + $content = Get-Content $file -Raw + if ($content -match $pattern) { + # ... complex processing ... + } + } + +# ✅ Good - call function from module +- name: Check files + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Test-SomeCondition -Path ${{ github.workspace }} +``` + +### Document Functions +Always include comment-based help for functions: +```powershell +function Test-MyFunction +{ + <# + .SYNOPSIS + Brief description + .DESCRIPTION + Detailed description + .PARAMETER ParameterName + Parameter description + .EXAMPLE + Test-MyFunction -ParameterName Value + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $ParameterName + ) + # Implementation +} +``` + +### Error Handling +Use proper error handling in modules: +```powershell +try { + # Operation +} +catch { + Write-Error "Detailed error message: $_" + throw +} +``` + +### Verbose Output +Use `Write-Verbose` for debugging information: +```powershell +Write-Verbose "Processing file: $filePath" +``` + +## Module Dependencies + +- **ci.psm1** imports both `build.psm1` and `packaging.psm1` +- **build.psm1** is standalone (minimal dependencies) +- **packaging.psm1** imports `build.psm1` + +When adding new functions, consider these import relationships to avoid circular dependencies. + +## Testing Modules + +Functions in modules should be testable: +```powershell +# Test locally +Import-Module ./tools/ci.psm1 -Force +Test-MyFunction -Parameter Value + +# Can be unit tested with Pester +Describe "Test-MyFunction" { + It "Should return expected result" { + # Test implementation + } +} +``` + +## Migration Checklist + +When moving code from YAML to a module: + +1. ✅ Determine which module is appropriate (ci, build, or packaging) +2. ✅ Create function with proper parameter validation +3. ✅ Add comment-based help documentation +4. ✅ Use `[CmdletBinding()]` for advanced function features +5. ✅ Include error handling +6. ✅ Add verbose output for debugging +7. ✅ Test the function independently +8. ✅ Update YAML to call the new function +9. ✅ Verify the workflow still works end-to-end + +## References + +- PowerShell Advanced Functions: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced +- Comment-Based Help: https://learn.microsoft.com/powershell/scripting/developer/help/writing-help-for-windows-powershell-scripts-and-functions diff --git a/PowerShell-master/.github/instructions/powershell-parameter-naming.instructions.md b/PowerShell-master/.github/instructions/powershell-parameter-naming.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..155fd1a85c33afd3f1642a863d2e6612fde0ed87 --- /dev/null +++ b/PowerShell-master/.github/instructions/powershell-parameter-naming.instructions.md @@ -0,0 +1,69 @@ +--- +applyTo: '**/*.ps1, **/*.psm1' +description: Naming conventions for PowerShell parameters +--- + +# PowerShell Parameter Naming Conventions + +## Purpose + +This instruction defines the naming conventions for parameters in PowerShell scripts and modules. Consistent parameter naming improves code readability, maintainability, and usability for users of PowerShell cmdlets and functions. + +## Parameter Naming Rules + +### General Conventions +- **Singular Nouns**: Use singular nouns for parameter names even if the parameter is expected to handle multiple values (e.g., `File` instead of `Files`). +- **Use PascalCase**: Parameter names must use PascalCase (e.g., `ParameterName`). +- **Descriptive Names**: Parameter names should be descriptive and convey their purpose clearly (e.g., `FilePath`, `UserName`). +- **Avoid Abbreviations**: Avoid using abbreviations unless they are widely recognized (e.g., `ID` for Identifier). +- **Avoid Reserved Words**: Do not use PowerShell reserved words as parameter names (e.g., `if`, `else`, `function`). + +### Units and Precision +- **Include Units in Parameter Names**: When a parameter represents a value with units, include the unit in the parameter name for clarity: + - `TimeoutSec` instead of `Timeout` + - `RetryIntervalSec` instead of `RetryInterval` + - `MaxSizeBytes` instead of `MaxSize` +- **Use Full Words for Clarity**: Spell out common terms to match PowerShell conventions: + - `MaximumRetryCount` instead of `MaxRetries` + - `MinimumLength` instead of `MinLength` + +### Alignment with Built-in Cmdlets +- **Follow Existing PowerShell Conventions**: When your parameter serves a similar purpose to a built-in cmdlet parameter, use the same or similar naming: + - Match `Invoke-WebRequest` parameters when making HTTP requests: `TimeoutSec`, `MaximumRetryCount`, `RetryIntervalSec` + - Follow common parameter patterns like `Path`, `Force`, `Recurse`, `WhatIf`, `Confirm` +- **Consistency Within Scripts**: If multiple parameters relate to the same concept, use consistent naming patterns (e.g., `TimeoutSec`, `RetryIntervalSec` both use `Sec` suffix). + +## Examples + +### Good Parameter Names +```powershell +param( + [string[]]$File, # Singular, even though it accepts arrays + [int]$TimeoutSec = 30, # Unit included + [int]$MaximumRetryCount = 2, # Full word "Maximum" + [int]$RetryIntervalSec = 2, # Consistent with TimeoutSec + [string]$Path, # Standard PowerShell convention + [switch]$Force # Common PowerShell parameter +) +``` + +### Names to Avoid +```powershell +param( + [string[]]$Files, # Should be singular: File + [int]$Timeout = 30, # Missing unit: TimeoutSec + [int]$MaxRetries = 2, # Should be: MaximumRetryCount + [int]$RetryInterval = 2, # Missing unit: RetryIntervalSec + [string]$FileLoc, # Avoid abbreviations: FilePath + [int]$Max # Ambiguous: MaximumWhat? +) +``` + +## Exceptions +- **Common Terms**: Some common terms may be used in plural form if they are widely accepted in the context (e.g., `Credentials`, `Permissions`). +- **Legacy Code**: Existing code that does not follow these conventions may be exempted to avoid breaking changes, but new code should adhere to these guidelines. +- **Well Established Naming Patterns**: If a naming pattern is well established in the PowerShell community, it may be used even if it does not strictly adhere to these guidelines. + +## References +- [PowerShell Cmdlet Design Guidelines](https://learn.microsoft.com/powershell/scripting/developer/cmdlet/strongly-encouraged-development-guidelines) +- [About Parameters - PowerShell Documentation](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_parameters) diff --git a/PowerShell-master/.github/instructions/publishing-pester-result.instructions.md b/PowerShell-master/.github/instructions/publishing-pester-result.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..49010e65a99c8baa451002004567aa6895f5ac0e --- /dev/null +++ b/PowerShell-master/.github/instructions/publishing-pester-result.instructions.md @@ -0,0 +1,272 @@ +--- +applyTo: ".github/**/*.{yml,yaml}" +--- + +# Publishing Pester Test Results Instructions + +This document describes how the PowerShell repository uses GitHub Actions to publish Pester test results. + +## Overview + +The PowerShell repository uses a custom composite GitHub Action located at `.github/actions/test/process-pester-results` to process and publish Pester test results in CI/CD workflows. +This action aggregates test results from NUnitXml formatted files, creates a summary in the GitHub Actions job summary, and uploads the results as artifacts. + +## How It Works + +### Action Location and Structure + +**Path**: `.github/actions/test/process-pester-results/` + +The action consists of two main files: + +1. **action.yml** - The composite action definition +1. **process-pester-results.ps1** - PowerShell script that processes test results + +### Action Inputs + +The action accepts the following inputs: + +- **name** (required): A descriptive name for the test run (e.g., "UnelevatedPesterTests-CI") + - Used for naming the uploaded artifact and in the summary + - Format: `junit-pester-{name}` + +- **testResultsFolder** (optional): Path to the folder containing test result XML files + - Default: `${{ runner.workspace }}/testResults` + - The script searches for all `*.xml` files in this folder recursively + +### Action Workflow + +The action performs the following steps: + +1. **Process Test Results** + - Runs `process-pester-results.ps1` with the provided name and test results folder + - Parses all NUnitXml formatted test result files (`*.xml`) + - Aggregates test statistics across all files: + - Total test cases + - Errors + - Failures + - Not run tests + - Inconclusive tests + - Ignored tests + - Skipped tests + - Invalid tests + +1. **Generate Summary** + - Creates a markdown summary using the `$GITHUB_STEP_SUMMARY` environment variable + - Uses `Write-Log` and `Write-LogGroupStart`/`Write-LogGroupEnd` functions from `build.psm1` + - Outputs a formatted summary with all test statistics + - Example format: + + ```markdown + # Summary of {Name} + + - Total Tests: X + - Total Errors: X + - Total Failures: X + - Total Not Run: X + - Total Inconclusive: X + - Total Ignored: X + - Total Skipped: X + - Total Invalid: X + ``` + +1. **Upload Artifacts** + - Uses `actions/upload-artifact@v4` to upload test results + - Artifact name: `junit-pester-{name}` + - Always runs (even if previous steps fail) via `if: always()` + - Uploads the entire test results folder + +1. **Exit Status** + - Fails the job (exit 1) if: + - Any test errors occurred (`$testErrorCount -gt 0`) + - Any test failures occurred (`$testFailureCount -gt 0`) + - No test cases were run (`$testCaseCount -eq 0`) + +## Usage in Test Actions + +The `process-pester-results` action is called by two platform-specific composite test actions: + +### Linux/macOS Tests: `.github/actions/test/nix` + +Used in: + +- `.github/workflows/linux-ci.yml` +- `.github/workflows/macos-ci.yml` + +Example usage (lines 99-104 in `nix/action.yml`): + +```yaml +- name: Convert, Publish, and Upload Pester Test Results + uses: "./.github/actions/test/process-pester-results" + with: + name: "${{ inputs.purpose }}-${{ inputs.tagSet }}" + testResultsFolder: "${{ runner.workspace }}/testResults" +``` + +### Windows Tests: `.github/actions/test/windows` + +Used in: + +- `.github/workflows/windows-ci.yml` + +Example usage (line 78-83 in `windows/action.yml`): + +```yaml +- name: Convert, Publish, and Upload Pester Test Results + uses: "./.github/actions/test/process-pester-results" + with: + name: "${{ inputs.purpose }}-${{ inputs.tagSet }}" + testResultsFolder: ${{ runner.workspace }}\testResults +``` + +## Workflow Integration + +The process-pester-results action is integrated into the CI workflows through a multi-level hierarchy: + +### Level 1: Main CI Workflows + +- `linux-ci.yml` +- `macos-ci.yml` +- `windows-ci.yml` + +### Level 2: Test Jobs + +Each workflow contains multiple test jobs with different purposes and tag sets: + +- `UnelevatedPesterTests` with tagSet `CI` +- `ElevatedPesterTests` with tagSet `CI` +- `UnelevatedPesterTests` with tagSet `Others` +- `ElevatedPesterTests` with tagSet `Others` + +### Level 3: Platform Test Actions + +Test jobs use platform-specific actions: + +- `nix` for Linux and macOS +- `windows` for Windows + +### Level 4: Process Results Action + +Platform actions call `process-pester-results` to publish results + +## Test Execution Flow + +1. **Build Phase**: Source code is built (e.g., in `ci_build` job) +1. **Test Preparation**: + - Build artifacts are downloaded + - PowerShell is bootstrapped + - Test binaries are extracted +1. **Test Execution**: + - `Invoke-CITest` is called with: + - `-Purpose`: Test purpose (e.g., "UnelevatedPesterTests") + - `-TagSet`: Test category (e.g., "CI", "Others") + - `-OutputFormat NUnitXml`: Results format + - Results are written to `${{ runner.workspace }}/testResults` +1. **Results Processing**: + - `process-pester-results` action runs + - Results are aggregated and summarized + - Artifacts are uploaded + - Job fails if any tests failed or errored + +## Key Dependencies + +### PowerShell Modules + +- **build.psm1**: Provides utility functions + - `Write-Log`: Logging function with GitHub Actions support + - `Write-LogGroupStart`: Creates collapsible log groups + - `Write-LogGroupEnd`: Closes collapsible log groups + +### GitHub Actions Features + +- **GITHUB_STEP_SUMMARY**: Environment variable for job summary +- **actions/upload-artifact@v4**: For uploading test results +- **Composite Actions**: For reusable workflow steps + +### Test Result Format + +- **NUnitXml**: XML format for test results +- Expected XML structure with `test-results` root element containing: + - `total`: Total number of tests + - `errors`: Number of errors + - `failures`: Number of failures + - `not-run`: Number of tests not run + - `inconclusive`: Number of inconclusive tests + - `ignored`: Number of ignored tests + - `skipped`: Number of skipped tests + - `invalid`: Number of invalid tests + +## Best Practices + +1. **Naming Convention**: Use descriptive names that include both purpose and tagSet: + - Format: `{purpose}-{tagSet}` + - Example: `UnelevatedPesterTests-CI` + +1. **Test Results Location**: + - Default location: `${{ runner.workspace }}/testResults` + - Use platform-appropriate path separators (Windows: `\`, Unix: `/`) + +1. **Always Upload**: The artifact upload step uses `if: always()` to ensure results are uploaded even when tests fail + +1. **Error Handling**: The action will fail the job if: + - Tests have errors or failures (intentional fail-fast behavior) + - No tests were executed (potential configuration issue) + - `GITHUB_STEP_SUMMARY` is not set (environment issue) + +## Customizing for Your Repository + +To use this pattern in another repository: + +1. **Copy the Action Files**: + - Copy `.github/actions/test/process-pester-results/` directory + - Ensure the PowerShell script has proper permissions + +1. **Adjust Dependencies**: + - Modify or remove the `Import-Module "$PSScriptRoot/../../../../build.psm1"` line + - Implement equivalent `Write-Log` and `Write-LogGroup*` functions if needed + +1. **Customize Summary Format**: + - Modify the here-string in `process-pester-results.ps1` to change summary format + - Add additional metrics or formatting as needed + +1. **Call from Your Workflows**: + + ```yaml + - name: Process Test Results + uses: "./.github/actions/test/process-pester-results" + with: + name: "my-test-run" + testResultsFolder: "path/to/results" + ``` + +## Related Documentation + +- [GitHub Actions: Creating composite actions](https://docs.github.com/en/actions/creating-actions/creating-a-composite-action) +- [GitHub Actions: Job summaries](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary) +- [GitHub Actions: Uploading artifacts](https://docs.github.com/en/actions/using-workflows/storing-workflow-data-as-artifacts) +- [Pester: PowerShell testing framework](https://pester.dev/) +- [NUnit XML Format](https://docs.nunit.org/articles/nunit/technical-notes/usage/Test-Result-XML-Format.html) + +## Troubleshooting + +### No Test Results Found + +- Verify `testResultsFolder` path is correct +- Ensure tests are generating NUnitXml formatted output +- Check that `*.xml` files exist in the specified folder + +### Action Fails with "GITHUB_STEP_SUMMARY is not set" + +- Ensure the action runs within a GitHub Actions environment +- Cannot be run locally without mocking this environment variable + +### All Tests Pass but Job Fails + +- Check if any tests are marked as errors (different from failures) +- Verify that at least some tests executed (`$testCaseCount -eq 0`) + +### Artifact Upload Fails + +- Check artifact name for invalid characters +- Ensure the test results folder exists +- Verify actions/upload-artifact version compatibility diff --git a/PowerShell-master/.github/instructions/start-native-execution.instructions.md b/PowerShell-master/.github/instructions/start-native-execution.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..347e496b3bfe70144b6bd4eae1e0dfb33980fca1 --- /dev/null +++ b/PowerShell-master/.github/instructions/start-native-execution.instructions.md @@ -0,0 +1,149 @@ +--- +applyTo: + - "**/*.ps1" + - "**/*.psm1" +--- + +# Using Start-NativeExecution for Native Command Execution + +## Purpose + +`Start-NativeExecution` is the standard function for executing native commands (external executables) in PowerShell scripts within this repository. It provides consistent error handling and better diagnostics when native commands fail. + +## When to Use + +Use `Start-NativeExecution` whenever you need to: +- Execute external commands (e.g., `git`, `dotnet`, `pkgbuild`, `productbuild`, `fpm`, `rpmbuild`) +- Ensure proper exit code checking +- Get better error messages with caller information +- Handle verbose output on error + +## Basic Usage + +```powershell +Start-NativeExecution { + git clone https://github.com/PowerShell/PowerShell.git +} +``` + +## With Parameters + +Use backticks for line continuation within the script block: + +```powershell +Start-NativeExecution { + pkgbuild --root $pkgRoot ` + --identifier $pkgIdentifier ` + --version $Version ` + --scripts $scriptsDir ` + $outputPath +} +``` + +## Common Parameters + +### -VerboseOutputOnError + +Captures command output and displays it only if the command fails: + +```powershell +Start-NativeExecution -VerboseOutputOnError { + dotnet build --configuration Release +} +``` + +### -IgnoreExitcode + +Allows the command to fail without throwing an exception: + +```powershell +Start-NativeExecution -IgnoreExitcode { + git diff --exit-code # Returns 1 if differences exist +} +``` + +## Availability + +The function is defined in `tools/buildCommon/startNativeExecution.ps1` and is available in: +- `build.psm1` (dot-sourced automatically) +- `tools/packaging/packaging.psm1` (dot-sourced automatically) +- Test modules that include `HelpersCommon.psm1` + +To use in other scripts, dot-source the function: + +```powershell +. "$PSScriptRoot/../buildCommon/startNativeExecution.ps1" +``` + +## Error Handling + +When a native command fails (non-zero exit code), `Start-NativeExecution`: +1. Captures the exit code +2. Identifies the calling location (file and line number) +3. Throws a descriptive error with full context + +Example error message: +``` +Execution of {git clone ...} by /path/to/script.ps1: line 42 failed with exit code 1 +``` + +## Examples from the Codebase + +### Git Operations +```powershell +Start-NativeExecution { + git fetch --tags --quiet upstream +} +``` + +### Build Operations +```powershell +Start-NativeExecution -VerboseOutputOnError { + dotnet publish --configuration Release +} +``` + +### Packaging Operations +```powershell +Start-NativeExecution -VerboseOutputOnError { + pkgbuild --root $pkgRoot --identifier $pkgId --version $version $outputPath +} +``` + +### Permission Changes +```powershell +Start-NativeExecution { + find $staging -type d | xargs chmod 755 + find $staging -type f | xargs chmod 644 +} +``` + +## Anti-Patterns + +**Don't do this:** +```powershell +& somecommand $args +if ($LASTEXITCODE -ne 0) { + throw "Command failed" +} +``` + +**Do this instead:** +```powershell +Start-NativeExecution { + somecommand $args +} +``` + +## Best Practices + +1. **Always use Start-NativeExecution** for native commands to ensure consistent error handling +2. **Use -VerboseOutputOnError** for commands with useful diagnostic output +3. **Use backticks for readability** when commands have multiple arguments +4. **Don't capture output unnecessarily** - let the function handle it +5. **Use -IgnoreExitcode sparingly** - only when non-zero exit codes are expected and acceptable + +## Related Documentation + +- Source: `tools/buildCommon/startNativeExecution.ps1` +- Blog post: https://mnaoumov.wordpress.com/2015/01/11/execution-of-external-commands-in-powershell-done-right/ diff --git a/PowerShell-master/.github/instructions/start-psbuild-basics.instructions.md b/PowerShell-master/.github/instructions/start-psbuild-basics.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..18a0026eb2d3c8a20be3e80476b42781dac01683 --- /dev/null +++ b/PowerShell-master/.github/instructions/start-psbuild-basics.instructions.md @@ -0,0 +1,100 @@ +--- +applyTo: + - "build.psm1" + - "tools/ci.psm1" + - ".github/**/*.yml" + - ".github/**/*.yaml" +--- + +# Start-PSBuild Basics + +## Purpose + +`Start-PSBuild` builds PowerShell from source. It's defined in `build.psm1` and used in CI/CD workflows. + +## Default Usage + +For most scenarios, use with no parameters: + +```powershell +Import-Module ./tools/ci.psm1 +Start-PSBuild +``` + +**Default behavior:** +- Configuration: `Debug` +- PSModuleRestore: Enabled +- Runtime: Auto-detected for platform + +## Common Configurations + +### Debug Build (Default) + +```powershell +Start-PSBuild +``` + +Use for: +- Testing (xUnit, Pester) +- Development +- Debugging + +### Release Build + +```powershell +Start-PSBuild -Configuration 'Release' +``` + +Use for: +- Production packages +- Distribution +- Performance testing + +### Code Coverage Build + +```powershell +Start-PSBuild -Configuration 'CodeCoverage' +``` + +Use for: +- Code coverage analysis +- Test coverage reports + +## Common Parameters + +### -Configuration + +Values: `Debug`, `Release`, `CodeCoverage`, `StaticAnalysis` + +Default: `Debug` + +### -CI + +Restores Pester module for CI environments. + +```powershell +Start-PSBuild -CI +``` + +### -PSModuleRestore + +Now enabled by default. Use `-NoPSModuleRestore` to skip. + +### -ReleaseTag + +Specifies version tag for release builds: + +```powershell +$releaseTag = Get-ReleaseTag +Start-PSBuild -Configuration 'Release' -ReleaseTag $releaseTag +``` + +## Workflow Example + +```yaml +- name: Build PowerShell + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Start-PSBuild +``` diff --git a/PowerShell-master/.github/instructions/troubleshooting-builds.instructions.md b/PowerShell-master/.github/instructions/troubleshooting-builds.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..e9b60cb8c80c35a27a30d2e799288da0525f891f --- /dev/null +++ b/PowerShell-master/.github/instructions/troubleshooting-builds.instructions.md @@ -0,0 +1,100 @@ +--- +applyTo: + - "build.psm1" + - "tools/ci.psm1" + - ".github/**/*.yml" + - ".github/**/*.yaml" +--- + +# Troubleshooting Build Issues + +## Git Describe Error + +**Error:** +``` +error MSB3073: The command "git describe --abbrev=60 --long" exited with code 128. +``` + +**Cause:** Insufficient git history (shallow clone) + +**Solution:** Add `fetch-depth: 1000` to checkout step + +```yaml +- name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 1000 +``` + +## Version Information Incorrect + +**Symptom:** Build produces wrong version numbers + +**Cause:** Git tags not synchronized + +**Solution:** Run `Sync-PSTags -AddRemoteIfMissing`: + +```yaml +- name: Bootstrap + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Invoke-CIInstall -SkipUser + Sync-PSTags -AddRemoteIfMissing +``` + +## PowerShell Binary Not Built + +**Error:** +``` +Exception: CoreCLR pwsh.exe was not built +``` + +**Causes:** +1. Build failed (check logs) +2. Wrong configuration used +3. Build output location incorrect + +**Solutions:** +1. Check build logs for errors +2. Verify correct configuration for use case +3. Use default parameters: `Start-PSBuild` + +## Module Restore Issues + +**Symptom:** Slow build or module restore failures + +**Causes:** +- Network issues +- Module cache problems +- Package source unavailable + +**Solutions:** +1. Retry the build +2. Check network connectivity +3. Use `-NoPSModuleRestore` if modules not needed +4. Clear package cache if persistent + +## .NET SDK Not Found + +**Symptom:** Build can't find .NET SDK + +**Solution:** Ensure .NET setup step runs first: + +```yaml +- name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + global-json-file: ./global.json +``` + +## Bootstrap Failures + +**Symptom:** Invoke-CIInstall fails + +**Causes:** +- Missing dependencies +- Network issues +- Platform-specific requirements not met + +**Solution:** Check prerequisites for your platform in build system docs diff --git a/PowerShell-master/.github/issue_label_bot.yaml b/PowerShell-master/.github/issue_label_bot.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4374b1996b525603d168dae494e93f6d3e1b7846 --- /dev/null +++ b/PowerShell-master/.github/issue_label_bot.yaml @@ -0,0 +1,4 @@ +label-alias: + bug: 'Issue-Bug' + feature_request: 'Issue-Enhancement' + question: 'Issue-Question' diff --git a/PowerShell-master/.github/policies/IssueManagement.CloseResolutions.yml b/PowerShell-master/.github/policies/IssueManagement.CloseResolutions.yml new file mode 100644 index 0000000000000000000000000000000000000000..23ab9422e1a335d7a5950982163efe1b060a9ffe --- /dev/null +++ b/PowerShell-master/.github/policies/IssueManagement.CloseResolutions.yml @@ -0,0 +1,137 @@ +id: CloseResolutionTags +name: GitOps.PullRequestIssueManagement +description: Closing issues with Resolution* +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + scheduledSearches: + - description: Close if marked as Resolution-Declined after one day of no activity + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Declined + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as declined and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + + - description: Close if marked as Resolution-By Design after one day of no activity + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-By Design + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as by-design and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + + - description: Close if marked as Resolution-Won't Fix after one day of no activity + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Won't Fix + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as won't fix and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + + - description: Close if marked as Resolution-No Activity after seven day of no activity, no reply + frequencies: + - hourly: + hour: 12 + filters: + - isOpen + - isIssue + - hasLabel: + label: Resolution-No Activity + - noActivitySince: + days: 7 + actions: + - closeIssue + + - description: Close if marked as Resolution-Duplicate after one day of no activity + frequencies: + - hourly: + hour: 3 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Duplicate + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as duplicate and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + + - description: Close if marked as Resolution-External after one day of no activity + frequencies: + - hourly: + hour: 3 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-External + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as external and has not had any activity for **1 day**. It has been be closed for housekeeping purposes. + - closeIssue + + - description: Close if marked as Resolution-Answered after one day of no activity + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Answered + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as answered and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + + - description: Close if marked as Resolution-Fixed after one day of no activity + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Fixed + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as fixed and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue +onFailure: +onSuccess: diff --git a/PowerShell-master/.github/policies/IssueManagement.ResolveStale.yml b/PowerShell-master/.github/policies/IssueManagement.ResolveStale.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd254715ea9766ac9144c3addf9a0af792a737be --- /dev/null +++ b/PowerShell-master/.github/policies/IssueManagement.ResolveStale.yml @@ -0,0 +1,109 @@ +id: IssueManagement.ResolveStale +name: GitOps.PullRequestIssueManagement +description: Other issue management rules for closing stale and waiting on author requests +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + scheduledSearches: + - description: Close if marked as Waiting on Author and no activity in 7 days + frequencies: + - hourly: + hour: 12 + filters: + - isOpen + - isIssue + - hasLabel: + label: Waiting on Author + - noActivitySince: + days: 7 + actions: + - addReply: + reply: This issue has been marked as "Waiting on Author" and has not had any activity for **7 day**. It has been closed for housekeeping purposes. + - closeIssue + + - description: Label as Resolution-No Activity if not labeled with KeepOpen and no activity in 6 months + frequencies: + - hourly: + hour: 24 + filters: + - isIssue + - isOpen + - isNotLabeledWith: + label: KeepOpen + - isNotLabeledWith: + label: In-PR + - isNotLabeledWith: + label: Needs-Triage + - isNotLabeledWith: + label: Resolution-No Activity + - isNotLabeledWith: + label: Issue-Meta + - isNotLabeledWith: + label: Review - Needed + - isNotLabeledWith: + label: Review - Committee + - isNotLabeledWith: + label: Review - Maintainer + - isNotLabeledWith: + label: WG-NeedsReview + # Up for grabs labeled issues will get closed after a 6 months of no activity unless KeepOpen label is included + - noActivitySince: + days: 180 + actions: + - addLabel: + label: Resolution-No Activity + - addReply: + reply: "This issue has not had any activity in 6 months, if there is no further activity in 7 days, the issue will be closed automatically.\n\nActivity in this case refers only to comments on the issue. If the issue is closed and you are the author, you can re-open the issue using the button below. Please add more information to be considered during retriage. If you are not the author but the issue is impacting you after it has been closed, please submit a new issue with updated details and a link to this issue and the original." + eventResponderTasks: + - description: Remove no resolution label if anyone comments while in 7 day window + if: + - payloadType: Issue_Comment + - hasLabel: + label: Resolution-No Activity + - isOpen + then: + - removeLabel: + label: Resolution-No Activity + + - description: If new issue comment is author then remove waiting on author + if: + - payloadType: Issue_Comment + - isActivitySender: + issueAuthor: True + - hasLabel: + label: Waiting on Author + then: + - removeLabel: + label: Waiting on Author + + - description: Remove Stale label if issue comment + if: + - payloadType: Issue_Comment + - hasLabel: + label: Stale + then: + - removeLabel: + label: Stale + + - description: Remove Needs-Triage label if issue is closed + if: + - payloadType: Issues + - isAction: + action: Closed + then: + - removeLabel: + label: Needs-Triage + + - description: Remove Keep Open label if closed by someone + if: + - payloadType: Issues + - isAction: + action: Closed + then: + - removeLabel: + label: KeepOpen +onFailure: +onSuccess: diff --git a/PowerShell-master/.github/policies/PRManagement.yml b/PowerShell-master/.github/policies/PRManagement.yml new file mode 100644 index 0000000000000000000000000000000000000000..9deaf0262bb0499d96f0a946cb08c75df9ab3d3a --- /dev/null +++ b/PowerShell-master/.github/policies/PRManagement.yml @@ -0,0 +1,226 @@ +id: PRManagement +name: GitOps.PullRequestIssueManagement +description: Collection of PR bot triaging behaviors +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + scheduledSearches: + - description: If Stale label and waiting on author and no activity since 10 days then close the PR + frequencies: + - hourly: + hour: 12 + filters: + - isPullRequest + - isOpen + - hasLabel: + label: Waiting on Author + - hasLabel: + label: Stale + - noActivitySince: + days: 10 + actions: + - closeIssue + + - description: If PR has Waiting on Author label and no activity in 15 days label as stale. + frequencies: + - hourly: + hour: 3 + filters: + - isPullRequest + - isOpen + - hasLabel: + label: Waiting on Author + - noActivitySince: + days: 15 + - isNotLabeledWith: + label: Stale + actions: + - addLabel: + label: Stale + - addReply: + reply: This pull request has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for **15 days**. It will be closed if no further activity occurs **within 10 days of this comment**. + + - description: Label Review - Needed if PR is opened an no activity in 7 days but no other labels on it + frequencies: + - hourly: + hour: 12 + filters: + - isPullRequest + - isOpen + - isNotLabeledWith: + label: Waiting on Author + - noActivitySince: + days: 7 + - isNotLabeledWith: + label: Stale + - isNotLabeledWith: + label: Review - Needed + - isNotLabeledWith: + label: Review - Committee + - isNotDraftPullRequest + actions: + - addLabel: + label: Review - Needed + - addReply: + reply: >- + This pull request has been automatically marked as Review Needed because it has been there has not been any activity for **7 days**. + + Maintainer, please provide feedback and/or mark it as `Waiting on Author` + + - description: Add waiting on Author label if is draft PR, if no activity label + frequencies: + - hourly: + hour: 12 + filters: + - isOpen + - isDraftPullRequest + - isNotLabeledWith: + label: Review - Committee + - isNotLabeledWith: + label: Waiting on Author + - isNotLabeledWith: + label: Stale + - noActivitySince: + days: 3 + actions: + - addLabel: + label: Waiting on Author + eventResponderTasks: + + - description: If PR has AutoMerge Label then enable Automerge to squash + if: + - payloadType: Pull_Request + - hasLabel: + label: AutoMerge + then: + - enableAutoMerge: + mergeMethod: Squash + + - description: If PR has label AutoMerge Removed then disable Automerge + if: + - payloadType: Pull_Request + - labelRemoved: + label: AutoMerge + then: + - disableAutoMerge + + - description: If PR review requests changes then add label waiting on Author and remove review needed + if: + - payloadType: Pull_Request_Review + - isAction: + action: Submitted + - isReviewState: + reviewState: Changes_requested + then: + - addLabel: + label: Waiting on Author + - removeLabel: + label: Review - Needed + + - description: Remove Waiting on author if has label and activity from author + if: + - payloadType: Pull_Request + - isActivitySender: + issueAuthor: True + - not: + isAction: + action: Closed + - hasLabel: + label: Waiting on Author + - not: + titleContains: + pattern: "(WIP|Work in progress|\U0001F6A7)" + isRegex: True + then: + - removeLabel: + label: Waiting on Author + + - description: remove waiting on author if review by author and has waiting on author + if: + - payloadType: Pull_Request_Review + - isActivitySender: + issueAuthor: True + - hasLabel: + label: Waiting on Author + then: + - removeLabel: + label: Waiting on Author + + - description: Remove Stale label if PR has activity from author which is not closure + if: + - payloadType: Pull_Request + - not: + isAction: + action: Closed + - hasLabel: + label: Stale + - isActivitySender: + issueAuthor: True + then: + - removeLabel: + label: Stale + + - description: Remove Stale label if PR is reviewed + if: + - payloadType: Pull_Request_Review + - hasLabel: + label: Stale + then: + - removeLabel: + label: Stale + + - description: Remove Review Needed if PR is created or done any action by Admins and iSazonov + if: + - payloadType: Pull_Request + - hasLabel: + label: Review - Needed + - or: + - isAction: + action: Null + - isAction: + action: Closed + - isAction: + action: Reopened + - isAction: + action: Assigned + - isAction: + action: Unassigned + - isAction: + action: Unlabeled + - or: + - activitySenderHasPermission: + permission: Admin + - isActivitySender: + user: iSazonov + issueAuthor: False + then: + - removeLabel: + label: Review - Needed + + - description: Remove Review - Needed if issue comment is by admin or iSazonov + if: + - payloadType: Issue_Comment + - hasLabel: + label: Review - Needed + - or: + - activitySenderHasPermission: + permission: Admin + - isActivitySender: + user: iSazonov + issueAuthor: False + then: + - removeLabel: + label: Review - Needed + + - description: If inPRLabel then label in PR + if: + - payloadType: Pull_Request + then: + - inPrLabel: + label: In-PR + +onFailure: +onSuccess: diff --git a/PowerShell-master/.github/policies/labelAdded.approvedLowRisk.yml b/PowerShell-master/.github/policies/labelAdded.approvedLowRisk.yml new file mode 100644 index 0000000000000000000000000000000000000000..bdeea5265a0fe796e1e3e2b45b249c7234acb1db --- /dev/null +++ b/PowerShell-master/.github/policies/labelAdded.approvedLowRisk.yml @@ -0,0 +1,48 @@ +id: labelAdded.approvedLowRisk +name: GitOps.PullRequestIssueManagement +description: Remove Approved-LowRisk if applied by an unauthorized user +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + eventResponderTasks: + - description: Remove Approved-LowRisk if label was added by someone not authorized + if: + - payloadType: Pull_Request + - isOpen + - labelAdded: + label: Approved-LowRisk + # Unauthorized = NOT admin AND NOT in explicit allowlist + - not: + or: + - activitySenderHasPermission: + permission: Admin + + # Allowlist (enabled) + - isActivitySender: + user: iSazonov + issueAuthor: False + - isActivitySender: + user: daxian-dbw + issueAuthor: False + + # Allowlist (commented out for now) + # - isActivitySender: + # user: TravisEz13 + # issueAuthor: False + # - isActivitySender: + # user: adityapatwardhan + # issueAuthor: False + # - isActivitySender: + # user: jshigetomi + # issueAuthor: False + then: + - removeLabel: + label: Approved-LowRisk + - addReply: + reply: >- + The `Approved-LowRisk` label is restricted to authorized maintainers and was removed. +onFailure: +onSuccess: diff --git a/PowerShell-master/.github/policies/labelAdded.clBuildPackaging.addBackportConsider.yml b/PowerShell-master/.github/policies/labelAdded.clBuildPackaging.addBackportConsider.yml new file mode 100644 index 0000000000000000000000000000000000000000..78edc18cb1a0228320c31409c43c63dbcacc0e6a --- /dev/null +++ b/PowerShell-master/.github/policies/labelAdded.clBuildPackaging.addBackportConsider.yml @@ -0,0 +1,56 @@ +id: labelAdded.clBuildPackaging.addBackportConsider +name: GitOps.PullRequestIssueManagement +description: Add backport consideration labels when CL-BuildPackaging is added to an open PR targeting master +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + eventResponderTasks: + - description: Add BackPort-7.4.x-Consider when CL-BuildPackaging is added to open PR targeting master + if: + - payloadType: Pull_Request + - isOpen + - labelAdded: + label: CL-BuildPackaging + - targetsBranch: + branch: master + - not: + hasLabel: + label: BackPort-7.4.x-Consider + then: + - addLabel: + label: BackPort-7.4.x-Consider + + - description: Add BackPort-7.5.x-Consider when CL-BuildPackaging is added to open PR targeting master + if: + - payloadType: Pull_Request + - isOpen + - labelAdded: + label: CL-BuildPackaging + - targetsBranch: + branch: master + - not: + hasLabel: + label: BackPort-7.5.x-Consider + then: + - addLabel: + label: BackPort-7.5.x-Consider + + - description: Add BackPort-7.6.x-Consider when CL-BuildPackaging is added to open PR targeting master + if: + - payloadType: Pull_Request + - isOpen + - labelAdded: + label: CL-BuildPackaging + - targetsBranch: + branch: master + - not: + hasLabel: + label: BackPort-7.6.x-Consider + then: + - addLabel: + label: BackPort-7.6.x-Consider +onFailure: +onSuccess: diff --git a/PowerShell-master/.github/prompts/backport-pr-to-release-branch.prompt.md b/PowerShell-master/.github/prompts/backport-pr-to-release-branch.prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..32bff10bd5efe4d5c8d5a7c3cd456afa6c5599e8 --- /dev/null +++ b/PowerShell-master/.github/prompts/backport-pr-to-release-branch.prompt.md @@ -0,0 +1,567 @@ +--- +description: Guide for backporting changes to PowerShell release branches +--- + +# Backport a Change to a PowerShell Release Branch + +## 1 — Goal + +Create a backport PR that applies changes from a merged PR to a release branch (e.g., `release/v7.4`, `release/v7.5`). The backport must follow the repository's established format and include proper references to the original PR. + +## 2 — Prerequisites for the model + +- You have full repository access +- You can run git commands +- You can read PR information from the repository +- Ask clarifying questions if the target release branch or original PR number is unclear + +## 3 — Required user inputs + +If the user hasn't specified a PR number, help them find one: + +### Finding PRs that need backporting + +1. Ask the user which release version they want to backport to (e.g., `7.4`, `7.5`) +2. Search for PRs with the appropriate label using GitHub CLI: + +```powershell +$Owner = "PowerShell" +$Repo = "PowerShell" +$version = "7.4" # or user-specified version +$considerLabel = "Backport-$version.x-Consider" + +$prsJson = gh pr list --repo "$Owner/$Repo" --label $considerLabel --state merged --json number,title,url,labels,mergedAt --limit 100 2>&1 +$prs = $prsJson | ConvertFrom-Json +# Sort PRs from oldest merged to newest merged +$prs = $prs | Sort-Object mergedAt +``` + +3. Present the list of PRs to the user with: + - PR number + - PR title + - Merged date + - URL + +4. Ask the user: "Which PR would you like to backport?" (provide the PR number) + +### After selecting a PR + +Once the user selects a PR (or if they provided one initially), confirm: +- **Original PR number**: The PR number that was merged to the main branch (e.g., 26193) +- **Target release**: The release number (e.g., `7.4`, `7.5`, `7.5.1`) + +Example: "Backport PR 26193 to release/v7.4" + +## 4 — Implementation steps (must be completed in order) + +### Step 1: Verify the original PR exists and is merged + +1. Fetch the original PR information using the PR number +2. Confirm the PR state is `MERGED` +3. Extract the following information: + - Merge commit SHA + - Original PR title + - Original PR author + - Original CL label (if present, typically starts with `CL-`) + +If the PR is not merged, stop and inform the user. + +4. Check if backport already exists or has been attempted: + ```powershell + gh pr list --repo PowerShell/PowerShell --search "in:title [release/v7.4] " --state all + ``` + + If a backport PR already exists, inform the user and ask if they want to continue. + +5. Check backport labels to understand status: + - `Backport-7.4.x-Migrated`: Indicates previous backport attempt (may have failed or had issues) + - `Backport-7.4.x-Done`: Already backported successfully + - `Backport-7.4.x-Approved`: Ready for backporting + - `Backport-7.4.x-Consider`: Under consideration for backporting + + If status is "Done", inform the user that backport may already be complete. + +### Step 2: Create the backport branch + +1. Identify the correct remote to fetch from: + ```bash + git remote -v + ``` + + Look for the remote that points to `https://github.com/PowerShell/PowerShell` (typically named `upstream` or `origin`). Use this remote name in subsequent commands. + +2. Ensure you have the latest changes from the target release branch: + ```bash + git fetch + ``` + + Example: `git fetch upstream release/v7.4` + +3. Create a new branch from the target release branch: + ```bash + git checkout -b backport- / + ``` + + Example: `git checkout -b backport-26193 upstream/release/v7.4` + +### Step 3: Cherry-pick the merge commit + +1. Cherry-pick the merge commit from the original PR: + ```bash + git cherry-pick + ``` + +2. If conflicts occur: + - Inform the user about the conflicts + - List the conflicting files + - Fetch the original PR diff to understand the changes: + ```bash + gh pr diff --repo PowerShell/PowerShell | Out-File pr-diff.txt + ``` + - Review the diff to understand what the PR changed + - Figure out why there is a conflict and resolve it + - Create a summary of the conflict resolution: + * Which files had conflicts + * Nature of each conflict (parameter changes, code removal, etc.) + * How you resolved it + * Whether any manual adjustments were needed beyond accepting one side + - Ask the user to review your conflict resolution summary before continuing + - After conflicts are resolved, continue with: + ```bash + git add + git cherry-pick --continue + ``` + +### Step 4: Push the backport branch + +Push to your fork (typically the remote that you have write access to): + +```bash +git push backport- +``` + +Example: `git push origin backport-26193` + +Note: If you're pushing to the official PowerShell repository and have permissions, you may push to `upstream` or the appropriate remote. + +### Step 5: Create the backport PR + +Create a new PR with the following format: + +**Title:** +``` +[] +``` + +Example: `[release/v7.4] GitHub Workflow cleanup` + +**Body:** +``` +Backport of # to + + + +Triggered by @ on behalf of @ + +Original CL Label: + +/cc @PowerShell/powershell-maintainers + +## Impact + +Choose either tooling or Customer impact. +### Tooling Impact + +- [ ] Required tooling change +- [ ] Optional tooling change (include reasoning) + +### Customer Impact + +- [ ] Customer reported +- [ ] Found internally + +[Select one or both of the boxes. Describe how this issue impacts customers, citing the expected and actual behaviors and scope of the issue. If customer-reported, provide the issue number.] + +## Regression + +- [ ] Yes +- [ ] No + +[If yes, specify when the regression was introduced. Provide the PR or commit if known.] + +## Testing + +[How was the fix verified? How was the issue missed previously? What tests were added?] + +## Risk + +- [ ] High +- [ ] Medium +- [ ] Low + +[High/Medium/Low. Justify the indication by mentioning how risks were measured and addressed.] +``` + +**Base branch:** `` (e.g., `release/v7.4`) + +**Head branch:** `backport-` (e.g., `backport-26193`) + +#### Guidelines for Filling Out the PR Body + +**For Impact Section**: +- If the original PR changed build/tooling/packaging, select "Tooling Impact" +- If it fixes a user-facing bug or changes user-visible behavior, select "Customer Impact" +- Copy relevant context from the original PR description +- Be specific about what changed and why + +**For Regression Section**: +- Mark "Yes" only if the original PR fixed a regression +- Include when the regression was introduced if known + +**For Testing Section**: +- Reference the original PR's testing approach +- Note any additional backport-specific testing needed +- Mention if manual testing was done to verify the backport + +**For Risk Assessment**: +- **High**: Changes core functionality, packaging, build systems, or security-related code +- **Medium**: Changes non-critical features, adds new functionality, or modifies existing behavior +- **Low**: Documentation, test-only changes, minor refactoring, or fixes with narrow scope +- Justify your assessment based on the scope of changes and potential impact +- **For CI/CD changes**: When backporting CI/CD infrastructure changes (workflows, build scripts, packaging), note in your justification that not taking these changes may create technical debt and make it difficult to apply future CI/CD changes that build on top of them. This doesn't change the risk level itself, but provides important context for why the change should be taken despite potentially higher risk + +**If there were merge conflicts**: +Add a note in the PR description after the Risk section describing what conflicts occurred and how they were resolved. + +### Step 6: Add the CL label to the backport PR + +After creating the backport PR, add the same changelog label (CL-*) from the original PR to the backport PR: + +```bash +gh pr edit --repo PowerShell/PowerShell --add-label "" +``` + +Example: `gh pr edit 26389 --repo PowerShell/PowerShell --add-label "CL-BuildPackaging"` + +This ensures the backport is properly categorized in the changelog for the release branch. + +### Step 7: Update the original PR's backport labels + +After successfully creating the backport PR, update the original PR to reflect that it has been backported: + +```bash +gh pr edit --repo PowerShell/PowerShell --add-label "Backport-.x-Migrated" --remove-label "Backport-.x-Consider" +``` + +Example: `gh pr edit 26193 --repo PowerShell/PowerShell --add-label "Backport-7.5.x-Migrated" --remove-label "Backport-7.5.x-Consider"` + +Notes: +- If the original PR had `Backport-.x-Approved` instead of `Consider`, remove that label +- This step helps track which PRs have been successfully backported +- The `Migrated` label indicates the backport PR has been created (not necessarily merged) +- The `Done` label should only be added once the backport PR is merged + +### Step 8: Clean up temporary files + +After successful PR creation and labeling, clean up any temporary files created during the process: + +```powershell +Remove-Item pr*.diff -ErrorAction SilentlyContinue +``` + +## 5 — Definition of Done (self-check list) + +- [ ] Original PR is verified as merged +- [ ] Checked for existing backport PRs +- [ ] Reviewed backport labels to understand status +- [ ] Backport branch created from correct release branch +- [ ] Merge commit cherry-picked successfully (or conflicts resolved) +- [ ] If conflicts occurred, provided resolution summary to user +- [ ] Branch pushed to origin +- [ ] PR created with correct title format: `[] ` +- [ ] CL label added to backport PR (matching original PR's CL label) +- [ ] Original PR labels updated (added Migrated, removed Consider/Approved) +- [ ] Temporary files cleaned up (pr*.diff) +- [ ] PR body includes: + - [ ] Backport reference: `Backport of (PR-number) to ` + - [ ] Auto-generated comment with original PR number + - [ ] Triggered by and original author attribution + - [ ] Original CL label (if available) + - [ ] CC to PowerShell maintainers + - [ ] Impact section filled out + - [ ] Regression section filled out + - [ ] Testing section filled out + - [ ] Risk section filled out +- [ ] Base branch set to target release branch +- [ ] No unrelated changes included + +## 6 — Branch naming convention + +**Format:** `backport/release//pr/` + +Examples: +- `backport/release/v7.5/pr/26193` +- `backport/release/v7.4.1/pr/26334` + +Note: Automated bot uses format `backport/release/v/-`, but manual backports should use the format `backport/release//pr/` as shown above. + +## 7 — Example backport PR + +Reference PR 26334 as the canonical example of a correct backport: + +**Original PR**: PR 26193 "GitHub Workflow cleanup" + +**Backport PR**: PR 26334 "[release/v7.4] GitHub Workflow cleanup" +- **Title**: `[release/v7.4] GitHub Workflow cleanup` +- **Body**: Started with backport reference to original PR and release branch +- **Branch**: `backport/release/v7.4/26193-4aff02475` (bot-created) +- **Base**: `release/v7.4` +- **Includes**: Auto-generated metadata, impact assessment, regression info, testing details, and risk level + +## 8 — Backport label system (for context) + +Backport labels follow pattern: `Backport-.x-` + +**Triage states:** +- `Consider` - Under review for backporting +- `Approved` - Approved and ready to be backported +- `Done` - Backport completed + +**Examples:** `Backport-7.4.x-Approved`, `Backport-7.5.x-Consider`, `Backport-7.3.x-Done` + +Note: The PowerShell repository has an automated bot (pwshBot) that creates backport PRs automatically when a merged PR has a backport approval label. Manual backports follow the same format. + +## Manual Backport Using PowerShell Tools + +For situations where automated backports fail or manual intervention is needed, use the `Invoke-PRBackport` function from `tools/releaseTools.psm1`. + +### Prerequisites + +1. **GitHub CLI**: Install from https://cli.github.com/ + - Required version: 2.17 or later + - Authenticate with `gh auth login` + +2. **Upstream Remote**: Configure a Git remote named `upstream` pointing to `PowerShell/PowerShell`: + ```powershell + git remote add upstream https://github.com/PowerShell/PowerShell.git + ``` + +### Using Invoke-PRBackport + +```powershell +# Import the release tools module +Import-Module ./tools/releaseTools.psm1 + +# Backport a single PR +Invoke-PRBackport -PrNumber 26193 -Target release/v7.4.1 + +# Backport with custom branch postfix +Invoke-PRBackport -PrNumber 26193 -Target release/v7.4.1 -BranchPostFix "retry" + +# Overwrite existing local branch if it exists +Invoke-PRBackport -PrNumber 26193 -Target release/v7.4.1 -Overwrite +``` + +### Parameters + +- **PrNumber** (Required): The PR number to backport +- **Target** (Required): Target release branch (must match pattern `release/v\d+\.\d+(\.\d+)?`) +- **Overwrite**: Switch to overwrite local branch if it already exists +- **BranchPostFix**: Add a postfix to the branch name (e.g., for retry attempts) +- **UpstreamRemote**: Name of the upstream remote (default: `upstream`) + +### How It Works + +1. Verifies the PR is merged +2. Fetches the target release branch from upstream +3. Creates a new branch: `backport-[-]` +4. Cherry-picks the merge commit +5. If conflicts occur, prompts you to resolve them +6. Creates the backport PR using GitHub CLI + +## Handling Merge Conflicts + +When cherry-picking fails due to conflicts: + +1. The script will pause and prompt you to fix conflicts +2. Resolve conflicts in your editor: + ```powershell + # Check which files have conflicts + git status + + # Edit files to resolve conflicts + # After resolving, stage the changes + git add + + # Continue the cherry-pick + git cherry-pick --continue + ``` +3. Type 'Yes' when prompted to continue the script +4. The script will create the PR + +### Understanding Conflict Patterns + +When resolving conflicts during backports, follow this approach: + +1. **Analyze the diff first**: Before resolving conflicts, fetch and review the original PR's diff to understand what changed: + ```powershell + gh pr diff --repo PowerShell/PowerShell | Out-File pr-diff.txt + ``` + +2. **Identify conflict types**: + - **Parameter additions**: New parameters added to functions (e.g., ValidateSet values) + - **Code removal**: Features removed in main but still exist in release branch + - **Code additions**: New code blocks that don't exist in release branch + - **Refactoring conflicts**: Code structure changes between branches + +3. **Resolution priorities**: + - Preserve the intent of the backported change + - Keep release branch-specific code that doesn't conflict with the fix + - When in doubt, favor the incoming change from the backport + - Document significant manual changes in the PR description + +4. **Verification**: + - After resolving conflicts, verify the file compiles/runs + - Check that the resolved code matches the original PR's intent + - Look for orphaned code that references removed functions + +5. **Create a conflict resolution summary**: + - List which files had conflicts + - Briefly explain the nature of each conflict + - Describe how you resolved it + - Ask user to review the resolution before continuing + +### Context-Aware Conflict Resolution + +**Key Principle**: The release branch may have different code than main. Your goal is to apply the *change* from the PR, not necessarily make the code identical to main. + +**Common Scenarios**: +1. **Function parameters differ**: If the release branch has fewer parameters than main, and the backport adds functionality unrelated to new parameters, keep the release branch parameters unless the new parameters are part of the fix +2. **Dependencies removed in main**: If main removed a dependency but the release branch still has it, and the backport is unrelated to that dependency, keep the release branch code +3. **New features in main**: If main has new features not in the release, focus on backporting only the specific fix, not the new features + +## Bulk Backporting Approved PRs + +To backport all PRs labeled as approved for a specific version: + +```powershell +Import-Module ./tools/releaseTools.psm1 + +# Backport all approved PRs for version 7.2.12 +Invoke-PRBackportApproved -Version 7.2.12 +``` + +This function: +1. Queries all merged PRs with the `Backport-.x-Approved` label +2. Attempts to backport each PR in order of merge date +3. Creates individual backport PRs for each + +## Viewing Backport Reports + +Get a list of PRs that need backporting: + +```powershell +Import-Module ./tools/releaseTools.psm1 + +# List all approved backports for 7.4 +Get-PRBackportReport -Version 7.4 -TriageState Approved + +# Open all approved backports in browser +Get-PRBackportReport -Version 7.4 -TriageState Approved -Web + +# Check which backports are done +Get-PRBackportReport -Version 7.4 -TriageState Done +``` + +## Branch Naming Conventions + +### Automated Bot Branches +Format: `backport/release/v/-` + +Example: `backport/release/v7.4/26193-4aff02475` + +### Manual Backport Branches +Format: `backport-[-]` + +Examples: +- `backport-26193` +- `backport-26193-retry` + +## PR Title and Description Format + +### Title +Format: `[release/v] ` + +Example: `[release/v7.4] GitHub Workflow cleanup` + +### Description +The backport PR description includes: +- Reference to original PR number +- Target release branch +- Auto-generated comment with original PR metadata +- Maintainer information +- Original CL label +- CC to PowerShell maintainers team + +Example description structure: +```text +Backport of (original-pr-number) to release/v + + + +Triggered by @ on behalf of @ + +Original CL Label: + +/cc @PowerShell/powershell-maintainers +``` + +## Best Practices + +1. **Verify PR is merged**: Only backport merged PRs +2. **Test backports**: Ensure backported changes work in the target release context +3. **Check for conflicts early**: Large PRs are more likely to have conflicts +4. **Use appropriate labels**: Apply correct version and triage state labels +5. **Document special cases**: If manual changes were needed, note them in the PR description +6. **Follow up on CI failures**: Backports should pass all CI checks before merging + +## Troubleshooting + +### "PR is not merged" Error +**Cause**: Attempting to backport a PR that hasn't been merged yet +**Solution**: Wait for the PR to be merged to the main branch first + +### "Please create an upstream remote" Error +**Cause**: No upstream remote configured +**Solution**: +```powershell +git remote add upstream https://github.com/PowerShell/PowerShell.git +git fetch upstream +``` + +### "GitHub CLI is not installed" Error +**Cause**: gh CLI not found in PATH +**Solution**: Install from https://cli.github.com/ and restart terminal + +### Cherry-pick Conflicts +**Cause**: Changes conflict with the target branch +**Solution**: Manually resolve conflicts, stage files, and continue cherry-pick + +### "Commit does not exist" Error +**Cause**: Local Git doesn't have the commit +**Solution**: +```powershell +git fetch upstream +``` + +## Related Resources + +- **Release Process**: See `docs/maintainers/releasing.md` +- **Release Tools**: See `tools/releaseTools.psm1` +- **Issue Management**: See `docs/maintainers/issue-management.md` diff --git a/PowerShell-master/.github/prquantifier.yaml b/PowerShell-master/.github/prquantifier.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ea891ba49882a53c3b5cf76a26fda56632b8d5f9 --- /dev/null +++ b/PowerShell-master/.github/prquantifier.yaml @@ -0,0 +1,11 @@ +# https://github.com/microsoft/PullRequestQuantifier/blob/main/docs/prquantifier-yaml.md +Excluded: +# defaults +- '*.csproj' +- prquantifier.yaml +- package-lock.json +- '*.md' +- '*.sln' +# autogenerated files +- tools/cgmanifest.json +- assets/wix/files.wxs diff --git a/PowerShell-master/.github/skills/analyze-pester-failures/SKILL.md b/PowerShell-master/.github/skills/analyze-pester-failures/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ec1b0fe82ec2814b4ca03b9d04598582c7b29931 --- /dev/null +++ b/PowerShell-master/.github/skills/analyze-pester-failures/SKILL.md @@ -0,0 +1,524 @@ +--- +name: analyze-pester-failures +description: Troubleshooting guide for analyzing and investigating Pester test failures in PowerShell CI jobs. Help agents understand why tests are failing, interpret test output, navigate test result artifacts, and provide actionable recommendations for fixing test issues. +--- + +# Analyze Pester Test Failures + +Investigate and troubleshoot Pester test failures in GitHub Actions workflows. Understand what tests are failing, why they're failing, and provide recommendations for test fixes. + +| Skill | When to Use | +|-------|-----------| +| analyze-pester-failures | When investigating why Pester tests are failing in a CI job. Use when a test job shows failures and you need to understand what test failed, why it failed, what the error message means, and what might need to be fixed. Also use when asked: "why did this test fail?", "what's the test error?", "test is broken", "test failure analysis", "debug test failure", or given test failure logs and stack traces. | + +## When to Use This Skill + +Use this skill when you need to: + +- Understand why a specific Pester test is failing +- Interpret test failure messages and error output +- Analyze test result data from CI workflow runs (XML, logs, stack traces) +- Identify the root cause of test failures (test logic, assertion failure, exception, timeout, skip/ignore reason) +- Provide recommendations for fixing failing tests +- Compare expected vs. actual test behavior +- Debug test environment issues (missing dependencies, configuration problems) +- Understand test skip/ignored/inconclusive status reasons + +**Do not use this skill for:** +- General PowerShell debugging unrelated to tests +- Test infrastructure/CI setup issues (except as they affect test failure interpretation) +- Performance analysis or benchmarking (that's a different investigation) + +## Quick Start + +### ⚠️ CRITICAL: The Workflow Must Be Followed IN ORDER + +This skill describes a **sequential 6-step analysis workflow**. Skipping steps or jumping around leads to **incomplete analysis and incorrect conclusions**. + +**The Problem**: It's easy to skip to Step 4 or 5 without doing Steps 1-2, resulting in missing data and bad conclusions. + +**The Solution**: Use the automated analysis script to enforce the workflow: + +```powershell +# Automatically runs Steps 1-6 in order, preventing skipping +./.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 -PR + +# Example: +./.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 -PR 26800 +``` + +This script: +1. ✓ Fetches PR status automatically +2. ✓ Downloads artifacts (can't skip, depends on Step 1) +3. ✓ Extracts failures (can't skip, depends on Step 2) +4. ✓ Analyzes error messages +5. ✓ Documents context +6. ✓ Generates recommendations + +**Only use the manual commands below if you fully understand the workflow.** + +### Manual Workflow (for reference) + +```powershell +# Step 1: Identify the failing job +gh pr view --json 'statusCheckRollup' | ConvertFrom-Json | Where-Object { $_.conclusion -eq 'FAILURE' } + +# Step 2: Download artifacts (extract RUN_ID from Step 1) +gh run download --dir ./artifacts +gh run view --log > test-logs.txt + +# Step 3-6: Extract, analyze, and interpret +# (See Analysis Workflow section below) +``` + +## Common Test Failure Analysis Approaches + +### 1. **Interpreting Assertion Failures** +The most common test failure is when an assertion doesn't match expectations. + +**Example:** +``` +Expected $true but got $false at /path/to/test.ps1:42 +Assertion failed: Should -Be "expected" but was "actual" +``` + +**How to analyze:** +- Read the assertion message: what was expected vs. what was actual? +- Check the test logic: is the expectation correct? +- Look for mock/stub issues: are dependencies configured correctly? +- Check parameter values: what inputs were passed to the function under test? + +### 2. **Exception Failures** +Tests fail when PowerShell throws an exception instead of successful completion. + +**Example:** +``` +Command: Write-Host $null +Error: Cannot bind argument to parameter 'Object' because it is null. +``` + +**How to analyze:** +- Read the exception message: what operation failed? +- Check the stack trace: where in the test or tested code did it throw? +- Verify preconditions: does the test setup provide required values/mocks? +- Look for environmental issues: missing modules, permissions, file system state? + +### 3. **Timeout Failures** +A test takes longer than the allowed timeout to complete. + +**Example:** +``` +Test 'Should complete in reasonable time' timed out after 30 seconds +``` + +**How to analyze:** +- Is the timeout appropriate for this test type? (network tests need more time) +- Is there an infinite loop in the test or tested code? +- Are there resource contention issues on the CI runner? +- Does the test hang waiting for something (file lock, network, process)? + +### 4. **Skip/Ignored Reason Analysis** +Tests marked as skipped or ignored provide clues about test environment. + +**Example:** +``` +Test marked [Skip("Only runs on Windows")] - running on Linux +Test marked [Ignore("Known issue #12345")] +``` + +**How to analyze:** +- Read the skip/ignore reason: is it still valid? +- Check if environment has changed: platform, module versions, etc. +- Verify issue status: is the known issue still open? Has it been fixed? +- Determine if skip should be removed or if test needs environment changes + +### 5. **Flaky/Intermittent Failures** +Tests that sometimes pass, sometimes fail indicate race conditions or environment sensitivity. + +**Example:** +- Test passes locally but fails on CI +- Test passes first run of suite, fails on second run +- Test passes on Windows but fails on Linux + +**How to analyze:** +- Look for timeout races: is timing involved in the test? +- Check for test isolation issues: does one test affect another? +- Verify environment differences: CI vs. local paths, permissions, versions +- Look for external dependencies: network calls, file I/O, process interactions + +## Key Artifacts and Locations + +| Item | Purpose | Location | +|------|---------|----------| +| Test result XML | Pester output with test cases, failures, errors | Workflow artifacts: `junit-pester-*.xml` | +| Job logs | Full job output including test execution and errors | GitHub Actions run logs or `gh run download` | +| Stack traces | Error location information from failed assertions | Within job logs and XML failure messages | +| Test files | The actual Pester test code (`.ps1` files) | `test/` directory in repository | + +## Analysis Workflow + +### ⚠️ Important: These Steps MUST Be Followed In Order + +Each step depends on the previous one. Skipping or re-ordering steps causes incomplete analysis: + +- **Step 1** (identify jobs) → You get the RUN_ID needed for Step 2 +- **Step 2** (download) → You get the artifacts needed for Step 3 +- **Step 3** (extract) → You discover what failures exist for Step 4 +- **Step 4** (read messages) → You understand the errors to analyze in Step 5 +- **Step 5** (context) → You gather information to make recommendations in Step 6 +- **Step 6** (interpret) → You use all above to recommend fixes + +**Real Problem We Had**: +- ❌ Jumped to Step 3 without Step 1-2 +- ❌ Used random test data from context instead of downloading PR artifacts +- ❌ Skipped Steps 5-6 entirely +- ❌ Made recommendations without full context + +**Result**: Wrong analysis and recommendations that didn't actually fix the problem. + +### Recommended: Use the Automated Script + +```powershell +./.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 -PR +``` + +This enforces the workflow and prevents skipping. + +### Step 2: Get Test Results + +Fetch the test result artifacts and job logs: + +```powershell +# Download artifacts including test XML results +gh run download --dir ./artifacts + +# Get job logs +gh run view --log > test-logs.txt + +# Inspect test XML +$xml = [xml](Get-Content ./artifacts/junit-pester-*.xml) +$xml.'test-results' | Select-Object total, failures, errors, ignored, inconclusive +``` + +### Step 3: Extract Specific Failures + +Find the failing test cases in the XML: + +```powershell +# Get all failed test cases +$xml = [xml](Get-Content ./artifacts/junit-pester-*.xml) +$failures = $xml.SelectNodes('.//test-case[@result = "Failure"]') + +# For each failure, display key info +$failures | ForEach-Object { + [PSCustomObject]@{ + Name = $_.name + Description = $_.description + Message = $_.failure.message + StackTrace = $_.failure.'stack-trace' + } +} +``` + +### Step 4: Read the Error Message + +The error message tells you what went wrong: + +**Assertion failures:** +``` +Expected $true but got $false +Expected "value1" but got "value2" +Expression should have failed with exception, but didn't +``` + +**Exceptions:** +``` +Cannot find a parameter with name 'Name' +Property 'Property' does not exist on 'Object' +Cannot bind argument to parameter because it is null +``` + +**Timeouts:** +``` +Test timed out after 30 seconds +Test is taking too long to complete +``` + +### Step 5: Understand the Context + +Look at the test file to understand what was being tested: + +```powershell +# Find the test file mentioned in the stack trace +# Example: /path/to/test/Feature.Tests.ps1:42 + +# Read the test code around that line +code : + +# Understand: +# - What assertion is on that line? +# - What is the test trying to verify? +# - What are the setup/mock/before conditions? +# - Are there recent changes to the function being tested? +``` + +### Step 6: Interpret the Failure + +Determine the root cause category: + +**Test issue (needs code fix):** +- Assertion logic is wrong +- Test expectations don't match actual behavior +- Test setup is incomplete +- Mock/stub configuration missing + +**Environmental issue (needs environment change):** +- Test assumes a specific file or registry entry exists +- Test requires Windows/Linux specifically +- Test requires specific PowerShell version +- Test requires specific module version +- Timing-sensitive test affected by CI load + +**Data issue (needs input data change):** +- Test data no longer valid +- External API changed format +- Configuration file has changed structure + +**Flakiness (needs test hardening):** +- Race condition in test +- Timing assumptions too tight +- Resource contention on CI runner +- Non-deterministic behavior in tested code + +## Common Test Failure Patterns + +| Pattern | What It Means | Example | Next Step | +|---------|---------------|---------|-----------| +| `Expected $true but got $false` | Assertion on boolean result failed | Test expects function returns true, but it returns false | Check function logic for bug or test logic for wrong expectation | +| `Cannot find path` | File or directory doesn't exist | Test tries to read config file that's not present | Verify file path, check test setup, ensure CI environment has file | +| `Cannot bind argument to parameter 'X'` | Required parameter value is null or wrong type | Function called with $null where object expected | Check test mock setup, verify parameter types | +| `Test timed out after X seconds` | Test exceeded time limit | Network call or loop takes too long | Increase timeout for slow test, find infinite loop, mock network calls | +| `Expression should have failed but didn't` | Exception wasn't thrown when expected | Test expects error but function succeeds | Check if function behavior changed, update test expectation | +| `Could not find parameter 'X'` | Function doesn't have parameter | Test calls function with parameter that doesn't exist | Check PowerShell version, verify function signature, update test | +| `This platform is not supported` | Test skipped on current OS | Windows-only test running on Linux | Add platform check, update test environment, or mark as platform-specific | +| `Test marked [Ignore]` | Test explicitly disabled | Test has `[Ignore("reason")]` attribute | Check if reason still valid, remove if issue fixed | + +## Interpreting Test Results + +### Test Result Counts + +Pester test outcomes are categorized as: + +| Count | Meaning | Notes | +|-------|---------|-------| +| `total` | Total number of test cases executed | Should match: passed + failed + errors + skipped + ignored | +| `failures` | Test assertions that failed | `Expected X but got Y` type failures | +| `errors` | Tests that threw exceptions | Unhandled PowerShell exceptions during test | +| `skipped` | Tests explicitly skipped (marked with `-Skip`) | Test code recognizes condition and skips | +| `ignored` | Tests marked as ignored (marked with `-Ignore`) | Test disabled intentionally, usually notes reason | +| `inconclusive` | Tests with unclear result | Rare; usually means test framework issue | +| `passed` | Tests with passing assertions | `total - failures - errors - skipped - ignored` | + +### Stack Trace Interpretation + +A stack trace shows where the failure occurred: + +``` +at /home/runner/work/PowerShell/test/Feature.Tests.ps1:42 + +Means: +- File: /home/runner/work/PowerShell/test/Feature.Tests.ps1 +- Line: 42 +- Look at that line to see which assertion failed +``` + +### Understanding Skipped Tests + +When XML shows `result="Ignored"` or `result="Skipped"`: + +```xml + + Only runs on Windows + +``` + +The reason explains why test didn't run. Not a failure, but important for understanding test coverage. + +## Providing Test Failure Analysis + +### Investigation Questions + +After gathering test output, ask yourself: + +1. **Is the test code correct?** + - Does the test assertion match the expected behavior? + - Are test expectations still valid? + - Has the function being tested changed? + +2. **Is the test setup correct?** + - Are mocks/stubs configured properly? + - Does the test environment have required files/configuration? + - Are preconditions (database, files, services) met? + +3. **Is this a code bug or test issue?** + - Does the tested function have a logic error? + - Or does the test have incorrect expectations? + +4. **Is this environment-specific?** + - Only fails on Windows/Linux? + - Only fails on CI but passes locally? + - Timing-dependent or resource-dependent? + +5. **Is this a known/expected failure?** + - Is there already an issue tracking this failure? + - Is the test marked as flaky or expected to fail? + - Does the skip/ignore reason still apply? + +### Recommendation Framework + +Based on your analysis: + +| Finding | Recommendation | +|---------|-----------------| +| Test logic is wrong | "Test assertion on line X is incorrect. Test expects Y but function correctly returns Z. Update test expectation." | +| Tested code has bug | "Function at file.ps1#L42 has logic error. When X happens, returns Y instead of Z. Fix the condition." | +| Missing test setup | "Test setup incomplete. Mock for dependency Y is not configured. Add `Mock Get-Y -MockWith { ... }`" | +| Environment issue | "Test is Windows-specific but running on Linux. Either add platform check or skip on non-Windows." | +| Flaky test | "Test is timing-sensitive (sleep 1 second). Increase timeout or use better synchronization." | +| Test should be skipped | "Test is marked Ignored for good reason. Keep it disabled until issue #12345 is fixed." | + +### Tone and Structure + +Provide analysis as: + +1. **Summary** (1 sentence): What test is failing and general category +2. **Failure Details** (2-3 sentences): What the test output says +3. **Root Cause** (1-2 sentences): Why it's failing (test bug vs. code bug vs. environment) +4. **Recommendation** (actionable): What should be done to fix it +5. **Context** (optional): Link to related code, issues, or recent changes + +## Examples + +### Example 1: Assertion Failure Due to Code Bug + +**Test Output:** +``` +Expected 5 but got 3 at /path/to/Test.ps1:42 +``` + +**Investigation:** +1. Look at line 42: `$result | Should -Be 5` +2. Check the test: It expects function to return 5 items +3. Check the function: It returns `$items | Where-Object {$_.Status -eq "Active"}` but the filter is wrong +4. Root cause: Function has logic error, not test error + +**Recommendation:** +``` +Test failure is due to a code bug: + +The test Set-Configuration should return 5 items but returns 3. + +Looking at the tested function at [module.ps1#L42](module.ps1#L42): + $activeItems = $items | Where-Object {$_.Status -eq "Active"} + +The issue is the filter condition. It's currently filtering by "Active" status, +but should include "Pending" status as well. + +Fix: Change line 42 to: + $activeItems = $items | Where-Object {$_.Status -ne "Disabled"} + +Then re-run the test to verify it now returns 5 items as expected. +``` + +### Example 2: Test Setup Issue + +**Test Output:** +``` +Cannot find path '/expected/config.json' because it does not exist at /path/to/Test.ps1:15 +``` + +**Investigation:** +1. Line 15 tries to read a config file +2. The test setup doesn't create this file +3. Works locally but fails on CI because CI doesn't have the same file + +**Recommendation:** +``` +Test setup is incomplete: + +The test Initialize-Config fails because it expects /expected/config.json but the test doesn't create this file. + +The test needs to ensure the config file exists. Currently line 12-14 doesn't set up the file: + + # Before: + # (no setup of config file) + + # After: + @{ setting1 = "value1"; setting2 = "value2" } | ConvertTo-Json | + Out-File $testConfigPath + +Alternatively, the test function should accept a parameter for the config path and use a temporary file: + param([string]$ConfigPath = (New-TemporaryFile)) + +Re-run the test to verify the config file is properly available. +``` + +### Example 3: Platform-Specific Test Failure + +**Test Output:** +``` +Test 'should read Windows Registry' failed on Linux runner +Cannot find path 'HKEY_LOCAL_MACHINE:\...' +``` + +**Investigation:** +1. Test assumes Windows Registry exists (Windows-only) +2. Running on Linux runner doesn't have Registry +3. Test should skip on non-Windows platforms + +**Recommendation:** +``` +Test is platform-specific but running on wrong platform: + +The test "should read Windows Registry" assumes Windows Registry exists but is running on Linux. + +Add a platform check to skip this test on non-Windows systems: + + It "should read Windows Registry" -Skip:$(-not $IsWindows) { + # test code here + } + +Or group Windows-only tests in a separate Describe block with platform check: + + Describe "Windows Registry Tests" -Skip:$(-not $IsWindows) { + # all Windows-specific tests here + } + +This allows the test to be skipped on Linux/Mac while still running on Windows CI. +``` + +## References + +- [Pester Testing Framework](https://pester.dev/) — Official documentation, best practices for test writing +- [Test Files](../../../test/) — PowerShell test suite in repository +- [GitHub Actions Documentation](https://docs.github.com/en/actions) — Understanding workflow runs and logs +- [PowerShell Documentation](https://learn.microsoft.com/en-us/powershell/) — Language reference for understanding test code + +## Tips + +1. **Read the error message first:** The error message is usually the most direct clue to the problem +2. **Check test vs. code blame:** Is the test wrong or is the code wrong? Look at both sides +3. **Verify test isolation:** Does one test failure affect others? Check for shared state or test ordering dependencies +4. **Test locally first:** Try running the failing test locally to reproduce and understand it better +5. **Check for environmental assumptions:** Windows-specific paths, module versions, file locations may differ on CI +6. **Look for skip/ignore patterns:** If a test is consistently ignored, check if the reason is still valid +7. **Compare passing vs. failing:** If test passes locally but fails on CI, the difference is usually environment-related +8. **Check recent changes:** Did a recent PR change the tested code or test itself? +9. **Understand Pester output format:** Different Pester versions, different `-ErrorAction`, `-WarningAction` produce different test results +10. **Don't assume CI is wrong:** Failures on CI often reveal real issues that local testing missed (network, file permissions, parallelization, etc.) + +## Additional Links + +- [PowerShell Repository](https://github.com/PowerShell/PowerShell) +- [GitHub Actions Documentation](https://docs.github.com/en/actions) +- [Pester Testing Framework](https://github.com/Pester/Pester) diff --git a/PowerShell-master/.github/skills/analyze-pester-failures/references/stack-trace-parsing.md b/PowerShell-master/.github/skills/analyze-pester-failures/references/stack-trace-parsing.md new file mode 100644 index 0000000000000000000000000000000000000000..707f45560a937a6b0f9cbe4a73816298c1183064 --- /dev/null +++ b/PowerShell-master/.github/skills/analyze-pester-failures/references/stack-trace-parsing.md @@ -0,0 +1,163 @@ +# Understanding Pester Test Failures + +This reference explains how to interpret Pester test output and understand failure messages. + +## Supported Formats + +### Pester 4 Format +``` +at line: 123 in C:\path\to\file.ps1 +``` + +**Regex Pattern:** +```powershell +if ($StackTraceString -match 'at line:\s*(\d+)\s+in\s+(.+?)(?:\r|\n|$)') { + $result.Line = $matches[1] + $result.File = $matches[2].Trim() + return $result +} +``` + +### Pester 5 Format (Common) +``` +at 1 | Should -Be 2, C:\path\to\file.ps1:123 +at 1 | Should -Be 2, /home/runner/work/PowerShell/PowerShell/test/file.ps1:123 +``` + +**Regex Pattern:** +```powershell +if ($StackTraceString -match ',\s*((?:[A-Za-z]:)?[\/\\].+?\.ps[m]?1):(\d+)') { + $result.File = $matches[1].Trim() + $result.Line = $matches[2] + return $result +} +``` + +### Alternative Format +``` +at C:\path\to\file.ps1:123 +at /path/to/file.ps1:123 +``` + +**Regex Pattern:** +```powershell +if ($StackTraceString -match 'at\s+((?:[A-Za-z]:)?[\/\\][^,]+?\.ps[m]?1):(\d+)(?:\r|\n|$)') { + $result.File = $matches[1].Trim() + $result.Line = $matches[2] + return $result +} +``` + +## Troubleshooting Parsing Failures + +### Issue: Line Number Extracted But File Path Is Null + +**Cause:** Stack trace matches line-with-path pattern but file extraction doesn't work + +**Solution:** +1. Check if file path exists as expected in filesystem +2. Verify regex doesn't have too-greedy bounds (check use of `.+?` vs `.+`) +3. Test regex against actual stack trace string: + ```powershell + $trace = "at line: 42 in C:\path\to\test.ps1" + if ($trace -match 'at line:\s*(\d+)\s+in\s+(.+?)(?:\r|\n|$)') { + Write-Host "File: $($matches[2])" # Should be "C:\path\to\test.ps1" + } + ``` + +### Issue: Special Characters in File Path Break Regex + +**Cause:** Characters like parens `()`, brackets `[]`, pipes `|` have special meaning in regex + +**Solution:** +1. Escape special chars in regex: `[Regex]::Escape($path)` +2. Use character class `[\/\\]` instead of alternation for path separators +3. Test with files containing problematic names: + ```powershell + $traces = @( + "at line: 1 in C:\path\(with)\parens\test.ps1", + "at /home/user/[brackets]/test.ps1:5", + "at C:\path\with spaces\test.ps1:10" + ) + # Test each against all patterns + ``` + +### Issue: Regex Matches But Extracts Wrong Values + +**Symptom:** $matches[1] is file instead of line, or vice versa + +**Debug Steps:** +1. Print all captured groups: `$matches.Values | Format-Table -AutoSize` +2. Verify group order in regex matches expectations +3. Test with sample Pester output: + ```powershell + $sampleTrace = @" + at 1 | Should -Be 2, /home/runner/work/PowerShell/test/file.ps1:42 + "@ + + if ($sampleTrace -match ',\s*((?:[A-Za-z]:)?[\/\\].+?\.ps[m]?1):(\d+)') { + Write-Host "Match 1: $($matches[1])" # Should be file path + Write-Host "Match 2: $($matches[2])" # Should be line number + } + ``` + +## Testing the Parser + +Use this PowerShell script to validate `Get-PesterFailureFileInfo`: + +```powershell +# Import the function +. ./build.psm1 + +$testCases = @( + @{ + Input = "at line: 42 in C:\path\to\test.ps1" + Expected = @{ File = "C:\path\to\test.ps1"; Line = "42" } + }, + @{ + Input = "at /home/runner/work/test.ps1:123" + Expected = @{ File = "/home/runner/work/test.ps1"; Line = "123" } + }, + @{ + Input = "at 1 | Should -Be 2, /path/to/file.ps1:99" + Expected = @{ File = "/path/to/file.ps1"; Line = "99" } + } +) + +foreach ($test in $testCases) { + $result = Get-PesterFailureFileInfo -StackTraceString $test.Input + + $fileMatch = $result.File -eq $test.Expected.File + $lineMatch = $result.Line -eq $test.Expected.Line + $status = if ($fileMatch -and $lineMatch) { "✓ PASS" } else { "✗ FAIL" } + + Write-Host "$status : $($test.Input)" + if (-not $fileMatch) { Write-Host " Expected file: $($test.Expected.File), got: $($result.File)" } + if (-not $lineMatch) { Write-Host " Expected line: $($test.Expected.Line), got: $($result.Line)" } +} +``` + +## Adding Support for New Formats + +When Pester changes its output format: + +1. **Capture sample output** from failing tests +2. **Identify the pattern** (e.g., "file path always after comma followed by colon") +3. **Write regex** to match pattern without over-matching +4. **Add to `Get-PesterFailureFileInfo`** before existing patterns (order matters for fallback) +5. **Test with samples** containing special characters, long paths, and edge cases + +Example: Adding a new format at the top of the function: + +```powershell +# Try pattern: "at , :" (Pester 5.1 hypothetical) +if ($StackTraceString -match 'at .+?, ((?:[A-Za-z]:)?[\/\\].+?\.ps[m]?1):(\d+)') { + $result.File = $matches[1].Trim() + $result.Line = $matches[2] + return $result +} + +# Try existing patterns... +``` + +Place new patterns **first** so they take precedence over fallback patterns. diff --git a/PowerShell-master/.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 b/PowerShell-master/.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..1248659607158634df2c5a5105f12e487a0afab7 --- /dev/null +++ b/PowerShell-master/.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 @@ -0,0 +1,456 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +<# +.SYNOPSIS + Automated Pester test failure analysis workflow for GitHub PRs. + +.DESCRIPTION + This script automates the complete analysis workflow defined in the analyze-pester-failures + skill. It performs all steps in order: + 1. Identify failing test jobs in the PR + 2. Download test artifacts and logs + 3. Extract specific test failures + 4. Parse error messages + 5. Search logs for error markers and generate recommendations + + By automating the workflow, this ensures analysis steps are followed in order + and nothing is skipped. + +.PARAMETER PR + The GitHub PR number to analyze (e.g., 26800) + +.PARAMETER Owner + Repository owner (default: PowerShell) + +.PARAMETER Repo + Repository name (default: PowerShell) + +.PARAMETER OutputDir + Directory to store analysis results (default: ./pester-analysis-PR) + +.PARAMETER Interactive + Prompt for recommendations after analysis (default: non-interactive) + +.PARAMETER ForceDownload + Force re-download of artifacts and logs, even if they already exist + +.EXAMPLE + .\.github\skills\analyze-pester-failures\scripts\analyze-pr-test-failures.ps1 -PR 26800 + Analyzes PR #26800 and saves results to ./pester-analysis-PR26800 + +.EXAMPLE + .\.github\skills\analyze-pester-failures\scripts\analyze-pr-test-failures.ps1 -PR 26800 -Interactive + Interactive mode: shows failures and prompts for next steps + +.EXAMPLE + .\.github\skills\analyze-pester-failures\scripts\analyze-pr-test-failures.ps1 -PR 26800 -ForceDownload + Re-download all logs and artifacts, skipping the cache + +.NOTES + Requires: GitHub CLI (gh) configured and authenticated + This script enforces the workflow defined in .github/skills/analyze-pester-failures/SKILL.md +#> + +param( + [Parameter(Mandatory)] + [int]$PR, + + [string]$Owner = 'PowerShell', + [string]$Repo = 'PowerShell', + [string]$OutputDir, + [switch]$Interactive, + [switch]$ForceDownload +) + +$ErrorActionPreference = 'Stop' + +if (-not $OutputDir) { + $OutputDir = "./pester-analysis-PR$PR" +} + +# Colors for output +$colors = @{ + Step = [ConsoleColor]::Cyan + Success = [ConsoleColor]::Green + Warning = [ConsoleColor]::Yellow + Error = [ConsoleColor]::Red + Info = [ConsoleColor]::Gray +} + +function Write-Step { + param([string]$text, [int]$number) + Write-Host "`n[$number/6] $text" -ForegroundColor $colors.Step -BackgroundColor Black +} + +function Write-Result { + param([string]$text, [ValidateSet('Success','Warning','Error','Info')]$type = 'Info') + Write-Host $text -ForegroundColor $colors[$type] +} + +Write-Host "`n=== Pester Test Failure Analysis ===" -ForegroundColor $colors.Step +Write-Host "PR: $Owner/$Repo#$PR" -ForegroundColor $colors.Info +Write-Host "Output Directory: $OutputDir" -ForegroundColor $colors.Info + +# Ensure output directory exists +if (-not (Test-Path $OutputDir)) { + New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null +} + +# STEP 1: Identify the Failing Test Job +Write-Step "Identify failing test jobs" 1 + +Write-Result "Fetching PR status checks..." Info +$prResponse = gh pr view $PR --repo "$Owner/$Repo" --json 'statusCheckRollup' | ConvertFrom-Json +$allChecks = $prResponse.statusCheckRollup + +$failedJobs = $allChecks | Where-Object { $_.conclusion -eq 'FAILURE' } + +if (-not $failedJobs) { + Write-Result "✓ No failed jobs found" Success + Write-Host " Total checks: $($allChecks.Count)" + $allChecks | Where-Object { $_ } | ForEach-Object { + Write-Host " - $($_.name): $($_.conclusion)" -ForegroundColor $colors.Info + } + exit 0 +} + +Write-Result "✓ Found $($failedJobs.Count) failing job(s)" Warning + +$failedJobs | Where-Object { $_.conclusion -eq 'FAILURE' } | ForEach-Object { + Write-Host " ✗ $($_.name) - $($_.conclusion)" -ForegroundColor $colors.Error + if ($_.detailsUrl) { + Write-Host " URL: $($_.detailsUrl)" -ForegroundColor $colors.Info + } +} + +if ($Interactive) { + Write-Host "`nPress Enter to continue to Step 2..." + Read-Host | Out-Null +} + +# STEP 2: Get Test Results +Write-Step "Download test artifacts and logs" 2 + +# Extract unique run IDs from failing jobs +$uniqueRuns = @() +foreach ($failedJob in $failedJobs) { + if ($failedJob.detailsUrl -match 'runs/(\d+)') { + $runId = $matches[1] + if ($runId -notin $uniqueRuns) { + $uniqueRuns += $runId + } + } +} + +if ($uniqueRuns.Count -eq 0) { + Write-Result "✗ Could not extract run IDs from failing jobs" Error + exit 1 +} + +Write-Result "Found $($uniqueRuns.Count) run(s): $($uniqueRuns -join ', ')" Info + +$artifactDir = Join-Path $OutputDir artifacts + +# Check if artifacts already exist +$existingArtifacts = Get-ChildItem $artifactDir -Recurse -File -ErrorAction SilentlyContinue + +if ($existingArtifacts -and -not $ForceDownload) { + Write-Result "✓ Artifacts already downloaded" Success + $existingArtifacts | ForEach-Object { + Write-Host " - $($_.FullName)" -ForegroundColor $colors.Info + } +} else { + Write-Result "Downloading artifacts from run $($uniqueRuns[0])..." Info + gh run download $uniqueRuns[0] --dir $artifactDir --repo "$Owner/$Repo" 2>&1 | Out-Null + + if (Test-Path $artifactDir) { + Write-Result "✓ Artifacts downloaded" Success + Get-ChildItem $artifactDir -Recurse -File | ForEach-Object { + Write-Host " - $($_.FullName)" -ForegroundColor $colors.Info + } + } else { + Write-Result "✗ Failed to download artifacts" Error + exit 1 + } +} + +# Download individual job logs for failing jobs +Write-Result "Downloading individual job logs..." Info + +$logsDir = Join-Path $OutputDir "logs" +if (-not (Test-Path $logsDir)) { + New-Item -ItemType Directory -Path $logsDir -Force | Out-Null +} + +# Check if logs already exist +$existingLogs = Get-ChildItem $logsDir -Filter "*.txt" -ErrorAction SilentlyContinue + +if ($existingLogs -and -not $ForceDownload) { + Write-Result "✓ Job logs already downloaded" Success + $existingLogs | ForEach-Object { + Write-Host " - $($_.Name)" -ForegroundColor $colors.Info + } +} else { + # Process each run and get its jobs + $failedJobIds = @() + foreach ($runId in $uniqueRuns) { + $runJobs = gh run view $runId --repo "$Owner/$Repo" --json jobs | ConvertFrom-Json + + foreach ($failedJob in $failedJobs) { + # Check if this failed job belongs to this run + if ($failedJob.detailsUrl -match "runs/$runId/") { + $jobMatch = $runJobs.jobs | Where-Object { $_.name -eq $failedJob.name } | Select-Object -First 1 + if ($jobMatch) { + $failedJobIds += @{ + name = $failedJob.name + id = $jobMatch.databaseId + runId = $runId + } + } + } + } + } + + # Download logs for all failed jobs + foreach ($jobInfo in $failedJobIds) { + $logFile = Join-Path $logsDir ("log-{0}.txt" -f ($jobInfo.name -replace '[^a-zA-Z0-9-]', '_')) + Write-Result " Downloading: $($jobInfo.name) (Run $($jobInfo.runId))" Info + gh run view $jobInfo.runId --log --job $jobInfo.id --repo "$Owner/$Repo" > $logFile 2>&1 + } + + Write-Result "✓ Job logs downloaded" Success + Get-ChildItem $logsDir -Filter "*.txt" | ForEach-Object { + Write-Host " - $($_.Name)" -ForegroundColor $colors.Info + } +} + +if ($Interactive) { + Write-Host "`nPress Enter to continue to Step 3..." + Read-Host | Out-Null +} + +# STEP 3: Extract Specific Failures +Write-Step "Extract test failures from XML" 3 + +$xmlFiles = Get-ChildItem $artifactDir -Filter "*.xml" -Recurse +if (-not $xmlFiles) { + Write-Result "✗ No test result XML files found" Error + exit 1 +} + +Write-Result "✓ Found $($xmlFiles.Count) test result file(s)" Success + +$allFailures = @() + +foreach ($xmlFile in $xmlFiles) { + Write-Result "`nParsing: $($xmlFile.Name)" Info + + try { + [xml]$xml = Get-Content $xmlFile + $testResults = $xml.'test-results' + + Write-Host " Total: $($testResults.total)" -ForegroundColor $colors.Info + Write-Host " Passed: $($testResults.passed)" -ForegroundColor $colors.Success + if ($testResults.failures -gt 0) { + Write-Host " Failed: $($testResults.failures)" -ForegroundColor $colors.Error + } + if ($testResults.errors -gt 0) { + Write-Host " Errors: $($testResults.errors)" -ForegroundColor $colors.Error + } + if ($testResults.skipped -gt 0) { + Write-Host " Skipped: $($testResults.skipped)" -ForegroundColor $colors.Warning + } + if ($testResults.ignored -gt 0) { + Write-Host " Ignored: $($testResults.ignored)" -ForegroundColor $colors.Warning + } + + # Extract failures + $failures = $xml.SelectNodes('.//test-case[@result = "Failure"]') + + foreach ($failure in $failures) { + $allFailures += @{ + Name = $failure.name + File = $xmlFile.Name + Message = $failure.failure.message + StackTrace = $failure.failure.'stack-trace' + } + } + } catch { + Write-Result "✗ Error parsing XML: $_" Error + } +} + +Write-Result "`n✓ Extracted $($allFailures.Count) failures total" Success + +# Save failures to JSON for later analysis +$allFailures | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputDir "failures.json") + +if ($Interactive) { + Write-Host "`nPress Enter to continue to Step 4..." + Read-Host | Out-Null +} + +# STEP 4: Read Error Messages +Write-Step "Analyze error messages" 4 + +$failuresByType = @{} + +foreach ($failure in $allFailures) { + $message = $failure.Message -split "`n" | Select-Object -First 1 + + # Categorize failure + $type = 'Other' + if ($message -match 'Expected .* but got') { $type = 'Assertion' } + elseif ($message -match 'Cannot (find|bind)') { $type = 'Exception' } + elseif ($message -match 'timed out') { $type = 'Timeout' } + + if (-not $failuresByType[$type]) { + $failuresByType[$type] = @() + } + $failuresByType[$type] += $failure +} + +Write-Result "Failure breakdown:" Info +$failuresByType.GetEnumerator() | ForEach-Object { + Write-Host " $($_.Key): $($_.Value.Count)" -ForegroundColor $colors.Warning +} + +Write-Result "`nTop failure messages:" Info +$allFailures | Group-Object Message | Sort-Object Count -Descending | Select-Object -First 3 | ForEach-Object { + Write-Host " [$($_.Count)x] $($_.Name -split "`n" | Select-Object -First 1)" -ForegroundColor $colors.Info +} + +# Save analysis +$analysis = @{ + FailuresByType = @{} + TopMessages = @() +} + +$failuresByType.GetEnumerator() | ForEach-Object { + $analysis.FailuresByType[$_.Key] = $_.Value.Count +} + +$allFailures | Group-Object Message | Sort-Object Count -Descending | Select-Object -First 5 | ForEach-Object { + $analysis.TopMessages += @{ + Count = $_.Count + Message = ($_.Name -split "`n" | Select-Object -First 1) + } +} + +$analysis | ConvertTo-Json | Out-File (Join-Path $OutputDir "analysis.json") + +if ($Interactive) { + Write-Host "`nPress Enter to continue to Step 5..." + Read-Host | Out-Null +} + +# STEP 5: Search Logs for Error Markers +Write-Step "Search logs for error markers" 5 + +$logsDir = Join-Path $OutputDir "logs" +if (-not (Test-Path $logsDir)) { + Write-Result "⚠ Logs directory not found" Warning +} else { + $logFiles = Get-ChildItem $logsDir -Filter "*.txt" -ErrorAction SilentlyContinue + if (-not $logFiles) { + Write-Result "⚠ No log files found in logs directory" Warning + } else { + Write-Result "Searching $($logFiles.Count) job log(s) for error markers ([-])" Info + Write-Result "Format: [JobName] [LineNumber] Content" Info + Write-Host "" + + $allErrorLines = @() + + foreach ($logFile in $logFiles) { + $jobName = $logFile.BaseName -replace '^log-', '' + $logLines = @(Get-Content $logFile) + + for ($i = 0; $i -lt $logLines.Count; $i++) { + $line = $logLines[$i] + if ($line -match '\s\[-\]\s') { + $allErrorLines += @{ + JobName = $jobName + LineNumber = $i + 1 + Content = $line + } + } + } + } + + if ($allErrorLines.Count -gt 0) { + Write-Result "✓ Found $($allErrorLines.Count) error marker line(s)" Warning + + $allErrorLines | ForEach-Object { + Write-Host " [$($_.JobName)] [$($_.LineNumber)] $($_.Content)" -ForegroundColor $colors.Error + } + + # Save to file + $allErrorLines | ConvertTo-Json | Out-File (Join-Path $OutputDir "error-markers.json") + Write-Result "✓ Error markers saved to error-markers.json" Success + } else { + Write-Result "✓ No error markers found in logs" Success + } + } +} + +if ($Interactive) { + Write-Host "`nPress Enter to continue to Step 6..." + Read-Host | Out-Null +} + +# STEP 6: Generate Recommendations +Write-Step "Generate recommendations" 6 + +$recommendations = @() + +# Analyze patterns +if ($failuresByType['Assertion']) { + $recommendations += "Multiple assertion failures detected. These indicate test expectations don't match actual behavior." +} + +if ($failuresByType['Exception']) { + $recommendations += "Exception errors found. Check test setup and prerequisites - may indicate missing files, modules, or permissions." +} + +if ($failuresByType['Timeout']) { + $recommendations += "Timeout failures suggest slow or hanging operations. Consider network issues or resource constraints on CI." +} + +# Check for patterns in failure messages +$failureMessages = $allFailures.Message -join "`n" +if ($failureMessages -match 'PackageManagement') { + $recommendations += "PackageManagement module issues detected. Verify module availability and help repository access." +} + +if ($failureMessages -match 'Update-Help') { + $recommendations += "Update-Help failures detected. Check network connectivity to help repository and help installation paths." +} + +Write-Result "`n📋 Recommendations:" Info +if ($recommendations) { + $recommendations | ForEach-Object { Write-Host " • $_" -ForegroundColor $colors.Info } +} else { + Write-Host " • Review failures in detail" -ForegroundColor $colors.Info + Write-Host " • Check if test changes are needed" -ForegroundColor $colors.Info + Write-Host " • Consider environment-specific issues" -ForegroundColor $colors.Info +} + +$recommendations | Out-File (Join-Path $OutputDir "recommendations.txt") + +# Summary +Write-Host "`n=== Analysis Complete ===" -ForegroundColor $colors.Step +Write-Host "Results saved to: $OutputDir" -ForegroundColor $colors.Info +Write-Host " - failures.json (detailed failure data)" -ForegroundColor $colors.Info +Write-Host " - analysis.json (summary analysis)" -ForegroundColor $colors.Info +Write-Host " - recommendations.txt (suggested fixes)" -ForegroundColor $colors.Info +Write-Host " - error-markers.json (error markers from logs)" -ForegroundColor $colors.Info +Write-Host " - logs/ (individual job log files)" -ForegroundColor $colors.Info +Write-Host " - artifacts/ (downloaded test artifacts)" -ForegroundColor $colors.Info + +Write-Host "`nNext steps:" -ForegroundColor $colors.Step +Write-Host "1. Review recommendations.txt for analysis" -ForegroundColor $colors.Info +Write-Host "2. Examine failures.json for detailed error messages" -ForegroundColor $colors.Info +Write-Host "3. Check error-markers.json for specific test failures in logs" -ForegroundColor $colors.Info +Write-Host "4. Review individual job logs in logs/ directory for contextual details" -ForegroundColor $colors.Info +Write-Host "`n" diff --git a/PowerShell-master/.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 b/PowerShell-master/.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 new file mode 100644 index 0000000000000000000000000000000000000000..f0524ce6f231f9b94a1bee702b29dad81e17ea83 --- /dev/null +++ b/PowerShell-master/.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 @@ -0,0 +1,27 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +function Set-GWVariable { + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [string]$Value + ) + + Write-Verbose "Setting CI variable $Name to $Value" -Verbose + + if ($env:GITHUB_ENV) { + "$Name=$Value" | Out-File $env:GITHUB_ENV -Append + } +} + +function Get-GWTempPath { + $temp = [System.IO.Path]::GetTempPath() + if ($env:RUNNER_TEMP) { + $temp = $env:RUNNER_TEMP + } + + Write-Verbose "Get CI Temp path: $temp" -Verbose + return $temp +} diff --git a/PowerShell-master/.github/workflows/analyze-reusable.yml b/PowerShell-master/.github/workflows/analyze-reusable.yml new file mode 100644 index 0000000000000000000000000000000000000000..bb90de8e264f9149f13ccbaa2d5bffcfd1bd43d6 --- /dev/null +++ b/PowerShell-master/.github/workflows/analyze-reusable.yml @@ -0,0 +1,77 @@ +name: CodeQL Analysis (Reusable) + +on: + workflow_call: + inputs: + runner_os: + description: 'Runner OS for CodeQL analysis' + type: string + required: false + default: ubuntu-latest + +permissions: + actions: read # for github/codeql-action/init to get workflow details + contents: read # for actions/checkout to fetch code + security-events: write # for github/codeql-action/analyze to upload SARIF results + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + +jobs: + analyze: + name: Analyze + runs-on: ${{ inputs.runner_os }} + + strategy: + fail-fast: false + matrix: + # Override automatic language detection by changing the below list + # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] + language: ['csharp'] + # Learn more... + # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: '0' + + - uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5.2.0 + with: + global-json-file: ./global.json + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@c10b8064de6f491fea524254123dbe5e09572f13 # v3.29.5 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + - run: | + Import-Module .\tools\ci.psm1 + Show-Environment + name: Capture Environment + shell: pwsh + + - run: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + name: Bootstrap + shell: pwsh + + - run: | + Import-Module .\tools\ci.psm1 + Invoke-CIBuild -Configuration 'StaticAnalysis' + name: Build + shell: pwsh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@c10b8064de6f491fea524254123dbe5e09572f13 # v3.29.5 diff --git a/PowerShell-master/.github/workflows/copilot-setup-steps.yml b/PowerShell-master/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 0000000000000000000000000000000000000000..d78e745a4a9cfcf2cc3ccceb7d5311cea9af1f77 --- /dev/null +++ b/PowerShell-master/.github/workflows/copilot-setup-steps.yml @@ -0,0 +1,64 @@ +name: "Copilot Setup Steps" + +# Allow testing of the setup steps from your repository's "Actions" tab. +on: + workflow_dispatch: + + pull_request: + branches: + - master + paths: + - ".github/workflows/copilot-setup-steps.yml" + +permissions: + contents: read + +jobs: + # The job MUST be called `copilot-setup-steps` or it will not be picked up by Copilot. + # See https://docs.github.com/en/copilot/customizing-copilot/customizing-the-development-environment-for-copilot-coding-agent + copilot-setup-steps: + runs-on: ubuntu-latest + + permissions: + contents: read + + # You can define any steps you want, and they will run before the agent starts. + # If you do not check out your code, Copilot will do this for you. + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + + - name: Bootstrap + if: success() + run: |- + $title = 'Import Build.psm1' + Write-Host "::group::$title" + Import-Module ./build.psm1 -Verbose -ErrorAction Stop + Write-LogGroupEnd -Title $title + + $title = 'Switch to public feed' + Write-LogGroupStart -Title $title + Switch-PSNugetConfig -Source Public + Write-LogGroupEnd -Title $title + + $title = 'Bootstrap' + Write-LogGroupStart -Title $title + Start-PSBootstrap -Scenario DotNet + Write-LogGroupEnd -Title $title + + $title = 'Install .NET Tools' + Write-LogGroupStart -Title $title + Start-PSBootstrap -Scenario Tools + Write-LogGroupEnd -Title $title + + $title = 'Sync Tags' + Write-LogGroupStart -Title $title + Sync-PSTags -AddRemoteIfMissing + Write-LogGroupEnd -Title $title + + $title = 'Setup .NET environment variables' + Write-LogGroupStart -Title $title + Find-DotNet -SetDotnetRoot + Write-LogGroupEnd -Title $title + shell: pwsh diff --git a/PowerShell-master/.github/workflows/dependency-review.yml b/PowerShell-master/.github/workflows/dependency-review.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b610326e44d1d06e7bdb2f12d1679b420bbf2f8 --- /dev/null +++ b/PowerShell-master/.github/workflows/dependency-review.yml @@ -0,0 +1,22 @@ +# Dependency Review Action +# +# This Action will scan dependency manifest files that change as part of a Pull Request, +# surfacing known-vulnerable versions of the packages declared or updated in the PR. +# Once installed, if the workflow run is marked as required, +# PRs introducing known-vulnerable packages will be blocked from merging. +# +# Source repository: https://github.com/actions/dependency-review-action +name: 'Dependency Review' +on: [pull_request] + +permissions: + contents: read + +jobs: + dependency-review: + runs-on: ubuntu-latest + steps: + - name: 'Checkout Repository' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: 'Dependency Review' + uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48 # v4.9.0 diff --git a/PowerShell-master/.github/workflows/labels.yml b/PowerShell-master/.github/workflows/labels.yml new file mode 100644 index 0000000000000000000000000000000000000000..27ceac59bbdc1c2bbc3e2f67ab76630c6a5619be --- /dev/null +++ b/PowerShell-master/.github/workflows/labels.yml @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +name: Verify PR Labels + +on: + pull_request: + types: [opened, reopened, edited, labeled, unlabeled, synchronize] + +permissions: + contents: read + pull-requests: read + +jobs: + verify-labels: + if: github.repository_owner == 'PowerShell' + runs-on: ubuntu-latest + + steps: + - name: Check out the repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Verify PR has label starting with 'cl-' + id: verify-labels + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const labels = context.payload.pull_request.labels.map(label => label.name.toLowerCase()); + if (!labels.some(label => label.startsWith('cl-'))) { + core.setFailed("Every PR must have at least one label starting with 'cl-'."); + } diff --git a/PowerShell-master/.github/workflows/linux-ci.yml b/PowerShell-master/.github/workflows/linux-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..77186125a9c2657ac057e647045cb5fd5f78d036 --- /dev/null +++ b/PowerShell-master/.github/workflows/linux-ci.yml @@ -0,0 +1,262 @@ +name: Linux-CI + +run-name: "${{ github.ref_name }} - ${{ github.run_number }}" + +on: + workflow_dispatch: + + push: + branches: + - master + - release/** + - github-mirror + paths: + - "**" + - "*" + - ".globalconfig" + - "!.github/ISSUE_TEMPLATE/**" + - "!.dependabot/config.yml" + - "!.pipelines/**" + - "!test/perf/**" + pull_request: + branches: + - master + - release/** + - github-mirror + - "*-feature" +# Path filters for PRs need to go into the changes job + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: ${{ contains(github.ref, 'merge')}} + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + FORCE_FEATURE: 'False' + FORCE_PACKAGE: 'False' + NUGET_KEY: none + POWERSHELL_TELEMETRY_OPTOUT: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + system_debug: 'false' +jobs: + changes: + if: startsWith(github.repository_owner, 'azure') || github.repository_owner == 'PowerShell' + name: Change Detection + runs-on: ubuntu-latest + # Required permissions + permissions: + pull-requests: read + contents: read + + # Set job outputs to values from filter step + outputs: + source: ${{ steps.filter.outputs.source }} + buildModuleChanged: ${{ steps.filter.outputs.buildModuleChanged }} + packagingChanged: ${{ steps.filter.outputs.packagingChanged }} + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Change Detection + id: filter + uses: "./.github/actions/infrastructure/path-filters" + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + merge_conflict_check: + name: Check for Merge Conflict Markers + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' && (startsWith(github.repository_owner, 'azure') || github.repository_owner == 'PowerShell') + permissions: + pull-requests: read + contents: read + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Check for merge conflict markers + uses: "./.github/actions/infrastructure/merge-conflict-checker" + + ci_build: + name: Build PowerShell + runs-on: ubuntu-latest + needs: changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + + - name: Build + uses: "./.github/actions/build/ci" + linux_test_unelevated_ci: + name: Linux Unelevated CI + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Linux Unelevated CI + uses: "./.github/actions/test/nix" + with: + purpose: UnelevatedPesterTests + tagSet: CI + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + linux_test_elevated_ci: + name: Linux Elevated CI + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Linux Elevated CI + uses: "./.github/actions/test/nix" + with: + purpose: ElevatedPesterTests + tagSet: CI + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + linux_test_unelevated_others: + name: Linux Unelevated Others + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Linux Unelevated Others + uses: "./.github/actions/test/nix" + with: + purpose: UnelevatedPesterTests + tagSet: Others + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + linux_test_elevated_others: + name: Linux Elevated Others + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Linux Elevated Others + uses: "./.github/actions/test/nix" + with: + purpose: ElevatedPesterTests + tagSet: Others + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + xunit_tests: + name: xUnit Tests + needs: + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + uses: ./.github/workflows/xunit-tests.yml + with: + runner_os: ubuntu-latest + test_results_artifact_name: testResults-xunit + + infrastructure_tests: + name: Infrastructure Tests + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1 + + - name: Install Pester + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Install-CIPester + + - name: Run Infrastructure Tests + shell: pwsh + run: | + $testResultsFolder = Join-Path $PWD "testResults" + New-Item -ItemType Directory -Path $testResultsFolder -Force | Out-Null + + $config = New-PesterConfiguration + $config.Run.Path = './test/infrastructure/' + $config.Run.PassThru = $true + $config.TestResult.Enabled = $true + $config.TestResult.OutputFormat = 'NUnitXml' + $config.TestResult.OutputPath = "$testResultsFolder/InfrastructureTests.xml" + $config.Output.Verbosity = 'Detailed' + + $result = Invoke-Pester -Configuration $config + + if ($result.FailedCount -gt 0 -or $result.Result -eq 'Failed') { + throw "Infrastructure tests failed" + } + + - name: Publish Test Results + uses: "./.github/actions/test/process-pester-results" + if: always() + with: + name: "InfrastructureTests" + testResultsFolder: "${{ github.workspace }}/testResults" + + ## Temporarily disable the CodeQL analysis on Linux as it doesn't work for .NET SDK 10-rc.2. + # analyze: + # name: CodeQL Analysis + # needs: changes + # if: ${{ needs.changes.outputs.source == 'true' }} + # uses: ./.github/workflows/analyze-reusable.yml + # permissions: + # actions: read + # contents: read + # security-events: write + # with: + # runner_os: ubuntu-latest + + ready_to_merge: + name: Linux ready to merge + needs: + - xunit_tests + - linux_test_elevated_ci + - linux_test_elevated_others + - linux_test_unelevated_ci + - linux_test_unelevated_others + - linux_packaging + - merge_conflict_check + - infrastructure_tests + # - analyze + if: always() + uses: PowerShell/compliance/.github/workflows/ready-to-merge.yml@c8b3ad5819ad7078f3e375519b4f8c6232d1cbdf # v1.0.0 + with: + needs_context: ${{ toJson(needs) }} + linux_packaging: + name: Linux Packaging + needs: + - changes + if: ${{ needs.changes.outputs.packagingChanged == 'true' }} + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + - name: Linux Packaging + uses: "./.github/actions/test/linux-packaging" diff --git a/PowerShell-master/.github/workflows/macos-ci.yml b/PowerShell-master/.github/workflows/macos-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..55d852bb68ac870bdee7851cc9f89a3271c45c34 --- /dev/null +++ b/PowerShell-master/.github/workflows/macos-ci.yml @@ -0,0 +1,248 @@ +name: macOS-CI + +run-name: "${{ github.ref_name }} - ${{ github.run_number }}" + +on: + push: + branches: + - master + - release/** + - github-mirror + paths: + - "**" + - "*" + - ".globalconfig" + - "!.github/ISSUE_TEMPLATE/**" + - "!.dependabot/config.yml" + - "!.pipelines/**" + - "!test/perf/**" + pull_request: + branches: + - master + - release/** + - github-mirror + - "*-feature" +# Path filters for PRs need to go into the changes job + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: ${{ contains(github.ref, 'merge')}} + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + FORCE_FEATURE: 'False' + FORCE_PACKAGE: 'False' + HOMEBREW_NO_ANALYTICS: 1 + NUGET_KEY: none + POWERSHELL_TELEMETRY_OPTOUT: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + system_debug: 'false' + +jobs: + changes: + name: Change Detection + runs-on: ubuntu-latest + if: startsWith(github.repository_owner, 'azure') || github.repository_owner == 'PowerShell' + # Required permissions + permissions: + pull-requests: read + contents: read + + # Set job outputs to values from filter step + outputs: + source: ${{ steps.filter.outputs.source }} + buildModuleChanged: ${{ steps.filter.outputs.buildModuleChanged }} + packagingChanged: ${{ steps.filter.outputs.packagingChanged }} + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Change Detection + id: filter + uses: "./.github/actions/infrastructure/path-filters" + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + ci_build: + name: Build PowerShell + runs-on: macos-15-large + needs: changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Build + uses: "./.github/actions/build/ci" + macos_test_unelevated_ci: + name: macos Unelevated CI + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: macos-15-large + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: macOS Unelevated CI + uses: "./.github/actions/test/nix" + with: + purpose: UnelevatedPesterTests + tagSet: CI + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + macos_test_elevated_ci: + name: macOS Elevated CI + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: macos-15-large + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: macOS Elevated CI + uses: "./.github/actions/test/nix" + with: + purpose: ElevatedPesterTests + tagSet: CI + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + macos_test_unelevated_others: + name: macOS Unelevated Others + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: macos-15-large + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: macOS Unelevated Others + uses: "./.github/actions/test/nix" + with: + purpose: UnelevatedPesterTests + tagSet: Others + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + macos_test_elevated_others: + name: macOS Elevated Others + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: macos-15-large + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: macOS Elevated Others + uses: "./.github/actions/test/nix" + with: + purpose: ElevatedPesterTests + tagSet: Others + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + xunit_tests: + name: xUnit Tests + needs: + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + uses: ./.github/workflows/xunit-tests.yml + with: + runner_os: macos-15-large + test_results_artifact_name: testResults-xunit + PackageMac-macos_packaging: + name: macOS packaging and testing + needs: + - changes + if: ${{ needs.changes.outputs.packagingChanged == 'true' }} + runs-on: + - macos-15-large + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5.2.0 + with: + global-json-file: ./global.json + - name: Bootstrap packaging + if: success() + run: |- + import-module ./build.psm1 + start-psbootstrap -Scenario package + shell: pwsh + - name: Build PowerShell and Create macOS package + if: success() + run: |- + import-module ./build.psm1 + import-module ./tools/ci.psm1 + import-module ./tools/packaging/packaging.psm1 + Switch-PSNugetConfig -Source Public + Sync-PSTags -AddRemoteIfMissing + $releaseTag = Get-ReleaseTag + Start-PSBuild -Configuration Release -PSModuleRestore -ReleaseTag $releaseTag + $macOSRuntime = if ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq 'Arm64') { 'osx-arm64' } else { 'osx-x64' } + Start-PSPackage -Type osxpkg -ReleaseTag $releaseTag -MacOSRuntime $macOSRuntime -SkipReleaseChecks + shell: pwsh + + - name: Install Pester + if: success() + run: |- + Import-Module ./tools/ci.psm1 + Install-CIPester + shell: pwsh + + - name: Test package contents + if: success() + run: |- + $env:PACKAGE_FOLDER = Get-Location + $testResultsPath = Join-Path $env:RUNNER_WORKSPACE "testResults" + if (-not (Test-Path $testResultsPath)) { + New-Item -ItemType Directory -Path $testResultsPath -Force | Out-Null + } + Import-Module Pester + $pesterConfig = New-PesterConfiguration + $pesterConfig.Run.Path = './test/packaging/macos/package-validation.tests.ps1' + $pesterConfig.Run.PassThru = $true + $pesterConfig.Output.Verbosity = 'Detailed' + $pesterConfig.TestResult.Enabled = $true + $pesterConfig.TestResult.OutputFormat = 'NUnitXml' + $pesterConfig.TestResult.OutputPath = Join-Path $testResultsPath "macOSPackage.xml" + $result = Invoke-Pester -Configuration $pesterConfig + if ($result.FailedCount -gt 0) { + throw "Package validation failed with $($result.FailedCount) failed test(s)" + } + shell: pwsh + - name: Publish and Upload Pester Test Results + if: always() + uses: "./.github/actions/test/process-pester-results" + with: + name: "macOSPackage" + testResultsFolder: "${{ runner.workspace }}/testResults" + - name: Upload package artifact + if: always() + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: macos-package + path: "*.pkg" + ready_to_merge: + name: macos ready to merge + needs: + - xunit_tests + - PackageMac-macos_packaging + - macos_test_elevated_ci + - macos_test_elevated_others + - macos_test_unelevated_ci + - macos_test_unelevated_others + if: always() + uses: PowerShell/compliance/.github/workflows/ready-to-merge.yml@c8b3ad5819ad7078f3e375519b4f8c6232d1cbdf # v1.0.0 + with: + needs_context: ${{ toJson(needs) }} diff --git a/PowerShell-master/.github/workflows/markdown-link/config.json b/PowerShell-master/.github/workflows/markdown-link/config.json new file mode 100644 index 0000000000000000000000000000000000000000..87d65922a915bbdf6103ddf96b156e13a910ddeb --- /dev/null +++ b/PowerShell-master/.github/workflows/markdown-link/config.json @@ -0,0 +1,7 @@ +{ + "timeout": "40s", + "retryOn429": true, + "retryCount": 5, + "fallbackRetryDelay": "30s", + "aliveStatusCodes": [504, 503, 403, 200] +} diff --git a/PowerShell-master/.github/workflows/scorecards.yml b/PowerShell-master/.github/workflows/scorecards.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b3711666aab2659a306275242787748fd03316e --- /dev/null +++ b/PowerShell-master/.github/workflows/scorecards.yml @@ -0,0 +1,72 @@ +# This workflow uses actions that are not certified by GitHub. They are provided +# by a third-party and are governed by separate terms of service, privacy +# policy, and support documentation. + +name: Scorecard supply-chain security +on: + # For Branch-Protection check. Only the default branch is supported. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection + branch_protection_rule: + # To guarantee Maintained check is occasionally updated. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained + schedule: + - cron: '20 7 * * 2' + push: + branches: ["master"] + +# Declare default permissions as read only. +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + if: github.repository_owner == 'PowerShell' + runs-on: ubuntu-latest + permissions: + # Needed to upload the results to code-scanning dashboard. + security-events: write + # Needed to publish results and get a badge (see publish_results below). + id-token: write + contents: read + actions: read + + steps: + - name: "Checkout code" + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: "Run analysis" + uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3 + with: + results_file: results.sarif + results_format: sarif + # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: + # - you want to enable the Branch-Protection check on a *public* repository, or + # - you are installing Scorecards on a *private* repository + # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. + # repo_token: ${{ secrets.SCORECARD_TOKEN }} + + # Public repositories: + # - Publish results to OpenSSF REST API for easy access by consumers + # - Allows the repository to include the Scorecard badge. + # - See https://github.com/ossf/scorecard-action#publishing-results. + # For private repositories: + # - `publish_results` will always be set to `false`, regardless + # of the value entered here. + publish_results: true + + # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF + # format to the repository Actions tab. + - name: "Upload artifact" + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + + # Upload the results to GitHub's code scanning dashboard. + - name: "Upload to code-scanning" + uses: github/codeql-action/upload-sarif@c10b8064de6f491fea524254123dbe5e09572f13 # v3.29.5 + with: + sarif_file: results.sarif diff --git a/PowerShell-master/.github/workflows/verify-markdown-links.yml b/PowerShell-master/.github/workflows/verify-markdown-links.yml new file mode 100644 index 0000000000000000000000000000000000000000..19da648a959b43773cf3b2ab5fc661f21417c478 --- /dev/null +++ b/PowerShell-master/.github/workflows/verify-markdown-links.yml @@ -0,0 +1,32 @@ +name: Verify Markdown Links + +on: + push: + branches: [ main, master ] + paths: + - '**/*.md' + - '.github/workflows/verify-markdown-links.yml' + - '.github/actions/infrastructure/markdownlinks/**' + pull_request: + branches: [ main, master ] + paths: + - '**/*.md' + schedule: + # Run weekly on Sundays at midnight UTC to catch external link rot + - cron: '0 0 * * 0' + workflow_dispatch: + +jobs: + verify-markdown-links: + name: Verify Markdown Links + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Verify markdown links + id: verify + uses: ./.github/actions/infrastructure/markdownlinks + with: + timeout-sec: 30 + maximum-retry-count: 2 diff --git a/PowerShell-master/.github/workflows/windows-ci.yml b/PowerShell-master/.github/workflows/windows-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..8a57b8b97263e5975f625f3cb152c006d698a7d2 --- /dev/null +++ b/PowerShell-master/.github/workflows/windows-ci.yml @@ -0,0 +1,194 @@ +name: Windows-CI +on: + workflow_dispatch: + push: + branches: + - master + - release/** + - github-mirror + paths: + - "**" + - "*" + - ".globalconfig" + - "!.vsts-ci/misc-analysis.yml" + - "!.github/ISSUE_TEMPLATE/**" + - "!.dependabot/config.yml" + - "!test/perf/**" + - "!.pipelines/**" + pull_request: + branches: + - master + - release/** + - github-mirror + - "*-feature" + +# Path filters for PRs need to go into the changes job + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: ${{ contains(github.ref, 'merge')}} + +permissions: + contents: read + +run-name: "${{ github.ref_name }} - ${{ github.run_number }}" + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" + NugetSecurityAnalysisWarningLevel: none + POWERSHELL_TELEMETRY_OPTOUT: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + SYSTEM_ARTIFACTSDIRECTORY: ${{ github.workspace }}/artifacts + BUILD_ARTIFACTSTAGINGDIRECTORY: ${{ github.workspace }}/artifacts +jobs: + changes: + name: Change Detection + runs-on: ubuntu-latest + if: startsWith(github.repository_owner, 'azure') || github.repository_owner == 'PowerShell' + # Required permissions + permissions: + pull-requests: read + contents: read + + # Set job outputs to values from filter step + outputs: + source: ${{ steps.filter.outputs.source }} + buildModuleChanged: ${{ steps.filter.outputs.buildModuleChanged }} + packagingChanged: ${{ steps.filter.outputs.packagingChanged }} + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Change Detection + id: filter + uses: "./.github/actions/infrastructure/path-filters" + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + ci_build: + name: Build PowerShell + needs: changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: windows-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Build + uses: "./.github/actions/build/ci" + windows_test_unelevated_ci: + name: Windows Unelevated CI + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: windows-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Windows Unelevated CI + uses: "./.github/actions/test/windows" + with: + purpose: UnelevatedPesterTests + tagSet: CI + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + windows_test_elevated_ci: + name: Windows Elevated CI + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: windows-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Windows Elevated CI + uses: "./.github/actions/test/windows" + with: + purpose: ElevatedPesterTests + tagSet: CI + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + windows_test_unelevated_others: + name: Windows Unelevated Others + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: windows-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Windows Unelevated Others + uses: "./.github/actions/test/windows" + with: + purpose: UnelevatedPesterTests + tagSet: Others + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + windows_test_elevated_others: + name: Windows Elevated Others + needs: + - ci_build + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + runs-on: windows-latest + steps: + - name: checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + - name: Windows Elevated Others + uses: "./.github/actions/test/windows" + with: + purpose: ElevatedPesterTests + tagSet: Others + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + xunit_tests: + name: xUnit Tests + needs: + - changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + uses: ./.github/workflows/xunit-tests.yml + with: + runner_os: windows-latest + test_results_artifact_name: testResults-xunit + analyze: + name: CodeQL Analysis + needs: changes + if: ${{ needs.changes.outputs.source == 'true' || needs.changes.outputs.buildModuleChanged == 'true' }} + uses: ./.github/workflows/analyze-reusable.yml + permissions: + actions: read + contents: read + security-events: write + with: + runner_os: windows-latest + windows_packaging: + name: Windows Packaging + needs: + - changes + if: ${{ needs.changes.outputs.packagingChanged == 'true' }} + uses: ./.github/workflows/windows-packaging-reusable.yml + ready_to_merge: + name: windows ready to merge + needs: + - xunit_tests + - windows_test_elevated_ci + - windows_test_elevated_others + - windows_test_unelevated_ci + - windows_test_unelevated_others + - analyze + - windows_packaging + if: always() + uses: PowerShell/compliance/.github/workflows/ready-to-merge.yml@c8b3ad5819ad7078f3e375519b4f8c6232d1cbdf # v1.0.0 + with: + needs_context: ${{ toJson(needs) }} diff --git a/PowerShell-master/.github/workflows/windows-packaging-reusable.yml b/PowerShell-master/.github/workflows/windows-packaging-reusable.yml new file mode 100644 index 0000000000000000000000000000000000000000..8d0255d4443d120a96bcf5a159b9428b628dd3bf --- /dev/null +++ b/PowerShell-master/.github/workflows/windows-packaging-reusable.yml @@ -0,0 +1,92 @@ +name: Windows Packaging (Reusable) + +on: + workflow_call: + +env: + GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + SYSTEM_ARTIFACTSDIRECTORY: ${{ github.workspace }}/artifacts + BUILD_ARTIFACTSTAGINGDIRECTORY: ${{ github.workspace }}/artifacts + +permissions: + contents: read + +jobs: + package: + name: ${{ matrix.architecture }} - ${{ matrix.channel }} + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + include: + - architecture: x64 + channel: preview + runtimePrefix: win7 + - architecture: x86 + channel: stable + runtimePrefix: win7 + - architecture: x86 + channel: preview + runtimePrefix: win7 + - architecture: arm64 + channel: preview + runtimePrefix: win + + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + + - name: Capture Environment + if: success() || failure() + run: | + Import-Module .\tools\ci.psm1 + Show-Environment + shell: pwsh + + - name: Capture PowerShell Version Table + if: success() || failure() + run: | + $PSVersionTable + shell: pwsh + + - name: Switch to Public Feeds + if: success() + run: | + Import-Module .\tools\ci.psm1 + Switch-PSNugetConfig -Source Public + shell: pwsh + + - name: Setup .NET + uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5.2.0 + with: + global-json-file: ./global.json + + - name: Bootstrap + if: success() + run: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + shell: pwsh + + - name: Build and Package + run: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + Invoke-CIFinish -Runtime ${{ matrix.runtimePrefix }}-${{ matrix.architecture }} -channel ${{ matrix.channel }} + shell: pwsh + + - name: Upload Build Artifacts + if: always() + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: windows-packaging-${{ matrix.architecture }}-${{ matrix.channel }} + path: | + ${{ github.workspace }}/artifacts/**/* + !${{ github.workspace }}/artifacts/**/*.pdb diff --git a/PowerShell-master/.github/workflows/xunit-tests.yml b/PowerShell-master/.github/workflows/xunit-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..c643917edd044fbfc8d92542b0eac6419f3bbbdc --- /dev/null +++ b/PowerShell-master/.github/workflows/xunit-tests.yml @@ -0,0 +1,56 @@ +name: xUnit Tests (Reusable) + +on: + workflow_call: + inputs: + runner_os: + description: 'Runner OS for xUnit tests' + type: string + required: false + default: ubuntu-latest + test_results_artifact_name: + description: 'Artifact name for xUnit test results directory' + type: string + required: false + default: testResults-xunit + +permissions: + contents: read + +jobs: + xunit: + name: Run xUnit Tests + runs-on: ${{ inputs.runner_os }} + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 1000 + + - name: Setup .NET + uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5.2.0 + with: + global-json-file: ./global.json + + - name: Bootstrap + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Invoke-CIInstall -SkipUser + Sync-PSTags -AddRemoteIfMissing + + - name: Build PowerShell and run xUnit tests + shell: pwsh + run: | + Import-Module ./tools/ci.psm1 + Start-PSBuild + Write-Host "Running full xUnit test suite (no skipping)..." + Invoke-CIxUnit + Write-Host "Completed xUnit test run." + + - name: Upload xUnit results + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + if: always() + with: + name: ${{ inputs.test_results_artifact_name }} + path: ${{ github.workspace }}/xUnitTestResults.xml diff --git a/PowerShell-master/.gitignore b/PowerShell-master/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..48556cf1b8c5fa134c37d83db208ae7ab6b0c39d --- /dev/null +++ b/PowerShell-master/.gitignore @@ -0,0 +1,126 @@ +bin/ +obj/ +.ionide/ +project.lock.json +*-tests.xml +/debug/ +/staging/ +/Packages/ +*.nuget.props + +# dotnet cli install/uninstall scripts +dotnet-install.ps1 +dotnet-install.sh +dotnet-install.sh.* +dotnet-uninstall-pkgs.sh +dotnet-uninstall-debian-packages.sh + +# VS auto-generated solution files for project.json solutions +*.xproj +*.xproj.user +*.suo + +# VS auto-generated files for csproj files +*.csproj.user + +# Visual Studio IDE directory +.vs/ + +# VSCode directories that are not at the repository root +/**/.vscode/ + +# Project Rider IDE files +.idea.powershell/ + +# Ignore executables +*.exe +*.msi +*.appx +*.msix + +# Ignore binaries and symbols +*.pdb +*.dll +*.wixpdb + +# Ignore packages +*.deb +*.tar.gz +*.zip +*.rpm +*.pkg +*.nupkg +*.AppImage + +# default location for produced nuget packages +/nuget-artifacts + +# resgen output +gen + +# Per repo profile +.profile.ps1 + +# macOS +.DS_Store +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk +.AppleDouble +.LSOverride + +# TestsResults +TestsResults*.xml +ParallelXUnitResults.xml +xUnitResults.xml + +# Attack Surface Analyzer results +asa-results/ + +# Resharper settings +PowerShell.sln.DotSettings.user +*.msp +StyleCop.Cache + +# Ignore SelfSignedCertificate autogenerated files +test/tools/Modules/SelfSignedCertificate/ + +# BenchmarkDotNet artifacts +test/perf/BenchmarkDotNet.Artifacts/ + +# Test generated module +test/tools/Modules/Microsoft.PowerShell.NamedPipeConnection/ + +# Test generated startup profile +StartupProfileData-NonInteractive + +# Ignore logfiles +logfile/* + +# Ignore nuget.config because it is dynamically generated +nuget.config + +# Ignore MSBuild Binary Logs +msbuild.binlog + +# Ignore gzip files in the manpage folder +assets/manpage/*.gz + +# Ignore files and folders generated by some gh cli extensions +tmp/* +.env.local + +# Pester test failure analysis results (generated by analyze-pr-test-failures.ps1) +**/pester-analysis-*/ + +# Ignore CTRF report files +crtf/* diff --git a/PowerShell-master/.globalconfig b/PowerShell-master/.globalconfig new file mode 100644 index 0000000000000000000000000000000000000000..e0dd4ccb9e56c8e9d6b7bccfc5183a1484bfe948 --- /dev/null +++ b/PowerShell-master/.globalconfig @@ -0,0 +1,2293 @@ +is_global = true + +# CA1000: Do not declare static members on generic types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1000 +dotnet_diagnostic.CA1000.severity = warning +dotnet_code_quality.CA1000.api_surface = all + +# CA1001: Types that own disposable fields should be disposable +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1001 +dotnet_diagnostic.CA1001.severity = silent + +# CA1002: Do not expose generic lists +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1002 +dotnet_diagnostic.CA1002.severity = none + +# CA1003: Use generic event handler instances +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1003 +dotnet_diagnostic.CA1003.severity = warning +dotnet_code_quality.CA1003.api_surface = private, internal + +# CA1005: Avoid excessive parameters on generic types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1005 +dotnet_diagnostic.CA1005.severity = none + +# CA1008: Enums should have zero value +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1008 +dotnet_diagnostic.CA1008.severity = none +dotnet_code_quality.CA1008.api_surface = public + +# CA1010: Generic interface should also be implemented +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1010 +dotnet_diagnostic.CA1010.severity = silent +dotnet_code_quality.CA1010.api_surface = public + +# CA1012: Abstract types should not have public constructors +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1012 +dotnet_diagnostic.CA1012.severity = warning +dotnet_code_quality.CA1012.api_surface = all + +# CA1014: Mark assemblies with CLSCompliant +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1014 +dotnet_diagnostic.CA1014.severity = none + +# CA1016: Mark assemblies with assembly version +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1016 +dotnet_diagnostic.CA1016.severity = warning + +# CA1017: Mark assemblies with ComVisible +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1017 +dotnet_diagnostic.CA1017.severity = none + +# CA1018: Mark attributes with AttributeUsageAttribute +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1018 +dotnet_diagnostic.CA1018.severity = warning + +# CA1019: Define accessors for attribute arguments +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1019 +dotnet_diagnostic.CA1019.severity = none + +# CA1021: Avoid out parameters +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1021 +dotnet_diagnostic.CA1021.severity = none + +# CA1024: Use properties where appropriate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1024 +dotnet_diagnostic.CA1024.severity = none +dotnet_code_quality.CA1024.api_surface = public + +# CA1027: Mark enums with FlagsAttribute +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1027 +dotnet_diagnostic.CA1027.severity = none +dotnet_code_quality.CA1027.api_surface = public + +# CA1028: Enum Storage should be Int32 +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1028 +dotnet_diagnostic.CA1028.severity = none +dotnet_code_quality.CA1028.api_surface = public + +# CA1030: Use events where appropriate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1030 +dotnet_diagnostic.CA1030.severity = none +dotnet_code_quality.CA1030.api_surface = public + +# CA1031: Do not catch general exception types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1031 +dotnet_diagnostic.CA1031.severity = none + +# CA1032: Implement standard exception constructors +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1032 +dotnet_diagnostic.CA1032.severity = none + +# CA1033: Interface methods should be callable by child types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1033 +dotnet_diagnostic.CA1033.severity = none + +# CA1034: Nested types should not be visible +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1034 +dotnet_diagnostic.CA1034.severity = none + +# CA1036: Override methods on comparable types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1036 +dotnet_diagnostic.CA1036.severity = silent +dotnet_code_quality.CA1036.api_surface = public + +# CA1040: Avoid empty interfaces +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1040 +dotnet_diagnostic.CA1040.severity = none +dotnet_code_quality.CA1040.api_surface = public + +# CA1041: Provide ObsoleteAttribute message +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1041 +dotnet_diagnostic.CA1041.severity = warning +dotnet_code_quality.CA1041.api_surface = public + +# CA1043: Use Integral Or String Argument For Indexers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1043 +dotnet_diagnostic.CA1043.severity = warning +dotnet_code_quality.CA1043.api_surface = all + +# CA1044: Properties should not be write only +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1044 +dotnet_diagnostic.CA1044.severity = none +dotnet_code_quality.CA1044.api_surface = public + +# CA1045: Do not pass types by reference +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1045 +dotnet_diagnostic.CA1045.severity = none + +# CA1046: Do not overload equality operator on reference types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1046 +dotnet_diagnostic.CA1046.severity = none + +# CA1047: Do not declare protected member in sealed type +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1047 +dotnet_diagnostic.CA1047.severity = warning + +# CA1050: Declare types in namespaces +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1050 +dotnet_diagnostic.CA1050.severity = warning + +# CA1051: Do not declare visible instance fields +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1051 +dotnet_diagnostic.CA1051.severity = silent +dotnet_code_quality.CA1051.api_surface = public + +# CA1052: Static holder types should be Static or NotInheritable +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1052 +dotnet_diagnostic.CA1052.severity = warning +dotnet_code_quality.CA1052.api_surface = all + +# CA1054: URI-like parameters should not be strings +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1054 +dotnet_diagnostic.CA1054.severity = none +dotnet_code_quality.CA1054.api_surface = public + +# CA1055: URI-like return values should not be strings +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1055 +dotnet_diagnostic.CA1055.severity = none +dotnet_code_quality.CA1055.api_surface = public + +# CA1056: URI-like properties should not be strings +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1056 +dotnet_diagnostic.CA1056.severity = none +dotnet_code_quality.CA1056.api_surface = public + +# CA1058: Types should not extend certain base types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1058 +dotnet_diagnostic.CA1058.severity = none +dotnet_code_quality.CA1058.api_surface = public + +# CA1060: Move pinvokes to native methods class +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1060 +dotnet_diagnostic.CA1060.severity = none + +# CA1061: Do not hide base class methods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1061 +dotnet_diagnostic.CA1061.severity = warning + +# CA1062: Validate arguments of public methods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1062 +dotnet_diagnostic.CA1062.severity = none + +# CA1063: Implement IDisposable Correctly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1063 +dotnet_diagnostic.CA1063.severity = none +dotnet_code_quality.CA1063.api_surface = public + +# CA1064: Exceptions should be public +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1064 +dotnet_diagnostic.CA1064.severity = none + +# CA1065: Do not raise exceptions in unexpected locations +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1065 +dotnet_diagnostic.CA1065.severity = warning + +# CA1066: Implement IEquatable when overriding Object.Equals +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1066 +dotnet_diagnostic.CA1066.severity = none + +# CA1067: Override Object.Equals(object) when implementing IEquatable +# # https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1067 +dotnet_diagnostic.CA1067.severity = warning + +# CA1068: CancellationToken parameters must come last +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1068 +dotnet_diagnostic.CA1068.severity = warning + +# CA1069: Enums values should not be duplicated +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1069 +dotnet_diagnostic.CA1069.severity = suggestion + +# CA1070: Do not declare event fields as virtual +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1070 +dotnet_diagnostic.CA1070.severity = warning + +# CA1200: Avoid using cref tags with a prefix +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1200 +dotnet_diagnostic.CA1200.severity = warning + +# CA1303: Do not pass literals as localized parameters +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1303 +dotnet_diagnostic.CA1303.severity = none + +# CA1304: Specify CultureInfo +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1304 +dotnet_diagnostic.CA1304.severity = silent + +# CA1305: Specify IFormatProvider +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1305 +dotnet_diagnostic.CA1305.severity = silent + +# CA1307: Specify StringComparison for clarity +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1307 +dotnet_diagnostic.CA1307.severity = none + +# CA1308: Normalize strings to uppercase +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1308 +dotnet_diagnostic.CA1308.severity = none + +# CA1309: Use ordinal string comparison +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1309 +dotnet_diagnostic.CA1309.severity = silent + +# CA1310: Specify StringComparison for correctness +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1310 +dotnet_diagnostic.CA1310.severity = silent + +# CA1401: P/Invokes should not be visible +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1401 +dotnet_diagnostic.CA1401.severity = warning + +# CA1416: Validate platform compatibility +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1416 +dotnet_diagnostic.CA1416.severity = warning + +# CA1417: Do not use 'OutAttribute' on string parameters for P/Invokes +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1417 +dotnet_diagnostic.CA1417.severity = warning + +# CA1418: Use valid platform string +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1418 +dotnet_diagnostic.CA1418.severity = warning + +# CA1501: Avoid excessive inheritance +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1501 +dotnet_diagnostic.CA1501.severity = none + +# CA1502: Avoid excessive complexity +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1502 +dotnet_diagnostic.CA1502.severity = none + +# CA1505: Avoid unmaintainable code +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1505 +dotnet_diagnostic.CA1505.severity = none + +# CA1506: Avoid excessive class coupling +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1506 +dotnet_diagnostic.CA1506.severity = none + +# CA1507: Use nameof to express symbol names +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1507 +dotnet_diagnostic.CA1507.severity = suggestion + +# CA1508: Avoid dead conditional code +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1508 +dotnet_diagnostic.CA1508.severity = none + +# CA1509: Invalid entry in code metrics rule specification file +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1509 +dotnet_diagnostic.CA1509.severity = none + +# CA1700: Do not name enum values 'Reserved' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1700 +dotnet_diagnostic.CA1700.severity = none + +# CA1707: Identifiers should not contain underscores +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1707 +dotnet_diagnostic.CA1707.severity = silent + +# CA1708: Identifiers should differ by more than case +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1708 +dotnet_diagnostic.CA1708.severity = silent +dotnet_code_quality.CA1708.api_surface = public + +# CA1710: Identifiers should have correct suffix +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1710 +dotnet_diagnostic.CA1710.severity = silent +dotnet_code_quality.CA1710.api_surface = public + +# CA1711: Identifiers should not have incorrect suffix +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1711 +dotnet_diagnostic.CA1711.severity = silent +dotnet_code_quality.CA1711.api_surface = public + +# CA1712: Do not prefix enum values with type name +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1712 +dotnet_diagnostic.CA1712.severity = silent + +# CA1713: Events should not have 'Before' or 'After' prefix +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1713 +dotnet_diagnostic.CA1713.severity = none + +# CA1715: Identifiers should have correct prefix +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1715 +dotnet_diagnostic.CA1715.severity = silent +dotnet_code_quality.CA1715.api_surface = public + +# CA1716: Identifiers should not match keywords +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1716 +dotnet_diagnostic.CA1716.severity = silent +dotnet_code_quality.CA1716.api_surface = public + +# CA1720: Identifier contains type name +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1720 +dotnet_diagnostic.CA1720.severity = silent +dotnet_code_quality.CA1720.api_surface = public + +# CA1721: Property names should not match get methods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1721 +dotnet_diagnostic.CA1721.severity = none +dotnet_code_quality.CA1721.api_surface = public + +# CA1724: Type names should not match namespaces +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1724 +dotnet_diagnostic.CA1724.severity = none + +# CA1725: Parameter names should match base declaration +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1725 +dotnet_diagnostic.CA1725.severity = silent +dotnet_code_quality.CA1725.api_surface = public + +# CA1801: Review unused parameters +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1801 +dotnet_diagnostic.CA1801.severity = none +dotnet_code_quality.CA1801.api_surface = all + +# CA1802: Use literals where appropriate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1802 +dotnet_diagnostic.CA1802.severity = none +dotnet_code_quality.CA1802.api_surface = public + +# CA1805: Do not initialize unnecessarily +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1805 +dotnet_diagnostic.CA1805.severity = suggestion + +# CA1806: Do not ignore method results +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1806 +dotnet_diagnostic.CA1806.severity = suggestion + +# CA1810: Initialize reference type static fields inline +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1810 +dotnet_diagnostic.CA1810.severity = none + +# CA1812: Avoid uninstantiated internal classes +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812 +dotnet_diagnostic.CA1812.severity = warning + +# CA1813: Avoid unsealed attributes +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1813 +dotnet_diagnostic.CA1813.severity = none + +# CA1814: Prefer jagged arrays over multidimensional +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1814 +dotnet_diagnostic.CA1814.severity = none + +# CA1815: Override equals and operator equals on value types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815 +dotnet_diagnostic.CA1815.severity = none +dotnet_code_quality.CA1815.api_surface = public + +# CA1816: Dispose methods should call SuppressFinalize +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1816 +dotnet_diagnostic.CA1816.severity = warning + +# CA1819: Properties should not return arrays +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1819 +dotnet_diagnostic.CA1819.severity = none +dotnet_code_quality.CA1819.api_surface = public + +# CA1820: Test for empty strings using string length +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1820 +dotnet_diagnostic.CA1820.severity = none + +# CA1821: Remove empty Finalizers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1821 +dotnet_diagnostic.CA1821.severity = warning + +# CA1822: Mark members as static +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822 +dotnet_diagnostic.CA1822.severity = warning +dotnet_code_quality.CA1822.api_surface = private + +# CA1823: Avoid unused private fields +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1823 +dotnet_diagnostic.CA1823.severity = none + +# CA1824: Mark assemblies with NeutralResourcesLanguageAttribute +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1824 +dotnet_diagnostic.CA1824.severity = warning + +# CA1825: Avoid zero-length array allocations +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1825 +dotnet_diagnostic.CA1825.severity = warning + +# CA1826: Do not use Enumerable methods on indexable collections +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1826 +dotnet_diagnostic.CA1826.severity = warning + +# CA1827: Do not use Count() or LongCount() when Any() can be used +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1827 +dotnet_diagnostic.CA1827.severity = warning + +# CA1828: Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1828 +dotnet_diagnostic.CA1828.severity = warning + +# CA1829: Use Length/Count property instead of Count() when available +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1829 +dotnet_diagnostic.CA1829.severity = warning + +# CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1830 +dotnet_diagnostic.CA1830.severity = warning + +# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1831 +dotnet_diagnostic.CA1831.severity = warning + +# CA1832: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1832 +dotnet_diagnostic.CA1832.severity = warning + +# CA1833: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1833 +dotnet_diagnostic.CA1833.severity = warning + +# CA1834: Consider using 'StringBuilder.Append(char)' when applicable +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1834 +dotnet_diagnostic.CA1834.severity = warning + +# CA1835: Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1835 +dotnet_diagnostic.CA1835.severity = suggestion + +# CA1836: Prefer IsEmpty over Count +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1836 +dotnet_diagnostic.CA1836.severity = warning + +# CA1837: Use 'Environment.ProcessId' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1837 +dotnet_diagnostic.CA1837.severity = warning + +# CA1838: Avoid 'StringBuilder' parameters for P/Invokes +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1838 +dotnet_diagnostic.CA1838.severity = silent + +# CA1839: Use 'Environment.ProcessPath' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1839 +dotnet_diagnostic.CA1839.severity = warning + +# CA1840: Use 'Environment.CurrentManagedThreadId' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1840 +dotnet_diagnostic.CA1840.severity = warning + +# CA1841: Prefer Dictionary.Contains methods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1841 +dotnet_diagnostic.CA1841.severity = warning + +# CA1842: Do not use 'WhenAll' with a single task +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1842 +dotnet_diagnostic.CA1842.severity = warning + +# CA1843: Do not use 'WaitAll' with a single task +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1843 +dotnet_diagnostic.CA1843.severity = warning + +# CA1844: Provide memory-based overrides of async methods when subclassing 'Stream' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1844 +dotnet_diagnostic.CA1844.severity = warning + +# CA1845: Use span-based 'string.Concat' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1845 +dotnet_diagnostic.CA1845.severity = warning + +# CA1846: Prefer 'AsSpan' over 'Substring' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1846 +dotnet_diagnostic.CA1846.severity = warning + +# CA1847: Use char literal for a single character lookup +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1847 +dotnet_diagnostic.CA1847.severity = warning + +# CA1852: Seal internal types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1852 +dotnet_diagnostic.CA1852.severity = warning + +# CA1853: Unnecessary call to 'Dictionary.ContainsKey(key)' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1853 +dotnet_diagnostic.CA1853.severity = warning + +# CA1858: Use 'StartsWith' instead of 'IndexOf' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1858 +dotnet_diagnostic.CA1858.severity = warning + +# CA1860: Avoid using 'Enumerable.Any()' extension method +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1860 +dotnet_diagnostic.CA1860.severity = warning + +# CA1865: Use char overload +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1865 +dotnet_diagnostic.CA1865.severity = warning + +# CA1866: Use char overload +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1866 +dotnet_diagnostic.CA1866.severity = warning + +# CA1867: Use char overload +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1867 +dotnet_diagnostic.CA1867.severity = warning + +# CA1868: Unnecessary call to 'Contains' for sets +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1868 +dotnet_diagnostic.CA1868.severity = warning + +# CA2000: Dispose objects before losing scope +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2000 +dotnet_diagnostic.CA2000.severity = none + +# CA2002: Do not lock on objects with weak identity +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2002 +dotnet_diagnostic.CA2002.severity = none + +# CA2007: Consider calling ConfigureAwait on the awaited task +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2007 +dotnet_diagnostic.CA2007.severity = none + +# CA2008: Do not create tasks without passing a TaskScheduler +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2008 +dotnet_diagnostic.CA2008.severity = none + +# CA2009: Do not call ToImmutableCollection on an ImmutableCollection value +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2009 +dotnet_diagnostic.CA2009.severity = warning + +# CA2011: Avoid infinite recursion +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2011 +dotnet_diagnostic.CA2011.severity = warning + +# CA2012: Use ValueTasks correctly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2012 +dotnet_diagnostic.CA2012.severity = warning + +# CA2013: Do not use ReferenceEquals with value types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2013 +dotnet_diagnostic.CA2013.severity = warning + +# CA2014: Do not use stackalloc in loops +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2014 +dotnet_diagnostic.CA2014.severity = warning + +# CA2015: Do not define finalizers for types derived from MemoryManager +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2015 +dotnet_diagnostic.CA2015.severity = warning + +# CA2016: Forward the 'CancellationToken' parameter to methods that take one +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2016 +dotnet_diagnostic.CA2016.severity = suggestion + +# CA2021: Do not call Enumerable.Cast or Enumerable.OfType with incompatible types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2021 +dotnet_diagnostic.CA2021.severity = warning + +# CA2022: Avoid inexact read with 'Stream.Read' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2022 +dotnet_diagnostic.CA2022.severity = warning + +# CA2100: Review SQL queries for security vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100 +dotnet_diagnostic.CA2100.severity = none + +# CA2101: Specify marshaling for P/Invoke string arguments +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2101 +dotnet_diagnostic.CA2101.severity = suggestion + +# CA2109: Review visible event handlers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2109 +dotnet_diagnostic.CA2109.severity = none + +# CA2119: Seal methods that satisfy private interfaces +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2119 +dotnet_diagnostic.CA2119.severity = none + +# CA2153: Do Not Catch Corrupted State Exceptions +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2153 +dotnet_diagnostic.CA2153.severity = none + +# CA2200: Rethrow to preserve stack details +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2200 +dotnet_diagnostic.CA2200.severity = warning + +# CA2201: Do not raise reserved exception types +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2201 +dotnet_diagnostic.CA2201.severity = silent + +# CA2207: Initialize value type static fields inline +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2207 +dotnet_diagnostic.CA2207.severity = warning + +# CA2208: Instantiate argument exceptions correctly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2208 +dotnet_diagnostic.CA2208.severity = suggestion +dotnet_code_quality.CA2208.api_surface = all + +# CA2211: Non-constant fields should not be visible +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2211 +dotnet_diagnostic.CA2211.severity = warning + +# CA2213: Disposable fields should be disposed +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2213 +dotnet_diagnostic.CA2213.severity = none + +# CA2214: Do not call overridable methods in constructors +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2214 +dotnet_diagnostic.CA2214.severity = none + +# CA2215: Dispose methods should call base class dispose +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2215 +dotnet_diagnostic.CA2215.severity = silent + +# CA2216: Disposable types should declare finalizer +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2216 +dotnet_diagnostic.CA2216.severity = warning + +# CA2217: Do not mark enums with FlagsAttribute +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2217 +dotnet_diagnostic.CA2217.severity = none +dotnet_code_quality.CA2217.api_surface = public + +# CA2218: Override GetHashCode on overriding Equals +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2218 +dotnet_diagnostic.CA2218.severity = suggestion + +# CA2219: Do not raise exceptions in finally clauses +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2219 +dotnet_diagnostic.CA2219.severity = suggestion + +# CA2224: Override Equals on overloading operator equals +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2224 +dotnet_diagnostic.CA2224.severity = suggestion + +# CA2225: Operator overloads have named alternates +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2225 +dotnet_diagnostic.CA2225.severity = none +dotnet_code_quality.CA2225.api_surface = public + +# CA2226: Operators should have symmetrical overloads +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2226 +dotnet_diagnostic.CA2226.severity = none +dotnet_code_quality.CA2226.api_surface = public + +# CA2227: Collection properties should be read only +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2227 +dotnet_diagnostic.CA2227.severity = none + +# CA2229: Implement serialization constructors +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2229 +dotnet_diagnostic.CA2229.severity = silent + +# CA2231: Overload operator equals on overriding value type Equals +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2231 +dotnet_diagnostic.CA2231.severity = suggestion +dotnet_code_quality.CA2231.api_surface = public + +# CA2234: Pass system uri objects instead of strings +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2234 +dotnet_diagnostic.CA2234.severity = none +dotnet_code_quality.CA2234.api_surface = public + +# CA2235: Mark all non-serializable fields +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2235 +dotnet_diagnostic.CA2235.severity = none + +# CA2237: Mark ISerializable types with serializable +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2237 +dotnet_diagnostic.CA2237.severity = none + +# CA2241: Provide correct arguments to formatting methods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2241 +dotnet_diagnostic.CA2241.severity = suggestion + +# CA2242: Test for NaN correctly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2242 +dotnet_diagnostic.CA2242.severity = suggestion + +# CA2243: Attribute string literals should parse correctly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2243 +dotnet_diagnostic.CA2243.severity = warning + +# CA2244: Do not duplicate indexed element initializations +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2244 +dotnet_diagnostic.CA2244.severity = suggestion + +# CA2245: Do not assign a property to itself +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2245 +dotnet_diagnostic.CA2245.severity = suggestion + +# CA2246: Assigning symbol and its member in the same statement +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2246 +dotnet_diagnostic.CA2246.severity = suggestion + +# CA2247: Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2247 +dotnet_diagnostic.CA2247.severity = warning + +# CA2248: Provide correct 'enum' argument to 'Enum.HasFlag' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2248 +dotnet_diagnostic.CA2248.severity = suggestion + +# CA2249: Consider using 'string.Contains' instead of 'string.IndexOf' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2249 +dotnet_diagnostic.CA2249.severity = warning + +# CA2250: Use 'ThrowIfCancellationRequested' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2250 +dotnet_diagnostic.CA2250.severity = warning + +# CA2251: Use 'string.Equals' +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2251 +dotnet_diagnostic.CA2251.severity = warning + +# CA2252: This API requires opting into preview features +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2252 +dotnet_diagnostic.CA2251.severity = none + +# CA2300: Do not use insecure deserializer BinaryFormatter +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2300 +dotnet_diagnostic.CA2300.severity = none + +# CA2301: Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2301 +dotnet_diagnostic.CA2301.severity = none + +# CA2302: Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2302 +dotnet_diagnostic.CA2302.severity = none + +# CA2305: Do not use insecure deserializer LosFormatter +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2305 +dotnet_diagnostic.CA2305.severity = none + +# CA2310: Do not use insecure deserializer NetDataContractSerializer +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2310 +dotnet_diagnostic.CA2310.severity = none + +# CA2311: Do not deserialize without first setting NetDataContractSerializer.Binder +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2311 +dotnet_diagnostic.CA2311.severity = none + +# CA2312: Ensure NetDataContractSerializer.Binder is set before deserializing +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2312 +dotnet_diagnostic.CA2312.severity = none + +# CA2315: Do not use insecure deserializer ObjectStateFormatter +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2315 +dotnet_diagnostic.CA2315.severity = none + +# CA2321: Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2321 +dotnet_diagnostic.CA2321.severity = none + +# CA2322: Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2322 +dotnet_diagnostic.CA2322.severity = none + +# CA2326: Do not use TypeNameHandling values other than None +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2326 +dotnet_diagnostic.CA2326.severity = none + +# CA2327: Do not use insecure JsonSerializerSettings +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2327 +dotnet_diagnostic.CA2327.severity = none + +# CA2328: Ensure that JsonSerializerSettings are secure +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2328 +dotnet_diagnostic.CA2328.severity = none + +# CA2329: Do not deserialize with JsonSerializer using an insecure configuration +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2329 +dotnet_diagnostic.CA2329.severity = none + +# CA2330: Ensure that JsonSerializer has a secure configuration when deserializing +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2330 +dotnet_diagnostic.CA2330.severity = none + +# CA2350: Do not use DataTable.ReadXml() with untrusted data +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2350 +dotnet_diagnostic.CA2350.severity = none + +# CA2351: Do not use DataSet.ReadXml() with untrusted data +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2351 +dotnet_diagnostic.CA2351.severity = none + +# CA2352: Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2352 +dotnet_diagnostic.CA2352.severity = none + +# CA2353: Unsafe DataSet or DataTable in serializable type +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2353 +dotnet_diagnostic.CA2353.severity = none + +# CA2354: Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2354 +dotnet_diagnostic.CA2354.severity = none + +# CA2355: Unsafe DataSet or DataTable type found in deserializable object graph +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2355 +dotnet_diagnostic.CA2355.severity = none + +# CA2356: Unsafe DataSet or DataTable type in web deserializable object graph +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2356 +dotnet_diagnostic.CA2356.severity = none + +# CA2361: Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2361 +dotnet_diagnostic.CA2361.severity = none + +# CA2362: Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2362 +dotnet_diagnostic.CA2362.severity = none + +# CA3001: Review code for SQL injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3001 +dotnet_diagnostic.CA3001.severity = none + +# CA3002: Review code for XSS vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3002 +dotnet_diagnostic.CA3002.severity = none + +# CA3003: Review code for file path injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3003 +dotnet_diagnostic.CA3003.severity = none + +# CA3004: Review code for information disclosure vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3004 +dotnet_diagnostic.CA3004.severity = none + +# CA3005: Review code for LDAP injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3005 +dotnet_diagnostic.CA3005.severity = none + +# CA3006: Review code for process command injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3006 +dotnet_diagnostic.CA3006.severity = none + +# CA3007: Review code for open redirect vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3007 +dotnet_diagnostic.CA3007.severity = none + +# CA3008: Review code for XPath injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3008 +dotnet_diagnostic.CA3008.severity = none + +# CA3009: Review code for XML injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3009 +dotnet_diagnostic.CA3009.severity = none + +# CA3010: Review code for XAML injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3010 +dotnet_diagnostic.CA3010.severity = none + +# CA3011: Review code for DLL injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3011 +dotnet_diagnostic.CA3011.severity = none + +# CA3012: Review code for regex injection vulnerabilities +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3012 +dotnet_diagnostic.CA3012.severity = none + +# CA3061: Do Not Add Schema By URL +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3061 +dotnet_diagnostic.CA3061.severity = silent + +# CA3075: Insecure DTD processing in XML +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3075 +dotnet_diagnostic.CA3075.severity = silent + +# CA3076: Insecure XSLT script processing. +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3076 +dotnet_diagnostic.CA3076.severity = silent + +# CA3077: Insecure Processing in API Design, XmlDocument and XmlTextReader +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3077 +dotnet_diagnostic.CA3077.severity = silent + +# CA3147: Mark Verb Handlers With Validate Antiforgery Token +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca3147 +dotnet_diagnostic.CA3147.severity = silent + +# CA5350: Do Not Use Weak Cryptographic Algorithms +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5350 +dotnet_diagnostic.CA5350.severity = silent + +# CA5351: Do Not Use Broken Cryptographic Algorithms +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5351 +dotnet_diagnostic.CA5351.severity = silent + +# CA5358: Review cipher mode usage with cryptography experts +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5358 +dotnet_diagnostic.CA5358.severity = none + +# CA5359: Do Not Disable Certificate Validation +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5359 +dotnet_diagnostic.CA5359.severity = silent + +# CA5360: Do Not Call Dangerous Methods In Deserialization +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5360 +dotnet_diagnostic.CA5360.severity = silent + +# CA5361: Do Not Disable SChannel Use of Strong Crypto +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5361 +dotnet_diagnostic.CA5361.severity = none + +# CA5362: Potential reference cycle in deserialized object graph +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5362 +dotnet_diagnostic.CA5362.severity = none + +# CA5363: Do Not Disable Request Validation +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5363 +dotnet_diagnostic.CA5363.severity = silent + +# CA5364: Do Not Use Deprecated Security Protocols +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5364 +dotnet_diagnostic.CA5364.severity = silent + +# CA5365: Do Not Disable HTTP Header Checking +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5365 +dotnet_diagnostic.CA5365.severity = silent + +# CA5366: Use XmlReader For DataSet Read Xml +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5366 +dotnet_diagnostic.CA5366.severity = silent + +# CA5367: Do Not Serialize Types With Pointer Fields +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5367 +dotnet_diagnostic.CA5367.severity = none + +# CA5368: Set ViewStateUserKey For Classes Derived From Page +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5368 +dotnet_diagnostic.CA5368.severity = silent + +# CA5369: Use XmlReader For Deserialize +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5369 +dotnet_diagnostic.CA5369.severity = silent + +# CA5370: Use XmlReader For Validating Reader +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5370 +dotnet_diagnostic.CA5370.severity = silent + +# CA5371: Use XmlReader For Schema Read +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5371 +dotnet_diagnostic.CA5371.severity = silent + +# CA5372: Use XmlReader For XPathDocument +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5372 +dotnet_diagnostic.CA5372.severity = silent + +# CA5373: Do not use obsolete key derivation function +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5373 +dotnet_diagnostic.CA5373.severity = silent + +# CA5374: Do Not Use XslTransform +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5374 +dotnet_diagnostic.CA5374.severity = silent + +# CA5375: Do Not Use Account Shared Access Signature +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5375 +dotnet_diagnostic.CA5375.severity = none + +# CA5376: Use SharedAccessProtocol HttpsOnly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5376 +dotnet_diagnostic.CA5376.severity = none + +# CA5377: Use Container Level Access Policy +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5377 +dotnet_diagnostic.CA5377.severity = none + +# CA5378: Do not disable ServicePointManagerSecurityProtocols +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5378 +dotnet_diagnostic.CA5378.severity = none + +# CA5379: Do Not Use Weak Key Derivation Function Algorithm +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5379 +dotnet_diagnostic.CA5379.severity = silent + +# CA5380: Do Not Add Certificates To Root Store +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5380 +dotnet_diagnostic.CA5380.severity = none + +# CA5381: Ensure Certificates Are Not Added To Root Store +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5381 +dotnet_diagnostic.CA5381.severity = none + +# CA5382: Use Secure Cookies In ASP.Net Core +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5382 +dotnet_diagnostic.CA5382.severity = none + +# CA5383: Ensure Use Secure Cookies In ASP.Net Core +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5383 +dotnet_diagnostic.CA5383.severity = none + +# CA5384: Do Not Use Digital Signature Algorithm (DSA) +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5384 +dotnet_diagnostic.CA5384.severity = silent + +# CA5385: Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5385 +dotnet_diagnostic.CA5385.severity = silent + +# CA5386: Avoid hardcoding SecurityProtocolType value +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5386 +dotnet_diagnostic.CA5386.severity = none + +# CA5387: Do Not Use Weak Key Derivation Function With Insufficient Iteration Count +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5387 +dotnet_diagnostic.CA5387.severity = none + +# CA5388: Ensure Sufficient Iteration Count When Using Weak Key Derivation Function +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5388 +dotnet_diagnostic.CA5388.severity = none + +# CA5389: Do Not Add Archive Item's Path To The Target File System Path +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5389 +dotnet_diagnostic.CA5389.severity = none + +# CA5390: Do not hard-code encryption key +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5390 +dotnet_diagnostic.CA5390.severity = none + +# CA5391: Use antiforgery tokens in ASP.NET Core MVC controllers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5391 +dotnet_diagnostic.CA5391.severity = none + +# CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5392 +dotnet_diagnostic.CA5392.severity = none + +# CA5393: Do not use unsafe DllImportSearchPath value +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5393 +dotnet_diagnostic.CA5393.severity = none + +# CA5394: Do not use insecure randomness +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5394 +dotnet_diagnostic.CA5394.severity = none + +# CA5395: Miss HttpVerb attribute for action methods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5395 +dotnet_diagnostic.CA5395.severity = none + +# CA5396: Set HttpOnly to true for HttpCookie +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5396 +dotnet_diagnostic.CA5396.severity = none + +# CA5397: Do not use deprecated SslProtocols values +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5397 +dotnet_diagnostic.CA5397.severity = silent + +# CA5398: Avoid hardcoded SslProtocols values +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5398 +dotnet_diagnostic.CA5398.severity = none + +# CA5399: HttpClients should enable certificate revocation list checks +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5399 +dotnet_diagnostic.CA5399.severity = none + +# CA5400: Ensure HttpClient certificate revocation list check is not disabled +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5400 +dotnet_diagnostic.CA5400.severity = none + +# CA5401: Do not use CreateEncryptor with non-default IV +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5401 +dotnet_diagnostic.CA5401.severity = none + +# CA5402: Use CreateEncryptor with the default IV +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5402 +dotnet_diagnostic.CA5402.severity = none + +# CA5403: Do not hard-code certificate +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca5403 +dotnet_diagnostic.CA5403.severity = none + +# IL3000: Avoid using accessing Assembly file path when publishing as a single-file +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/il3000 +dotnet_diagnostic.IL3000.severity = warning + +# IL3001: Avoid using accessing Assembly file path when publishing as a single-file +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/il3001 +dotnet_diagnostic.IL3001.severity = warning + +# IL3002: Using member with RequiresAssemblyFilesAttribute can break functionality when embedded in a single-file app +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/il3002 +dotnet_diagnostic.IL3002.severity = warning + +# DOC100: PlaceTextInParagraphs +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC100.md +dotnet_diagnostic.DOC100.severity = none + +# DOC101: UseChildBlocksConsistently +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC101.md +dotnet_diagnostic.DOC101.severity = none + +# DOC102: UseChildBlocksConsistentlyAcrossElementsOfTheSameKind +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC102.md +dotnet_diagnostic.DOC102.severity = none + +# DOC103: UseUnicodeCharacters +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC103.md +dotnet_diagnostic.DOC103.severity = none + +# DOC104: UseSeeLangword +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC104.md +dotnet_diagnostic.DOC104.severity = suggestion + +# DOC105: UseParamref +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC105.md +dotnet_diagnostic.DOC105.severity = none + +# DOC106: UseTypeparamref +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC106.md +dotnet_diagnostic.DOC106.severity = none + +# DOC107: UseSeeCref +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC107.md +dotnet_diagnostic.DOC107.severity = none + +# DOC108: AvoidEmptyParagraphs +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC108.md +dotnet_diagnostic.DOC108.severity = none + +# DOC200: UseXmlDocumentationSyntax +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC200.md +dotnet_diagnostic.DOC200.severity = none + +# DOC201: ItemShouldHaveDescription +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC201.md +dotnet_diagnostic.DOC201.severity = none + +# DOC202: UseSectionElementsCorrectly +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC202.md +dotnet_diagnostic.DOC202.severity = none + +# DOC203: UseBlockElementsCorrectly +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC203.md +dotnet_diagnostic.DOC203.severity = none + +# DOC204: UseInlineElementsCorrectly +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC204.md +dotnet_diagnostic.DOC204.severity = none + +# DOC207: UseSeeLangwordCorrectly +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC207.md +dotnet_diagnostic.DOC207.severity = none + +# DOC209: UseSeeHrefCorrectly +# https://github.com/DotNetAnalyzers/DocumentationAnalyzers/blob/master/docs/DOC209.md +dotnet_diagnostic.DOC209.severity = none + +# IDE0001: SimplifyNames +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0001 +dotnet_diagnostic.IDE0001.severity = silent + +# IDE0002: SimplifyMemberAccess +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0002 +dotnet_diagnostic.IDE0002.severity = silent + +# IDE0003: RemoveQualification +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0003 +dotnet_diagnostic.IDE0003.severity = silent + +# IDE0004: RemoveUnnecessaryCast +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0004 +dotnet_diagnostic.IDE0004.severity = silent + +# IDE0005: RemoveUnnecessaryImports +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0005 +dotnet_diagnostic.IDE0005.severity = silent + +# IDE0006: IntellisenseBuildFailed +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0006 +dotnet_diagnostic.IDE0006.severity = silent + +# IDE0007: UseImplicitType +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0007 +dotnet_diagnostic.IDE0007.severity = silent + +# IDE0008: UseExplicitType +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0008 +dotnet_diagnostic.IDE0008.severity = silent + +# IDE0009: AddQualification +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0009 +dotnet_diagnostic.IDE0009.severity = silent + +# IDE0010: PopulateSwitchStatement +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0010 +dotnet_diagnostic.IDE0010.severity = silent + +# IDE0011: AddBraces +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0011 +dotnet_diagnostic.IDE0011.severity = silent + +# IDE0016: UseThrowExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0016 +dotnet_diagnostic.IDE0016.severity = silent + +# IDE0017: UseObjectInitializer +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0017 +dotnet_diagnostic.IDE0017.severity = silent + +# IDE0018: InlineDeclaration +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0018 +dotnet_diagnostic.IDE0018.severity = silent + +# IDE0019: InlineAsTypeCheck +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0019 +dotnet_diagnostic.IDE0019.severity = warning + +# IDE0020: InlineIsTypeCheck +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0020 +dotnet_diagnostic.IDE0020.severity = silent + +# IDE0021: UseExpressionBodyForConstructors +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0021 +dotnet_diagnostic.IDE0021.severity = silent + +# IDE0022: UseExpressionBodyForMethods +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0022 +dotnet_diagnostic.IDE0022.severity = silent + +# IDE0023: UseExpressionBodyForConversionOperators +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0023 +dotnet_diagnostic.IDE0023.severity = silent + +# IDE0024: UseExpressionBodyForOperators +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0024 +dotnet_diagnostic.IDE0024.severity = silent + +# IDE0025: UseExpressionBodyForProperties +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0025 +dotnet_diagnostic.IDE0025.severity = silent + +# IDE0026: UseExpressionBodyForIndexers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0026 +dotnet_diagnostic.IDE0026.severity = silent + +# IDE0027: UseExpressionBodyForAccessors +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0027 +dotnet_diagnostic.IDE0027.severity = silent + +# IDE0028: UseCollectionInitializer +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0028 +dotnet_diagnostic.IDE0028.severity = silent + +# IDE0029: UseCoalesceExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0029 +dotnet_diagnostic.IDE0029.severity = warning + +# IDE0030: UseCoalesceExpressionForNullable +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0030 +dotnet_diagnostic.IDE0030.severity = warning + +# IDE0031: UseNullPropagation +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0031 +dotnet_diagnostic.IDE0031.severity = warning + +# IDE0032: UseAutoProperty +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0032 +dotnet_diagnostic.IDE0032.severity = silent + +# IDE0033: UseExplicitTupleName +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0033 +dotnet_diagnostic.IDE0033.severity = silent + +# IDE0034: UseDefaultLiteral +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0034 +dotnet_diagnostic.IDE0034.severity = silent + +# IDE0035: RemoveUnreachableCode +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0035 +dotnet_diagnostic.IDE0035.severity = silent + +# IDE0036: OrderModifiers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0036 +dotnet_diagnostic.IDE0036.severity = warning + +# IDE0037: UseInferredMemberName +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0037 +dotnet_diagnostic.IDE0037.severity = silent + +# IDE0038: InlineIsTypeWithoutNameCheck +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0038 +dotnet_diagnostic.IDE0038.severity = silent + +# IDE0039: UseLocalFunction +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0039 +dotnet_diagnostic.IDE0039.severity = silent + +# IDE0040: AddAccessibilityModifiers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0040 +dotnet_diagnostic.IDE0040.severity = warning + +# IDE0041: UseIsNullCheck +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0041 +dotnet_diagnostic.IDE0041.severity = warning + +# IDE0042: UseDeconstruction +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0042 +dotnet_diagnostic.IDE0042.severity = silent + +# IDE0043: ValidateFormatString +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0043 +dotnet_diagnostic.IDE0043.severity = silent + +# IDE0044: MakeFieldReadonly +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0044 +dotnet_diagnostic.IDE0044.severity = warning + +# IDE0045: UseConditionalExpressionForAssignment +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0045 +dotnet_diagnostic.IDE0045.severity = silent + +# IDE0046: UseConditionalExpressionForReturn +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0046 +dotnet_diagnostic.IDE0046.severity = silent + +# IDE0047: RemoveUnnecessaryParentheses +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0047 +dotnet_diagnostic.IDE0047.severity = silent + +# IDE0048: AddRequiredParentheses +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0048 +dotnet_diagnostic.IDE0048.severity = suggestion + +# IDE0049: PreferBuiltInOrFrameworkType +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0049 +dotnet_diagnostic.IDE0049.severity = suggestion + +# IDE0050: ConvertAnonymousTypeToTuple +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0050 +dotnet_diagnostic.IDE0050.severity = silent + +# IDE0051: RemoveUnusedMembers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0051 +dotnet_diagnostic.IDE0051.severity = silent + +# IDE0052: RemoveUnreadMembers +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0052 +dotnet_diagnostic.IDE0052.severity = silent + +# IDE0053: UseExpressionBodyForLambdaExpressions +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0053 +dotnet_diagnostic.IDE0053.severity = silent + +# IDE0054: UseCompoundAssignment +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0054 +dotnet_diagnostic.IDE0054.severity = warning + +# IDE0055: Formatting +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0055 +dotnet_diagnostic.IDE0055.severity = silent + +# IDE0056: UseIndexOperator +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0056 +dotnet_diagnostic.IDE0056.severity = silent + +# IDE0057: UseRangeOperator +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0057 +dotnet_diagnostic.IDE0057.severity = silent + +# IDE0058: ExpressionValueIsUnused +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0058 +dotnet_diagnostic.IDE0058.severity = silent + +# IDE0059: ValueAssignedIsUnused +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0059 +dotnet_diagnostic.IDE0059.severity = silent + +# IDE0060: UnusedParameter +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0060 +dotnet_diagnostic.IDE0060.severity = silent + +# IDE0061: UseExpressionBodyForLocalFunctions +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0061 +dotnet_diagnostic.IDE0061.severity = silent + +# IDE0062: MakeLocalFunctionStatic +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0062 +dotnet_diagnostic.IDE0062.severity = warning + +# IDE0063: UseSimpleUsingStatement +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0063 +dotnet_diagnostic.IDE0063.severity = silent + +# IDE0064: MakeStructFieldsWritable +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0064 +dotnet_diagnostic.IDE0064.severity = warning + +# IDE0065: MoveMisplacedUsingDirectives +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0065 +dotnet_diagnostic.IDE0065.severity = silent + +# IDE0066: ConvertSwitchStatementToExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0066 +dotnet_diagnostic.IDE0066.severity = silent + +# IDE0070: UseSystemHashCode +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0070 +dotnet_diagnostic.IDE0070.severity = warning + +# IDE0071: SimplifyInterpolation +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0071 +dotnet_diagnostic.IDE0071.severity = silent + +# IDE0072: PopulateSwitchExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0072 +dotnet_diagnostic.IDE0072.severity = silent + +# IDE0073: FileHeaderMismatch +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073 +dotnet_diagnostic.IDE0073.severity = suggestion + +# IDE0074: UseCoalesceCompoundAssignment +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0074 +dotnet_diagnostic.IDE0074.severity = warning + +# IDE0075: SimplifyConditionalExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0075 +dotnet_diagnostic.IDE0075.severity = warning + +# IDE0076: InvalidSuppressMessageAttribute +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0076 +dotnet_diagnostic.IDE0076.severity = warning + +# IDE0077: LegacyFormatSuppressMessageAttribute +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0077 +dotnet_diagnostic.IDE0077.severity = warning + +# IDE0078: UsePatternCombinators +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0078 +dotnet_diagnostic.IDE0078.severity = silent + +# IDE0079: RemoveUnnecessarySuppression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0079 +dotnet_diagnostic.IDE0079.severity = silent + +# IDE0080: RemoveConfusingSuppressionForIsExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0080 +dotnet_diagnostic.IDE0080.severity = warning + +# IDE0081: RemoveUnnecessaryByVal +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0081 +dotnet_diagnostic.IDE0081.severity = silent + +# IDE0082: ConvertTypeOfToNameOf +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0082 +dotnet_diagnostic.IDE0082.severity = warning + +# IDE0083: UseNotPattern +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0083 +dotnet_diagnostic.IDE0083.severity = silent + +# IDE0084: UseIsNotExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0084 +dotnet_diagnostic.IDE0084.severity = silent + +# IDE0090: UseNew +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 +dotnet_diagnostic.IDE0090.severity = suggestion + +# IDE0100: RemoveRedundantEquality +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0100 +dotnet_diagnostic.IDE0100.severity = warning + +# IDE0110: RemoveUnnecessaryDiscard +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0110 +dotnet_diagnostic.IDE0110.severity = suggestion + +# IDE0120: SimplifyLINQExpression +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0120 +dotnet_diagnostic.IDE0120.severity = warning + +# IDE0130: NamespaceDoesNotMatchFolderStructure +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0130 +dotnet_diagnostic.IDE0130.severity = silent + +# IDE1001: AnalyzerChanged +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1001 +dotnet_diagnostic.IDE1001.severity = silent + +# IDE1002: AnalyzerDependencyConflict +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1002 +dotnet_diagnostic.IDE1002.severity = silent + +# IDE1003: MissingAnalyzerReference +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1003 +dotnet_diagnostic.IDE1003.severity = silent + +# IDE1004: ErrorReadingRuleset +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1004 +dotnet_diagnostic.IDE1004.severity = silent + +# IDE1005: InvokeDelegateWithConditionalAccess +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1005 +dotnet_diagnostic.IDE1005.severity = warning + +# IDE1006: NamingRule +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1006 +dotnet_diagnostic.IDE1006.severity = silent + +# IDE1007: UnboundIdentifier +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1007 +dotnet_diagnostic.IDE1007.severity = silent + +# IDE1008: UnboundConstructor +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide1008 +dotnet_diagnostic.IDE1008.severity = silent + +# IDE2000: MultipleBlankLines +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide2000 +dotnet_diagnostic.IDE2000.severity = warning + +# IDE2001: EmbeddedStatementsMustBeOnTheirOwnLine +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide2001 +dotnet_diagnostic.IDE2001.severity = warning + +# IDE2002: ConsecutiveBracesMustNotHaveBlankLinesBetweenThem +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide2002 +dotnet_diagnostic.IDE2002.severity = warning + +# IDE2003: ConsecutiveStatementPlacement +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide2003 +dotnet_diagnostic.IDE2003.severity = warning + +# IDE2004: BlankLineNotAllowedAfterConstructorInitializerColon +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide2004 +dotnet_diagnostic.IDE2004.severity = warning + +# SA0001: XML comment analysis disabled +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA0001.md +dotnet_diagnostic.SA0001.severity = none + +# SA0002: Invalid settings file +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA0002.md +dotnet_diagnostic.SA0002.severity = none + +# SA1000: Keywords should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1000.md +dotnet_diagnostic.SA1000.severity = warning + +# SA1001: Commas should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1001.md +dotnet_diagnostic.SA1001.severity = warning + +# SA1002: Semicolons should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1002.md +dotnet_diagnostic.SA1002.severity = warning + +# SA1003: Symbols should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1003.md +dotnet_diagnostic.SA1003.severity = warning + +# SA1004: Documentation lines should begin with single space +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1004.md +dotnet_diagnostic.SA1004.severity = none + +# SA1005: Single line comments should begin with single space +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1005.md +dotnet_diagnostic.SA1005.severity = none + +# SA1006: Preprocessor keywords should not be preceded by space +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1006.md +dotnet_diagnostic.SA1006.severity = warning + +# SA1007: Operator keyword should be followed by space +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1007.md +dotnet_diagnostic.SA1007.severity = warning + +# SA1008: Opening parenthesis should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1008.md +dotnet_diagnostic.SA1008.severity = warning + +# SA1009: Closing parenthesis should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1009.md +dotnet_diagnostic.SA1009.severity = none + +# SA1010: Opening square brackets should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1010.md +dotnet_diagnostic.SA1010.severity = none + +# SA1011: Closing square brackets should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1011.md +dotnet_diagnostic.SA1011.severity = none + +# SA1012: Opening braces should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1012.md +dotnet_diagnostic.SA1012.severity = none + +# SA1013: Closing braces should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1013.md +dotnet_diagnostic.SA1013.severity = none + +# SA1014: Opening generic brackets should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1014.md +dotnet_diagnostic.SA1014.severity = none + +# SA1015: Closing generic brackets should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1015.md +dotnet_diagnostic.SA1015.severity = none + +# SA1016: Opening attribute brackets should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1016.md +dotnet_diagnostic.SA1016.severity = none + +# SA1017: Closing attribute brackets should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1017.md +dotnet_diagnostic.SA1017.severity = none + +# SA1018: Nullable type symbols should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1018.md +dotnet_diagnostic.SA1018.severity = none + +# SA1019: Member access symbols should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1019.md +dotnet_diagnostic.SA1019.severity = none + +# SA1020: Increment decrement symbols should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1020.md +dotnet_diagnostic.SA1020.severity = none + +# SA1021: Negative signs should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1021.md +dotnet_diagnostic.SA1021.severity = none + +# SA1022: Positive signs should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1022.md +dotnet_diagnostic.SA1022.severity = none + +# SA1023: Dereference and access of symbols should be spaced correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1023.md +dotnet_diagnostic.SA1023.severity = none + +# SA1024: Colons Should Be Spaced Correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1024.md +dotnet_diagnostic.SA1024.severity = none + +# SA1025: Code should not contain multiple whitespace in a row +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1025.md +dotnet_diagnostic.SA1025.severity = none + +# SA1026: Code should not contain space after new or stackalloc keyword in implicitly typed array allocation +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1026.md +dotnet_diagnostic.SA1026.severity = none + +# SA1027: Use tabs correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1027.md +dotnet_diagnostic.SA1027.severity = none + +# SA1028: Code should not contain trailing whitespace +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1028.md +dotnet_diagnostic.SA1028.severity = none + +# SA1100: Do not prefix calls with base unless local implementation exists +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1100.md +dotnet_diagnostic.SA1100.severity = none + +# SA1101: Prefix local calls with this +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1101.md +dotnet_diagnostic.SA1101.severity = none + +# SA1102: Query clause should follow previous clause +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1102.md +dotnet_diagnostic.SA1102.severity = none + +# SA1103: Query clauses should be on separate lines or all on one line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1103.md +dotnet_diagnostic.SA1103.severity = none + +# SA1104: Query clause should begin on new line when previous clause spans multiple lines +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1104.md +dotnet_diagnostic.SA1104.severity = none + +# SA1105: Query clauses spanning multiple lines should begin on own line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1105.md +dotnet_diagnostic.SA1105.severity = none + +# SA1106: Code should not contain empty statements +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1106.md +dotnet_diagnostic.SA1106.severity = warning + +# SA1107: Code should not contain multiple statements on one line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1107.md +dotnet_diagnostic.SA1107.severity = none + +# SA1108: Block statements should not contain embedded comments +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1108.md +dotnet_diagnostic.SA1108.severity = none + +# SA1110: Opening parenthesis or bracket should be on declaration line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1110.md +dotnet_diagnostic.SA1110.severity = none + +# SA1111: Closing parenthesis should be on line of last parameter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1111.md +dotnet_diagnostic.SA1111.severity = none + +# SA1112: Closing parenthesis should be on line of opening parenthesis +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1112.md +dotnet_diagnostic.SA1112.severity = none + +# SA1113: Comma should be on the same line as previous parameter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1113.md +dotnet_diagnostic.SA1113.severity = none + +# SA1114: Parameter list should follow declaration +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1114.md +dotnet_diagnostic.SA1114.severity = none + +# SA1115: Parameter should follow comma +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1115.md +dotnet_diagnostic.SA1115.severity = none + +# SA1116: Split parameters should start on line after declaration +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1116.md +dotnet_diagnostic.SA1116.severity = none + +# SA1117: Parameters should be on same line or separate lines +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1117.md +dotnet_diagnostic.SA1117.severity = none + +# SA1118: Parameter should not span multiple lines +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1118.md +dotnet_diagnostic.SA1118.severity = none + +# SA1119: Statement should not use unnecessary parenthesis +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1119.md +dotnet_diagnostic.SA1119.severity = none + +# SA1120: Comments should contain text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1120.md +dotnet_diagnostic.SA1120.severity = none + +# SA1121: Use built-in type alias +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1121.md +dotnet_diagnostic.SA1121.severity = none + +# SA1122: Use string.Empty for empty strings +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1122.md +dotnet_diagnostic.SA1122.severity = warning + +# SA1123: Do not place regions within elements +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1123.md +dotnet_diagnostic.SA1123.severity = none + +# SA1124: Do not use regions +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1124.md +dotnet_diagnostic.SA1124.severity = none + +# SA1125: Use shorthand for nullable types +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1125.md +dotnet_diagnostic.SA1125.severity = none + +# SA1127: Generic type constraints should be on their own line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1127.md +dotnet_diagnostic.SA1127.severity = none + +# SA1128: Put constructor initializers on their own line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1128.md +dotnet_diagnostic.SA1128.severity = none + +# SA1129: Do not use default value type constructor +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1129.md +dotnet_diagnostic.SA1129.severity = none + +# SA1130: Use lambda syntax +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1130.md +dotnet_diagnostic.SA1130.severity = none + +# SA1131: Use readable conditions +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1131.md +dotnet_diagnostic.SA1131.severity = warning + +# SA1132: Do not combine fields +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1132.md +dotnet_diagnostic.SA1132.severity = none + +# SA1133: Do not combine attributes +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1133.md +dotnet_diagnostic.SA1133.severity = none + +# SA1134: Attributes should not share line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1134.md +dotnet_diagnostic.SA1134.severity = none + +# SA1135: Using directives should be qualified +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1135.md +dotnet_diagnostic.SA1135.severity = none + +# SA1136: Enum values should be on separate lines +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1136.md +dotnet_diagnostic.SA1136.severity = none + +# SA1137: Elements should have the same indentation +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1137.md +dotnet_diagnostic.SA1137.severity = none + +# SA1139: Use literal suffix notation instead of casting +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1139.md +dotnet_diagnostic.SA1139.severity = none + +# SA1141: Use tuple syntax +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1141.md +dotnet_diagnostic.SA1141.severity = none + +# SA1142: Refer to tuple fields by name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1142.md +dotnet_diagnostic.SA1142.severity = none + +# SA1200: Using directives should be placed correctly +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1200.md +dotnet_diagnostic.SA1200.severity = none + +# SA1201: Elements should appear in the correct order +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1201.md +dotnet_diagnostic.SA1201.severity = none + +# SA1202: Elements should be ordered by access +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md +dotnet_diagnostic.SA1202.severity = none + +# SA1203: Constants should appear before fields +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md +dotnet_diagnostic.SA1203.severity = none + +# SA1204: Static elements should appear before instance elements +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1204.md +dotnet_diagnostic.SA1204.severity = none + +# SA1205: Partial elements should declare access +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1205.md +dotnet_diagnostic.SA1205.severity = warning + +# SA1206: Declaration keywords should follow order +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1206.md +dotnet_diagnostic.SA1206.severity = warning + +# SA1207: Protected should come before internal +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1207.md +dotnet_diagnostic.SA1207.severity = none + +# SA1208: System using directives should be placed before other using directives +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1208.md +dotnet_diagnostic.SA1208.severity = none + +# SA1209: Using alias directives should be placed after other using directives +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1209.md +dotnet_diagnostic.SA1209.severity = none + +# SA1210: Using directives should be ordered alphabetically by namespace +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1210.md +dotnet_diagnostic.SA1210.severity = none + +# SA1211: Using alias directives should be ordered alphabetically by alias name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1211.md +dotnet_diagnostic.SA1211.severity = none + +# SA1212: Property accessors should follow order +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1212.md +dotnet_diagnostic.SA1212.severity = warning + +# SA1213: Event accessors should follow order +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1213.md +dotnet_diagnostic.SA1213.severity = warning + +# SA1214: Readonly fields should appear before non-readonly fields +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md +dotnet_diagnostic.SA1214.severity = none + +# SA1216: Using static directives should be placed at the correct location +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1216.md +dotnet_diagnostic.SA1216.severity = warning + +# SA1217: Using static directives should be ordered alphabetically +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1217.md +dotnet_diagnostic.SA1217.severity = warning + +# SA1300: Element should begin with upper-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md +dotnet_diagnostic.SA1300.severity = none + +# SA1302: Interface names should begin with I +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1302.md +dotnet_diagnostic.SA1302.severity = none + +# SA1303: Const field names should begin with upper-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1303.md +dotnet_diagnostic.SA1303.severity = none + +# SA1304: Non-private readonly fields should begin with upper-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1304.md +dotnet_diagnostic.SA1304.severity = none + +# SA1305: Field names should not use Hungarian notation +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1305.md +dotnet_diagnostic.SA1305.severity = none + +# SA1306: Field names should begin with lower-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1306.md +dotnet_diagnostic.SA1306.severity = none + +# SA1307: Accessible fields should begin with upper-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1307.md +dotnet_diagnostic.SA1307.severity = none + +# SA1308: Variable names should not be prefixed +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1308.md +dotnet_diagnostic.SA1308.severity = none + +# SA1309: Field names should not begin with underscore +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1309.md +dotnet_diagnostic.SA1309.severity = none + +# SA1310: Field names should not contain underscore +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1310.md +dotnet_diagnostic.SA1310.severity = none + +# SA1311: Static readonly fields should begin with upper-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1311.md +dotnet_diagnostic.SA1311.severity = none + +# SA1312: Variable names should begin with lower-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1312.md +dotnet_diagnostic.SA1312.severity = none + +# SA1313: Parameter names should begin with lower-case letter +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1313.md +dotnet_diagnostic.SA1313.severity = none + +# SA1314: Type parameter names should begin with T +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1314.md +dotnet_diagnostic.SA1314.severity = warning + +# SA1316: Tuple element names should use correct casing +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1316.md +dotnet_diagnostic.SA1316.severity = none + +# SA1400: Access modifier should be declared +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1400.md +dotnet_diagnostic.SA1400.severity = none + +# SA1401: Fields should be private +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md +dotnet_diagnostic.SA1401.severity = none + +# SA1402: File may only contain a single type +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1402.md +dotnet_diagnostic.SA1402.severity = none + +# SA1403: File may only contain a single namespace +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1403.md +dotnet_diagnostic.SA1403.severity = none + +# SA1404: Code analysis suppression should have justification +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1404.md +dotnet_diagnostic.SA1404.severity = none + +# SA1405: Debug.Assert should provide message text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1405.md +dotnet_diagnostic.SA1405.severity = none + +# SA1406: Debug.Fail should provide message text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1406.md +dotnet_diagnostic.SA1406.severity = none + +# SA1407: Arithmetic expressions should declare precedence +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1407.md +dotnet_diagnostic.SA1407.severity = none + +# SA1408: Conditional expressions should declare precedence +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1408.md +dotnet_diagnostic.SA1408.severity = none + +# SA1410: Remove delegate parenthesis when possible +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1410.md +dotnet_diagnostic.SA1410.severity = none + +# SA1411: Attribute constructor should not use unnecessary parenthesis +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1411.md +dotnet_diagnostic.SA1411.severity = none + +# SA1412: Store files as UTF-8 with byte order mark +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1412.md +dotnet_diagnostic.SA1412.severity = none + +# SA1413: Use trailing comma in multi-line initializers +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1413.md +dotnet_diagnostic.SA1413.severity = none + +# SA1414: Tuple types in signatures should have element names +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1414.md +dotnet_diagnostic.SA1414.severity = none + +# SA1500: Braces for multi-line statements should not share line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1500.md +dotnet_diagnostic.SA1500.severity = none + +# SA1501: Statement should not be on a single line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1501.md +dotnet_diagnostic.SA1501.severity = none + +# SA1502: Element should not be on a single line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1502.md +dotnet_diagnostic.SA1502.severity = none + +# SA1503: Braces should not be omitted +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1503.md +dotnet_diagnostic.SA1503.severity = none + +# SA1504: All accessors should be single-line or multi-line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1504.md +dotnet_diagnostic.SA1504.severity = warning + +# SA1505: Opening braces should not be followed by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md +dotnet_diagnostic.SA1505.severity = none + +# SA1506: Element documentation headers should not be followed by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1506.md +dotnet_diagnostic.SA1506.severity = none + +# SA1507: Code should not contain multiple blank lines in a row +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1507.md +dotnet_diagnostic.SA1507.severity = warning + +# SA1508: Closing braces should not be preceded by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1508.md +dotnet_diagnostic.SA1508.severity = none + +# SA1509: Opening braces should not be preceded by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1509.md +dotnet_diagnostic.SA1509.severity = none + +# SA1510: Chained statement blocks should not be preceded by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1510.md +dotnet_diagnostic.SA1510.severity = none + +# SA1511: While-do footer should not be preceded by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1511.md +dotnet_diagnostic.SA1511.severity = none + +# SA1512: Single-line comments should not be followed by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1512.md +dotnet_diagnostic.SA1512.severity = none + +# SA1513: Closing brace should be followed by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1513.md +dotnet_diagnostic.SA1513.severity = none + +# SA1514: Element documentation header should be preceded by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1514.md +dotnet_diagnostic.SA1514.severity = none + +# SA1515: Single-line comment should be preceded by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1515.md +dotnet_diagnostic.SA1515.severity = none + +# SA1516: Elements should be separated by blank line +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1516.md +dotnet_diagnostic.SA1516.severity = warning + +# SA1517: Code should not contain blank lines at start of file +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1517.md +dotnet_diagnostic.SA1517.severity = warning + +# SA1518: Use line endings correctly at end of file +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1518.md +dotnet_diagnostic.SA1518.severity = warning + +# SA1519: Braces should not be omitted from multi-line child statement +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1519.md +dotnet_diagnostic.SA1519.severity = none + +# SA1520: Use braces consistently +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1520.md +dotnet_diagnostic.SA1520.severity = none + +# SA1600: Elements should be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1600.md +dotnet_diagnostic.SA1600.severity = none + +# SA1601: Partial elements should be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1601.md +dotnet_diagnostic.SA1601.severity = none + +# SA1602: Enumeration items should be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1602.md +dotnet_diagnostic.SA1602.severity = none + +# SA1604: Element documentation should have summary +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1604.md +dotnet_diagnostic.SA1604.severity = none + +# SA1605: Partial element documentation should have summary +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1605.md +dotnet_diagnostic.SA1605.severity = none + +# SA1606: Element documentation should have summary text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1606.md +dotnet_diagnostic.SA1606.severity = none + +# SA1607: Partial element documentation should have summary text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1607.md +dotnet_diagnostic.SA1607.severity = none + +# SA1608: Element documentation should not have default summary +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1608.md +dotnet_diagnostic.SA1608.severity = none + +# SA1609: Property documentation should have value +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1609.md +dotnet_diagnostic.SA1609.severity = none + +# SA1610: Property documentation should have value text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1610.md +dotnet_diagnostic.SA1610.severity = none + +# SA1611: Element parameters should be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1611.md +dotnet_diagnostic.SA1611.severity = none + +# SA1612: Element parameter documentation should match element parameters +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1612.md +dotnet_diagnostic.SA1612.severity = none + +# SA1613: Element parameter documentation should declare parameter name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1613.md +dotnet_diagnostic.SA1613.severity = none + +# SA1614: Element parameter documentation should have text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1614.md +dotnet_diagnostic.SA1614.severity = none + +# SA1615: Element return value should be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1615.md +dotnet_diagnostic.SA1615.severity = none + +# SA1616: Element return value documentation should have text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1616.md +dotnet_diagnostic.SA1616.severity = none + +# SA1617: Void return value should not be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1617.md +dotnet_diagnostic.SA1617.severity = none + +# SA1618: Generic type parameters should be documented +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1618.md +dotnet_diagnostic.SA1618.severity = none + +# SA1619: Generic type parameters should be documented partial class +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1619.md +dotnet_diagnostic.SA1619.severity = none + +# SA1620: Generic type parameter documentation should match type parameters +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1620.md +dotnet_diagnostic.SA1620.severity = none + +# SA1621: Generic type parameter documentation should declare parameter name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1621.md +dotnet_diagnostic.SA1621.severity = none + +# SA1622: Generic type parameter documentation should have text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1622.md +dotnet_diagnostic.SA1622.severity = none + +# SA1623: Property summary documentation should match accessors +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1623.md +dotnet_diagnostic.SA1623.severity = none + +# SA1624: Property summary documentation should omit accessor with restricted access +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1624.md +dotnet_diagnostic.SA1624.severity = none + +# SA1625: Element documentation should not be copied and pasted +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1625.md +dotnet_diagnostic.SA1625.severity = none + +# SA1626: Single-line comments should not use documentation style slashes +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1626.md +dotnet_diagnostic.SA1626.severity = none + +# SA1627: Documentation text should not be empty +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1627.md +dotnet_diagnostic.SA1627.severity = none + +# SA1629: Documentation text should end with a period +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1629.md +dotnet_diagnostic.SA1629.severity = none + +# SA1633: File should have header +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1633.md +dotnet_diagnostic.SA1633.severity = none + +# SA1634: File header should show copyright +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1634.md +dotnet_diagnostic.SA1634.severity = none + +# SA1635: File header should have copyright text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1635.md +dotnet_diagnostic.SA1635.severity = none + +# SA1636: File header copyright text should match +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1636.md +dotnet_diagnostic.SA1636.severity = none + +# SA1637: File header should contain file name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1637.md +dotnet_diagnostic.SA1637.severity = none + +# SA1638: File header file name documentation should match file name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1638.md +dotnet_diagnostic.SA1638.severity = none + +# SA1639: File header should have summary +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1639.md +dotnet_diagnostic.SA1639.severity = none + +# SA1640: File header should have valid company text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1640.md +dotnet_diagnostic.SA1640.severity = none + +# SA1641: File header company name text should match +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1641.md +dotnet_diagnostic.SA1641.severity = none + +# SA1642: Constructor summary documentation should begin with standard text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1642.md +dotnet_diagnostic.SA1642.severity = none + +# SA1643: Destructor summary documentation should begin with standard text +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1643.md +dotnet_diagnostic.SA1643.severity = warning + +# SA1648: inheritdoc should be used with inheriting class +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1648.md +dotnet_diagnostic.SA1648.severity = none + +# SA1649: File name should match first type name +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1649.md +dotnet_diagnostic.SA1649.severity = none + +# SA1651: Do not use placeholder elements +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1651.md +dotnet_diagnostic.SA1651.severity = none + +# SX1101: Do not prefix local calls with 'this.' +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SX1101.md +dotnet_diagnostic.SX1101.severity = none + +# SX1309: Field names should begin with underscore +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SX1309.md +dotnet_diagnostic.SX1309.severity = none + +# SX1309S: Static field names should begin with underscore +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SX1309S.md +dotnet_diagnostic.SX1309S.severity = none diff --git a/PowerShell-master/.mailmap b/PowerShell-master/.mailmap new file mode 100644 index 0000000000000000000000000000000000000000..0bc786ac445fa177fdd7f1f65ebb8dde63f4a1f0 --- /dev/null +++ b/PowerShell-master/.mailmap @@ -0,0 +1 @@ +Andy Jordan diff --git a/PowerShell-master/.markdownlint.json b/PowerShell-master/.markdownlint.json new file mode 100644 index 0000000000000000000000000000000000000000..14e0732107fd52aa41affb72c314f6afb00879b4 --- /dev/null +++ b/PowerShell-master/.markdownlint.json @@ -0,0 +1,22 @@ +{ + "default": true, + "MD004": false, + "MD007": { + "indent": 4 + }, + "MD013": { + "line_length": 240 + }, + "MD026": { + "punctuation": ".,;:!" + }, + "MD029": { + "style": "one" + }, + "MD033": false, + "MD034": false, + "MD038": false, + "MD042": false, + "MD024": false, + "no-hard-tabs": true +} diff --git a/PowerShell-master/.markdownlintignore b/PowerShell-master/.markdownlintignore new file mode 100644 index 0000000000000000000000000000000000000000..1d3c5b1ac92bfabcca8c198524077006f5550fe1 --- /dev/null +++ b/PowerShell-master/.markdownlintignore @@ -0,0 +1 @@ +.github/SECURITY.md diff --git a/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/RolloutSpec.json b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/RolloutSpec.json new file mode 100644 index 0000000000000000000000000000000000000000..9ed971068cc9fa1eead1b36fd382e9cb6b9d12e7 --- /dev/null +++ b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/RolloutSpec.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://ev2schema.azure.net/schemas/2020-01-01/rolloutSpecification.json", + "contentVersion": "1.0.0.0", + "rolloutMetadata": { + "serviceModelPath": "ServiceModel.json", + "ScopeBindingsPath": "ScopeBindings.json", + "name": "OneBranch-Demo-Container-Deployment", + "rolloutType": "Major", + "buildSource": { + "parameters": { + "versionFile": "buildver.txt" + } + }, + "Notification": { + "Email": { + "To": "default" + } + } + }, + "orchestratedSteps": [ + { + "name": "UploadLinuxContainer", + "targetType": "ServiceResource", + "targetName": "LinuxContainerUpload", + "actions": ["Shell/Run"] + } + ] +} diff --git a/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/ScopeBindings.json b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/ScopeBindings.json new file mode 100644 index 0000000000000000000000000000000000000000..c3a98555867577323cb759ab7d05762d09a49ded --- /dev/null +++ b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/ScopeBindings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://ev2schema.azure.net/schemas/2020-01-01/scopeBindings.json", + "contentVersion": "0.0.0.1", + "scopeBindings": [ + { + "scopeTagName": "Global", + "bindings": [ + { + "find": "__SUBSCRIPTION_ID__", + "replaceWith": "$azureSubscriptionId()" + }, + { + "find": "__RESOURCE_GROUP__", + "replaceWith": "$azureResourceGroup()" + }, + { + "find": "__BUILD_VERSION__", + "replaceWith": "$buildVersion()" + } + ] + } + ] +} diff --git a/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/ServiceModel.json b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/ServiceModel.json new file mode 100644 index 0000000000000000000000000000000000000000..ce974fe69e59cd3c6cb24f834b0077a10bc73468 --- /dev/null +++ b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/ServiceModel.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://ev2schema.azure.net/schemas/2020-01-01/serviceModel.json", + "contentVersion": "1.0.0.0", + "serviceMetadata": { + "serviceGroup": "OneBranch-PowerShellDocker", + "environment": "Test" + }, + "serviceResourceGroupDefinitions": [ + { + "name": "OneBranch-PowerShellDocker-RGDef", + "serviceResourceDefinitions": [ + { + "name": "OneBranch-PowerShellDocker.Shell-SRDef", + "composedOf": { + "extension": { + "shell": [ + { + "type": "Run", + "properties": { + "imageName": "adm-azurelinux-30-l", + "imageVersion": "v2" + } + } + ] + } + } + } + ] + } + ], + "serviceResourceGroups": [ + { + "azureResourceGroupName": "default", + "location": "West US 3", + "instanceOf": "OneBranch-PowerShellDocker-RGDef", + "azureSubscriptionId": "default", + "scopeTags": [ + { + "name": "Global" + } + ], + "serviceResources": [ + { + "Name": "LinuxContainerUpload", + "InstanceOf": "OneBranch-PowerShellDocker.Shell-SRDef", + "RolloutParametersPath": "UploadLinux.Rollout.json" + } + ] + } + ] +} diff --git a/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/Shell/Run/Run.ps1 b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/Shell/Run/Run.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..6797ff945758f26f345c9f4c8def53f82fb87eaa --- /dev/null +++ b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/Shell/Run/Run.ps1 @@ -0,0 +1,397 @@ +<# +This function gets info from pmc's derived list of all repositories and from mapping.json (which contains info on just the repositories powershell publishes packages to, their package formats, etc) +to create a list of repositories PowerShell cares about along with repository Ids, repository full Urls and associated package that will be published to it. +#> +function Get-MappedRepositoryIds { + param( + [Parameter(Mandatory)] + [hashtable] + $Mapping, + + [Parameter(Mandatory)] + $RepoList, + + # LTS is not consider a package in this context. + # LTS is just another package name. + [Parameter(Mandatory)] + [ValidateSet('stable', 'preview')] + $Channel + ) + + $mappedReposUsedByPwsh = @() + foreach ($package in $Mapping.Packages) + { + Write-Verbose "package: $package" + $packageChannel = $package.channel + if (!$packageChannel) { + $packageChannel = 'all' + } + + Write-Verbose "package channel: $packageChannel" + if ($packageChannel -eq 'all' -or $packageChannel -eq $Channel) + { + $repoIds = [System.Collections.Generic.List[string]]::new() + $packageFormat = $package.PackageFormat + Write-Verbose "package format: $packageFormat" -Verbose + $extension = [System.io.path]::GetExtension($packageFormat) + $packageType = $extension -replace '^\.' + + if ($package.distribution.count -gt 1) { + throw "Package $($package | out-string) has more than one Distribution." + } + + foreach ($distribution in $package.distribution) + { + $urlGlob = $package.url + switch ($packageType) + { + 'deb' { + $urlGlob = $urlGlob + '-apt' + } + 'rpm' { + $urlGlob = $urlGlob + '-yum' + } + default { + throw "Unknown package type: $packageType" + } + } + + Write-Verbose "---Finding repo id for: $urlGlob---" -Verbose + $repos = $RepoList | Where-Object { $_.name -eq $urlGlob } + + if ($repos.id) { + Write-Verbose "Found repo id: $($repos.id)" -Verbose + $repoIds.AddRange(([string[]]$repos.id)) + } + else { + throw "Could not find repo for $urlGlob" + } + + if ($repoIds.Count -gt 0) { + $mappedReposUsedByPwsh += ($package + @{ "RepoId" = $repoIds.ToArray() }) + } + } + } + } + + Write-Verbose -Verbose "mapped repos length: $($mappedReposUsedByPwsh.Length)" + return $mappedReposUsedByPwsh +} + +<# +This function creates package objects for the packages to be published, +with the package name (ie package name format resolve with channel based PackageName and pwsh version), repoId, distribution and package path. +#> +function Get-PackageObjects() { + param( + [Parameter(Mandatory)] + [psobject[]] + $RepoObjects, + + [Parameter(Mandatory)] + [string] + $ReleaseVersion, + + [Parameter(Mandatory)] + [string[]] + $PackageName + ) + + $packages = @() + + foreach ($pkg in $RepoObjects) + { + if ($pkg.RepoId.count -gt 1) { + throw "Package $($pkg.name) has more than one repo id." + } + + if ($pkg.Distribution.count -gt 1) { + throw "Package $($pkg.name) has more than one Distribution." + } + + $pkgRepo = $pkg.RepoId | Select-Object -First 1 + $pkgDistribution = $pkg.Distribution | Select-Object -First 1 + + foreach ($name in $PackageName) { + $pkgName = $pkg.PackageFormat.Replace('PACKAGE_NAME', $name).Replace('POWERSHELL_RELEASE', $ReleaseVersion) + + if ($pkgName.EndsWith('.rpm')) { + $pkgName = $pkgName.Replace($ReleaseVersion, $ReleaseVersion.Replace('-', '_')) + } + + $packagePath = "$pwshPackagesFolder/$pkgName" + $packagePathExists = Test-Path -Path $packagePath + if (!$packagePathExists) + { + throw "package path $packagePath does not exist" + } + + Write-Verbose "Creating package info object for package '$pkgName' for repo '$pkgRepo'" + $packages += @{ + PackagePath = $packagePath + PackageName = $pkgName + RepoId = $pkgRepo + Distribution = $pkgDistribution + } + + Write-Verbose -Verbose "package info obj: Name: $pkgName RepoId: $pkgRepo Distribution: $pkgDistribution PackagePath: $packagePath" + } + } + + Write-Verbose -Verbose "count of packages objects: $($packages.Length)" + return $packages +} + +<# +This function stages, uploads and publishes the powershell packages to their associated repositories in PMC. +#> +function Publish-PackageToPMC() { + param( + [Parameter(Mandatory)] + [pscustomobject[]] + $PackageObject, + + [Parameter(Mandatory)] + [string] + $ConfigPath, + + [Parameter(Mandatory)] + [bool] + $SkipPublish + ) + + # Don't fail outright when an error occurs, but instead pool them until + # after attempting to publish every package. That way we can choose to + # proceed for a partial failure. + $errorMessage = [System.Collections.Generic.List[string]]::new() + foreach ($finalPackage in $PackageObject) + { + Write-Verbose "---Staging package: $($finalPackage.PackageName)---" -Verbose + $packagePath = $finalPackage.PackagePath + $pkgRepo = $finalPackage.RepoId + + $extension = [System.io.path]::GetExtension($packagePath) + $packageType = $extension -replace '^\.' + Write-Verbose "packageType: $packageType" -Verbose + + $packageListJson = pmc --config $ConfigPath package $packageType list --file $packagePath + $list = $packageListJson | ConvertFrom-Json + + $packageId = @() + if ($list.count -ne 0) + { + Write-Verbose "Package '$packagePath' already exists, skipping upload" -Verbose + $packageId = $list.results.id | Select-Object -First 1 + } + else { + # PMC UPLOAD COMMAND + Write-Verbose -Verbose "Uploading package, config: '$ConfigPath' package: '$packagePath'" + $uploadResult = $null + try { + $uploadResult = pmc --config $ConfigPath package upload $packagePath --type $packageType + } + catch { + $errorMessage.Add("Uploading package $($finalPackage.PackageName) to $pkgRepo failed. See errors above for details.") + continue + } + + $packageId = ($uploadResult | ConvertFrom-Json).id + } + + Write-Verbose "Got package ID: '$packageId'" -Verbose + $distribution = $finalPackage.Distribution | select-object -First 1 + Write-Verbose "distribution: $distribution" -Verbose + + if (!$SkipPublish) + { + Write-Verbose "---Publishing package: $($finalPackage.PackageName) to $pkgRepo---" -Verbose + + if (($packageType -ne 'rpm') -and ($packageType -ne 'deb')) + { + throw "Unsupported package type: $packageType" + return 1 + } + else { + # PMC UPDATE COMMAND + $rawUpdateResponse = $null + try { + if ($packageType -eq 'rpm') { + $rawUpdateResponse = pmc --config $ConfigPath repo package update $pkgRepo --add-packages $packageId + } elseif ($packageType -eq 'deb') { + $rawUpdateResponse = pmc --config $ConfigPath repo package update $pkgRepo $distribution --add-packages $packageId + } + } + catch { + $errorMessage.Add("Invoking update for package $($finalPackage.PackageName) to $pkgRepo failed. See errors above for details.") + continue + } + + $state = ($rawUpdateResponse | ConvertFrom-Json).state + Write-Verbose -Verbose "update response state: $state" + if ($state -ne 'completed') { + $errorMessage.Add("Publishing package $($finalPackage.PackageName) to $pkgRepo failed: $rawUpdateResponse") + continue + } + } + + # PMC PUBLISH COMMAND + # The CLI outputs messages and JSON in the same stream, so we must sift through it for now + # This is planned to be fixed with a switch in a later release + Write-Verbose -Verbose ([pscustomobject]($package + @{ + PackageId = $packageId + })) + + # At this point, the changes are staged and will eventually be publish. + # Running publish, causes them to go live "immediately" + $rawPublishResponse = $null + try { + $rawPublishResponse = pmc --config $ConfigPath repo publish $pkgRepo + } + catch { + $errorMessage.Add("Invoking final publish for package $($finalPackage.PackageName) to $pkgRepo failed. See errors above for details.") + continue + } + + $publishState = ($rawPublishResponse | ConvertFrom-Json).state + Write-Verbose -Verbose "publish response state: $publishState" + if ($publishState -ne 'completed') { + $errorMessage.Add("Final publishing of package $($finalPackage.PackageName) to $pkgRepo failed: $rawPublishResponse") + continue + } + } else { + Write-Verbose -Verbose "Skipping Uploading package --config-file '$ConfigPath' package add '$packagePath' --repoID '$pkgRepo'" + } + } + + if ($errorMessage) { + throw $errorMessage -join [Environment]::NewLine + } +} + +if ($null -eq $env:MAPPING_FILE) +{ + Write-Verbose -Verbose "MAPPING_FILE variable didn't get passed correctly" + return 1 +} + +if ($null -eq $env:PWSH_PACKAGES_TARGZIP) +{ + Write-Verbose -Verbose "PWSH_PACKAGES_TARGZIP variable didn't get passed correctly" + return 1 +} + +if ($null -eq $env:PMC_METADATA) +{ + Write-Verbose -Verbose "PMC_METADATA variable didn't get passed correctly" + return 1 +} + +try { + Write-Verbose -Verbose "Downloading files" + Invoke-WebRequest -Uri $env:MAPPING_FILE -OutFile mapping.json + Invoke-WebRequest -Uri $env:PWSH_PACKAGES_TARGZIP -OutFile packages.tar.gz + Invoke-WebRequest -Uri $env:PMC_METADATA -OutFile pmcMetadata.json + + # create variables to those paths and test them + $mappingFilePath = Join-Path "/package/unarchive/" -ChildPath "mapping.json" + $mappingFilePathExists = Test-Path $mappingFilePath + if (!$mappingFilePathExists) + { + Write-Verbose -Verbose "mapping.json expected at $mappingFilePath does not exist" + return 1 + } + + $packagesTarPath = Join-Path -Path "/package/unarchive/" -ChildPath "packages.tar.gz" + $packagesTarPathExists = Test-Path $packagesTarPath + if (!$packagesTarPathExists) + { + Write-Verbose -Verbose "packages.tar.gz expected at $packagesTarPath does not exist" + return 1 + } + + # Extract files from 'packages.tar.gz' + Write-Verbose -Verbose "---Extracting files from packages.tar.gz---" + $pwshPackagesFolder = Join-Path -Path "/package/unarchive/" -ChildPath "packages" + New-Item -Path $pwshPackagesFolder -ItemType Directory + tar -xzvf $packagesTarPath -C $pwshPackagesFolder --force-local + Get-ChildItem $pwshPackagesFolder -Recurse + + $metadataFilePath = Join-Path -Path "/package/unarchive/" -ChildPath "pmcMetadata.json" + $metadataFilePathExists = Test-Path $metadataFilePath + if (!$metadataFilePathExists) + { + Write-Verbose -Verbose "pmcMetadata.json expected at $metadataFilePath does not exist" + return 1 + } + + # files in the extracted Run dir + $configPath = Join-Path '/package/unarchive/Run' -ChildPath 'settings.toml' + $configPathExists = Test-Path -Path $configPath + if (!$configPathExists) + { + Write-Verbose -Verbose "settings.toml expected at $configPath does not exist" + return 1 + } + + $pythonDlFolder = Join-Path '/package/unarchive/Run' -ChildPath 'python_dl' + $pyPathExists = Test-Path -Path $pythonDlFolder + if (!$pyPathExists) + { + Write-Verbose -Verbose "python_dl expected at $pythonDlFolder does not exist" + return 1 + } + + Write-Verbose -Verbose "Installing pmc-cli" + pip install --upgrade pip + pip --version --verbose + pip install /package/unarchive/Run/python_dl/*.whl + + # Get metadata + $channel = "" + $packageNames = @() + $metadataContent = Get-Content -Path $metadataFilePath | ConvertFrom-Json + $releaseVersion = $metadataContent.ReleaseTag.TrimStart('v') + $skipPublish = $metadataContent.SkipPublish + $lts = $metadataContent.LTS + + # Check if this is a rebuild version (e.g., 7.4.13-rebuild.5) + $isRebuild = $releaseVersion -match '-rebuild\.' + + if ($releaseVersion.Contains('-')) { + $channel = 'preview' + $packageNames = @('powershell-preview') + } + else { + $channel = 'stable' + $packageNames = @('powershell') + } + + # Only add LTS package if not a rebuild branch + if ($lts -and -not $isRebuild) { + $packageNames += @('powershell-lts') + } + + Write-Verbose -Verbose "---Getting repository list---" + $rawResponse = pmc --config $configPath repo list --limit 800 + $response = $rawResponse | ConvertFrom-Json + $limit = $($response.limit) + $count = $($response.count) + Write-Verbose -Verbose "'pmc repo list' limit is: $limit and count is: $count" + $repoList = $response.results + + Write-Verbose -Verbose "---Getting package info---" + + + Write-Verbose "Reading mapping file from '$mappingFilePath'" -Verbose + $mapping = Get-Content -Raw -LiteralPath $mappingFilePath | ConvertFrom-Json -AsHashtable + $mappedReposUsedByPwsh = Get-MappedRepositoryIds -Mapping $mapping -RepoList $repoList -Channel $channel + $packageObjects = Get-PackageObjects -RepoObjects $mappedReposUsedByPwsh -PackageName $packageNames -ReleaseVersion $releaseVersion + Write-Verbose -Verbose "skip publish $skipPublish" + Publish-PackageToPMC -PackageObject $packageObjects -ConfigPath $configPath -SkipPublish $skipPublish +} +catch { + Write-Error -ErrorAction Stop $_.Exception.Message + return 1 +} + +return 0 diff --git a/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/UploadLinux.Rollout.json b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/UploadLinux.Rollout.json new file mode 100644 index 0000000000000000000000000000000000000000..d7c75c2e216c7a814c7228f7ccb58fd7e4449ac7 --- /dev/null +++ b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/UploadLinux.Rollout.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://ev2schema.azure.net/schemas/2020-01-01/rolloutParameters.json", + "contentVersion": "1.0.0.0", + "shellExtensions": [ + { + "name": "Run", + "type": "Run", + "properties": { + "maxExecutionTime": "PT2H" + }, + "package": { + "reference": { + "path": "Shell/Run.tar" + } + }, + "launch": { + "command": [ + "/bin/bash", + "-c", + "pwsh ./Run/Run.ps1" + ], + "environmentVariables": [ + { + "name": "MAPPING_FILE", + "reference": + { + "path": "Parameters\\mapping.json" + } + }, + { + "name": "PWSH_PACKAGES_TARGZIP", + "reference": + { + "path": "Parameters\\packages.tar.gz" + } + }, + { + "name": "PMC_METADATA", + "reference": + { + "path": "Parameters\\pmcMetadata.json" + } + } + ], + "identity": { + "type": "userAssigned", + "userAssignedIdentities": [ + "default" + ] + } + } + } + ] +} diff --git a/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/buildVer.txt b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/buildVer.txt new file mode 100644 index 0000000000000000000000000000000000000000..7dea76edb3dc51b6e5e8223e9f941a35c1e364d6 --- /dev/null +++ b/PowerShell-master/.pipelines/EV2Specs/ServiceGroupRoot/buildVer.txt @@ -0,0 +1 @@ +1.0.1 diff --git a/PowerShell-master/.pipelines/MSIXBundle-vPack-Official.yml b/PowerShell-master/.pipelines/MSIXBundle-vPack-Official.yml new file mode 100644 index 0000000000000000000000000000000000000000..08edd0367bd0facc13a3990b3d40a9453b3eb54b --- /dev/null +++ b/PowerShell-master/.pipelines/MSIXBundle-vPack-Official.yml @@ -0,0 +1,509 @@ +trigger: none +pr: none + +parameters: # parameters are shown up in ADO UI in a build queue time +- name: 'createVPack' + displayName: 'Create and Submit VPack' + type: boolean + default: true +- name: 'ReleaseTagVar' + type: string + displayName: 'Release Tag Var:' + default: 'fromBranch' +- name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false +- name: netiso + displayName: "Network Isolation Policy" + type: string + values: + - KS4 + - R1 + - Netlock + default: "R1" + +name: msixbundle_vPack_$(Build.SourceBranchName)_Prod.True_Create.${{ parameters.createVPack }}_$(date:yyyyMMdd).$(rev:rr) + +variables: + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] + - name: system.debug + value: ${{ parameters.debug }} + - name: BuildSolution + value: $(Build.SourcesDirectory)\dirs.proj + - name: BuildConfiguration + value: Release + - name: WindowsContainerImage + value: 'onebranch.azurecr.io/windows/ltsc2022/vse2022:latest' + - name: Codeql.Enabled + value: false # pipeline is not building artifacts; it repackages existing artifacts into a vpack + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + - name: nugetMultiFeedWarnLevel + value: none + - name: ReleaseTagVar + value: ${{ parameters.ReleaseTagVar }} + - name: netiso + value: ${{ parameters.netiso }} + - group: certificate_logical_to_actual # used within signing task + - group: MSIXSigningProfile + - group: msixTools + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +extends: + template: v2/Microsoft.Official.yml@onebranchTemplates + parameters: + platform: + name: 'windows_undocked' # windows undocked + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: ${{ variables.netiso }} + cloudvault: + enabled: false + globalSdl: + useCustomPolicy: true # for signing code + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + compiled: + enabled: false + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config/tsaoptions.json + + stages: + - stage: Build_MSIX_Package + displayName: 'Build and create MSIX packages' + dependsOn: [] + jobs: + - job: Build + pool: + type: windows + + strategy: + matrix: + x64: + Architecture: x64 + arm64: + Architecture: arm64 + + variables: + ArtifactPlatform: 'windows' + ob_outputDirectory: '$(BUILD.SOURCESDIRECTORY)\out' + ob_artifactBaseName: drop_build_$(Architecture) + + steps: + - checkout: self + displayName: Checkout source code - during restore + clean: true + path: s ## $(Build.SourcesDirectory) is at '$(Pipeline.Workspace)\s', so we need to check out repo to the 's' folder. + env: + ob_restore_phase: true + + # The env variable 'ReleaseTagVar' will be updated in this step. + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: yes + + - pwsh: | + $releaseTag = '$(ReleaseTagVar)' + if ($releaseTag -match '-') { + throw "Never release msixbundle vpack for a preview build. Current version: $releaseTag" + } + + # Check if release tag matches the expected format v#.#.# + $matched = $releaseTag -match '^v\d+\.(\d+)\.\d+$' + if (-not $matched) { + throw "Release tag must be in the format v#.#.#, such as 'v7.4.3'. Current version: $releaseTag" + } + + # Extract minor version and verify it's even (LTS versions only) + $minorVersion = [int]$Matches[1] + if($minorVersion % 2 -ne 0) { + throw "Only release msixbundle vpack for LTS releases. Current version: $releaseTag" + } + displayName: Stop any preview release + env: + ob_restore_phase: true + + ### START BUILD ### + + # Clone the checked out PowerShell repo to '/PowerShell' and set the variable 'PowerShellRoot'. + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(PowerShellRoot) + + # Add CodeQL Init task right before your 'Build' step. + - task: CodeQL3000Init@0 + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + inputs: + Enabled: true + # AnalyzeInPipeline: false = upload results + # AnalyzeInPipeline: true = do not upload results + AnalyzeInPipeline: false + Language: csharp + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $runtime = switch ($env:Architecture) + { + "x64" { "win7-x64" } + "arm64" { "win-arm64" } + } + + $vstsCommandString = "vso[task.setvariable variable=Runtime]$runtime" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + + Write-Verbose -Message "Building PowerShell with Runtime: $runtime for '$env:BuildConfiguration' configuration" + Import-Module -Name $(PowerShellRoot)/build.psm1 -Force + $buildWithSymbolsPath = New-Item -ItemType Directory -Path $(Pipeline.Workspace)/Symbols_$(Architecture) -Force + + Start-PSBootstrap -Scenario Package + $null = New-Item -ItemType Directory -Path $buildWithSymbolsPath -Force -Verbose + + Start-PSBuild -Runtime $runtime -Configuration Release -Output $buildWithSymbolsPath -Clean -PSModuleRestore -ReleaseTag $(ReleaseTagVar) + + $refFolderPath = Join-Path $buildWithSymbolsPath 'ref' + Write-Verbose -Verbose "refFolderPath: $refFolderPath" + $outputPath = Join-Path '$(ob_outputDirectory)' 'psoptions' + $null = New-Item -ItemType Directory -Path $outputPath -Force + $psOptPath = "$outputPath/psoptions.json" + Save-PSOptions -PSOptionsPath $psOptPath + + Write-Verbose -Verbose "Verifying pdbs exist in build folder" + $pdbs = Get-ChildItem -Path $buildWithSymbolsPath -Recurse -Filter *.pdb + if ($pdbs.Count -eq 0) { + throw "No pdbs found in build folder" + } + else { + Write-Verbose -Verbose "Found $($pdbs.Count) pdbs in build folder" + $pdbs | ForEach-Object { + Write-Verbose -Verbose "Pdb: $($_.FullName)" + } + + $pdbs | Compress-Archive -DestinationPath '$(ob_outputDirectory)\symbols-$(Architecture).zip' -Update + } + + Write-Verbose -Verbose "Completed building PowerShell for '$env:BuildConfiguration' configuration" + displayName: 'Build Windows Universal - $(Architecture)-$(BuildConfiguration) Symbols folder' + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + # Add CodeQL Finalize task right after your 'Build' step. + - task: CodeQL3000Finalize@0 + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 + displayName: 'Component Detection' + inputs: + sourceScanPath: '$(PowerShellRoot)\src' + ob_restore_phase: true + + # The signed files will be put in '$(ob_outputDirectory)\Signed-$(Runtime)' after this step. + - template: /.pipelines/templates/obp-file-signing.yml@self + parameters: + binPath: '$(Pipeline.Workspace)/Symbols_$(Architecture)' + OfficialBuild: true + + ### END OF BUILD ### + + - pwsh: | + Get-ChildItem -Path '$(ob_outputDirectory)\Signed-$(Runtime)' -Recurse | Out-String -Width 9999 + displayName: Capture signed files + condition: succeededOrFailed() + + - pwsh: | + Get-ChildItem -Path env: | Out-String -Width 9999 + displayName: Capture Environment + condition: succeededOrFailed() + + ### START Packaging ### + + - template: /.pipelines/templates/shouldSign.yml@self + parameters: + ob_restore_phase: false + + - pwsh: | + Write-Verbose -Verbose "runtime = '$(Runtime)'" + Write-Verbose -Verbose "RepoRoot = '$(PowerShellRoot)'" + + $runtime = '$(Runtime)' + $repoRoot = '$(PowerShellRoot)' + Import-Module "$repoRoot\build.psm1" + Import-Module "$repoRoot\tools\packaging" + + Find-Dotnet + + $signedFilesPath = '$(ob_outputDirectory)\Signed-$(Runtime)' + $psoptionsFilePath = '$(ob_outputDirectory)\psoptions\psoptions.json' + + Write-Verbose -Verbose "signedFilesPath: $signedFilesPath" + Write-Verbose -Verbose "psoptionsFilePath: $psoptionsFilePath" + + Write-Verbose -Message "checking pwsh exists in $signedFilesPath" -Verbose + if (-not (Test-Path $signedFilesPath\pwsh.exe)) { + throw "pwsh.exe not found in $signedFilesPath" + } + + Write-Verbose -Message "Restoring PSOptions from $psoptionsFilePath" -Verbose + + Restore-PSOptions -PSOptionsPath "$psoptionsFilePath" + Get-PSOptions | Write-Verbose -Verbose + + ## Generated packages are placed in the current directory by default. + Set-Location $repoRoot + Start-PSPackage -Type msix -SkipReleaseChecks -WindowsRuntime $runtime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath -LTS + + $msixPkgNameFilter = "PowerShell*.msix" + $msixPkgFile = Get-ChildItem -Path $repoRoot -Filter $msixPkgNameFilter -File + $msixPkgPath = $msixPkgFile.FullName + Write-Verbose -Verbose "Unsigned msix package: $msixPkgPath" + + $pkgDir = '$(ob_outputDirectory)\pkgs' + $null = New-Item -ItemType Directory -Path $pkgDir -Force + Copy-Item -Path $msixPkgPath -Destination $pkgDir -Force -Verbose + displayName: 'Build MSIX Package (Unsigned)' + + ### END OF Packaging ### + + - pwsh: | + Get-ChildItem -Path '$(ob_outputDirectory)\pkgs' -Recurse + displayName: 'List Unsigned Package' + + - stage: Pack_MSIXBundle_And_Sign + displayName: 'Pack and sign MSIXBundle' + dependsOn: [Build_MSIX_Package] + jobs: + - job: Bundle + pool: + type: windows + variables: + ArtifactPlatform: 'windows' + ob_outputDirectory: '$(BUILD.SOURCESDIRECTORY)\out' + ob_artifactBaseName: drop_pack_msixbundle + ob_createvpack_enabled: ${{ parameters.createVPack }} + ob_createvpack_packagename: 'PowerShell7.Store.app' + ob_createvpack_owneralias: 'dongbow' + ob_createvpack_description: 'VPack for the PowerShell 7 Store Application' + ob_createvpack_targetDestinationDirectory: '$(Destination)' ## The value is from the 'CreateVpack' task, used when pulling the generated VPack. + ob_createvpack_propsFile: false + ob_createvpack_provData: true + ob_createvpack_metadata: '$(Build.SourceVersion)' + ob_createvpack_versionAs: string + ob_createvpack_version: '$(Version)' + ob_createvpack_verbose: true + + steps: + - checkout: self + displayName: Checkout source code - during restore + clean: true + path: s ## $(Build.SourcesDirectory) is at '$(Pipeline.Workspace)\s', so we need to check out repo to the 's' folder. + env: + ob_restore_phase: true + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: /.pipelines/templates/shouldSign.yml@self + + - task: DownloadPipelineArtifact@2 + inputs: + artifactName: drop_build_x64 + itemPattern: | + **/*.msix + targetPath: '$(Build.ArtifactStagingDirectory)\downloads' + displayName: Download msix for x64 + + - task: DownloadPipelineArtifact@2 + inputs: + artifactName: drop_build_arm64 + itemPattern: | + **/*.msix + targetPath: '$(Build.ArtifactStagingDirectory)\downloads' + displayName: Download msix for arm64 + + # Finds the makeappx tool on the machine. + - pwsh: | + Write-Verbose -Verbose 'PowerShell Version: $(Version)' + $cmd = Get-Command makeappx.exe -ErrorAction Ignore + if ($cmd) { + Write-Verbose -Verbose 'makeappx available in PATH' + $exePath = $cmd.Source + } else { + $makeappx = Get-ChildItem -Recurse 'C:\Program Files (x86)\Windows Kits\10\makeappx.exe' | + Where-Object { $_.DirectoryName -match 'x64' } | + Select-Object -Last 1 + $exePath = $makeappx.FullName + Write-Verbose -Verbose "makeappx was found: $exePath" + } + $vstsCommandString = "vso[task.setvariable variable=MakeAppxPath]$exePath" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: Find makeappx tool + retryCountOnTaskFailure: 1 + + - pwsh: | + $sourceDir = '$(Pipeline.Workspace)\releasePipeline\msix' + $null = New-Item -Path $sourceDir -ItemType Directory -Force + + $msixFiles = Get-ChildItem -Path "$(Build.ArtifactStagingDirectory)\downloads\*.msix" -Recurse + foreach ($msixFile in $msixFiles) { + $null = Copy-Item -Path $msixFile.FullName -Destination $sourceDir -Force -Verbose + } + + $file = Get-ChildItem $sourceDir | Select-Object -First 1 + $prefix = ($file.BaseName -split "-win")[0] + $pkgName = "$prefix.msixbundle" + Write-Verbose -Verbose "Creating $pkgName" + + $makeappx = '$(MakeAppxPath)' + $outputDir = "$sourceDir\output" + New-Item $outputDir -Type Directory -Force > $null + & $makeappx bundle /d $sourceDir /p "$outputDir\$pkgName" + if ($LASTEXITCODE -ne 0) { + throw "makeappx bundle failed with exit code $LASTEXITCODE" + } + + Get-ChildItem -Path $sourceDir -Recurse | Out-String -Width 200 + $vstsCommandString = "vso[task.setvariable variable=BundleDir]$outputDir" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: Create MsixBundle + retryCountOnTaskFailure: 1 + + - task: onebranch.pipeline.signing@1 + displayName: Sign MsixBundle + inputs: + command: 'sign' + signing_profile: $(MSIXProfile) + files_to_sign: '**/*.msixbundle' + search_root: '$(BundleDir)' + + - pwsh: | + $signedBundle = Get-ChildItem -Path $(BundleDir) -Filter "*.msixbundle" -File + Write-Verbose -Verbose "Signed bundle: $signedBundle" + + $signature = Get-AuthenticodeSignature -FilePath $signedBundle.FullName + if ($signature.Status -ne 'Valid') { + throw "The bundle file doesn't have a valid signature. Signature status: $($signature.Status)" + } + + if (-not (Test-Path '$(ob_outputDirectory)' -PathType Container)) { + $null = New-Item '$(ob_outputDirectory)' -ItemType Directory -ErrorAction Stop + } + + $targetPath = Join-Path '$(ob_outputDirectory)' 'Microsoft.PowerShell-LTS_8wekyb3d8bbwe.msixbundle' + Copy-Item -Verbose -Path $signedBundle.FullName -Destination $targetPath + + Write-Verbose -Verbose "Uploaded Bundle:" + Get-ChildItem -Path $(ob_outputDirectory) | Out-String -Width 200 -Stream | Write-Verbose -Verbose + displayName: 'Stage msixbundle for VPack' + + - pwsh: | + Write-Verbose "VPack Version: $(ob_createvpack_version)" -Verbose + $vpackFiles = Get-ChildItem -Path '$(ob_outputDirectory)\*' -Recurse + if($vpackFiles.Count -eq 0) { + throw "No files found in $(ob_outputDirectory)" + } + $vpackFiles | Out-String -Width 200 + displayName: Debug Output Directory and Version + condition: succeededOrFailed() + + - stage: Publish_Symbols + displayName: 'Publish Symbols' + dependsOn: [Pack_MSIXBundle_And_Sign] + jobs: + - job: PublishSymbols + pool: + type: windows + variables: + ob_outputDirectory: '$(BUILD.SOURCESDIRECTORY)\out' + + steps: + - checkout: self + displayName: Checkout source code - during restore + clean: true + path: s ## $(Build.SourcesDirectory) is at '$(Pipeline.Workspace)\s', so we need to check out repo to the 's' folder. + env: + ob_restore_phase: true + + - pwsh: | + Get-ChildItem Env: | Out-String -Width 9999 + displayName: 'Capture Environment Variables' + + - task: DownloadPipelineArtifact@2 + inputs: + artifactName: drop_build_x64 + itemPattern: | + **/symbols-*.zip + targetPath: '$(Build.ArtifactStagingDirectory)\downloads' + displayName: Download symbols for x64 + + - task: DownloadPipelineArtifact@2 + inputs: + artifactName: drop_build_arm64 + itemPattern: | + **/symbols-*.zip + targetPath: '$(Build.ArtifactStagingDirectory)\downloads' + displayName: Download symbols for arm64 + + - pwsh: | + $downloadDir = '$(Build.ArtifactStagingDirectory)\downloads' + Write-Verbose -Verbose "Enumerating $downloadDir" + $downloadedArtifacts = Get-ChildItem -Path $downloadDir -Recurse -Filter 'symbols-*.zip' + $downloadedArtifacts | Out-String -Width 9999 + + $expandedRoot = New-Item -Path "$(Pipeline.Workspace)\expanded" -ItemType Directory -Verbose + $downloadedArtifacts | ForEach-Object { + $expandDir = Join-Path $expandedRoot $_.BaseName + Write-Verbose -Verbose "Expanding $($_.FullName) to $expandDir" + $null = New-Item -Path $expandDir -ItemType Directory -Verbose + Expand-Archive -Path $_.FullName -DestinationPath $expandDir -Force + } + + Write-Verbose -Verbose "Enumerating $expandedRoot" + Get-ChildItem -Path $expandedRoot -Recurse | Out-String -Width 9999 + $vstsCommandString = "vso[task.setvariable variable=SymbolsPath]$expandedRoot" + Write-Verbose -Message "$vstsCommandString" -Verbose + Write-Host -Object "##$vstsCommandString" + displayName: Expand and capture symbols folders + + - task: PublishSymbols@2 + condition: and(succeeded(), ${{ parameters.createVPack }}) + inputs: + symbolsFolder: '$(SymbolsPath)' + searchPattern: '**/*.pdb' + indexSources: false + publishSymbols: true + symbolServerType: TeamServices + detailedLog: true diff --git a/PowerShell-master/.pipelines/NonOfficial/PowerShell-Coordinated_Packages-NonOfficial.yml b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Coordinated_Packages-NonOfficial.yml new file mode 100644 index 0000000000000000000000000000000000000000..0b417df5c05681428a7001fb7ccbc821e14ec7ca --- /dev/null +++ b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Coordinated_Packages-NonOfficial.yml @@ -0,0 +1,97 @@ +trigger: none + +parameters: + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: ReleaseTagVar + displayName: Release Tag + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + displayName: Debugging - Skip Signing + type: string + default: 'NO' + - name: RUN_TEST_AND_RELEASE + displayName: Debugging - Run Test and Release Artifacts Stage + type: boolean + default: true + - name: RUN_WINDOWS + displayName: Debugging - Enable Windows Stage + type: boolean + default: true + - name: ENABLE_MSBUILD_BINLOGS + displayName: Debugging - Enable MSBuild Binary Logs + type: boolean + default: false + - name: FORCE_CODEQL + displayName: Debugging - Enable CodeQL and set cadence to 1 hour + type: boolean + default: false + +name: bins-$(BUILD.SOURCEBRANCHNAME)-nonofficial-$(Build.BuildId) + +resources: + repositories: + - repository: ComplianceRepo + type: github + endpoint: ComplianceGHRepo + name: PowerShell/compliance + ref: master + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +variables: + - template: ./pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml@self + parameters: + InternalSDKBlobURL: ${{ parameters.InternalSDKBlobURL }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + SKIP_SIGNING: ${{ parameters.SKIP_SIGNING }} + ENABLE_MSBUILD_BINLOGS: ${{ parameters.ENABLE_MSBUILD_BINLOGS }} + FORCE_CODEQL: ${{ parameters.FORCE_CODEQL }} + +extends: + template: v2/OneBranch.NonOfficial.CrossPlat.yml@onebranchTemplates + parameters: + customTags: 'ES365AIMigrationTooling' + featureFlags: + LinuxHostVersion: + Network: KS3 + WindowsHostVersion: + Network: KS3 + incrementalSDLBinaryAnalysis: true + globalSdl: + disableLegacyManifest: true + # disabled Armorty as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + codeql: + compiled: + enabled: $(CODEQL_ENABLED) + tsaEnabled: true # This enables TSA bug filing only for CodeQL 3000 + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + cg: + enabled: true + ignoreDirectories: '.devcontainer,demos,docker,docs,src,test,tools/packaging' + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config\tsaoptions.json + + stages: + - template: ./pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml@self + parameters: + RUN_WINDOWS: ${{ parameters.RUN_WINDOWS }} + RUN_TEST_AND_RELEASE: ${{ parameters.RUN_TEST_AND_RELEASE }} + OfficialBuild: false diff --git a/PowerShell-master/.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml new file mode 100644 index 0000000000000000000000000000000000000000..9419d3f29b5755ee2d550b7f4981389a47470eae --- /dev/null +++ b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml @@ -0,0 +1,97 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time + - name: ForceAzureBlobDelete + displayName: Delete Azure Blob + type: string + values: + - true + - false + default: false + - name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: ReleaseTagVar + displayName: Release Tag + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + displayName: Skip Signing + type: string + default: 'NO' + - name: disableNetworkIsolation + type: boolean + default: false + +name: pkgs-$(BUILD.SOURCEBRANCHNAME)-nonofficial-$(Build.BuildId) + +variables: + - template: ./pipelines/templates/variables/PowerShell-Packages-Variables.yml@self + parameters: + debug: ${{ parameters.debug }} + ForceAzureBlobDelete: ${{ parameters.ForceAzureBlobDelete }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + disableNetworkIsolation: ${{ parameters.disableNetworkIsolation }} + +resources: + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated_Packages-NonOfficial' + trigger: + branches: + include: + - master + - releases/* + + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +extends: + template: v2/OneBranch.NonOfficial.CrossPlat.yml@onebranchTemplates + parameters: + cloudvault: + enabled: false + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: KS3 + LinuxHostVersion: + Network: KS3 + linuxEsrpSigning: true + incrementalSDLBinaryAnalysis: true + disableNetworkIsolation: ${{ variables.disableNetworkIsolation }} + globalSdl: + disableLegacyManifest: true + # disabled Armorty as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + compiled: + enabled: false + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + cg: + enabled: true + ignoreDirectories: '.devcontainer,demos,docker,docs,src,test,tools/packaging' + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config\tsaoptions.json + stages: + - template: ./pipelines/templates/stages/PowerShell-Packages-Stages.yml@self + parameters: + OfficialBuild: false diff --git a/PowerShell-master/.pipelines/NonOfficial/PowerShell-Release-Azure-NonOfficial.yml b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Release-Azure-NonOfficial.yml new file mode 100644 index 0000000000000000000000000000000000000000..b524cb0ff816e30c07f3eeb5698c8f9db7b3ac2b --- /dev/null +++ b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Release-Azure-NonOfficial.yml @@ -0,0 +1,76 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time + - name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false + - name: skipPublish + displayName: Skip PMC Publish + type: boolean + default: false + - name: SKIP_SIGNING + displayName: Skip Signing + type: string + default: 'NO' + +name: ev2-$(BUILD.SOURCEBRANCHNAME)-nonofficial-$(Build.BuildId) + +variables: + - template: ./pipelines/templates/variables/PowerShell-Release-Azure-Variables.yml@self + parameters: + debug: ${{ parameters.debug }} + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated_Packages-NonOfficial' + + - pipeline: PSPackagesOfficial + source: 'PowerShell-Packages-NonOfficial' + trigger: + branches: + include: + - master + - releases/* + +extends: + template: v2/OneBranch.NonOfficial.CrossPlat.yml@onebranchTemplates + parameters: + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: Netlock + linuxEsrpSigning: true + incrementalSDLBinaryAnalysis: true + cloudvault: + enabled: false + globalSdl: + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + tsa: + enabled: true + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + break: false # always break the build on binskim issues in addition to TSA upload + exactToolVersion: 4.4.2 + policheck: + break: true # always break the build on policheck issues. You can disable it by setting to 'false' + tsaOptionsFile: .config\tsaoptions.json + stages: + - template: /.pipelines/templates/release-prep-for-ev2.yml@self + parameters: + skipPublish: ${{ parameters.skipPublish }} + + - template: /.pipelines/templates/release-publish-pmc.yml@self diff --git a/PowerShell-master/.pipelines/NonOfficial/PowerShell-Release-NonOfficial.yml b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Release-NonOfficial.yml new file mode 100644 index 0000000000000000000000000000000000000000..7864513fc2c3ff91a3e58df016d081f4c1609b5f --- /dev/null +++ b/PowerShell-master/.pipelines/NonOfficial/PowerShell-Release-NonOfficial.yml @@ -0,0 +1,106 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time + - name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: ReleaseTagVar + displayName: Release Tag + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + displayName: Skip Signing + type: string + default: 'NO' + - name: SkipPublish + displayName: Skip Publishing to Nuget + type: boolean + default: false + - name: SkipPSInfraInstallers + displayName: Skip Copying Archives and Installers to PSInfrastructure Public Location + type: boolean + default: false + - name: skipMSIXPublish + displayName: Skip MSIX Publish + type: boolean + default: false + +name: release-$(BUILD.SOURCEBRANCHNAME)-nonofficial-$(Build.BuildId) + +variables: + - template: ./pipelines/templates/variables/PowerShell-Release-Variables.yml@self + parameters: + debug: ${{ parameters.debug }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + - repository: PSInternalTools + type: git + name: PowerShellCore/Internal-PowerShellTeam-Tools + ref: refs/heads/master + + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated_Packages-NonOfficial' + + # NOTE: The alias name "PSPackagesOfficial" is intentionally reused here even + # for the NonOfficial pipeline source. Downstream shared templates (for example, + # release-validate-sdk.yml and release-upload-buildinfo.yml) reference artifacts + # using `download: PSPackagesOfficial`, so changing this alias would break them. + - pipeline: PSPackagesOfficial + source: 'PowerShell-Packages-NonOfficial' + trigger: + branches: + include: + - master + - releases/* + +extends: + template: v2/OneBranch.NonOfficial.CrossPlat.yml@onebranchTemplates + parameters: + release: + category: NonAzure + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: KS3 + incrementalSDLBinaryAnalysis: true + cloudvault: + enabled: false + globalSdl: + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + tsa: + enabled: true + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + break: false # always break the build on binskim issues in addition to TSA upload + exactToolVersion: 4.4.2 + policheck: + break: true # always break the build on policheck issues. You can disable it by setting to 'false' + # suppression: + # suppressionFile: $(Build.SourcesDirectory)\.gdn\global.gdnsuppress + tsaOptionsFile: .config\tsaoptions.json + + stages: + - template: ./pipelines/templates/stages/PowerShell-Release-Stages.yml@self + parameters: + releaseEnvironment: Test + SkipPublish: ${{ parameters.SkipPublish }} + SkipPSInfraInstallers: ${{ parameters.SkipPSInfraInstallers }} + skipMSIXPublish: ${{ parameters.skipMSIXPublish }} diff --git a/PowerShell-master/.pipelines/NonOfficial/PowerShell-vPack-NonOfficial.yml b/PowerShell-master/.pipelines/NonOfficial/PowerShell-vPack-NonOfficial.yml new file mode 100644 index 0000000000000000000000000000000000000000..f1f4211ca8f5dbce27be2da9652980429ab67c05 --- /dev/null +++ b/PowerShell-master/.pipelines/NonOfficial/PowerShell-vPack-NonOfficial.yml @@ -0,0 +1,88 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time +- name: 'createVPack' + displayName: 'Create and Submit VPack' + type: boolean + default: true +- name: vPackName + type: string + displayName: 'VPack Name:' + default: 'PowerShell.BuildTool' + values: + - PowerShell.BuildTool + - PowerShell + - PowerShellDoNotUse +- name: 'ReleaseTagVar' + type: string + displayName: 'Release Tag Var:' + default: 'fromBranch' +- name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false +- name: netiso + displayName: "Network Isolation Policy" + type: string + values: + - KS4 + - R1 + - Netlock + default: "R1" + +name: vPack_$(Build.SourceBranchName)_NonOfficial_Create.${{ parameters.createVPack }}_Name.${{ parameters.vPackName}}_$(date:yyyyMMdd).$(rev:rr) + +variables: + - template: ./pipelines/templates/variables/PowerShell-vPack-Variables.yml@self + parameters: + debug: ${{ parameters.debug }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + netiso: ${{ parameters.netiso }} + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +extends: + template: v2/Microsoft.NonOfficial.yml@onebranchTemplates + parameters: + platform: + name: 'windows_undocked' # windows undocked + + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: ${{ variables.netiso }} + + cloudvault: + enabled: false + + globalSdl: + useCustomPolicy: true # for signing code + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + compiled: + enabled: false + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config/tsaoptions.json + stages: + - template: ./pipelines/templates/stages/PowerShell-vPack-Stages.yml@self + parameters: + createVPack: ${{ parameters.createVPack }} + vPackName: ${{ parameters.vPackName }} diff --git a/PowerShell-master/.pipelines/PowerShell-Coordinated_Packages-Official.yml b/PowerShell-master/.pipelines/PowerShell-Coordinated_Packages-Official.yml new file mode 100644 index 0000000000000000000000000000000000000000..82f129a0a5ebe38082a7900a0769c5c2b9989c6e --- /dev/null +++ b/PowerShell-master/.pipelines/PowerShell-Coordinated_Packages-Official.yml @@ -0,0 +1,98 @@ +trigger: none + +parameters: + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: ReleaseTagVar + displayName: Release Tag + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + displayName: Debugging - Skip Signing + type: string + default: 'NO' + - name: RUN_TEST_AND_RELEASE + displayName: Debugging - Run Test and Release Artifacts Stage + type: boolean + default: true + - name: RUN_WINDOWS + displayName: Debugging - Enable Windows Stage + type: boolean + default: true + - name: ENABLE_MSBUILD_BINLOGS + displayName: Debugging - Enable MSBuild Binary Logs + type: boolean + default: false + - name: FORCE_CODEQL + displayName: Debugging - Enable CodeQL and set cadence to 1 hour + type: boolean + default: false + +name: bins-$(BUILD.SOURCEBRANCHNAME)-prod-$(Build.BuildId) + +resources: + repositories: + - repository: ComplianceRepo + type: github + endpoint: ComplianceGHRepo + name: PowerShell/compliance + ref: master + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +variables: + - template: templates/variables/PowerShell-Coordinated_Packages-Variables.yml + parameters: + InternalSDKBlobURL: ${{ parameters.InternalSDKBlobURL }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + SKIP_SIGNING: ${{ parameters.SKIP_SIGNING }} + ENABLE_MSBUILD_BINLOGS: ${{ parameters.ENABLE_MSBUILD_BINLOGS }} + FORCE_CODEQL: ${{ parameters.FORCE_CODEQL }} + +extends: + template: v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates + parameters: + customTags: 'ES365AIMigrationTooling' + featureFlags: + LinuxHostVersion: + Network: KS3 + WindowsHostVersion: + Version: 2022 + Network: KS3 + incrementalSDLBinaryAnalysis: true + globalSdl: + disableLegacyManifest: true + # disabled Armorty as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + codeql: + compiled: + enabled: $(CODEQL_ENABLED) + tsaEnabled: true # This enables TSA bug filing only for CodeQL 3000 + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + cg: + enabled: true + ignoreDirectories: '.devcontainer,demos,docker,docs,src,test,tools/packaging' + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config\tsaoptions.json + + stages: + - template: templates/stages/PowerShell-Coordinated_Packages-Stages.yml + parameters: + RUN_WINDOWS: ${{ parameters.RUN_WINDOWS }} + RUN_TEST_AND_RELEASE: ${{ parameters.RUN_TEST_AND_RELEASE }} + OfficialBuild: true diff --git a/PowerShell-master/.pipelines/PowerShell-Packages-Official.yml b/PowerShell-master/.pipelines/PowerShell-Packages-Official.yml new file mode 100644 index 0000000000000000000000000000000000000000..8afce29ede71b5b8fc91519780bd7d1fcd3eeef9 --- /dev/null +++ b/PowerShell-master/.pipelines/PowerShell-Packages-Official.yml @@ -0,0 +1,97 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time + - name: ForceAzureBlobDelete + displayName: Delete Azure Blob + type: string + values: + - true + - false + default: false + - name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: ReleaseTagVar + displayName: Release Tag + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + displayName: Skip Signing + type: string + default: 'NO' + - name: disableNetworkIsolation + type: boolean + default: false + +name: pkgs-$(BUILD.SOURCEBRANCHNAME)-prod-$(Build.BuildId) + +variables: + - template: templates/variables/PowerShell-Packages-Variables.yml + parameters: + debug: ${{ parameters.debug }} + ForceAzureBlobDelete: ${{ parameters.ForceAzureBlobDelete }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + disableNetworkIsolation: ${{ parameters.disableNetworkIsolation }} + +resources: + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated Binaries-Official' + trigger: + branches: + include: + - master + - releases/* + + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +extends: + template: v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates + parameters: + cloudvault: + enabled: false + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: KS3 + LinuxHostVersion: + Network: KS3 + linuxEsrpSigning: true + incrementalSDLBinaryAnalysis: true + disableNetworkIsolation: ${{ variables.disableNetworkIsolation }} + globalSdl: + disableLegacyManifest: true + # disabled Armorty as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + compiled: + enabled: false + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + cg: + enabled: true + ignoreDirectories: '.devcontainer,demos,docker,docs,src,test,tools/packaging' + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config\tsaoptions.json + stages: + - template: templates/stages/PowerShell-Packages-Stages.yml + parameters: + OfficialBuild: true diff --git a/PowerShell-master/.pipelines/PowerShell-Release-Official-Azure.yml b/PowerShell-master/.pipelines/PowerShell-Release-Official-Azure.yml new file mode 100644 index 0000000000000000000000000000000000000000..24040a2463da08af033ab55e8cead798c75a3f18 --- /dev/null +++ b/PowerShell-master/.pipelines/PowerShell-Release-Official-Azure.yml @@ -0,0 +1,76 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time + - name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false + - name: skipPublish + displayName: Skip PMC Publish + type: boolean + default: false + - name: SKIP_SIGNING + displayName: Skip Signing + type: string + default: 'NO' + +name: ev2-$(BUILD.SOURCEBRANCHNAME)-prod-$(Build.BuildId) + +variables: + - template: templates/variables/PowerShell-Release-Azure-Variables.yml + parameters: + debug: ${{ parameters.debug }} + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated Binaries-Official' + + - pipeline: PSPackagesOfficial + source: 'PowerShell-Packages-Official' + trigger: + branches: + include: + - master + - releases/* + +extends: + template: v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates + parameters: + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: Netlock + linuxEsrpSigning: true + incrementalSDLBinaryAnalysis: true + cloudvault: + enabled: false + globalSdl: + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + tsa: + enabled: true + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + break: false # always break the build on binskim issues in addition to TSA upload + exactToolVersion: 4.4.2 + policheck: + break: true # always break the build on policheck issues. You can disable it by setting to 'false' + tsaOptionsFile: .config\tsaoptions.json + stages: + - template: /.pipelines/templates/release-prep-for-ev2.yml@self + parameters: + skipPublish: ${{ parameters.skipPublish }} + + - template: /.pipelines/templates/release-publish-pmc.yml@self diff --git a/PowerShell-master/.pipelines/PowerShell-Release-Official.yml b/PowerShell-master/.pipelines/PowerShell-Release-Official.yml new file mode 100644 index 0000000000000000000000000000000000000000..3528e6b14712913950102f22ed2f42e2d24b76dc --- /dev/null +++ b/PowerShell-master/.pipelines/PowerShell-Release-Official.yml @@ -0,0 +1,102 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time + - name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: ReleaseTagVar + displayName: Release Tag + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + displayName: Skip Signing + type: string + default: 'NO' + - name: SkipPublish + displayName: Skip Publishing to Nuget + type: boolean + default: false + - name: SkipPSInfraInstallers + displayName: Skip Copying Archives and Installers to PSInfrastructure Public Location + type: boolean + default: false + - name: skipMSIXPublish + displayName: Skip MSIX Publish + type: boolean + default: false + +name: release-$(BUILD.SOURCEBRANCHNAME)-prod-$(Build.BuildId) + +variables: + - template: templates/variables/PowerShell-Release-Variables.yml + parameters: + debug: ${{ parameters.debug }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + - repository: PSInternalTools + type: git + name: PowerShellCore/Internal-PowerShellTeam-Tools + ref: refs/heads/master + + pipelines: + - pipeline: CoOrdinatedBuildPipeline + source: 'PowerShell-Coordinated Binaries-Official' + + - pipeline: PSPackagesOfficial + source: 'PowerShell-Packages-Official' + trigger: + branches: + include: + - master + - releases/* + +extends: + template: v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates + parameters: + release: + category: NonAzure + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: KS3 + incrementalSDLBinaryAnalysis: true + cloudvault: + enabled: false + globalSdl: + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + tsa: + enabled: true + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + break: false # always break the build on binskim issues in addition to TSA upload + exactToolVersion: 4.4.2 + policheck: + break: true # always break the build on policheck issues. You can disable it by setting to 'false' + # suppression: + # suppressionFile: $(Build.SourcesDirectory)\.gdn\global.gdnsuppress + tsaOptionsFile: .config\tsaoptions.json + + stages: + - template: templates/stages/PowerShell-Release-Stages.yml + parameters: + releaseEnvironment: Production + SkipPublish: ${{ parameters.SkipPublish }} + SkipPSInfraInstallers: ${{ parameters.SkipPSInfraInstallers }} + skipMSIXPublish: ${{ parameters.skipMSIXPublish }} diff --git a/PowerShell-master/.pipelines/PowerShell-vPack-Official.yml b/PowerShell-master/.pipelines/PowerShell-vPack-Official.yml new file mode 100644 index 0000000000000000000000000000000000000000..13087fbbf6590795d56d3de9d5534ebae67ae879 --- /dev/null +++ b/PowerShell-master/.pipelines/PowerShell-vPack-Official.yml @@ -0,0 +1,88 @@ +trigger: none + +parameters: # parameters are shown up in ADO UI in a build queue time +- name: 'createVPack' + displayName: 'Create and Submit VPack' + type: boolean + default: true +- name: vPackName + type: string + displayName: 'VPack Name:' + default: 'PowerShell.BuildTool' + values: + - PowerShell.BuildTool + - PowerShell + - PowerShellDoNotUse +- name: 'ReleaseTagVar' + type: string + displayName: 'Release Tag Var:' + default: 'fromBranch' +- name: 'debug' + displayName: 'Enable debug output' + type: boolean + default: false +- name: netiso + displayName: "Network Isolation Policy" + type: string + values: + - KS4 + - R1 + - Netlock + default: "R1" + +name: vPack_$(Build.SourceBranchName)_Prod_Create.${{ parameters.createVPack }}_Name.${{ parameters.vPackName}}_$(date:yyyyMMdd).$(rev:rr) + +variables: + - template: templates/variables/PowerShell-vPack-Variables.yml + parameters: + debug: ${{ parameters.debug }} + ReleaseTagVar: ${{ parameters.ReleaseTagVar }} + netiso: ${{ parameters.netiso }} + +resources: + repositories: + - repository: onebranchTemplates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +extends: + template: v2/Microsoft.Official.yml@onebranchTemplates + parameters: + platform: + name: 'windows_undocked' # windows undocked + + featureFlags: + WindowsHostVersion: + Version: 2022 + Network: ${{ variables.netiso }} + + cloudvault: + enabled: false + + globalSdl: + useCustomPolicy: true # for signing code + disableLegacyManifest: true + # disabled Armory as we dont have any ARM templates to scan. It fails on some sample ARM templates. + armory: + enabled: false + sbom: + enabled: true + compiled: + enabled: false + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + enabled: false + exactToolVersion: 4.4.2 + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: false + tsaOptionsFile: .config/tsaoptions.json + stages: + - template: templates/stages/PowerShell-vPack-Stages.yml + parameters: + createVPack: ${{ parameters.createVPack }} + vPackName: ${{ parameters.vPackName }} diff --git a/PowerShell-master/.pipelines/apiscan-gen-notice.yml b/PowerShell-master/.pipelines/apiscan-gen-notice.yml new file mode 100644 index 0000000000000000000000000000000000000000..9cc83e7136a7c61c361aae2c38e912772e09b891 --- /dev/null +++ b/PowerShell-master/.pipelines/apiscan-gen-notice.yml @@ -0,0 +1,115 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +name: apiscan-genNotice-$(BUILD.SOURCEBRANCHNAME)-$(Build.BuildId) +trigger: none + +parameters: + - name: FORCE_CODEQL + displayName: Debugging - Enable CodeQL and set cadence to 1 hour + type: boolean + default: false + - name: SkipVerifyPackages + type: boolean + default: false + +variables: + # PAT permissions NOTE: Declare a SymbolServerPAT variable in this group with a 'microsoft' organizanization scoped PAT with 'Symbols' Read permission. + # A PAT in the wrong org will give a single Error 203. No PAT will give a single Error 401, and individual pdbs may be missing even if permissions are correct. + - group: symbols + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] + # Defines the variables AzureFileCopySubscription, StorageAccount, StorageAccountKey, StorageResourceGroup, StorageSubscriptionName + - group: 'Azure Blob variable group' + # Defines the variables CgPat, CgOrganization, and CgProject + - group: 'ComponentGovernance' + - group: 'PoolNames' + - name: LinuxContainerImage + value: mcr.microsoft.com/onebranch/azurelinux/build:3.0 + - name: WindowsContainerImage + value: onebranch.azurecr.io/windows/ltsc2022/vse2022:latest + - ${{ if eq(parameters['FORCE_CODEQL'],'true') }}: + # Cadence is hours before CodeQL will allow a re-upload of the database + - name: CodeQL.Cadence + value: 0 + - name: CODEQL_ENABLED + ${{ if or(eq(variables['Build.SourceBranch'], 'refs/heads/master'), eq(parameters['FORCE_CODEQL'],'true')) }}: + value: true + ${{ else }}: + value: false + - name: Codeql.TSAEnabled + value: $(CODEQL_ENABLED) + # AnalyzeInPipeline: false = upload results + # AnalyzeInPipeline: true = do not upload results + - name: Codeql.AnalyzeInPipeline + ${{ if or(eq(variables['Build.SourceBranch'], 'refs/heads/master'), eq(parameters['FORCE_CODEQL'],'true')) }}: + value: false + ${{ else }}: + value: true + +resources: + repositories: + - repository: templates + type: git + name: OneBranch.Pipelines/GovernedTemplates + ref: refs/heads/main + +extends: + template: v2/OneBranch.NonOfficial.CrossPlat.yml@templates + parameters: + featureFlags: + WindowsHostVersion: + Version: 2022 + globalSdl: + codeql: + compiled: + enabled: $(CODEQL_ENABLED) + tsaEnabled: $(CODEQL_ENABLED) # This enables TSA bug filing only for CodeQL 3000 + armory: + enabled: false + sbom: + enabled: false + cg: + enabled: true + ignoreDirectories: '.devcontainer,demos,docker,docs,src,test,tools/packaging' + tsa: + enabled: true # onebranch publish all SDL results to TSA. If TSA is disabled all SDL tools will forced into 'break' build mode. + credscan: + enabled: true + scanFolder: $(Build.SourcesDirectory) + suppressionsFile: $(Build.SourcesDirectory)\.config\suppress.json + binskim: + break: true # always break the build on binskim issues in addition to TSA upload + policheck: + break: true # always break the build on policheck issues. You can disable it by setting to 'false' + # APIScan requires a non-Ready-To-Run build + apiscan: + enabled: true + softwareName: "PowerShell" # Default is repo name + versionNumber: "7.6" # Default is build number + isLargeApp: false # Default: false. + symbolsFolder: $(SymbolsServerUrl);$(ob_outputDirectory) +#softwareFolder - relative path to a folder to be scanned. Default value is root of artifacts folder + tsaOptionsFile: .config\tsaoptions.json + psscriptanalyzer: + enabled: true + policyName: Microsoft + break: false + + stages: + - stage: APIScan + displayName: 'ApiScan' + dependsOn: [] + jobs: + - template: /.pipelines/templates/compliance/apiscan.yml@self + parameters: + parentJobs: [] + - stage: notice + displayName: Generate Notice File + dependsOn: [] + jobs: + - template: /.pipelines/templates/compliance/generateNotice.yml@self + parameters: + parentJobs: [] + SkipVerifyPackages: ${{ parameters.SkipVerifyPackages }} diff --git a/PowerShell-master/.pipelines/store/PDP/PDP-Media/en-US/.gitkeep b/PowerShell-master/.pipelines/store/PDP/PDP-Media/en-US/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PowerShell-master/.pipelines/store/PDP/PDP/en-US/PDP.xml b/PowerShell-master/.pipelines/store/PDP/PDP/en-US/PDP.xml new file mode 100644 index 0000000000000000000000000000000000000000..ce36a3677f7b31688d9c4b8eb95e98b22b48573a --- /dev/null +++ b/PowerShell-master/.pipelines/store/PDP/PDP/en-US/PDP.xml @@ -0,0 +1,151 @@ + + + + + + + + + + + + + Shell + + PowerShell + + Terminal + + Command Line + + Automation + + Task Automation + + Scripting + + + PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate task that manage operating systems (Linux, macOS, and Windows) and processes. + +PowerShell commands let you manage computers from the command line. PowerShell providers let you access data stores, such as the registry and certificate store, as easily as you access the file system. PowerShell includes a rich expression parser and a fully developed scripting language. + +PowerShell is Open Source. See https://github.com/powershell/powershell + + + + + + + + + + + + + + + + + + + + + + Please see our GitHub releases page for additional details. + + + + + + + + + + + + + + + + + + + + Interactive Shell + + Scripting Language + + Remote Management + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Microsoft Corporation + + + + + https://github.com/PowerShell/PowerShell + + https://github.com/PowerShell/PowerShell/issues + + https://go.microsoft.com/fwlink/?LinkID=521839 + diff --git a/PowerShell-master/.pipelines/store/SBConfig.json b/PowerShell-master/.pipelines/store/SBConfig.json new file mode 100644 index 0000000000000000000000000000000000000000..a52d60b045febefb076798e79a2fb5c62be54e0f --- /dev/null +++ b/PowerShell-master/.pipelines/store/SBConfig.json @@ -0,0 +1,69 @@ +{ + "helpUri": "https:\\\\aka.ms\\StoreBroker_Config", + "schemaVersion": 2, + "packageParameters": { + "PDPRootPath": "", + "Release": "", + "PDPInclude": [ + "PDP.xml" + ], + "PDPExclude": [], + "LanguageExclude": [ + "default", + "qps-ploc", + "qps-ploca", + "qps-plocm" + ], + "MediaRootPath": "", + "MediaFallbackLanguage": "en-US", + "PackagePath": [], + "OutPath": "", + "OutName": "", + "DisableAutoPackageNameFormatting": false + }, + "appSubmission": { + "productId": "", + "targetPublishMode": "Immediate", + "targetPublishDate": null, + "visibility": "NotSet", + "pricing": { + "priceId": "NotAvailable", + "trialPeriod": "NoFreeTrial", + "marketSpecificPricings": {}, + "sales": [] + }, + "allowTargetFutureDeviceFamilies": { + "Xbox": false, + "Team": false, + "Holographic": false, + "Desktop": false, + "Mobile": false + }, + "allowMicrosoftDecideAppAvailabilityToFutureDeviceFamilies": false, + "enterpriseLicensing": "None", + "applicationCategory": "NotSet", + "hardwarePreferences": [], + "hasExternalInAppProducts": false, + "meetAccessibilityGuidelines": false, + "canInstallOnRemovableMedia": false, + "automaticBackupEnabled": false, + "isGameDvrEnabled": false, + "gamingOptions": [ + { + "genres": [], + "isLocalMultiplayer": false, + "isLocalCooperative": false, + "isOnlineMultiplayer": false, + "isOnlineCooperative": false, + "localMultiplayerMinPlayers": 0, + "localMultiplayerMaxPlayers": 0, + "localCooperativeMinPlayers": 0, + "localCooperativeMaxPlayers": 0, + "isBroadcastingPrivilegeGranted": false, + "isCrossPlayEnabled": false, + "kinectDataForExternal": "Disabled" + } + ], + "notesForCertification": "" + } +} diff --git a/PowerShell-master/.pipelines/templates/SetVersionVariables.yml b/PowerShell-master/.pipelines/templates/SetVersionVariables.yml new file mode 100644 index 0000000000000000000000000000000000000000..30ed1704022bd6c9f72b065420250f26fc518712 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/SetVersionVariables.yml @@ -0,0 +1,48 @@ +parameters: +- name: ReleaseTagVar + default: v6.2.0 +- name: ReleaseTagVarName + default: ReleaseTagVar +- name: CreateJson + default: 'no' +- name: ob_restore_phase + type: boolean + default: true + +steps: +- template: set-reporoot.yml@self + parameters: + ob_restore_phase: ${{ parameters.ob_restore_phase }} + +- powershell: | + $createJson = ("${{ parameters.CreateJson }}" -ne "no") + + $REPOROOT = $env:REPOROOT + + if (-not (Test-Path $REPOROOT/tools/releaseBuild/setReleaseTag.ps1)) { + if (Test-Path "$REPOROOT/PowerShell/tools/releaseBuild/setReleaseTag.ps1") { + $REPOROOT = "$REPOROOT/PowerShell" + } else { + throw "Could not find setReleaseTag.ps1 in $REPOROOT/tools/releaseBuild or $REPOROOT/PowerShell/tools/releaseBuild" + } + } + + $releaseTag = & "$REPOROOT/tools/releaseBuild/setReleaseTag.ps1" -ReleaseTag ${{ parameters.ReleaseTagVar }} -Variable "${{ parameters.ReleaseTagVarName }}" -CreateJson:$createJson + $version = $releaseTag.Substring(1) + $vstsCommandString = "vso[task.setvariable variable=Version]$version" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + $azureVersion = $releaseTag.ToLowerInvariant() -replace '\.', '-' + $vstsCommandString = "vso[task.setvariable variable=AzureVersion]$azureVersion" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: 'Set ${{ parameters.ReleaseTagVarName }} and other version Variables' + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} + +- powershell: | + Get-ChildItem -Path Env: | Out-String -Width 150 + displayName: Capture environment + condition: succeededOrFailed() + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} diff --git a/PowerShell-master/.pipelines/templates/approvalJob.yml b/PowerShell-master/.pipelines/templates/approvalJob.yml new file mode 100644 index 0000000000000000000000000000000000000000..ac3b8bc2ab2e9d1bd2ecba26f8e63b27cf1b00d8 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/approvalJob.yml @@ -0,0 +1,36 @@ +parameters: + - name: displayName + type: string + - name: instructions + type: string + - name: jobName + type: string + default: approval + - name: timeoutInMinutes + type: number + # 2 days + default: 2880 + - name: onTimeout + type: string + default: 'reject' + values: + - resume + - reject + - name: dependsOnJob + type: string + default: '' + +jobs: + - job: ${{ parameters.jobName }} + dependsOn: ${{ parameters.dependsOnJob }} + displayName: ${{ parameters.displayName }} + pool: + type: agentless + timeoutInMinutes: 4320 # job times out in 3 days + steps: + - task: ManualValidation@0 + displayName: ${{ parameters.displayName }} + timeoutInMinutes: ${{ parameters.timeoutInMinutes }} + inputs: + instructions: ${{ parameters.instructions }} + onTimeout: ${{ parameters.onTimeout }} diff --git a/PowerShell-master/.pipelines/templates/channelSelection.yml b/PowerShell-master/.pipelines/templates/channelSelection.yml new file mode 100644 index 0000000000000000000000000000000000000000..d6ddb53256e8dd019d281efd3584422837379fee --- /dev/null +++ b/PowerShell-master/.pipelines/templates/channelSelection.yml @@ -0,0 +1,49 @@ +steps: +- pwsh: | + # Determine LTS, Preview, or Stable + $metadata = Get-Content "$(Build.SourcesDirectory)/PowerShell/tools/metadata.json" -Raw | ConvertFrom-Json + + $LTS = $metadata.LTSRelease.PublishToChannels + $Stable = $metadata.StableRelease.PublishToChannels + $isPreview = '$(OutputReleaseTag.releaseTag)' -match '-' + $releaseTag = '$(OutputReleaseTag.releaseTag)' + + # Rebuild branches should be treated as preview builds + # NOTE: The following regex is duplicated from rebuild-branch-check.yml. + # This duplication is necessary because channelSelection.yml does not call rebuild-branch-check.yml, + # and is used in contexts where that check may not have run. + # If you update this regex, also update it in rebuild-branch-check.yml to keep them in sync. + $isRebuildBranch = '$(Build.SourceBranch)' -match 'refs/heads/rebuild/.*-rebuild\.' + + # If this is a rebuild branch, force preview mode and ignore LTS metadata + if ($isRebuildBranch) { + $IsLTS = $false + $IsStable = $false + $IsPreview = $true + Write-Verbose -Message "Rebuild branch detected, forcing Preview channel" -Verbose + } + else { + $IsLTS = [bool]$LTS + $IsStable = [bool]$Stable + $IsPreview = [bool]$isPreview + } + + $channelVars = @{ + IsLTS = $IsLTS + IsStable = $IsStable + IsPreview = $IsPreview + } + + $trueCount = ($channelVars.Values | Where-Object { $_ }) | Measure-Object | Select-Object -ExpandProperty Count + if ($trueCount -gt 1) { + Write-Error "Only one of IsLTS, IsStable, or IsPreview can be true. Current values: IsLTS=$IsLTS, IsStable=$IsStable, IsPreview=$IsPreview" + exit 1 + } + + foreach ($name in $channelVars.Keys) { + $value = if ($channelVars[$name]) { 'true' } else { 'false' } + Write-Verbose -Message "Setting $name variable: $value" -Verbose + Write-Host "##vso[task.setvariable variable=$name;isOutput=true]$value" + } + name: ChannelSelection + displayName: Select Preview, Stable, or LTS Channel diff --git a/PowerShell-master/.pipelines/templates/checkAzureContainer.yml b/PowerShell-master/.pipelines/templates/checkAzureContainer.yml new file mode 100644 index 0000000000000000000000000000000000000000..3e383d2c57244dd7aaf0e1aade5f468db278c08c --- /dev/null +++ b/PowerShell-master/.pipelines/templates/checkAzureContainer.yml @@ -0,0 +1,86 @@ +jobs: +- job: DeleteBlob + variables: + - group: Azure Blob variable group + - group: AzureBlobServiceConnection + - name: ob_artifactBaseName + value: BuildInfoJson + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT/BuildJson' + - name: ob_sdl_sbom_enabled + value: false + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_codeql_compiled_enabled + value: false + + displayName: Delete blob is exists + pool: + type: windows + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: yes + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(PowerShellRoot) + + - pwsh: | + if (-not (Test-Path -Path $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json)) { + Get-ChildItem -Path $(Build.SourcesDirectory) -Recurse + throw 'tsaoptions.json not found' + } + displayName: 'Check tsaoptions.json' + + - pwsh: | + if (-not (Test-Path -Path $(Build.SourcesDirectory)\PowerShell\.config\suppress.json)) { + Get-ChildItem -Path $(Build.SourcesDirectory) -Recurse + throw 'suppress.json not found' + } + displayName: 'Check suppress.json' + + - task: AzurePowerShell@5 + displayName: Check if blob exists and delete if specified + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + pwsh: true + inline: | + $containersToDelete = @('$(AzureVersion)', '$(AzureVersion)-private', '$(AzureVersion)-nuget', '$(AzureVersion)-gc') + + $containersToDelete | ForEach-Object { + $containerName = $_ + try { + $container = Get-AzStorageContainer -Container $containerName -Context (New-AzStorageContext -StorageAccountName '$(StorageAccount)') -ErrorAction Stop + if ($container -ne $null -and '$(ForceAzureBlobDelete)' -eq 'false') { + throw "Azure blob container $containerName already exists. To overwrite, use ForceAzureBlobDelete parameter" + } + elseif ($container -ne $null -and '$(ForceAzureBlobDelete)' -eq 'true') { + Write-Verbose -Verbose "Removing container $containerName due to ForceAzureBlobDelete parameter" + Remove-AzStorageContainer -Name $containerName -Context (New-AzStorageContext -StorageAccountName '$(StorageAccount)') -Force + } + } + catch { + if ($_.FullyQualifiedErrorId -eq 'ResourceNotFoundException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzureStorageContainerCommand') { + Write-Verbose -Verbose "Container $containerName does not exists." + } + else { + throw $_ + } + } + } + - template: /.pipelines/templates/step/finalize.yml@self diff --git a/PowerShell-master/.pipelines/templates/cloneToOfficialPath.yml b/PowerShell-master/.pipelines/templates/cloneToOfficialPath.yml new file mode 100644 index 0000000000000000000000000000000000000000..b060c713683066e38fa2171005a3e766dd752297 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/cloneToOfficialPath.yml @@ -0,0 +1,31 @@ +parameters: +- name: nativePathRoot + default: '' +- name: ob_restore_phase + type: boolean + default: true + +steps: +- powershell: | + $dirSeparatorChar = [system.io.path]::DirectorySeparatorChar + $nativePath = "${{parameters.nativePathRoot }}${dirSeparatorChar}PowerShell" + Write-Host "##vso[task.setvariable variable=PowerShellRoot]$nativePath" + if ((Test-Path "$nativePath")) { + Remove-Item -Path "$nativePath" -Force -Recurse -Verbose -ErrorAction ignore + } + else { + Write-Verbose -Verbose -Message "No cleanup required." + } + # REPOROOT must be set by the pipeline - this is where the repository was checked out + $sourceDir = $env:REPOROOT + if (-not $sourceDir) { throw "REPOROOT environment variable is not set. This step depends on REPOROOT being configured in the pipeline." } + + $buildModulePath = Join-Path $sourceDir "build.psm1" + if (-not (Test-Path $buildModulePath)) { throw "build.psm1 not found at: $buildModulePath. REPOROOT must point to the PowerShell repository root." } + + Write-Verbose -Verbose -Message "Cloning from: $sourceDir to $nativePath" + git clone --quiet $sourceDir $nativePath + displayName: Clone PowerShell Repo to /PowerShell + errorActionPreference: silentlycontinue + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} diff --git a/PowerShell-master/.pipelines/templates/compliance/apiscan.yml b/PowerShell-master/.pipelines/templates/compliance/apiscan.yml new file mode 100644 index 0000000000000000000000000000000000000000..b5a156990260db9b4dd7cab998d21d2a2eceff80 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/compliance/apiscan.yml @@ -0,0 +1,170 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +jobs: + - job: APIScan + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: ReleaseTagVar + value: fromBranch + # Defines the variables APIScanClient, APIScanTenant and APIScanSecret + - group: PS-PS-APIScan + - name: branchCounterKey + value: $[format('{0:yyyyMMdd}-{1}', pipeline.startTime,variables['Build.SourceBranch'])] + - name: branchCounter + value: $[counter(variables['branchCounterKey'], 1)] + - group: DotNetPrivateBuildAccess + - group: ReleasePipelineSecrets + - group: mscodehub-feed-read-general + - group: mscodehub-feed-read-akv + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: repoRoot + value: '$(Build.SourcesDirectory)\PowerShell' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: Codeql.SourceRoot + value: $(repoRoot) + + pool: + type: windows + + # APIScan can take a long time + timeoutInMinutes: 180 + + steps: + - checkout: self + clean: true + fetchTags: true + fetchDepth: 1000 + displayName: Checkout PowerShell + retryCountOnTaskFailure: 1 + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: ../SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: ../insert-nuget-config-azfeed.yml + parameters: + repoRoot: '$(repoRoot)' + + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + useGlobalJson: true + packageType: 'sdk' + workingDirectory: $(Build.SourcesDirectory)" + + - pwsh: | + Import-Module .\build.psm1 -force + Find-DotNet + dotnet tool install dotnet-symbol --tool-path $(Agent.ToolsDirectory)\tools\dotnet-symbol + $symbolToolPath = Get-ChildItem -Path $(Agent.ToolsDirectory)\tools\dotnet-symbol\dotnet-symbol.exe | Select-Object -First 1 -ExpandProperty FullName + Write-Host "##vso[task.setvariable variable=symbolToolPath]$symbolToolPath" + displayName: Install dotnet-symbol + workingDirectory: '$(repoRoot)' + retryCountOnTaskFailure: 2 + + - task: CodeQL3000Init@0 # Add CodeQL Init task right before your 'Build' step. + displayName: 🔏 CodeQL 3000 Init + condition: eq(variables['CODEQL_ENABLED'], 'true') + inputs: + Language: csharp + + - pwsh: | + Import-Module .\build.psm1 -force + Find-DotNet + Start-PSBuild -Configuration StaticAnalysis -PSModuleRestore -Clean -Runtime fxdependent-win-desktop + + $OutputFolder = Split-Path (Get-PSOutput) + + Write-Verbose -Verbose -Message "Deleting ref folder from output folder" + if (Test-Path $OutputFolder/ref) { + Remove-Item -Recurse -Force $OutputFolder/ref + } + + $Destination = '$(ob_outputDirectory)' + if (-not (Test-Path $Destination)) { + Write-Verbose -Verbose -Message "Creating destination folder '$Destination'" + $null = mkdir $Destination + } + + Copy-Item -Path "$OutputFolder\*" -Destination $Destination -Recurse -Verbose + workingDirectory: '$(repoRoot)' + displayName: 'Build PowerShell Source' + + - pwsh: | + # Only keep windows runtimes + Write-Verbose -Verbose -Message "Deleting non-win-x64 runtimes ..." + Get-ChildItem -Path '$(ob_outputDirectory)\runtimes\*' | Where-Object {$_.FullName -notmatch '.*\\runtimes\\win'} | Foreach-Object { + Write-Verbose -Verbose -Message "Deleting $($_.FullName)" + Remove-Item -Path $_.FullName -Recurse -Force + } + + # Remove win-x86/arm/arm64 runtimes due to issues with those runtimes + Write-Verbose -Verbose -Message "Temporarily deleting win-x86/arm/arm64 runtimes ..." + Get-ChildItem -Path '$(ob_outputDirectory)\runtimes\*' | Where-Object {$_.FullName -match '.*\\runtimes\\win-(x86|arm)'} | Foreach-Object { + Write-Verbose -Verbose -Message "Deleting $($_.FullName)" + Remove-Item -Path $_.FullName -Recurse -Force + } + + Write-Host + Write-Verbose -Verbose -Message "Show content in 'runtimes' folder:" + Get-ChildItem -Path '$(ob_outputDirectory)\runtimes' + Write-Host + workingDirectory: '$(repoRoot)' + displayName: 'Remove unused runtimes' + + - task: CodeQL3000Finalize@0 # Add CodeQL Finalize task right after your 'Build' step. + displayName: 🔏 CodeQL 3000 Finalize + condition: eq(variables['CODEQL_ENABLED'], 'true') + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + workingDirectory: '$(repoRoot)' + displayName: Capture Environment + condition: succeededOrFailed() + + # Explicitly download symbols for the drop since the SDL image doesn't have http://SymWeb access and APIScan cannot handle https yet. + - pwsh: | + Import-Module .\build.psm1 -force + Find-DotNet + $pat = '$(SymbolServerPAT)' + if ($pat -like '*PAT*' -or $pat -eq '') + { + throw 'No PAT defined' + } + $url = 'https://microsoft.artifacts.visualstudio.com/defaultcollection/_apis/symbol/symsrv' + $(symbolToolPath) --authenticated-server-path $(SymbolServerPAT) $url --symbols -d "$env:ob_outputDirectory\*" --recurse-subdirectories + displayName: 'Download Symbols for binaries' + retryCountOnTaskFailure: 2 + workingDirectory: '$(repoRoot)' + + - pwsh: | + Get-ChildItem '$(ob_outputDirectory)' -File -Recurse | + Foreach-Object { + [pscustomobject]@{ + Path = $_.FullName + Version = $_.VersionInfo.FileVersion + Md5Hash = (Get-FileHash -Algorithm MD5 -Path $_.FullName).Hash + Sha512Hash = (Get-FileHash -Algorithm SHA512 -Path $_.FullName).Hash + } + } | Export-Csv -Path '$(Build.SourcesDirectory)/ReleaseFileHash.csv' + workingDirectory: '$(repoRoot)' + displayName: 'Create release file hash artifact' + + - pwsh: | + Copy-Item -Path '$(Build.SourcesDirectory)/ReleaseFileHash.csv' -Destination '$(ob_outputDirectory)' -Verbose + displayName: 'Publish Build File Hash artifact' + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + workingDirectory: '$(repoRoot)' diff --git a/PowerShell-master/.pipelines/templates/compliance/generateNotice.yml b/PowerShell-master/.pipelines/templates/compliance/generateNotice.yml new file mode 100644 index 0000000000000000000000000000000000000000..90fd08dd8d9491fa903def0497911ae5f6c9235c --- /dev/null +++ b/PowerShell-master/.pipelines/templates/compliance/generateNotice.yml @@ -0,0 +1,119 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +parameters: + - name: parentJobs + type: jobList + - name: SkipVerifyPackages + type: boolean + +jobs: +- job: generateNotice + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT/notice' + - name: ob_sdl_apiscan_enabled + value: false + - name: repoRoot + value: '$(Build.SourcesDirectory)\PowerShell' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + + displayName: Generate Notice + dependsOn: + ${{ parameters.parentJobs }} + pool: + type: windows + + timeoutInMinutes: 15 + + steps: + - checkout: self + clean: true + + - pwsh: | + [string]$Branch=$env:BUILD_SOURCEBRANCH + $branchOnly = $Branch -replace '^refs/heads/'; + $branchOnly = $branchOnly -replace '[_\-]' + + if ($branchOnly -eq 'master') { + $container = 'tpn' + } else { + $branchOnly = $branchOnly -replace '[\./]', '-' + $container = "tpn-$branchOnly" + } + + $vstsCommandString = "vso[task.setvariable variable=tpnContainer]$container" + Write-Verbose -Message $vstsCommandString -Verbose + Write-Host -Object "##$vstsCommandString" + displayName: Set ContainerName + + - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 + displayName: 'Component Detection' + inputs: + sourceScanPath: '$(repoRoot)\tools\cgmanifest\tpn' + + - pwsh: | + $(repoRoot)/tools/clearlyDefined/ClearlyDefined.ps1 -TestAndHarvest + displayName: Verify that packages have license data + condition: eq(${{ parameters.SkipVerifyPackages }}, false) + + - task: msospo.ospo-extension.8d7f9abb-6896-461d-9e25-4f74ed65ddb2.notice@0 + displayName: 'NOTICE File Generator' + inputs: + outputfile: '$(ob_outputDirectory)\ThirdPartyNotices.txt' + # output format can be html or text + outputformat: text + # this isn't working + # additionaldata: $(Build.SourcesDirectory)\assets\additionalAttributions.txt + + - pwsh: | + Get-Content -Raw -Path $(repoRoot)\assets\additionalAttributions.txt | Out-File '$(ob_outputDirectory)\ThirdPartyNotices.txt' -Encoding utf8NoBOM -Force -Append + Get-Content -Raw -Path $(repoRoot)\assets\additionalAttributions.txt + displayName: Append Additional Attributions + continueOnError: true + + - pwsh: | + Get-Content -Raw -Path '$(ob_outputDirectory)\ThirdPartyNotices.txt' + displayName: Capture Notice + continueOnError: true + + - task: AzurePowerShell@5 + displayName: Upload Notice + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + workingDirectory: '$(repoRoot)' + pwsh: true + inline: | + try { + $downloadsDirectory = '$(Build.ArtifactStagingDirectory)/downloads' + $uploadedDirectory = '$(Build.ArtifactStagingDirectory)/uploaded' + $storageAccountName = "pscoretestdata" + $containerName = '$(tpnContainer)' + $blobName = 'ThirdPartyNotices.txt' + $noticePath = "$(ob_outputDirectory)\$blobName" + + Write-Verbose -Verbose "creating context ($storageAccountName) ..." + $context = New-AzStorageContext -StorageAccountName $storageAccountName -UseConnectedAccount + + Write-Verbose -Verbose "checking if container ($containerName) exists ..." + $containerExists = Get-AzStorageContainer -Name $containerName -Context $context -ErrorAction SilentlyContinue + if (-not $containerExists) { + Write-Verbose -Verbose "Creating container ..." + $null = New-AzStorageContainer -Name $containerName -Context $context + Write-Verbose -Verbose "Blob container $containerName created successfully." + } + + Write-Verbose -Verbose "Setting blob ($blobName) content ($noticePath) ..." + $null = Set-AzStorageBlobContent -File $noticePath -Container $containerName -Blob $blobName -Context $context -confirm:$false -force + Write-Verbose -Verbose "Done" + } catch { + Get-Error + throw + } diff --git a/PowerShell-master/.pipelines/templates/insert-nuget-config-azfeed.yml b/PowerShell-master/.pipelines/templates/insert-nuget-config-azfeed.yml new file mode 100644 index 0000000000000000000000000000000000000000..20057440c00c5b18ac5759331c7d2ee72a6571b4 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/insert-nuget-config-azfeed.yml @@ -0,0 +1,53 @@ +parameters: +- name: "repoRoot" + default: $(REPOROOT) +- name: "ob_restore_phase" + type: boolean + default: true + +steps: +- task: NuGetAuthenticate@1 + displayName: Install Azure Artifacts Credential Provider + inputs: + forceReinstallCredentialProvider: true + +- pwsh: | + try { + $configPath = "${env:NugetConfigDir}/nuget.config" + Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force + + Write-Verbose -Verbose "Running: Switch-PSNugetConfig -Source Private -UserName '$(AzDevopsFeedUserNameKVPAT)' -ClearTextPAT '$(powershellPackageReadPat)'" + Switch-PSNugetConfig -Source Private -UserName '$(AzDevopsFeedUserNameKVPAT)' -ClearTextPAT '$(powershellPackageReadPat)' + + if(-not (Test-Path $configPath)) + { + throw "nuget.config is not created" + } + } + catch { + Get-Error + throw + } + displayName: 'Switch to production Azure DevOps feed for all nuget.configs' + condition: and(succeededOrFailed(), ne(variables['UseAzDevOpsFeed'], '')) + env: + NugetConfigDir: ${{ parameters.repoRoot }}/src/Modules + ob_restore_phase: ${{ parameters.ob_restore_phase }} + +- pwsh: | + Get-ChildItem ${{ parameters.repoRoot }}/nuget.config -Recurse | Foreach-Object { + Write-Verbose -Verbose "--- START $($_.fullname) ---" + get-content $_.fullname | Out-String -width 9999 -Stream | write-Verbose -Verbose + Write-Verbose -Verbose "--- END $($_.fullname) ---" + } + displayName: 'Capture all nuget.config files' + condition: and(succeededOrFailed(), ne(variables['UseAzDevOpsFeed'], '')) + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} + +- pwsh: | + Get-ChildItem -Path env:VSS* | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture VSS* Environment + condition: and(succeededOrFailed(), ne(variables['UseAzDevOpsFeed'], '')) + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} diff --git a/PowerShell-master/.pipelines/templates/install-dotnet.yml b/PowerShell-master/.pipelines/templates/install-dotnet.yml new file mode 100644 index 0000000000000000000000000000000000000000..464e13d10471c6e46a0f54b7d61a3c612c75ef34 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/install-dotnet.yml @@ -0,0 +1,24 @@ +parameters: +- name: ob_restore_phase + type: boolean + default: true + +steps: + - pwsh: | + if (-not (Test-Path '$(RepoRoot)')) { + $psRoot = '$(Build.SourcesDirectory)/PowerShell' + Set-Location $psRoot -Verbose + } + + $version = Get-Content ./global.json | ConvertFrom-Json | Select-Object -ExpandProperty sdk | Select-Object -ExpandProperty version + + Write-Verbose -Verbose "Installing .NET SDK with version $version" + + Import-Module ./build.psm1 -Force + Install-Dotnet -Version $version -Verbose + + displayName: 'Install dotnet SDK' + workingDirectory: $(RepoRoot) + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} + diff --git a/PowerShell-master/.pipelines/templates/linux-package-build.yml b/PowerShell-master/.pipelines/templates/linux-package-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..bb7ed723f42854a0b8986484fcdb38193ab61f41 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/linux-package-build.yml @@ -0,0 +1,201 @@ +parameters: + unsignedDrop: 'drop_linux_build_linux_x64' + signedeDrop: 'drop_linux_sign_linux_x64' + packageType: deb + jobName: 'deb' + signingProfile: 'CP-450779-pgpdetached' + +jobs: +- job: ${{ parameters.jobName }} + displayName: Package linux ${{ parameters.packageType }} + condition: succeeded() + pool: + type: linux + + variables: + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_binskim_enabled + value: true + - name: PackageType + value: ${{ parameters.packageType }} + - name: signedDrop + value: ${{ parameters.signedDrop }} + - name: unsignedDrop + value: ${{ parameters.unsignedDrop }} + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)/PowerShell/.config/tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)/PowerShell/.config/suppress.json + - name: SigningProfile + value: ${{ parameters.signingProfile }} + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - template: SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: shouldSign.yml + + - template: cloneToOfficialPath.yml + parameters: + nativePathRoot: '$(Agent.TempDirectory)' + + - template: rebuild-branch-check.yml@self + + - download: CoOrdinatedBuildPipeline + artifact: ${{ parameters.unsignedDrop }} + displayName: 'Download unsigned artifacts' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - download: CoOrdinatedBuildPipeline + artifact: ${{ parameters.signedDrop }} + displayName: 'Download signed artifacts' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - pwsh: | + Write-Verbose -Verbose "Unsigned artifacts" + Get-ChildItem "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/${{ parameters.unsignedDrop }}" -Recurse + + Write-Verbose -Verbose "Signed artifacts" + Get-ChildItem "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/${{ parameters.signedDrop }}" -Recurse + displayName: 'Capture Downloaded Artifacts' + # Diagnostics is not critical it passes every time it runs + continueOnError: true + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $packageType = '$(PackageType)' + Write-Verbose -Verbose "packageType = $packageType" + + $signedDrop = '$(signedDrop)' + Write-Verbose -Verbose "signedDrop = $signedDrop" + + $unsignedDrop = '$(unsignedDrop)' + Write-Verbose -Verbose "unsignedDrop = $unsignedDrop" + + Write-Verbose -Message "Init..." -Verbose + + $repoRoot = "$env:REPOROOT" + Import-Module "$repoRoot/build.psm1" + Import-Module "$repoRoot/tools/packaging" + + Start-PSBootstrap -Scenario Both + + $psOptionsPath = "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/${unsignedDrop}/psoptions/psoptions.json" + + if (-not (Test-Path $psOptionsPath)) { + throw "psOptionsPath file not found at $psOptionsPath" + } + + Restore-PSOptions $psOptionsPath + Write-Verbose -Message "Restoring PSOptions from $psoptionsFilePath" -Verbose + Get-PSOptions | Write-Verbose -Verbose + + $signedFolder, $pkgFilter = switch ($packageType) { + 'tar-arm' { 'Signed-linux-arm', 'powershell*.tar.gz' } + 'tar-arm64' { 'Signed-linux-arm64', 'powershell*.tar.gz' } + 'tar-alpine' { 'Signed-linux-musl-x64', 'powershell*.tar.gz' } + 'fxdependent' { 'Signed-fxdependent', 'powershell*.tar.gz' } + 'tar' { 'Signed-linux-x64', 'powershell*.tar.gz' } + 'tar-alpine-fxdependent' { 'Signed-fxdependent-noopt-linux-musl-x64', 'powershell*.tar.gz' } + 'deb' { 'Signed-linux-x64', 'powershell*.deb' } + 'rpm-fxdependent' { 'Signed-fxdependent-linux-x64', 'powershell*.rpm' } + 'rpm-fxdependent-arm64' { 'Signed-fxdependent-linux-arm64', 'powershell*.rpm' } + 'rpm' { 'Signed-linux-x64', 'powershell*.rpm' } + 'min-size' { 'Signed-linux-x64', 'powershell*.tar.gz' } + } + + $signedFilesPath = "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/${signedDrop}/${signedFolder}" + Write-Verbose -Verbose "signedFilesPath: $signedFilesPath" + + Write-Verbose -Message "checking pwsh exists in $signedFilesPath" -Verbose + if (-not (Test-Path "$signedFilesPath/pwsh")) { + throw "pwsh not found in $signedFilesPath" + } + + $metadata = Get-Content "$repoRoot/tools/metadata.json" -Raw | ConvertFrom-Json + + Write-Verbose -Verbose "metadata:" + $metadata | Out-String | Write-Verbose -Verbose + + # Use the rebuild branch check from the template + $isRebuildBranch = '$(RebuildBranchCheck.IsRebuildBranch)' -eq 'true' + + # Don't build LTS packages for rebuild branches + $LTS = $metadata.LTSRelease.Package -and -not $isRebuildBranch + + if ($isRebuildBranch) { + Write-Verbose -Message "Rebuild branch detected, skipping LTS package build" -Verbose + } + + Write-Verbose -Verbose "LTS: $LTS" + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + $packageType = '$(PackageType)' + Write-Verbose -Verbose "packageType = $packageType" + + Start-PSPackage -Type $packageType -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath + + if ($LTS) { + Write-Verbose -Message "LTS Release: $LTS" -Verbose + Start-PSPackage -Type $packageType -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath -LTS + } + + $vstsCommandString = "vso[task.setvariable variable=PackageFilter]$pkgFilter" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: 'Package ${{ parameters.packageType}}' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - task: onebranch.pipeline.signing@1 + displayName: Sign deb and rpm packages + inputs: + command: 'sign' + signing_profile: '$(SigningProfile)' + files_to_sign: '**/*.rpm;**/*.deb' + search_root: '$(Pipeline.Workspace)' + + - pwsh: | + $pkgFilter = '$(PackageFilter)' + Write-Verbose -Verbose "pkgFilter: $pkgFilter" + + $pkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $pkgFilter -Recurse -File | Select-Object -ExpandProperty FullName + Write-Verbose -Verbose "pkgPath: $pkgPath" + Copy-Item -Path $pkgPath -Destination '$(ob_outputDirectory)' -Force -Verbose + displayName: 'Copy artifacts to output directory' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - pwsh: | + Get-ChildItem -Path $(ob_outputDirectory) -Recurse + displayName: 'List artifacts' diff --git a/PowerShell-master/.pipelines/templates/linux.yml b/PowerShell-master/.pipelines/templates/linux.yml new file mode 100644 index 0000000000000000000000000000000000000000..97b594830b38c94c56bb99ea0ea3c965c3b75dc2 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/linux.yml @@ -0,0 +1,197 @@ +parameters: + Runtime: 'linux-x64' + BuildConfiguration: 'release' + JobName: 'build_linux' + +jobs: +- job: build_${{ parameters.JobName }} + displayName: Build_Linux_${{ parameters.Runtime }}_${{ parameters.BuildConfiguration }} + condition: succeeded() + pool: + type: linux + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: DOTNET_NOLOGO + value: 1 + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: true + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: BUILDCONFIGURATION + value: ${{ parameters.BuildConfiguration }} + - name: Runtime + value: ${{ parameters.Runtime }} + - name: ob_sdl_sbom_packageName + value: 'Microsoft.Powershell.Linux.${{ parameters.Runtime }}' + # We add this manually, so we need it disabled the OneBranch auto-injected one. + - name: ob_sdl_codeql_compiled_enabled + value: false + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(PowerShellRoot) + + - task: CodeQL3000Init@0 # Add CodeQL Init task right before your 'Build' step. + condition: eq(variables['CODEQL_ENABLED'], 'true') + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + inputs: + Enabled: true + # AnalyzeInPipeline: false = upload results + # AnalyzeInPipeline: true = do not upload results + AnalyzeInPipeline: false + Language: csharp + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $runtime = $env:RUNTIME + + $params = @{} + if ($env:BUILDCONFIGURATION -eq 'minSize') { + Write-Verbose -Message "Building for minimal size" + $params['ForMinimalSize'] = $true + } + + Write-Verbose -Message "Building PowerShell with Runtime: $runtime" + Import-Module -Name $(PowerShellRoot)/build.psm1 -Force + $buildWithSymbolsPath = New-Item -ItemType Directory -Path $(Pipeline.Workspace)/Symbols_$(Runtime) -Force + + $null = New-Item -ItemType Directory -Path $buildWithSymbolsPath -Force -Verbose + + $ReleaseTagParam = @{} + + if ($env:RELEASETAGVAR) { + $ReleaseTagParam['ReleaseTag'] = $env:RELEASETAGVAR + } + + Start-PSBuild -Runtime $runtime -Configuration Release -Output $buildWithSymbolsPath @params -Clean -PSModuleRestore @ReleaseTagParam + + $outputPath = Join-Path '$(ob_outputDirectory)' 'psoptions' + $null = New-Item -ItemType Directory -Path $outputPath -Force + $psOptPath = "$outputPath/psoptions.json" + Save-PSOptions -PSOptionsPath $psOptPath + + Write-Verbose -Verbose "Verifying pdbs exist in build folder" + $pdbs = Get-ChildItem -Path $buildWithSymbolsPath -Recurse -Filter *.pdb + if ($pdbs.Count -eq 0) { + Write-Error -Message "No pdbs found in build folder" + } + else { + Write-Verbose -Verbose "Found $($pdbs.Count) pdbs in build folder" + $pdbs | ForEach-Object { + Write-Verbose -Verbose "Pdb: $($_.FullName)" + } + } + + Write-Verbose -Verbose "Completed building PowerShell for '$env:BUILDCONFIGURATION' configuration" + displayName: 'Build Linux - $(Runtime)' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - task: CodeQL3000Finalize@0 # Add CodeQL Finalize task right after your 'Build' step. + condition: eq(variables['CODEQL_ENABLED'], 'true') + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - pwsh: | + $platform = 'linux' + $vstsCommandString = "vso[task.setvariable variable=ArtifactPlatform]$platform" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: Set artifact platform + + - pwsh: | + $pathForUpload = New-Item -ItemType Directory -Path '$(ob_outputDirectory)/Unsigned-$(Runtime)' -Force + Write-Verbose -Verbose -Message "pathForUpload: $pathForUpload" + Copy-Item -Path '$(Pipeline.Workspace)/Symbols_$(Runtime)/*' -Destination $pathForUpload -Recurse -Force -Verbose + displayName: Copy unsigned files for upload + + - template: /.pipelines/templates/step/finalize.yml@self + +- job: sign_${{ parameters.JobName }} + displayName: Sign_Linux_${{ parameters.Runtime }}_${{ parameters.BuildConfiguration }} + condition: succeeded() + dependsOn: build_${{ parameters.JobName }} + pool: + type: windows + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: DOTNET_NOLOGO + value: 1 + - group: DotNetPrivateBuildAccess + - group: certificate_logical_to_actual + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: false + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: BuildConfiguration + value: ${{ parameters.BuildConfiguration }} + - name: Runtime + value: ${{ parameters.Runtime }} + - name: ob_sdl_codeql_compiled_enabled + value: false + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: drop_linux_build_${{ parameters.JobName }} + path: $(Pipeline.Workspace)/drop_linux_build + displayName: Download build + + - pwsh: | + Get-ChildItem -Path $(Pipeline.Workspace)/drop_linux_build -Recurse + displayName: Capture downloaded files + + - pwsh: | + $pwshPath = Get-ChildItem -Path $(Pipeline.Workspace)/drop_linux_build -File -Recurse | Where-Object { $_.Name -eq 'pwsh' } + $rootPath = Split-Path -Path $pwshPath.FullName -Parent + Write-Verbose -Verbose "Setting vso[task.setvariable variable=DropRootPath]$rootPath" + Write-Host "##vso[task.setvariable variable=DropRootPath]$rootPath" + displayName: Set drop root path + + - template: /.pipelines/templates/obp-file-signing.yml@self + parameters: + binPath: $(DropRootPath) + OfficialBuild: $(ps_official_build) + + - template: /.pipelines/templates/step/finalize.yml@self diff --git a/PowerShell-master/.pipelines/templates/mac-package-build.yml b/PowerShell-master/.pipelines/templates/mac-package-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..6585773c743d941ae91947befdb9e3416ba72e4e --- /dev/null +++ b/PowerShell-master/.pipelines/templates/mac-package-build.yml @@ -0,0 +1,249 @@ +parameters: + parentJob: '' + buildArchitecture: x64 + +jobs: +- job: package_macOS_${{ parameters.buildArchitecture }} + displayName: Package macOS ${{ parameters.buildArchitecture }} + condition: succeeded() + pool: + type: linux + isCustom: true + name: Azure Pipelines + vmImage: 'macOS-latest' + + variables: + - name: HOMEBREW_NO_ANALYTICS + value: 1 + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_binskim_enabled + value: true + - name: ob_sdl_credscan_suppressionsfileforartifacts + value: $(Build.SourcesDirectory)/PowerShell/.config/suppress.json + - name: BuildArch + value: ${{ parameters.buildArchitecture }} + + steps: + - checkout: self + clean: true + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + + - pwsh: | + # create folder + sudo mkdir "$(Agent.TempDirectory)/PowerShell" + + # make the current user the owner + sudo chown $env:USER "$(Agent.TempDirectory)/PowerShell" + displayName: 'Create $(Agent.TempDirectory)/PowerShell' + + - template: SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: shouldSign.yml + + - template: cloneToOfficialPath.yml + parameters: + nativePathRoot: '$(Agent.TempDirectory)' + + - template: rebuild-branch-check.yml@self + + - download: CoOrdinatedBuildPipeline + artifact: macosBinResults-${{ parameters.buildArchitecture }} + + - download: CoOrdinatedBuildPipeline + artifact: drop_macos_sign_${{ parameters.buildArchitecture }} + + - pwsh: | + Write-Verbose -Verbose "unsigned artifacts" + Get-ChildItem "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/macosBinResults-${{ parameters.buildArchitecture }}" -Recurse + + Write-Verbose -Verbose "unsigned artifacts" + Get-ChildItem "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/drop_macos_sign_${{ parameters.buildArchitecture }}" -Recurse + displayName: 'Capture Downloaded Artifacts' + # Diagnostics is not critical it passes every time it runs + continueOnError: true + + - pwsh: | + # Add -SkipReleaseChecks as a mitigation to unblock release. + # macos-10.15 does not allow creating a folder under root. Hence, moving the folder. + + $buildArch = '${{ parameters.buildArchitecture }}' + + Write-Verbose -Message "Init..." -Verbose + $repoRoot = $env:REPOROOT + Set-Location $repoRoot + Import-Module "$repoRoot/build.psm1" + Import-Module "$repoRoot/tools/packaging" + + $unsignedFilesPath = "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/macosBinResults-$buildArch" + $signedFilesPath = "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/drop_macos_sign_$buildArch/Signed-$buildArch" + + Write-Verbose -Message "checking pwsh exists in $signedFilesPath" -Verbose + if (-not (Test-Path $signedFilesPath/pwsh)) { + throw "pwsh not found in $signedFilesPath" + } + + $psoptionsPath = Get-ChildItem -Path $unsignedFilesPath -Filter 'psoptions.json' -Recurse -File | Select-Object -ExpandProperty FullName + Write-Verbose -Message "Restoring PSOptions from $psoptionsPath" -Verbose + + Restore-PSOptions -PSOptionsPath "$psoptionsPath" + Get-PSOptions | Write-Verbose -Verbose + + if (-not (Test-Path "$repoRoot/tools/metadata.json")) { + throw "metadata.json not found in $repoRoot/tools" + } + + $metadata = Get-Content "$repoRoot/tools/metadata.json" -Raw | ConvertFrom-Json + + Write-Verbose -Verbose "metadata:" + $metadata | Out-String | Write-Verbose -Verbose + + # Use the rebuild branch check from the template + $isRebuildBranch = '$(RebuildBranchCheck.IsRebuildBranch)' -eq 'true' + + # Don't build LTS packages for rebuild branches + $LTS = $metadata.LTSRelease.Package -and -not $isRebuildBranch + + if ($isRebuildBranch) { + Write-Verbose -Message "Rebuild branch detected, skipping LTS package build" -Verbose + } + + Write-Verbose -Verbose "LTS: $LTS" + + if ($LTS) { + Write-Verbose -Message "LTS Release: $LTS" -Verbose + } + + Start-PSBootstrap -Scenario Package + + $macosRuntime = "osx-$buildArch" + + Start-PSPackage -Type osxpkg -SkipReleaseChecks -MacOSRuntime $macosRuntime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath + + if ($LTS) { + Start-PSPackage -Type osxpkg -SkipReleaseChecks -MacOSRuntime $macosRuntime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath -LTS + } + + $pkgNameFilter = "powershell-*$macosRuntime.pkg" + Write-Verbose -Verbose "Looking for pkg packages with filter: $pkgNameFilter in '$(Pipeline.Workspace)' to upload..." + $pkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $pkgNameFilter -Recurse -File + + foreach($p in $pkgPath) { + $file = $p.FullName + Write-Verbose -verbose "Uploading $file to macos-pkgs" + Write-Host "##vso[artifact.upload containerfolder=macos-pkgs;artifactname=macos-pkgs]$file" + } + + Start-PSPackage -Type tar -SkipReleaseChecks -MacOSRuntime $macosRuntime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath -LTS:$LTS + $tarPkgNameFilter = "powershell-*$macosRuntime.tar.gz" + Write-Verbose -Verbose "Looking for tar packages with filter: $tarPkgNameFilter in '$(Pipeline.Workspace)' to upload..." + $tarPkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $tarPkgNameFilter -Recurse -File + + foreach($t in $tarPkgPath) { + $file = $t.FullName + Write-Verbose -verbose "Uploading $file to macos-pkgs" + Write-Host "##vso[artifact.upload containerfolder=macos-pkgs;artifactname=macos-pkgs]$file" + } + + displayName: 'Package ${{ parameters.buildArchitecture}}' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + +- job: sign_package_macOS_${{ parameters.buildArchitecture }} + displayName: Sign Package macOS ${{ parameters.buildArchitecture }} + dependsOn: package_macOS_${{ parameters.buildArchitecture }} + condition: succeeded() + pool: + type: windows + + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_binskim_enabled + value: true + - name: ob_sdl_credscan_suppressionsfileforartifacts + value: $(Build.SourcesDirectory)/PowerShell/.config/suppress.json + - name: BuildArch + value: ${{ parameters.buildArchitecture }} + - group: mscodehub-macos-package-signing + + steps: + - download: current + artifact: macos-pkgs + + - pwsh: | + $buildArch = '${{ parameters.buildArchitecture }}' + $macosRuntime = "osx-$buildArch" + $pkgNameFilter = "powershell-*$macosRuntime.pkg" + $pkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $pkgNameFilter -Recurse -File + + if ($pkgPath.Count -eq 0) { + throw "No package found for $macosRuntime" + } + + foreach($p in $pkgPath) { + $file = $p.FullName + $fileName = $p.BaseName + Write-Verbose -verbose "Compressing $file" + $zipFile = "$(Pipeline.Workspace)\${fileName}.zip" + Write-Verbose -Verbose "Zip file: $zipFile" + Compress-Archive -Path $file -Destination $zipFile + } + + Write-Verbose -Verbose "Compressed files:" + Get-ChildItem -Path $(Pipeline.Workspace) -Filter "*.zip" -File | Write-Verbose -Verbose + displayName: Compress package files for signing + + - task: onebranch.pipeline.signing@1 + displayName: 'OneBranch CodeSigning Package' + inputs: + command: 'sign' + files_to_sign: '**/*-osx-*.zip' + search_root: '$(Pipeline.Workspace)' + inline_operation: | + [ + { + "KeyCode": "$(KeyCode)", + "OperationCode": "MacAppDeveloperSign", + "ToolName": "sign", + "ToolVersion": "1.0", + "Parameters": { + "Hardening": "Enable", + "OpusInfo": "http://microsoft.com" + } + } + ] + + - pwsh: | + $signedPkg = Get-ChildItem -Path $(Pipeline.Workspace) -Filter "*osx*.zip" -File + + $signedPkg | ForEach-Object { + Write-Verbose -Verbose "Signed package zip: $_" + + if (-not (Test-Path $_)) { + throw "Package not found: $_" + } + + if (-not (Test-Path $(ob_outputDirectory))) { + $null = New-Item -Path $(ob_outputDirectory) -ItemType Directory + } + + Expand-Archive -Path $_ -DestinationPath $(ob_outputDirectory) -Verbose + } + + Write-Verbose -Verbose "Expanded pkg file:" + Get-ChildItem -Path $(ob_outputDirectory) | Write-Verbose -Verbose + displayName: Expand signed file diff --git a/PowerShell-master/.pipelines/templates/mac.yml b/PowerShell-master/.pipelines/templates/mac.yml new file mode 100644 index 0000000000000000000000000000000000000000..1699207c6572112e5ca8396c6b2a49c89c24849f --- /dev/null +++ b/PowerShell-master/.pipelines/templates/mac.yml @@ -0,0 +1,147 @@ +parameters: + buildArchitecture: 'x64' +jobs: +- job: build_macOS_${{ parameters.buildArchitecture }} + displayName: Build macOS ${{ parameters.buildArchitecture }} + condition: succeeded() + pool: + type: linux + isCustom: true + name: Azure Pipelines + vmImage: 'macOS-latest' + + variables: + - name: HOMEBREW_NO_ANALYTICS + value: 1 + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: PowerShellRoot + value: $(Build.SourcesDirectory) + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + - pwsh: | + # create folder + sudo mkdir "$(Agent.TempDirectory)/PowerShell" + # make the current user the owner + sudo chown $env:USER "$(Agent.TempDirectory)/PowerShell" + displayName: 'Create $(Agent.TempDirectory)/PowerShell' + + ## We cross compile for arm64, so the arch is always x64 + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + Import-Module $(PowerShellRoot)/build.psm1 -Force + Start-PSBootstrap -Scenario Package + displayName: 'Bootstrap VM' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(PowerShellRoot) + - pwsh: | + $env:AzDevOpsFeedPAT2 = '$(powershellPackageReadPat)' + # Add -SkipReleaseChecks as a mitigation to unblock release. + # macos-10.15 does not allow creating a folder under root. Hence, moving the folder. + + Import-Module ./build.psm1 -Force + + $ReleaseTagParam = @{} + + if ($env:RELEASETAGVAR) { + $ReleaseTagParam['ReleaseTag'] = $env:RELEASETAGVAR + } + + Start-PSBuild -Runtime 'osx-${{ parameters.buildArchitecture }}' -Configuration Release -PSModuleRestore -Clean -Output $(OB_OUTPUTDIRECTORY) @ReleaseTagParam + $artifactName = "macosBinResults-${{ parameters.buildArchitecture }}" + + $psOptPath = "$(OB_OUTPUTDIRECTORY)/psoptions.json" + Save-PSOptions -PSOptionsPath $psOptPath + + # Since we are using custom pool for macOS, we need to use artifact.upload to publish the artifacts + Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName]$(OB_OUTPUTDIRECTORY)" + + $env:AzDevOpsFeedPAT2 = $null + displayName: 'Build' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - template: /.pipelines/templates/step/finalize.yml@self + +- job: sign_${{ parameters.buildArchitecture }} + displayName: Sign_macOS_${{ parameters.buildArchitecture }} + condition: succeeded() + dependsOn: build_macOS_${{ parameters.buildArchitecture }} + pool: + type: windows + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: DotNetPrivateBuildAccess + - group: certificate_logical_to_actual + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: true + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: BuildArchitecture + value: ${{ parameters.buildArchitecture }} + - name: ob_sdl_codeql_compiled_enabled + value: false + - name: ob_sdl_sbom_packageName + value: 'Microsoft.Powershell.MacOS.${{parameters.buildArchitecture}}' + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: 'macosBinResults-$(BuildArchitecture)' + path: '$(Pipeline.Workspace)\Symbols' + displayName: Download build + + - pwsh: | + Get-ChildItem "$(Pipeline.Workspace)\*" -Recurse + displayName: 'Capture Downloaded Artifacts' + # Diagnostics is not critical it passes every time it runs + continueOnError: true + + - pwsh: | + $runtime = '$(BuildArchitecture)' + Write-Host "sending.. vso[task.setvariable variable=Runtime]$runtime" + Write-Host "##vso[task.setvariable variable=Runtime]$runtime" + + $rootPath = "$(Pipeline.Workspace)\Symbols" + Write-Verbose -Verbose "Setting vso[task.setvariable variable=DropRootPath]$rootPath" + Write-Host "##vso[task.setvariable variable=DropRootPath]$rootPath" + displayName: Expand symbols zip + + - template: /.pipelines/templates/obp-file-signing.yml@self + parameters: + binPath: $(DropRootPath) + OfficialBuild: $(ps_official_build) + + - template: /.pipelines/templates/step/finalize.yml@self diff --git a/PowerShell-master/.pipelines/templates/nupkg.yml b/PowerShell-master/.pipelines/templates/nupkg.yml new file mode 100644 index 0000000000000000000000000000000000000000..c296aadc242de0e3ae51311fe1daddc65b0a620f --- /dev/null +++ b/PowerShell-master/.pipelines/templates/nupkg.yml @@ -0,0 +1,298 @@ +jobs: +- job: build_nupkg + displayName: Package NuPkgs + condition: succeeded() + pool: + type: windows + + variables: + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)\ONEBRANCH_ARTIFACT' + - name: ob_sdl_binskim_enabled + value: true + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - group: mscodehub-feed-read-general + - group: mscodehub-feed-read-akv + - group: DotNetPrivateBuildAccess + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - template: SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: shouldSign.yml + + - template: cloneToOfficialPath.yml + parameters: + nativePathRoot: '$(Agent.TempDirectory)' + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_fxdependent_release + displayName: 'Download drop_windows_build_windows_fxdependent_release' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_fxdependentWinDesktop_release + displayName: 'Download drop_windows_build_windows_fxdependentWinDesktop_release' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - download: CoOrdinatedBuildPipeline + artifact: drop_linux_sign_linux_fxd + displayName: 'Download drop_linux_sign_linux_fxd' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - download: CoOrdinatedBuildPipeline + artifact: drop_linux_sign_linux_fxd_x64_alpine + displayName: 'Download drop_linux_sign_linux_fxd_x64_alpine' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - pwsh: | + Write-Verbose -Verbose "drop_windows_build_windows_fxdependent_release" + Get-ChildItem -Path $(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependent_release -Recurse | Out-String | Write-Verbose -Verbose + + Write-Verbose -Verbose "drop_windows_build_windows_fxdependentWinDesktop_release" + Get-ChildItem -Path $(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependentWinDesktop_release -Recurse | Out-String | Write-Verbose -Verbose + + Write-Verbose -Verbose "drop_linux_sign_linux_fxd" + Get-ChildItem -Path $(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd -Recurse | Out-String | Write-Verbose -Verbose + + Write-Verbose -Verbose "drop_linux_sign_linux_fxd_x64_alpine" + Get-ChildItem -Path $(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd_x64_alpine -Recurse | Out-String | Write-Verbose -Verbose + displayName: 'Capture download artifacts' + env: + ob_restore_phase: true # This ensures this done in restore phase to workaround signing issue + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(PowerShellRoot) + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + Set-Location -Path '$(PowerShellRoot)' + Import-Module "$(PowerShellRoot)/build.psm1" -Force + + $sharedModules = @('Microsoft.PowerShell.Commands.Management', + 'Microsoft.PowerShell.Commands.Utility', + 'Microsoft.PowerShell.ConsoleHost', + 'Microsoft.PowerShell.Security', + 'System.Management.Automation' + ) + + $winOnlyModules = @('Microsoft.Management.Infrastructure.CimCmdlets', + 'Microsoft.PowerShell.Commands.Diagnostics', + 'Microsoft.PowerShell.CoreCLR.Eventing', + 'Microsoft.WSMan.Management', + 'Microsoft.WSMan.Runtime' + ) + + $refAssemblyFolder = Join-Path '$(System.ArtifactsDirectory)' 'RefAssembly' + $null = New-Item -Path $refAssemblyFolder -Force -Verbose -Type Directory + + Start-PSBuild -Clean -Runtime linux-x64 -Configuration Release -ReleaseTag $(ReleaseTagVar) + + $sharedModules | Foreach-Object { + $refFile = Get-ChildItem -Path "$(PowerShellRoot)\src\$_\obj\Release\net11.0\refint\$_.dll" + Write-Verbose -Verbose "RefAssembly: $refFile" + Copy-Item -Path $refFile -Destination "$refAssemblyFolder\$_.dll" -Verbose + $refDoc = "$(PowerShellRoot)\src\$_\bin\Release\net11.0\$_.xml" + if (-not (Test-Path $refDoc)) { + Write-Warning "$refDoc not found" + Get-ChildItem -Path "$(PowerShellRoot)\src\$_\bin\Release\net11.0\" | Out-String | Write-Verbose -Verbose + } + else { + Copy-Item -Path $refDoc -Destination "$refAssemblyFolder\$_.xml" -Verbose + } + } + + Start-PSBuild -Clean -Runtime win7-x64 -Configuration Release -ReleaseTag $(ReleaseTagVar) + + $winOnlyModules | Foreach-Object { + $refFile = Get-ChildItem -Path "$(PowerShellRoot)\src\$_\obj\Release\net11.0\refint\*.dll" + Write-Verbose -Verbose 'RefAssembly: $refFile' + Copy-Item -Path $refFile -Destination "$refAssemblyFolder\$_.dll" -Verbose + $refDoc = "$(PowerShellRoot)\src\$_\bin\Release\net11.0\$_.xml" + if (-not (Test-Path $refDoc)) { + Write-Warning "$refDoc not found" + Get-ChildItem -Path "$(PowerShellRoot)\src\$_\bin\Release\net11.0" | Out-String | Write-Verbose -Verbose + } + else { + Copy-Item -Path $refDoc -Destination "$refAssemblyFolder\$_.xml" -Verbose + } + } + + Get-ChildItem $refAssemblyFolder -Recurse | Out-String | Write-Verbose -Verbose + + # Set RefAssemblyPath path variable + $vstsCommandString = "vso[task.setvariable variable=RefAssemblyPath]${refAssemblyFolder}" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: Build reference assemblies + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - task: onebranch.pipeline.signing@1 + displayName: Sign ref assemblies + inputs: + command: 'sign' + signing_profile: external_distribution + files_to_sign: '**\*.dll' + search_root: '$(System.ArtifactsDirectory)\RefAssembly' + + - pwsh: | + $files = @( + "Microsoft.Management.Infrastructure.CimCmdlets.dll" + "Microsoft.PowerShell.Commands.Diagnostics.dll" + "Microsoft.PowerShell.Commands.Management.dll" + "Microsoft.PowerShell.Commands.Utility.dll" + "Microsoft.PowerShell.ConsoleHost.dll" + "Microsoft.PowerShell.CoreCLR.Eventing.dll" + "Microsoft.PowerShell.Security.dll" + "Microsoft.PowerShell.SDK.dll" + "Microsoft.WSMan.Management.dll" + "Microsoft.WSMan.Runtime.dll" + "System.Management.Automation.dll" + ) + + Import-Module -Name '$(PowerShellRoot)\build.psm1' + Import-Module -Name '$(PowerShellRoot)\tools\packaging' + Find-DotNet + + Write-Verbose -Verbose "Version == $(Version)" + + $winFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependent_release\Signed-fxdependent" + Write-Verbose -Verbose "winFxdPath == $winFxdPath" + + $linuxFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd\Signed-fxdependent" + Write-Verbose -Verbose "linuxFxdPath == $linuxFxdPath" + + $nupkgOutputPath = Join-Path -Path '$(Pipeline.Workspace)' -ChildPath 'nupkg' + New-Item -Path $nupkgOutputPath -ItemType Directory -Force + + $files | Foreach-Object { + $FileBaseName = [System.IO.Path]::GetFileNameWithoutExtension($_) + $FilePackagePath = Join-Path -Path $nupkgOutputPath -ChildPath $FileBaseName + Write-Verbose -Verbose "FileName to package: $_" + Write-Verbose -Verbose "FilePackage path: $FilePackagePath" + New-ILNugetPackageSource -File $_ -PackagePath $FilePackagePath -PackageVersion '$(Version)' -WinFxdBinPath $winFxdPath -LinuxFxdBinPath $linuxFxdPath -RefAssemblyPath $(RefAssemblyPath) + New-ILNugetPackageFromSource -FileName $_ -PackageVersion '$(Version)' -PackagePath $FilePackagePath + } + displayName: 'Create NuGet Package for single file' + + - task: onebranch.pipeline.signing@1 + displayName: Sign nupkg files + inputs: + command: 'sign' + cp_code: 'CP-401405' + files_to_sign: '**\*.nupkg' + search_root: '$(Pipeline.Workspace)\nupkg' + + ### Create global tools + + - pwsh: | + $winFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependent_release\Signed-fxdependent" + $winDesktopFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependentWinDesktop_release\Signed-fxdependent-win-desktop" + $linuxFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd\Signed-fxdependent" + $alpineFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd_x64_alpine\Signed-fxdependent-noopt-linux-musl-x64" + + Import-Module -Name '$(PowerShellRoot)\build.psm1' + Import-Module -Name '$(PowerShellRoot)\tools\packaging' + + Start-PrepForGlobalToolNupkg -LinuxBinPath $linuxFxdPath -WindowsBinPath $winFxdPath -WindowsDesktopBinPath $winDesktopFxdPath -AlpineBinPath $alpineFxdPath + displayName: 'Prepare for global tool packages' + + - pwsh: | + Import-Module -Name '$(PowerShellRoot)\build.psm1' + Import-Module -Name '$(PowerShellRoot)\tools\packaging' + Find-DotNet + + $gblToolOutputPath = Join-Path -Path '$(Pipeline.Workspace)' -ChildPath 'globaltools' + New-Item -Path $gblToolOutputPath -ItemType Directory -Force + + $winFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependent_release\Signed-fxdependent" + $winDesktopFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependentWinDesktop_release\Signed-fxdependent-win-desktop" + $linuxFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd\Signed-fxdependent" + $alpineFxdPath = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_linux_sign_linux_fxd_x64_alpine\Signed-fxdependent-noopt-linux-musl-x64" + + # Build global tools which do not have the shims exe generated in build. + $packageTypes = @('Unified', 'PowerShell.Linux.Alpine', 'PowerShell.Linux.x64', 'PowerShell.Linux.arm32', 'PowerShell.Linux.arm64') + + $packageTypes | Foreach-Object { + $PackageType = $_ + Write-Verbose -Verbose "PackageType: $PackageType" + + New-GlobalToolNupkgSource -PackageType $PackageType -PackageVersion '$(Version)' -LinuxBinPath $linuxFxdPath -WindowsBinPath $winFxdPath -WindowsDesktopBinPath $winDesktopFxdPath -AlpineBinPath $alpineFxdPath -SkipCGManifest + + Write-Verbose -Verbose "GlobalToolNuspecSourcePath = $global:GlobalToolNuSpecSourcePath" + Write-Verbose -Verbose "GlobalToolPkgName = $global:GlobalToolPkgName" + + Write-Verbose -Verbose "Starting global tool package creation for $PackageType" + New-GlobalToolNupkgFromSource -PackageNuSpecPath "$global:GlobalToolNuSpecSourcePath" -PackageName "$global:GlobalToolPkgName" -DestinationPath $gblToolOutputPath + Write-Verbose -Verbose "Global tool package created for $PackageType" + $global:GlobalToolNuSpecSourcePath = $null + $global:GlobalToolPkgName = $null + } + displayName: 'Create global tools' + + - pwsh: | + $gblToolOutputPath = Join-Path -Path '$(Pipeline.Workspace)' -ChildPath 'globaltools' + Get-ChildItem -Path $gblToolOutputPath + displayName: Capture global tools + + - task: onebranch.pipeline.signing@1 + displayName: Sign nupkg files + inputs: + command: 'sign' + cp_code: 'CP-401405' + files_to_sign: '**\*.nupkg' + search_root: '$(Pipeline.Workspace)\globaltools' + + - pwsh: | + if (-not (Test-Path '$(ob_outputDirectory)')) { + New-Item -ItemType Directory -Path '$(ob_outputDirectory)' -Force + } + + Write-Verbose -Verbose "Copying nupkgs to output directory" + $nupkgOutputPath = Join-Path -Path '$(Pipeline.Workspace)' -ChildPath 'nupkg' + Get-ChildItem -Path $nupkgOutputPath -Filter *.nupkg -Recurse | Copy-Item -Destination '$(ob_outputDirectory)' -Force -Verbose + + # Copy Windows.x86 global tool from build to output directory + $winX64GlobalTool = "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_fxdependent_release\globaltool\powershell*.nupkg" + Write-Verbose -Verbose "Finding Windows.x64 global tool at $winX64GlobalTool" + $globalToolPath = Get-Item $winX64GlobalTool + Copy-Item -Path $globalToolPath -Destination '$(ob_outputDirectory)' -Force -Verbose + + Write-Verbose -Verbose "Copying global tools to output directory" + $gblToolOutputPath = Join-Path -Path '$(Pipeline.Workspace)' -ChildPath 'globaltools' + Get-ChildItem -Path $gblToolOutputPath -Filter *.nupkg -Recurse | Copy-Item -Destination '$(ob_outputDirectory)' -Force -Verbose + displayName: Copy artifacts to output directory + + - pwsh: | + $nupkgOutputPath = '$(ob_outputDirectory)' + Get-ChildItem -Path $nupkgOutputPath | Out-String | Write-Verbose -Verbose + displayName: List artifacts diff --git a/PowerShell-master/.pipelines/templates/obp-file-signing.yml b/PowerShell-master/.pipelines/templates/obp-file-signing.yml new file mode 100644 index 0000000000000000000000000000000000000000..cbe44ad00189877d555fe9454659e14ff549b3e3 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/obp-file-signing.yml @@ -0,0 +1,175 @@ +parameters: + binPath: '$(ob_outputDirectory)' + globalTool: 'false' + SigningProfile: 'external_distribution' + OfficialBuild: true + vPackScenario: false + +steps: +- pwsh: | + $fullSymbolsFolder = '${{ parameters.binPath }}' + Write-Verbose -Verbose "fullSymbolsFolder == $fullSymbolsFolder" + Get-ChildItem -Recurse $fullSymbolsFolder | Select-Object -ExpandProperty FullName | Write-Verbose -Verbose + $filesToSignDirectory = "$(Pipeline.Workspace)/toBeSigned" + if ((Test-Path -Path $filesToSignDirectory)) { + Remove-Item -Path $filesToSignDirectory -Recurse -Force + } + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force + + $itemsToCopyWithRecurse = @( + "$($fullSymbolsFolder)/*.ps1" + "$($fullSymbolsFolder)/Microsoft.PowerShell*.dll" + ) + $itemsToCopy = @{ + "$($fullSymbolsFolder)/*.ps1" = "" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1" = "Modules/Microsoft.PowerShell.Host" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1" = "Modules/Microsoft.PowerShell.Management" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" = "Modules/Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1" = "Modules/Microsoft.PowerShell.Utility" + "$($fullSymbolsFolder)/pwsh.dll" = "" + "$($fullSymbolsFolder)/System.Management.Automation.dll" = "" + } + ## Windows only modules + if('$(ArtifactPlatform)' -eq 'windows') { + $itemsToCopy += @{ + "$($fullSymbolsFolder)/pwsh.exe" = "" + "$($fullSymbolsFolder)/Microsoft.Management.Infrastructure.CimCmdlets.dll" = "" + "$($fullSymbolsFolder)/Microsoft.WSMan.*.dll" = "" + "$($fullSymbolsFolder)/Modules/CimCmdlets/CimCmdlets.psd1" = "Modules/CimCmdlets" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml" = "Modules/Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml" = "Modules/Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml" = "Modules/Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Security/Security.types.ps1xml" = "Modules/Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)/Modules/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1" = "Modules/Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)/Modules/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1" = "Modules/Microsoft.WSMan.Management" + "$($fullSymbolsFolder)/Modules/Microsoft.WSMan.Management/WSMan.format.ps1xml" = "Modules/Microsoft.WSMan.Management" + "$($fullSymbolsFolder)/Modules/PSDiagnostics/PSDiagnostics.ps?1" = "Modules/PSDiagnostics" + } + } + + $itemsToExclude = @( + # This package is retrieved from https://www.github.com/powershell/MarkdownRender + "$($fullSymbolsFolder)/Microsoft.PowerShell.MarkdownRender.dll" + ) + + if('$(ArtifactPlatform)' -eq 'linux' -or '$(ArtifactPlatform)' -eq 'macos') { + $itemsToExclude += "$($fullSymbolsFolder)/pwsh" + } + + Write-Verbose -verbose "recursively copying $($itemsToCopyWithRecurse | out-string) to $filesToSignDirectory" + Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose -exclude $itemsToExclude + Write-Verbose -verbose "recursive copy done." + + foreach($pattern in $itemsToCopy.Keys) { + $destinationFolder = Join-Path $filesToSignDirectory -ChildPath $itemsToCopy.$pattern + $null = New-Item -ItemType Directory -Path $destinationFolder -Force + Write-Verbose -verbose "copying $pattern to $destinationFolder" + + if (-not (Test-Path -Path $pattern)) { + Write-Verbose -verbose "No files found for pattern $pattern" + continue + } + + Copy-Item -Path $pattern -Destination $destinationFolder -Recurse -verbose + } + + Write-Verbose -verbose "copying done." + Write-Verbose -verbose "Files to be signed at: $filesToSignDirectory" + + Get-ChildItem -Recurse -File $filesToSignDirectory | Select-Object -Property FullName + displayName: 'Prepare files to be signed' + +- task: onebranch.pipeline.signing@1 + displayName: Sign 1st party files + inputs: + command: 'sign' + signing_profile: ${{ parameters.SigningProfile }} + files_to_sign: '**\*.psd1;**\*.psm1;**\*.ps1xml;**\*.ps1;**\*.dll;**\*.exe;**\pwsh' + search_root: $(Pipeline.Workspace)/toBeSigned + +- pwsh : | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + +- pwsh: | + Import-Module $(PowerShellRoot)/build.psm1 -Force + Import-Module $(PowerShellRoot)/tools/packaging -Force + + $BuildPath = (Get-Item '${{ parameters.binPath }}').FullName + Write-Verbose -Verbose -Message "BuildPath: $BuildPath" + + $officialBuild = [System.Convert]::ToBoolean('${{ parameters.OfficialBuild }}') + ## copy all files to be signed to build folder + Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath '$(Pipeline.Workspace)/toBeSigned' -OfficialBuild $officialBuild + + $dlls = Get-ChildItem $BuildPath/*.dll, $BuildPath/*.exe -Recurse + $signatures = $dlls | Get-AuthenticodeSignature + $officialIssuerPattern = '^CN=(Microsoft Code Signing PCA|Microsoft Root Certificate Authority|Microsoft Corporation).*' + $testCert = '^CN=(Microsoft|TestAzureEngBuildCodeSign).*' + $missingSignatures = $signatures | Where-Object { $_.status -eq 'notsigned' -or $_.SignerCertificate.Issuer -notmatch $testCert -or $_.SignerCertificate.Issuer -notmatch $officialIssuerPattern} | select-object -ExpandProperty Path + + Write-Verbose -verbose "to be signed:`r`n $($missingSignatures | Out-String)" + + $filesToSignDirectory = "$(Pipeline.Workspace)/thirdPartyToBeSigned" + if (Test-Path $filesToSignDirectory) { + Remove-Item -Path $filesToSignDirectory -Recurse -Force + } + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force -Verbose + + $missingSignatures | ForEach-Object { + $pathWithoutLeaf = Split-Path $_ + $relativePath = $pathWithoutLeaf.replace($BuildPath,'') + Write-Verbose -Verbose -Message "relativePath: $relativePath" + $targetDirectory = Join-Path -Path $filesToSignDirectory -ChildPath $relativePath + Write-Verbose -Verbose -Message "targetDirectory: $targetDirectory" + if(!(Test-Path $targetDirectory)) + { + $null = New-Item -ItemType Directory -Path $targetDirectory -Force -Verbose + } + Copy-Item -Path $_ -Destination $targetDirectory + } + displayName: Create ThirdParty Signing Folder + +- task: onebranch.pipeline.signing@1 + displayName: Sign 3rd Party files + inputs: + command: 'sign' + signing_profile: $(msft_3rd_party_cert_id) + files_to_sign: '**\*.dll;**\*.exe' + search_root: $(Pipeline.Workspace)/thirdPartyToBeSigned + +- pwsh: | + Get-ChildItem '$(Pipeline.Workspace)/thirdPartyToBeSigned/*' + displayName: Capture ThirdParty Signed files + +- pwsh: | + $officialBuild = [System.Convert]::ToBoolean('${{ parameters.OfficialBuild }}') + $vPackScenario = [System.Convert]::ToBoolean('${{ parameters.vPackScenario }}') + Import-Module '$(PowerShellRoot)/build.psm1' -Force + Import-Module '$(PowerShellRoot)/tools/packaging' -Force + $isGlobalTool = '${{ parameters.globalTool }}' -eq 'true' + + if ($vPackScenario) { + Write-Verbose -Verbose -Message "vPackScenario is true, copying to $(ob_outputDirectory)" + $pathForUpload = New-Item -ItemType Directory -Path '$(ob_outputDirectory)' -Force + Write-Verbose -Verbose -Message "pathForUpload: $pathForUpload" + Copy-Item -Path '${{ parameters.binPath }}\*' -Destination $pathForUpload -Recurse -Force -Verbose + Write-Verbose -Verbose -Message "Files copied to $pathForUpload" + } + elseif (-not $isGlobalTool) { + $pathForUpload = New-Item -ItemType Directory -Path '$(ob_outputDirectory)/Signed-$(Runtime)' -Force + Write-Verbose -Verbose -Message "pathForUpload: $pathForUpload" + Copy-Item -Path '${{ parameters.binPath }}\*' -Destination $pathForUpload -Recurse -Force -Verbose + Write-Verbose -Verbose -Message "Files copied to $pathForUpload" + } + else { + $pathForUpload = '${{ parameters.binPath }}' + } + + Write-Verbose "Copying third party signed files to the build folder" + $thirdPartySignedFilesPath = (Get-Item '$(Pipeline.Workspace)/thirdPartyToBeSigned').FullName + Update-PSSignedBuildFolder -BuildPath $pathForUpload -SignedFilesPath $thirdPartySignedFilesPath -OfficialBuild $officialBuild + + displayName: 'Copy signed files for upload' + +- template: /.pipelines/templates/step/finalize.yml@self diff --git a/PowerShell-master/.pipelines/templates/package-create-msix.yml b/PowerShell-master/.pipelines/templates/package-create-msix.yml new file mode 100644 index 0000000000000000000000000000000000000000..97d2f4fc46a4cee0a0bda6766dfac42fb6efe63e --- /dev/null +++ b/PowerShell-master/.pipelines/templates/package-create-msix.yml @@ -0,0 +1,154 @@ +parameters: + - name: OfficialBuild + type: boolean + default: false + +jobs: +- job: CreateMSIXBundle + displayName: Create .msixbundle file + pool: + type: windows + + variables: + - group: msixTools + - group: 'Azure Blob variable group' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: release-SetReleaseTagandContainerName.yml@self + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_arm64 + itemPattern: | + **/*.msix + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows arm64 packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_x64 + itemPattern: | + **/*.msix + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows x64 packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_x86 + itemPattern: | + **/*.msix + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows x86 packages + + # Finds the makeappx tool on the machine with image: 'onebranch.azurecr.io/windows/ltsc2022/vse2022:latest' + - pwsh: | + $cmd = Get-Command makeappx.exe -ErrorAction Ignore + if ($cmd) { + Write-Verbose -Verbose 'makeappx available in PATH' + $exePath = $cmd.Source + } else { + $toolsDir = '$(Pipeline.Workspace)\releasePipeline\tools' + New-Item $toolsDir -Type Directory -Force > $null + $makeappx = Get-ChildItem -Recurse 'C:\Program Files (x86)\Windows Kits\10\makeappx.exe' | + Where-Object { $_.DirectoryName -match 'x64' } | + Select-Object -Last 1 + $exePath = $makeappx.FullName + Write-Verbose -Verbose 'makeappx was found:' + } + $vstsCommandString = "vso[task.setvariable variable=MakeAppxPath]$exePath" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: Find makeappx tool + retryCountOnTaskFailure: 1 + + - pwsh: | + $sourceDir = '$(Pipeline.Workspace)\releasePipeline\msix' + $null = New-Item -Path $sourceDir -ItemType Directory -Force + + $msixFiles = Get-ChildItem -Path "$(Build.ArtifactStagingDirectory)/downloads/*.msix" -Recurse + foreach ($msixFile in $msixFiles) { + $null = Copy-Item -Path $msixFile.FullName -Destination $sourceDir -Force -Verbose + } + + $makeappx = '$(MakeAppxPath)' + $outputDir = "$sourceDir\output" + New-Item $outputDir -Type Directory -Force > $null + + # Separate LTS and Stable/Preview MSIX files by filename convention + $ltsMsix = @(Get-ChildItem $sourceDir -Filter '*.msix' | Where-Object { $_.BaseName -match '-LTS-' }) + $stableMsix = @(Get-ChildItem $sourceDir -Filter '*.msix' | Where-Object { $_.BaseName -notmatch '-LTS-' }) + + Write-Verbose -Verbose "Stable/Preview MSIX files: $($stableMsix.Name -join ', ')" + Write-Verbose -Verbose "LTS MSIX files: $($ltsMsix.Name -join ', ')" + + # Create Stable/Preview bundle + if ($stableMsix.Count -gt 0) { + $stableDir = "$sourceDir\stable" + New-Item $stableDir -Type Directory -Force > $null + $stableMsix | Copy-Item -Destination $stableDir -Force + $file = $stableMsix | Select-Object -First 1 + $prefix = ($file.BaseName -split "-win")[0] + $stableBundleName = "$prefix.msixbundle" + Write-Verbose -Verbose "Creating Stable/Preview bundle: $stableBundleName" + & $makeappx bundle /d $stableDir /p "$outputDir\$stableBundleName" + } + + # Create LTS bundle + if ($ltsMsix.Count -gt 0) { + $ltsDir = "$sourceDir\lts" + New-Item $ltsDir -Type Directory -Force > $null + $ltsMsix | Copy-Item -Destination $ltsDir -Force + $file = $ltsMsix | Select-Object -First 1 + $prefix = ($file.BaseName -split "-win")[0] + $ltsBundleName = "$prefix.msixbundle" + Write-Verbose -Verbose "Creating LTS bundle: $ltsBundleName" + & $makeappx bundle /d $ltsDir /p "$outputDir\$ltsBundleName" + } + + Write-Verbose -Verbose "Created bundles:" + Get-ChildItem -Path $outputDir -Recurse + + $vstsCommandString = "vso[task.setvariable variable=BundleDir]$outputDir" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: Create MsixBundle + retryCountOnTaskFailure: 1 + + - task: onebranch.pipeline.signing@1 + displayName: Sign MsixBundle + condition: eq('${{ parameters.OfficialBuild }}', 'true') + inputs: + command: 'sign' + signing_profile: $(MSIXProfile) + files_to_sign: '**/*.msixbundle' + search_root: '$(BundleDir)' + + - pwsh: | + $signedBundles = @(Get-ChildItem -Path $(BundleDir) -Filter "*.msixbundle" -File) + Write-Verbose -Verbose "Signed bundles: $($signedBundles.Name -join ', ')" + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + foreach ($bundle in $signedBundles) { + Copy-Item -Path $bundle.FullName -Destination "$(ob_outputDirectory)" -Verbose + } + + Write-Verbose -Verbose "Uploaded Bundles:" + Get-ChildItem -Path $(ob_outputDirectory) | Write-Verbose -Verbose + displayName: Upload msixbundle to Artifacts diff --git a/PowerShell-master/.pipelines/templates/package-store-package.yml b/PowerShell-master/.pipelines/templates/package-store-package.yml new file mode 100644 index 0000000000000000000000000000000000000000..6abddae685116dd4d72cb94739d81ea002f27daf --- /dev/null +++ b/PowerShell-master/.pipelines/templates/package-store-package.yml @@ -0,0 +1,244 @@ +jobs: +- job: CreateStorePackage + displayName: Create StoreBroker Package + pool: + type: windows + + variables: + - group: 'Azure Blob variable group' + - group: 'Store Publish Variables' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_signing_setup_enabled + value: false + - name: ob_sdl_codeSignValidation_enabled + value: false + + steps: + - checkout: self + clean: true + + - template: release-SetReleaseTagandContainerName.yml@self + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_msixbundle_CreateMSIXBundle + itemPattern: | + **/*.msixbundle + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download signed msixbundle + + - pwsh: | + $bundleDir = '$(Build.ArtifactStagingDirectory)/downloads' + $bundle = Get-ChildItem -Path $bundleDir -Filter '*.msixbundle' -Recurse | Select-Object -First 1 + if (-not $bundle) { + Write-Error "No .msixbundle file found in $bundleDir" + exit 1 + } + Write-Verbose -Verbose "Found bundle: $($bundle.FullName)" + $vstsCommandString = "vso[task.setvariable variable=BundleDir]$($bundle.DirectoryName)" + Write-Host "##$vstsCommandString" + displayName: Locate msixbundle + + - template: channelSelection.yml@self + + - pwsh: | + $IsLTS = '$(ChannelSelection.IsLTS)' -eq 'true' + $IsStable = '$(ChannelSelection.IsStable)' -eq 'true' + $IsPreview = '$(ChannelSelection.IsPreview)' -eq 'true' + + Write-Verbose -Verbose "Channel Selection - LTS: $IsLTS, Stable: $IsStable, Preview: $IsPreview" + + # Define app configurations for each channel + $channelConfigs = @{ + 'LTS' = @{ + AppStoreName = 'PowerShell-LTS' + ProductId = '$(productId-LTS)' + AppId = '$(AppID-LTS)' + ServiceEndpoint = "StoreAppPublish-Stable" + } + 'Stable' = @{ + AppStoreName = 'PowerShell' + ProductId = '$(productId-Stable)' + AppId = '$(AppID-Stable)' + ServiceEndpoint = "StoreAppPublish-Stable" + } + 'Preview' = @{ + AppStoreName = 'PowerShell (Preview)' + ProductId = '$(productId-Preview)' + AppId = '$(AppID-Preview)' + ServiceEndpoint = "StoreAppPublish-Preview" + } + } + + $currentChannel = if ($IsLTS) { 'LTS' } + elseif ($IsStable) { 'Stable' } + elseif ($IsPreview) { 'Preview' } + else { + Write-Error "No valid channel detected" + exit 1 + } + + $config = $channelConfigs[$currentChannel] + Write-Verbose -Verbose "Selected channel: $currentChannel" + Write-Verbose -Verbose "App Store Name: $($config.AppStoreName)" + Write-Verbose -Verbose "Product ID: $($config.ProductId)" + + # Update PDP.xml file + $pdpPath = '$(System.DefaultWorkingDirectory)/PowerShell/.pipelines/store/PDP/PDP/en-US/PDP.xml' + if (Test-Path $pdpPath) { + Write-Verbose -Verbose "Updating PDP file: $pdpPath" + + [xml]$pdpXml = Get-Content $pdpPath -Raw + + # Create namespace manager for XML with default namespace + $nsManager = New-Object System.Xml.XmlNamespaceManager($pdpXml.NameTable) + $nsManager.AddNamespace("pd", "http://schemas.microsoft.com/appx/2012/ProductDescription") + + $appStoreNameElement = $pdpXml.SelectSingleNode("//pd:AppStoreName", $nsManager) + if ($appStoreNameElement) { + $appStoreNameElement.SetAttribute("_locID", $config.AppStoreName) + Write-Verbose -Verbose "Updated AppStoreName _locID to: $($config.AppStoreName)" + } else { + Write-Warning "AppStoreName element not found in PDP file" + } + + $pdpXml.Save($pdpPath) + Write-Verbose -Verbose "PDP file updated successfully" + Get-Content -Path $pdpPath | Write-Verbose -Verbose + } else { + Write-Error "PDP file not found: $pdpPath" + exit 1 + } + + # Update SBConfig.json file + $sbConfigPath = '$(System.DefaultWorkingDirectory)/PowerShell/.pipelines/store/SBConfig.json' + if (Test-Path $sbConfigPath) { + Write-Verbose -Verbose "Updating SBConfig file: $sbConfigPath" + + $sbConfigJson = Get-Content $sbConfigPath -Raw | ConvertFrom-Json + + $sbConfigJson.appSubmission.productId = $config.ProductId + Write-Verbose -Verbose "Updated productId to: $($config.ProductId)" + + $sbConfigJson | ConvertTo-Json -Depth 100 | Set-Content $sbConfigPath -Encoding UTF8 + Write-Verbose -Verbose "SBConfig file updated successfully" + Get-Content -Path $sbConfigPath | Write-Verbose -Verbose + } else { + Write-Error "SBConfig file not found: $sbConfigPath" + exit 1 + } + + Write-Host "##vso[task.setvariable variable=ServiceConnection]$($config.ServiceEndpoint)" + Write-Host "##vso[task.setvariable variable=SBConfigPath]$($sbConfigPath)" + + # Select the correct bundle based on channel + $bundleFiles = @(Get-ChildItem -Path '$(BundleDir)' -Filter '*.msixbundle') + Write-Verbose -Verbose "Available bundles: $($bundleFiles.Name -join ', ')" + + if ($IsLTS) { + $bundleFile = $bundleFiles | Where-Object { $_.Name -match '-LTS-' } + } else { + # Catches Stable or Preview + $bundleFile = $bundleFiles | Where-Object { $_.Name -notmatch '-LTS-' } + } + + if (-not $bundleFile) { + Write-Error "No matching bundle found for channel '$currentChannel'. Available bundles: $($bundleFiles.Name -join ', ')" + exit 1 + } + + # Copy the selected bundle to a dedicated directory for store packaging + $storeBundleDir = '$(Pipeline.Workspace)\releasePipeline\msix\store-bundle' + New-Item $storeBundleDir -Type Directory -Force > $null + Copy-Item -Path $bundleFile.FullName -Destination $storeBundleDir -Force -Verbose + Write-Host "##vso[task.setvariable variable=StoreBundleDir]$storeBundleDir" + Write-Verbose -Verbose "Selected bundle for store packaging: $($bundleFile.Name)" + + # These variables are used in the next tasks to determine which ServiceEndpoint to use + $ltsValue = $IsLTS.ToString().ToLower() + $stableValue = $IsStable.ToString().ToLower() + $previewValue = $IsPreview.ToString().ToLower() + + Write-Verbose -Verbose "About to set variables:" + Write-Verbose -Verbose " LTS=$ltsValue" + Write-Verbose -Verbose " STABLE=$stableValue" + Write-Verbose -Verbose " PREVIEW=$previewValue" + + Write-Host "##vso[task.setvariable variable=LTS]$ltsValue" + Write-Host "##vso[task.setvariable variable=STABLE]$stableValue" + Write-Host "##vso[task.setvariable variable=PREVIEW]$previewValue" + + Write-Verbose -Verbose "Variables set successfully" + name: UpdateConfigs + displayName: Update PDPs and SBConfig.json + + - pwsh: | + Write-Verbose -Verbose "Checking variables after UpdateConfigs:" + Write-Verbose -Verbose "LTS=$(LTS)" + Write-Verbose -Verbose "STABLE=$(STABLE)" + Write-Verbose -Verbose "PREVIEW=$(PREVIEW)" + displayName: Debug - Check Variables + + - task: MS-RDX-MRO.windows-store-publish.package-task.store-package@3 + displayName: 'Create StoreBroker Package (Preview)' + condition: eq(variables['PREVIEW'], 'true') + inputs: + serviceEndpoint: 'StoreAppPublish-Preview' + sbConfigPath: '$(SBConfigPath)' + sourceFolder: '$(StoreBundleDir)' + contents: '*.msixBundle' + outSBName: 'PowerShellStorePackage' + pdpPath: '$(System.DefaultWorkingDirectory)/PowerShell/.pipelines/store/PDP/PDP' + pdpMediaPath: '$(System.DefaultWorkingDirectory)/PowerShell/.pipelines/store/PDP/PDP-Media' + + - task: MS-RDX-MRO.windows-store-publish.package-task.store-package@3 + displayName: 'Create StoreBroker Package (Stable/LTS)' + condition: or(eq(variables['STABLE'], 'true'), eq(variables['LTS'], 'true')) + inputs: + serviceEndpoint: 'StoreAppPublish-Stable' + sbConfigPath: '$(SBConfigPath)' + sourceFolder: '$(StoreBundleDir)' + contents: '*.msixBundle' + outSBName: 'PowerShellStorePackage' + pdpPath: '$(System.DefaultWorkingDirectory)/PowerShell/.pipelines/store/PDP/PDP' + pdpMediaPath: '$(System.DefaultWorkingDirectory)/PowerShell/.pipelines/store/PDP/PDP-Media' + + - pwsh: | + $outputDirectory = "$(ob_outputDirectory)" + if (-not (Test-Path -LiteralPath $outputDirectory)) { + New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null + } + + Get-Item -Path "$(System.DefaultWorkingDirectory)/SBLog.txt" -ErrorAction SilentlyContinue | + Copy-Item -Destination $outputDirectory -Verbose + displayName: Upload Store Failure Log + condition: failed() + + - pwsh: | + $outputDirectory = "$(ob_outputDirectory)" + if (-not (Test-Path -LiteralPath $outputDirectory)) { + New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null + } + + $submissionPackageDir = "$(System.DefaultWorkingDirectory)/SBOutDir" + $jsonFile = "$submissionPackageDir/PowerShellStorePackage.json" + $zipFile = "$submissionPackageDir/PowerShellStorePackage.zip" + + if ((Test-Path $jsonFile) -and (Test-Path $zipFile)) { + Write-Verbose -Verbose "Uploading StoreBroker Package files:" + Write-Verbose -Verbose "JSON File: $jsonFile" + Write-Verbose -Verbose "ZIP File: $zipFile" + + Copy-Item -Path $submissionPackageDir -Destination $outputDirectory -Verbose -Recurse + } + else { + Write-Error "Required files not found in $submissionPackageDir" + exit 1 + } + displayName: 'Upload StoreBroker Package' diff --git a/PowerShell-master/.pipelines/templates/packaging/windows/package.yml b/PowerShell-master/.pipelines/templates/packaging/windows/package.yml new file mode 100644 index 0000000000000000000000000000000000000000..8b0e230b6b82136829e3a1e213ac3d798b07d329 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/packaging/windows/package.yml @@ -0,0 +1,225 @@ +parameters: + runtime: x64 + +jobs: +- job: build_win_${{ parameters.runtime }} + displayName: Build Windows Packages ${{ parameters.runtime }} + condition: succeeded() + pool: + type: windows + + variables: + - name: ob_sdl_codeSignValidation_enabled + value: false # Skip signing validation in build-only stage + - name: ob_signing_setup_enabled + value: false # Disable signing setup - this is a build-only stage, signing happens in separate stage + - name: ob_artifactBaseName + value: drop_windows_package_${{ parameters.runtime }} + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - group: DotNetPrivateBuildAccess + - group: certificate_logical_to_actual + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)\ONEBRANCH_ARTIFACT' + - name: ob_sdl_binskim_enabled + value: false # Disable for build-only, enable in signing stage + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: Runtime + value: ${{ parameters.runtime }} + - group: msixTools + + steps: + - checkout: self + clean: true + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + ob_restore_phase: false + + - template: /.pipelines/templates/shouldSign.yml@self + parameters: + ob_restore_phase: false + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + parameters: + nativePathRoot: '$(Agent.TempDirectory)' + ob_restore_phase: false + + - template: /.pipelines/templates/rebuild-branch-check.yml@self + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_${{ parameters.runtime }}_release + displayName: Download signed artifacts + condition: ${{ ne(parameters.runtime, 'minSize') }} + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_x64_${{ parameters.runtime }} + displayName: Download minsize signed artifacts + condition: ${{ eq(parameters.runtime, 'minSize') }} + + - pwsh: | + Write-Verbose -Verbose "signed artifacts" + Get-ChildItem "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_${{ parameters.runtime }}_release" -Recurse + displayName: 'Capture Downloaded Artifacts' + # Diagnostics is not critical it passes every time it runs + continueOnError: true + + - template: /.pipelines/templates/install-dotnet.yml@self + parameters: + ob_restore_phase: false + + - pwsh: | + $runtime = '$(Runtime)' + Write-Verbose -Verbose "runtime = '$(Runtime)'" + + $signedFolder = switch ($runtime) { + 'x64' { 'Signed-win7-x64' } + 'x86' { 'Signed-win7-x86' } + 'arm64' { 'Signed-win-arm64' } + 'fxdependent' { 'Signed-fxdependent' } + 'fxdependentWinDesktop' { 'Signed-fxdependent-win-desktop' } + 'minsize' { 'Signed-win7-x64' } + } + + Write-Verbose -Message "Init..." -Verbose + + $repoRoot = "$env:REPOROOT" + Import-Module "$repoRoot\build.psm1" + Import-Module "$repoRoot\tools\packaging" + + Start-PSBootstrap -Scenario Both + + Find-Dotnet + + $signedFilesPath, $psoptionsFilePath = if ($env:RUNTIME -eq 'minsize') { + "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_x64_${runtime}\$signedFolder" + "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_x64_${runtime}\psoptions\psoptions.json" + } + else { + "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_${runtime}_release\$signedFolder" + "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_${runtime}_release\psoptions\psoptions.json" + } + + Write-Verbose -Verbose "signedFilesPath: $signedFilesPath" + Write-Verbose -Verbose "psoptionsFilePath: $psoptionsFilePath" + + Write-Verbose -Message "checking pwsh exists in $signedFilesPath" -Verbose + if (-not (Test-Path $signedFilesPath\pwsh.exe)) { + throw "pwsh.exe not found in $signedFilesPath" + } + + Write-Verbose -Message "Restoring PSOptions from $psoptionsFilePath" -Verbose + + Restore-PSOptions -PSOptionsPath "$psoptionsFilePath" + Get-PSOptions | Write-Verbose -Verbose + + $metadata = Get-Content "$repoRoot/tools/metadata.json" -Raw | ConvertFrom-Json + + Write-Verbose -Verbose "metadata:" + $metadata | Out-String | Write-Verbose -Verbose + + # Use the rebuild branch check from the template + $isRebuildBranch = '$(RebuildBranchCheck.IsRebuildBranch)' -eq 'true' + + # Don't build LTS packages for rebuild branches + $LTS = $metadata.LTSRelease.Package -and -not $isRebuildBranch + $Stable = [bool]$metadata.StableRelease.Package + + if ($isRebuildBranch) { + Write-Verbose -Message "Rebuild branch detected, skipping LTS package build" -Verbose + } + + Write-Verbose -Verbose "LTS: $LTS" + Write-Verbose -Verbose "Stable: $Stable" + + if ($LTS) { + Write-Verbose -Message "LTS Release: $LTS" + } + + Start-PSBootstrap -Scenario Package + + $WindowsRuntime = switch ($runtime) { + 'x64' { 'win7-x64' } + 'x86' { 'win7-x86' } + 'arm64' { 'win-arm64' } + 'fxdependent' { 'win7-x64' } + 'fxdependentWinDesktop' { 'win7-x64' } + 'minsize' { 'win7-x64' } + } + + $packageTypes = switch ($runtime) { + 'x64' { @('zip', 'msix') } + 'x86' { @('zip', 'msix') } + 'arm64' { @('zip', 'msix') } + 'fxdependent' { 'fxdependent' } + 'fxdependentWinDesktop' { 'fxdependent-win-desktop' } + 'minsize' { 'min-size' } + } + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + Set-Location $repoRoot + + Start-PSPackage -Type $packageTypes -SkipReleaseChecks -WindowsRuntime $WindowsRuntime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath -LTS:$LTS + + # When both LTS and Stable are requested, also build the Stable MSIX + if ($packageTypes -contains 'msix' -and $LTS -and $Stable) { + Write-Verbose -Verbose "Both LTS and Stable packages requested. Building additional Stable MSIX." + Start-PSPackage -Type msix -SkipReleaseChecks -WindowsRuntime $WindowsRuntime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath + } + + displayName: 'Build Packages (Unsigned)' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + # Copy unsigned packages to output directory + - pwsh: | + $runtime = '$(Runtime)' + Write-Verbose -Verbose "runtime = '$(Runtime)'" + + $packageTypes = switch ($runtime) { + 'x64' { @('zip', 'msix') } + 'x86' { @('zip', 'msix') } + 'arm64' { @('zip', 'msix') } + 'fxdependent' { 'fxdependent' } + 'fxdependentWinDesktop' { 'fxdependent-win-desktop' } + 'minsize' { 'min-size' } + } + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + if ($packageTypes -contains 'zip' -or $packageTypes -contains 'fxdependent' -or $packageTypes -contains 'min-size' -or $packageTypes -contains 'fxdependent-win-desktop') { + $zipPkgNameFilter = "powershell-*.zip" + $zipPkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $zipPkgNameFilter -Recurse -File | Select-Object -ExpandProperty FullName + Write-Verbose -Verbose "unsigned zipPkgPath: $zipPkgPath" + Copy-Item -Path $zipPkgPath -Destination '$(ob_outputDirectory)' -Force -Verbose + } + + if ($packageTypes -contains 'msix') { + $msixPkgNameFilter = "PowerShell*.msix" + $msixPkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $msixPkgNameFilter -Recurse -File | Select-Object -ExpandProperty FullName + Write-Verbose -Verbose "unsigned msixPkgPath: $msixPkgPath" + Copy-Item -Path $msixPkgPath -Destination '$(ob_outputDirectory)' -Force -Verbose + } + displayName: Copy unsigned packages to output directory + + - pwsh: | + Get-ChildItem -Path $(ob_outputDirectory) -Recurse + displayName: 'List unsigned artifacts' diff --git a/PowerShell-master/.pipelines/templates/packaging/windows/sign.yml b/PowerShell-master/.pipelines/templates/packaging/windows/sign.yml new file mode 100644 index 0000000000000000000000000000000000000000..151b5d676fba6b632bc7713df386a663cde8b1b9 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/packaging/windows/sign.yml @@ -0,0 +1,117 @@ +parameters: + runtime: x64 + +jobs: +- job: sign_win_${{ parameters.runtime }} + displayName: Sign Windows Packages ${{ parameters.runtime }} + condition: succeeded() + pool: + type: windows + + variables: + - name: runCodesignValidationInjection + value: false + - name: ob_artifactBaseName + value: drop_windows_package_package_win_${{ parameters.runtime }} + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - group: DotNetPrivateBuildAccess + - group: certificate_logical_to_actual + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)\ONEBRANCH_ARTIFACT' + - name: ob_sdl_binskim_enabled + value: true + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: Runtime + value: ${{ parameters.runtime }} + - group: msixTools + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: /.pipelines/templates/shouldSign.yml@self + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + parameters: + nativePathRoot: '$(Agent.TempDirectory)' + + # Download unsigned packages from the build stage + - download: current + artifact: drop_windows_package_${{ parameters.runtime }} + displayName: Download unsigned packages + env: + ob_restore_phase: true + + - pwsh: | + Write-Verbose -Verbose "Downloaded unsigned artifacts:" + Get-ChildItem "$(Pipeline.Workspace)\drop_windows_package_${{ parameters.runtime }}" -Recurse + displayName: 'Capture Downloaded Unsigned Artifacts' + continueOnError: true + env: + ob_restore_phase: true + + - template: /.pipelines/templates/install-dotnet.yml@self + + # Import build.psm1 and bootstrap packaging dependencies + - pwsh: | + $repoRoot = "$env:REPOROOT" + Import-Module "$repoRoot\build.psm1" + Import-Module "$repoRoot\tools\packaging" + Write-Verbose -Verbose "Modules imported successfully" + displayName: 'Import modules' + env: + ob_restore_phase: true + + # Copy all signed packages to output directory + - pwsh: | + $runtime = '$(Runtime)' + Write-Verbose -Verbose "runtime = '$(Runtime)'" + + $packageTypes = switch ($runtime) { + 'x64' { @('zip', 'msix') } + 'x86' { @('zip', 'msix') } + 'arm64' { @('zip', 'msix') } + 'fxdependent' { 'fxdependent' } + 'fxdependentWinDesktop' { 'fxdependent-win-desktop' } + 'minsize' { 'min-size' } + } + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + if ($packageTypes -contains 'zip' -or $packageTypes -contains 'fxdependent' -or $packageTypes -contains 'min-size' -or $packageTypes -contains 'fxdependent-win-desktop') { + $zipPkgNameFilter = "powershell-*.zip" + $zipPkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $zipPkgNameFilter -Recurse -File | Select-Object -ExpandProperty FullName + Write-Verbose -Verbose "signed zipPkgPath: $zipPkgPath" + Copy-Item -Path $zipPkgPath -Destination '$(ob_outputDirectory)' -Force -Verbose + } + + if ($packageTypes -contains 'msix') { + $msixPkgNameFilter = "PowerShell*.msix" + $msixPkgPath = Get-ChildItem -Path $(Pipeline.Workspace) -Filter $msixPkgNameFilter -Recurse -File | Select-Object -ExpandProperty FullName + Write-Verbose -Verbose "signed msixPkgPath: $msixPkgPath" + Copy-Item -Path $msixPkgPath -Destination '$(ob_outputDirectory)' -Force -Verbose + } + displayName: Copy signed packages to output directory + + - pwsh: | + Get-ChildItem -Path $(ob_outputDirectory) -Recurse + displayName: 'List signed artifacts' + env: + ob_restore_phase: true diff --git a/PowerShell-master/.pipelines/templates/rebuild-branch-check.yml b/PowerShell-master/.pipelines/templates/rebuild-branch-check.yml new file mode 100644 index 0000000000000000000000000000000000000000..a4b546a0dc66a9bba574d31f7b09b04a7fb06030 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/rebuild-branch-check.yml @@ -0,0 +1,17 @@ +# This template checks if the current branch is a rebuild branch +# and sets an output variable IsRebuildBranch that can be used by other templates +steps: +- pwsh: | + # Check if this is a rebuild branch (e.g., rebuild/v7.4.13-rebuild.5) + $isRebuildBranch = '$(Build.SourceBranch)' -match 'refs/heads/rebuild/.*-rebuild\.' + + $value = if ($isRebuildBranch) { 'true' } else { 'false' } + Write-Verbose -Message "IsRebuildBranch: $value" -Verbose + + if ($isRebuildBranch) { + Write-Verbose -Message "Rebuild branch detected: $(Build.SourceBranch)" -Verbose + } + + Write-Host "##vso[task.setvariable variable=IsRebuildBranch;isOutput=true]$value" + name: RebuildBranchCheck + displayName: Check if Rebuild Branch diff --git a/PowerShell-master/.pipelines/templates/release-MSIX-Publish.yml b/PowerShell-master/.pipelines/templates/release-MSIX-Publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..cbbdb70cc4ffbfa494ce72316c32b1745818d2dd --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-MSIX-Publish.yml @@ -0,0 +1,138 @@ +parameters: + - name: skipMSIXPublish + type: boolean + +jobs: +- job: Store_Publish_MSIX + displayName: Publish MSIX to the Microsoft Store + pool: + type: release + os: windows + templateContext: + inputs: + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_store_package_CreateStorePackage + variables: + - group: 'Store Publish Variables' + - name: LTS + value: $[ stageDependencies.setReleaseTagAndChangelog.setTagAndChangelog.outputs['ChannelSelection.IsLTS'] ] + - name: STABLE + value: $[ stageDependencies.setReleaseTagAndChangelog.setTagAndChangelog.outputs['ChannelSelection.IsStable'] ] + - name: PREVIEW + value: $[ stageDependencies.setReleaseTagAndChangelog.setTagAndChangelog.outputs['ChannelSelection.IsPreview'] ] + - template: ./variables/release-shared.yml@self + parameters: + RELEASETAG: $[ stageDependencies.setReleaseTagAndChangelog.setTagAndChangelog.outputs['OutputReleaseTag.releaseTag'] ] + steps: + - task: PowerShell@2 + inputs: + targetType: inline + script: | + Write-Verbose -Verbose "Release Tag: $(ReleaseTag)" + Get-ChildItem $(Pipeline.Workspace) -Recurse | Select-Object -ExpandProperty FullName + displayName: 'Capture ReleaseTag and Downloaded Packages' + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + if ("$(ReleaseTag)" -eq '') { + Write-Error "ReleaseTag is not set. Cannot proceed with publishing to the Store." + exit 1 + } + $middleURL = '' + $tagString = "$(ReleaseTag)" + if ($tagString -match '-preview') { + $middleURL = "preview" + } + elseif ($tagString -match '(\d+\.\d+)') { + $middleURL = $matches[1] + } + + $endURL = $tagString -replace '^v','' -replace '\.','' + $message = "Changelog: https://github.com/PowerShell/PowerShell/blob/master/CHANGELOG/$middleURL.md#$endURL" + Write-Verbose -Verbose "Release Notes for the Store:" + Write-Verbose -Verbose "$message" + $jsonPath = "$(Pipeline.Workspace)\SBOutDir\PowerShellStorePackage.json" + $json = Get-Content $jsonPath -Raw | ConvertFrom-Json + + $json.listings.'en-us'.baseListing.releaseNotes = $message + + # Add PowerShell version to the top of the description + $description = $json.listings.'en-us'.baseListing.description + $version = "$(ReleaseTag)" + $updatedDescription = "Version: $version`n`n$description" + $json.listings.'en-us'.baseListing.description = $updatedDescription + Write-Verbose -Verbose "Updated description: $updatedDescription" + + $json | ConvertTo-Json -Depth 100 | Set-Content $jsonPath -Encoding UTF8 + displayName: 'Add Changelog Link and Version Number to SBJSON' + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + # Convert ADO variables to PowerShell boolean variables + $IsLTS = '$(LTS)' -eq 'true' + $IsStable = '$(STABLE)' -eq 'true' + $IsPreview = '$(PREVIEW)' -eq 'true' + + Write-Verbose -Verbose "Channel Selection - LTS: $(LTS), Stable: $(STABLE), Preview: $(PREVIEW)" + + $currentChannel = if ($IsLTS) { 'LTS' } + elseif ($IsStable) { 'Stable' } + elseif ($IsPreview) { 'Preview' } + else { + Write-Error "No valid channel detected" + exit 1 + } + + # Assign AppID for Store-Publish Task + $appID = $null + if ($IsLTS) { + $appID = '$(AppID-LTS)' + } + elseif ($IsStable) { + $appID = '$(AppID-Stable)' + } + else { + $appID = '$(AppID-Preview)' + } + + Write-Host "##vso[task.setvariable variable=AppID]$appID" + Write-Verbose -Verbose "Selected channel: $currentChannel" + Write-Verbose -Verbose "Conditional tasks will handle the publishing based on channel variables" + displayName: 'Validate Channel Selection' + + - task: MS-RDX-MRO.windows-store-publish.publish-task.store-publish@3 + displayName: 'Publish StoreBroker Package (Stable/LTS)' + condition: and(not(${{ parameters.skipMSIXPublish }}), or(eq(variables['STABLE'], 'true'), eq(variables['LTS'], 'true'))) + inputs: + serviceEndpoint: 'StoreAppPublish-Stable' + appId: '$(AppID)' + inputMethod: JsonAndZip + jsonPath: '$(Pipeline.Workspace)\SBOutDir\PowerShellStorePackage.json' + zipPath: '$(Pipeline.Workspace)\SBOutDir\PowerShellStorePackage.zip' + force: true + deletePackages: true + numberOfPackagesToKeep: 2 + jsonZipUpdateMetadata: true + targetPublishMode: 'Immediate' + skipPolling: true + + - task: MS-RDX-MRO.windows-store-publish.publish-task.store-publish@3 + displayName: 'Publish StoreBroker Package (Preview)' + condition: and(not(${{ parameters.skipMSIXPublish }}), eq(variables['PREVIEW'], 'true')) + inputs: + serviceEndpoint: 'StoreAppPublish-Preview' + appId: '$(AppID)' + inputMethod: JsonAndZip + jsonPath: '$(Pipeline.Workspace)\SBOutDir\PowerShellStorePackage.json' + zipPath: '$(Pipeline.Workspace)\SBOutDir\PowerShellStorePackage.zip' + force: true + deletePackages: true + numberOfPackagesToKeep: 2 + jsonZipUpdateMetadata: true + targetPublishMode: 'Immediate' + skipPolling: true diff --git a/PowerShell-master/.pipelines/templates/release-MakeBlobPublic.yml b/PowerShell-master/.pipelines/templates/release-MakeBlobPublic.yml new file mode 100644 index 0000000000000000000000000000000000000000..758298202a1fabe6cec61b6e1ec612bf36330260 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-MakeBlobPublic.yml @@ -0,0 +1,177 @@ +parameters: + - name: SkipPSInfraInstallers + displayName: Skip Copying Archives and Installers to PSInfrastructure Public Location + type: boolean + default: false + +jobs: +- template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Approve Copy release packages to PSInfra storage + jobName: CopyReleaseBlobApproval + instructions: | + Approval for Copy release packages to PSInfra storage + +- job: PSInfraReleaseBlobPublic + displayName: Copy release to PSInfra storage + dependsOn: CopyReleaseBlobApproval + condition: and(succeeded(), ne('${{ parameters.SkipPSInfraInstallers }}', true)) + pool: + name: PowerShell1ES + type: windows + isCustom: true + demands: + - ImageOverride -equals PSMMS2019-Secure + + + variables: + - group: 'PSInfraStorage' + - group: 'Azure Blob variable group' + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_codeql_compiled_enabled + value: false + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - pwsh: | + Get-ChildItem Env: + displayName: 'Capture Environment Variables' + + - task: AzurePowerShell@5 + displayName: Copy blobs to PSInfra storage + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + pwsh: true + inline: | + $sourceStorageAccountName = '$(StorageAccount)' + $destinationStorageAccountName = '$(PSInfraStorageAccount)' + $destinationContainerName = '$web' + $destinationPrefix = 'install/$(ReleaseTagVar)' + + $sourceContext = New-AzStorageContext -StorageAccountName $sourceStorageAccountName + Write-Verbose -Verbose "Source context: $($sourceContext.BlobEndPoint)" + + $destinationContext = New-AzStorageContext -StorageAccountName $destinationStorageAccountName + Write-Verbose -Verbose "Destination context: $($destinationContext.BlobEndPoint)" + + foreach ($sourceContainerName in '$(AzureVersion)', '$(AzureVersion)-gc') { + $blobs = Get-AzStorageBlob -Context $sourceContext -Container $sourceContainerName + + Write-Verbose -Verbose "Blobs found in $sourceContainerName" + $blobs.Name | Write-Verbose -Verbose + + Write-Verbose -Verbose "Copying blobs from $sourceContainerName to $destinationContainerName/$destinationPrefix" + + foreach ($blob in $blobs) { + $sourceBlobName = $blob.Name + Write-Verbose -Verbose "sourceBlobName = $sourceBlobName" + + $destinationBlobName = "$destinationPrefix/$sourceBlobName" + Write-Verbose -Verbose "destinationBlobName = $destinationBlobName" + $existingBlob = Get-AzStorageBlob -Blob $destinationBlobName -Container $destinationContainerName -Context $destinationContext -ErrorAction Ignore + if ($existingBlob) { + Write-Verbose -Verbose "Blob $destinationBlobName already exists in '$destinationStorageAccountName/$destinationContainerName', removing before copy." + $existingBlob | Remove-AzStorageBlob -ErrorAction Stop -Verbose + } + + Copy-AzStorageBlob -SourceContext $sourceContext -DestinationContext $destinationContext -SrcContainer $sourceContainerName -SrcBlob $sourceBlobName -DestContainer $destinationContainerName -DestBlob $destinationBlobName -Force -Verbose -Confirm:$false + } + } + + +- template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Approve Copy Global tool packages to PSInfra storage + jobName: CopyBlobApproval + instructions: | + Approval for Copy global tool packages to PSInfra storage + +- job: PSInfraBlobPublic + displayName: Copy global tools to PSInfra storage + dependsOn: CopyBlobApproval + pool: + name: PowerShell1ES + type: windows + isCustom: true + demands: + - ImageOverride -equals PSMMS2019-Secure + + variables: + - group: 'PSInfraStorage' + - group: 'Azure Blob variable group' + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - pwsh: | + Get-ChildItem Env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: 'Capture Environment Variables' + + - task: AzurePowerShell@5 + displayName: Copy blobs to PSInfra storage + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + pwsh: true + inline: | + $sourceStorageAccountName = '$(StorageAccount)' + $sourceContainerName = '$(AzureVersion)-nuget' + $prefix = 'globaltool' + + $destinationStorageAccountName = '$(PSInfraStorageAccount)' + $destinationContainerName = '$web' + $destinationPrefix = 'tool/$(Version)' + + $sourceContext = New-AzStorageContext -StorageAccountName $sourceStorageAccountName + Write-Verbose -Verbose "Source context: $($sourceContext.BlobEndPoint)" + + $destinationContext = New-AzStorageContext -StorageAccountName $destinationStorageAccountName + Write-Verbose -Verbose "Destination context: $($destinationContext.BlobEndPoint)" + + $blobs = Get-AzStorageBlob -Context $sourceContext -Container $sourceContainerName -Prefix $prefix + + Write-Verbose -Verbose "Blobs found in $sourceContainerName" + $blobs.Name | Write-Verbose -Verbose + + Write-Verbose -Verbose "Copying blobs from $sourceContainerName to $destinationContainerName/$destinationPrefix" + + foreach ($blob in $blobs) { + $sourceBlobName = $blob.Name + Write-Verbose -Verbose "sourceBlobName = $sourceBlobName" + + $destinationBlobName = $sourceBlobName -replace "$prefix", $destinationPrefix + Write-Verbose -Verbose "destinationBlobName = $destinationBlobName" + + Copy-AzStorageBlob -SourceContext $sourceContext -DestinationContext $destinationContext -SrcContainer $sourceContainerName -SrcBlob $sourceBlobName -DestContainer $destinationContainerName -DestBlob $destinationBlobName -Force -Verbose -Confirm:$false + } diff --git a/PowerShell-master/.pipelines/templates/release-SetReleaseTagandContainerName.yml b/PowerShell-master/.pipelines/templates/release-SetReleaseTagandContainerName.yml new file mode 100644 index 0000000000000000000000000000000000000000..d40551353d2f69e002bdca834f8417a34a21a8f1 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-SetReleaseTagandContainerName.yml @@ -0,0 +1,36 @@ +parameters: +- name: restorePhase + default: false + +steps: +- pwsh: | + $variable = 'releaseTag' + $branch = $ENV:BUILD_SOURCEBRANCH + if($branch -notmatch '^.*((release/|rebuild/.*rebuild))') + { + throw "Branch name is not in release format: '$branch'" + } + + $releaseTag = $Branch -replace '^.*((release|rebuild)/)' + $vstsCommandString = "vso[task.setvariable variable=$Variable;isOutput=true]$releaseTag" + Write-Verbose -Message "setting $Variable to $releaseTag" -Verbose + Write-Host -Object "##$vstsCommandString" + name: OutputReleaseTag + displayName: Set Release Tag + env: + ob_restore_phase: ${{ parameters.restorePhase }} + +- pwsh: | + $azureVersion = '$(OutputReleaseTag.ReleaseTag)'.ToLowerInvariant() -replace '\.', '-' + $vstsCommandString = "vso[task.setvariable variable=AzureVersion;isOutput=true]$azureVersion" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + + $version = '$(OutputReleaseTag.ReleaseTag)'.ToLowerInvariant().Substring(1) + $vstsCommandString = "vso[task.setvariable variable=Version;isOutput=true]$version" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + name: OutputVersion + displayName: Set container name + env: + ob_restore_phase: ${{ parameters.restorePhase }} diff --git a/PowerShell-master/.pipelines/templates/release-SetTagAndChangelog.yml b/PowerShell-master/.pipelines/templates/release-SetTagAndChangelog.yml new file mode 100644 index 0000000000000000000000000000000000000000..b33e652b3c72d03cb4c83f5c3445e7cf36fb94d8 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-SetTagAndChangelog.yml @@ -0,0 +1,51 @@ +jobs: +- job: setTagAndChangelog + displayName: Set Tag and Upload Changelog + condition: succeeded() + pool: + type: windows + variables: + - group: 'mscodehub-code-read-akv' + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + steps: + - template: release-SetReleaseTagandContainerName.yml@self + + - checkout: self + clean: true + env: + ob_restore_phase: true + + - pwsh: | + Write-Verbose -Verbose "Release Tag: $(OutputReleaseTag.releaseTag)" + $releaseVersion = '$(OutputReleaseTag.releaseTag)' -replace '^v','' + Write-Verbose -Verbose "Release Version: $releaseVersion" + $semanticVersion = [System.Management.Automation.SemanticVersion]$releaseVersion + + $isPreview = $semanticVersion.PreReleaseLabel -ne $null + + $fileName = if ($isPreview) { + "preview.md" + } + else { + $semanticVersion.Major.ToString() + "." + $semanticVersion.Minor.ToString() + ".md" + } + + $filePath = "$(Build.SourcesDirectory)/PowerShell/CHANGELOG/$fileName" + Write-Verbose -Verbose "Selected Log file: $filePath" + + if (-not (Test-Path -Path $filePath)) { + Write-Error "Changelog file not found: $filePath" + exit 1 + } + + Write-Verbose -Verbose "Creating output directory for CHANGELOG: $(ob_outputDirectory)/CHANGELOG" + New-Item -Path $(ob_outputDirectory)/CHANGELOG -ItemType Directory -Force + Copy-Item -Path $filePath -Destination $(ob_outputDirectory)/CHANGELOG + displayName: Upload Changelog + + - template: channelSelection.yml@self diff --git a/PowerShell-master/.pipelines/templates/release-githubNuget.yml b/PowerShell-master/.pipelines/templates/release-githubNuget.yml new file mode 100644 index 0000000000000000000000000000000000000000..e7c36a49fe66bc84b925b65efc22351db8a029a9 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-githubNuget.yml @@ -0,0 +1,218 @@ +parameters: + - name: skipPublish + type: boolean + +jobs: +- job: GithubReleaseDraft + displayName: Create GitHub Release Draft + condition: succeeded() + pool: + type: release + os: windows + templateContext: + inputs: + - input: pipelineArtifact + artifactName: drop_setReleaseTagAndChangelog_SetTagAndChangelog + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_upload_upload_packages + variables: + - template: ./variables/release-shared.yml@self + parameters: + RELEASETAG: $[ stageDependencies.setReleaseTagAndChangelog.setTagAndChangelog.outputs['OutputReleaseTag.releaseTag'] ] + + steps: + - task: PowerShell@2 + inputs: + targetType: inline + script: | + Write-Verbose -Verbose "Release Tag: $(ReleaseTag)" + Get-ChildItem Env: | Out-String -Stream | Write-Verbose -Verbose + displayName: 'Capture Environment Variables' + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + $Path = "$(Pipeline.Workspace)/GitHubPackages" + + # The .exe packages are for Windows Update only and should not be uploaded to GitHub release. + $exefiles = Get-ChildItem -Path $Path -Filter *.exe + if ($exefiles) { + Write-Verbose -Verbose "Remove .exe packages:" + $exefiles | Remove-Item -Force -Verbose + } + + # The .msi packages should not be uploaded to GitHub release. + $msifiles = Get-ChildItem -Path $Path -Filter *.msi + if ($msifiles) { + Write-Verbose -Verbose "Remove .msi packages:" + $msifiles | Remove-Item -Force -Verbose + } + + $OutputPath = Join-Path $Path 'hashes.sha256' + $packages = Get-ChildItem -Path $Path -Include * -Recurse -File + $checksums = $packages | + ForEach-Object { + Write-Verbose -Verbose "Generating checksum file for $($_.FullName)" + $packageName = $_.Name + $hash = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash.ToLower() + # the '*' before the packagename signifies it is a binary + "$hash *$packageName" + } + $checksums | Out-File -FilePath $OutputPath -Force + $fileContent = Get-Content -Path $OutputPath -Raw | Out-String + Write-Verbose -Verbose -Message $fileContent + displayName: Add sha256 hashes + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + Get-ChildItem $(Pipeline.Workspace) -recurse | Select-Object -ExpandProperty FullName + displayName: List all files in the workspace + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + $releaseVersion = '$(ReleaseTag)' -replace '^v','' + Write-Verbose -Verbose "Available modules: " + Get-Module | Write-Verbose -Verbose + + $filePath = Get-ChildItem -Path "$(Pipeline.Workspace)/CHANGELOG" -Filter '*.md' | Select-Object -First 1 -ExpandProperty FullName + + if (-not (Test-Path $filePath)) { + throw "$filePath not found" + } + + $changelog = Get-Content -Path $filePath + + $headingPattern = "^## \[\d+\.\d+\.\d+" + $headingStartLines = $changelog | Select-String -Pattern $headingPattern | Select-Object -ExpandProperty LineNumber + $startLine = $headingStartLines[0] + $endLine = $headingStartLines[1] - 1 + + $clContent = $changelog | Select-Object -Skip ($startLine-1) -First ($endLine - $startLine) | Out-String + + $StringBuilder = [System.Text.StringBuilder]::new($clContent, $clContent.Length + 2kb) + $StringBuilder.AppendLine().AppendLine() > $null + $StringBuilder.AppendLine("### SHA256 Hashes of the release artifacts").AppendLine() > $null + Get-ChildItem -Path "$(Pipeline.Workspace)/GitHubPackages/" -File | ForEach-Object { + $PackageName = $_.Name + $SHA256 = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash + $StringBuilder.AppendLine("- $PackageName").AppendLine(" - $SHA256") > $null + } + + $clContent = $StringBuilder.ToString() + + Write-Verbose -Verbose "Selected content: `n$clContent" + + $releaseNotesFilePath = "$(Pipeline.Workspace)/release-notes.md" + $clContent | Out-File -FilePath $releaseNotesFilePath -Encoding utf8 + + Write-Host "##vso[task.setvariable variable=ReleaseNotesFilePath;]$releaseNotesFilePath" + + #if name has prelease then make prerelease true as a variable + if ($releaseVersion -like '*-*') { + Write-Host "##vso[task.setvariable variable=IsPreRelease;]true" + } else { + Write-Host "##vso[task.setvariable variable=IsPreRelease;]false" + } + displayName: Set variables for GitHub release task + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + Write-Host "ReleaseNotes content:" + Get-Content "$(Pipeline.Workspace)/release-notes.md" -Raw | Out-String -width 9999 | Write-Host + displayName: Verify Release Notes + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + $middleURL = '' + $tagString = "$(ReleaseTag)" + Write-Verbose -Verbose "Use the following command to push the tag:" + if ($tagString -match '-preview') { + $middleURL = "preview" + } + elseif ($tagString -match '(\d+\.\d+)') { + $middleURL = $matches[1] + } + $endURL = $tagString -replace '^v|\.', '' + $message = "https://github.com/PowerShell/PowerShell/blob/master/CHANGELOG/$middleURL.md#$endURL" + Write-Verbose -Verbose "git tag -a $(ReleaseTag) $env:BUILD_SOURCEVERSION -m $message" + displayName: Git Push Tag Command + + - task: GitHubRelease@1 + inputs: + gitHubConnection: GitHubReleasePAT + repositoryName: PowerShell/PowerShell + target: master + assets: '$(Pipeline.Workspace)/GitHubPackages/*' + tagSource: 'userSpecifiedTag' + tag: '$(ReleaseTag)' + title: "$(ReleaseTag) Release of PowerShell" + isDraft: true + addChangeLog: false + action: 'create' + releaseNotesFilePath: '$(ReleaseNotesFilePath)' + isPrerelease: '$(IsPreRelease)' + +- job: NuGetPublish + displayName: Publish to NuGet + condition: succeeded() + pool: + type: release + os: windows + templateContext: + inputs: + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_upload_upload_packages + variables: + - template: ./variables/release-shared.yml@self + parameters: + VERSION: $[ stageDependencies.setReleaseTagAndChangelog.SetTagAndChangelog.outputs['OutputVersion.Version'] ] + + steps: + - task: PowerShell@2 + inputs: + targetType: inline + script: | + Write-Verbose -Verbose "Version: $(Version)" + Get-ChildItem Env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: 'Capture Environment Variables' + + - task: PowerShell@2 + inputs: + targetType: inline + script: | + #Exclude all global tool packages. Their names start with 'PowerShell.' + $null = New-Item -ItemType Directory -Path "$(Pipeline.Workspace)/release" + Copy-Item "$(Pipeline.Workspace)/NuGetPackages/*.nupkg" -Destination "$(Pipeline.Workspace)/release" -Exclude "PowerShell.*.nupkg" -Force -Verbose + + $releaseVersion = '$(Version)' + $globalToolPath = "$(Pipeline.Workspace)/NuGetPackages/PowerShell.$releaseVersion.nupkg" + + if ($releaseVersion -notlike '*-*') { + # Copy the global tool package for stable releases + Copy-Item $globalToolPath -Destination "$(Pipeline.Workspace)/release" + } + + Write-Verbose -Verbose "The .nupkgs below will be pushed:" + Get-ChildItem "$(Pipeline.Workspace)/release" -recurse + displayName: Download and capture nupkgs + condition: and(ne('${{ parameters.skipPublish }}', 'true'), succeeded()) + + - task: NuGetCommand@2 + displayName: 'NuGet push' + condition: and(ne('${{ parameters.skipPublish }}', 'true'), succeeded()) + inputs: + command: push + packagesToPush: '$(Pipeline.Workspace)/release/*.nupkg' + nuGetFeedType: external + publishFeedCredentials: PowerShellNuGetOrgPush diff --git a/PowerShell-master/.pipelines/templates/release-prep-for-ev2.yml b/PowerShell-master/.pipelines/templates/release-prep-for-ev2.yml new file mode 100644 index 0000000000000000000000000000000000000000..e644bece68f3a1a1777a8a491b52d4501ed29e3d --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-prep-for-ev2.yml @@ -0,0 +1,237 @@ +parameters: +- name: skipPublish + type: boolean + default: false + +stages: +- stage: PrepForEV2 + displayName: 'Copy and prep all files needed for EV2 stage' + jobs: + - job: CopyEV2FilesToArtifact + displayName: 'Copy EV2 Files to Artifact' + pool: + type: linux + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: repoRoot + value: '$(Build.SourcesDirectory)/PowerShell' + - name: ev2ServiceGroupRootFolder + value: '$(Build.SourcesDirectory)/PowerShell/.pipelines/EV2Specs/ServiceGroupRoot' + - name: ev2ParametersFolder + value: '$(Build.SourcesDirectory)/PowerShell/.pipelines/EV2Specs/ServiceGroupRoot/Parameters' + - group: 'mscodehub-code-read-akv' + - group: 'packages.microsoft.com' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + steps: + - checkout: self ## the global setting on lfs didn't work + lfs: false + env: + ob_restore_phase: true + + - template: release-SetReleaseTagandContainerName.yml + parameters: + restorePhase: true + + - pwsh: | + $packageVersion = '$(OutputReleaseTag.ReleaseTag)'.ToLowerInvariant() -replace '^v','' + $vstsCommandString = "vso[task.setvariable variable=packageVersion]$packageVersion" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: Set Package version + env: + ob_restore_phase: true + + - pwsh: | + $branch = 'mirror-target' + $gitArgs = "clone", + "--verbose", + "--branch", + "$branch", + "https://$(mscodehubCodeReadPat)@mscodehub.visualstudio.com/PowerShellCore/_git/Internal-PowerShellTeam-Tools", + '$(Pipeline.Workspace)/tools' + $gitArgs | Write-Verbose -Verbose + git $gitArgs + displayName: Clone Internal-PowerShellTeam-Tools from MSCodeHub + env: + ob_restore_phase: true + + - pwsh: | + Get-ChildItem Env: | Out-String -Stream | write-Verbose -Verbose + displayName: 'Capture Environment Variables' + env: + ob_restore_phase: true + + - pwsh: | + Get-ChildItem '$(Build.SourcesDirectory)' + displayName: 'Capture BuildDirectory' + env: + ob_restore_phase: true + + - pwsh: | + Get-ChildItem '$(Pipeline.Workspace)' -Recurse | Out-String -Stream | write-Verbose -Verbose + displayName: 'Capture Workspace' + env: + ob_restore_phase: true + + - pwsh: | + New-Item -Path '$(ev2ParametersFolder)' -ItemType Directory + displayName: 'Create Parameters folder under EV2Specs folder' + env: + ob_restore_phase: true + + - task: PipAuthenticate@1 + inputs: + artifactFeeds: 'PowerShellCore/PowerShellCore_PublicPackages' + displayName: 'Pip Authenticate' + env: + ob_restore_phase: true + + - pwsh: | + python3 -m pip install --upgrade pip + pip --version --verbose + + Write-Verbose -Verbose "Download pmc-cli to folder without installing it" + $pythonDlFolderPath = Join-Path '$(ev2ServiceGroupRootFolder)/Shell/Run' -ChildPath "python_dl" + pip download -d $pythonDlFolderPath pmc-cli --platform=manylinux_2_17_x86_64 --only-binary=:all: --verbose + displayName: 'Download pmc-cli package' + env: + ob_restore_phase: true + + - download: PSPackagesOfficial + artifact: 'drop_linux_package_deb' + displayName: 'Download artifact containing .deb_amd64.deb file from PSPackagesOfficial triggering pipeline' + env: + ob_restore_phase: true + + - download: PSPackagesOfficial + artifact: 'drop_linux_package_rpm' + displayName: 'Download artifact containing .rh.x64_86.rpm file from PSPackagesOfficial triggering pipeline' + env: + ob_restore_phase: true + + - download: PSPackagesOfficial + artifact: 'drop_linux_package_mariner_x64' + displayName: 'Download artifact containing .cm.x86_64.rpm file from PSPackagesOfficial triggering pipeline' + env: + ob_restore_phase: true + + - download: PSPackagesOfficial + artifact: 'drop_linux_package_mariner_arm64' + displayName: 'Download artifact containing .cm.aarch64.rpm file from PSPackagesOfficial triggering pipeline' + env: + ob_restore_phase: true + + - pwsh: | + Write-Verbose -Verbose "Copy ESRP signed .deb and .rpm packages" + $downloadedPipelineFolder = Join-Path '$(Pipeline.Workspace)' -ChildPath 'PSPackagesOfficial' + $srcFilesFolder = Join-Path -Path '$(Pipeline.Workspace)' -ChildPath 'SourceFiles' + New-Item -Path $srcFilesFolder -ItemType Directory + $packagesFolder = Join-Path -Path $srcFilesFolder -ChildPath 'packages' + New-Item -Path $packagesFolder -ItemType Directory + + $packageFiles = Get-ChildItem -Path $downloadedPipelineFolder -Recurse -Directory -Filter "drop_*" | Get-ChildItem -File -Include *.deb, *.rpm + foreach ($file in $packageFiles) + { + Write-Verbose -Verbose "copying file: $($file.FullName)" + Copy-Item -Path $($file.FullName) -Destination $packagesFolder -Verbose + } + + $packagesTarGzDestination = Join-Path -Path '$(ev2ParametersFolder)' -ChildPath 'packages.tar.gz' + tar -czvf $packagesTarGzDestination -C $packagesFolder . + displayName: 'Copy signed .deb and .rpm packages to .tar.gz to pass as a file var to shell extension' + env: + ob_restore_phase: true + + - pwsh: | + $pathToPMCMetadataFile = Join-Path -Path '$(ev2ParametersFolder)' -ChildPath 'pmcMetadata.json' + + $metadata = Get-Content -Path "$(repoRoot)/tools/metadata.json" -Raw | ConvertFrom-Json + $metadataHash = @{} + $skipPublishValue = '${{ parameters.skipPublish }}' + $metadataHash["ReleaseTag"] = '$(OutputReleaseTag.ReleaseTag)' + $metadataHash["LTS"] = $metadata.LTSRelease.PublishToChannels + $metadataHash["ForProduction"] = $true + $metadataHash["SkipPublish"] = [System.Convert]::ToBoolean($skipPublishValue) + + $metadataHash | ConvertTo-Json | Out-File $pathToPMCMetadataFile + + $mappingFilePath = Join-Path -Path '$(repoRoot)/tools/packages.microsoft.com' -ChildPath 'mapping.json' + $mappingFilePathExists = Test-Path $mappingFilePath + $mappingFileEV2Path = Join-Path -Path '$(ev2ParametersFolder)' -ChildPath "mapping.json" + Write-Verbose -Verbose "Copy mapping.json file at: $mappingFilePath which exists: $mappingFilePathExists to: $mappingFileEV2Path" + Copy-Item -Path $mappingFilePath -Destination $mappingFileEV2Path + displayName: 'Create pmcScriptMetadata.json and mapping.json file' + env: + ob_restore_phase: true + + - pwsh: | + $pathToJsonFile = Join-Path -Path '$(ev2ServiceGroupRootFolder)' -ChildPath 'RolloutSpec.json' + $content = Get-Content -Path $pathToJsonFile | ConvertFrom-Json + $content.RolloutMetadata.Notification.Email.To = '$(PmcEV2SupportEmail)' + Remove-Item -Path $pathToJsonFile + $content | ConvertTo-Json -Depth 4 | Out-File $pathToJsonFile + displayName: 'Replace values in RolloutSpecPath.json' + env: + ob_restore_phase: true + + - pwsh: | + $pathToJsonFile = Join-Path -Path '$(ev2ServiceGroupRootFolder)' -ChildPath 'UploadLinux.Rollout.json' + $content = Get-Content -Path $pathToJsonFile | ConvertFrom-Json + + $identityString = "/subscriptions/$(PmcSubscription)/resourcegroups/$(PmcResourceGroup)/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$(PmcMIName)" + $content.shellExtensions.launch.identity.userAssignedIdentities[0] = $identityString + + Remove-Item -Path $pathToJsonFile + $content | ConvertTo-Json -Depth 6 | Out-File $pathToJsonFile + displayName: 'Replace values in UploadLinux.Rollout.json file' + env: + ob_restore_phase: true + + - pwsh: | + $pathToJsonFile = Join-Path -Path '$(ev2ServiceGroupRootFolder)' -ChildPath 'ServiceModel.json' + $content = Get-Content -Path $pathToJsonFile | ConvertFrom-Json + $content.ServiceResourceGroups[0].AzureResourceGroupName = '$(PmcResourceGroup)' + $content.ServiceResourceGroups[0].AzureSubscriptionId = '$(PmcSubscription)' + + Remove-Item -Path $pathToJsonFile + $content | ConvertTo-Json -Depth 9 | Out-File $pathToJsonFile + displayName: 'Replace values in ServiceModel.json' + env: + ob_restore_phase: true + + - pwsh: | + $settingFilePath = Join-Path '$(ev2ServiceGroupRootFolder)/Shell/Run' -ChildPath 'settings.toml' + New-Item -Path $settingFilePath -ItemType File + $pmcMIClientID = '$(PmcMIClientID)' + $pmcEndpoint = '$(PmcEndpointUrl)' + + Add-Content -Path $settingFilePath -Value "[default]" + Add-Content -Path $settingFilePath -Value "base_url = `"$pmcEndpoint`"" + Add-Content -Path $settingFilePath -Value "auth_type = `"msi`"" + Add-Content -Path $settingFilePath -Value "client_id = `"$pmcMIClientID`"" + displayName: 'Create settings.toml file with MI clientId populated' + env: + ob_restore_phase: true + + - task: onebranch.pipeline.signing@1 + inputs: + command: 'sign' + signing_profile: external_distribution + files_to_sign: '*.ps1' + search_root: '$(repoRoot)/.pipelines/EV2Specs/ServiceGroupRoot/Shell/Run' + displayName: Sign Run.ps1 + + - pwsh: | + # folder to tar must have: Run.ps1, settings.toml, python_dl + $srcPath = Join-Path '$(ev2ServiceGroupRootFolder)' -ChildPath 'Shell' + $pathToRunTarFile = Join-Path $srcPath -ChildPath "Run.tar" + tar -cvf $pathToRunTarFile -C $srcPath ./Run + displayName: 'Create archive for the shell extension' + + - task: CopyFiles@2 + inputs: + SourceFolder: '$(repoRoot)/.pipelines' + Contents: 'EV2Specs/**' + TargetFolder: $(ob_outputDirectory) diff --git a/PowerShell-master/.pipelines/templates/release-publish-pmc.yml b/PowerShell-master/.pipelines/templates/release-publish-pmc.yml new file mode 100644 index 0000000000000000000000000000000000000000..d5454845211f6623dec65045204175cad7d15dce --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-publish-pmc.yml @@ -0,0 +1,37 @@ +stages: +- stage: 'Prod_Release' + displayName: 'Deploy packages to PMC with EV2' + dependsOn: + - PrepForEV2 + variables: + - name: ob_release_environment + value: "Production" + - name: repoRoot + value: $(Build.SourcesDirectory) + jobs: + - job: Prod_ReleaseJob + displayName: Publish to PMC + pool: + type: release + + steps: + - task: DownloadPipelineArtifact@2 + inputs: + targetPath: '$(Pipeline.Workspace)' + artifact: drop_PrepForEV2_CopyEv2FilesToArtifact + displayName: 'Download drop_PrepForEV2_CopyEv2FilesToArtifact artifact that has all files needed' + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + targetPath: '$(Pipeline.Workspace)' + displayName: 'Download to get EV2 Files' + + - task: vsrm-ev2.vss-services-ev2.adm-release-task.ExpressV2Internal@1 + displayName: 'Ev2: Push to PMC' + inputs: + UseServerMonitorTask: true + EndpointProviderType: ApprovalService + ApprovalServiceEnvironment: Production + ServiceRootPath: '$(Pipeline.Workspace)/drop_PrepForEV2_CopyEV2FilesToArtifact/EV2Specs/ServiceGroupRoot' + RolloutSpecPath: '$(Pipeline.Workspace)/drop_PrepForEV2_CopyEV2FilesToArtifact/EV2Specs/ServiceGroupRoot/RolloutSpec.json' diff --git a/PowerShell-master/.pipelines/templates/release-symbols.yml b/PowerShell-master/.pipelines/templates/release-symbols.yml new file mode 100644 index 0000000000000000000000000000000000000000..a628f4d7127c828e0900106a65ece1c9265e70b9 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-symbols.yml @@ -0,0 +1,89 @@ +parameters: + - name: skipPublish + default: false + type: boolean + +jobs: +- job: PublishSymbols + displayName: Publish Symbols + condition: succeeded() + pool: + type: windows + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: DOTNET_NOLOGO + value: 1 + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: false + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: release-SetReleaseTagandContainerName.yml + + - pwsh: | + Get-ChildItem Env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: 'Capture Environment Variables' + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_x64_release + patterns: 'symbols.zip' + displayName: Download winx64 + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_x86_release + patterns: 'symbols.zip' + displayName: Download winx86 + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_arm64_release + patterns: 'symbols.zip' + displayName: Download winx64 + + - pwsh: | + Write-Verbose -Verbose "Enumerating $(Pipeline.Workspace)\CoOrdinatedBuildPipeline" + $downloadedArtifacts = Get-ChildItem -Path "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline" -Recurse -Filter 'symbols.zip' + $downloadedArtifacts + $expandedRoot = New-Item -Path "$(Pipeline.Workspace)/expanded" -ItemType Directory -Verbose + $symbolsRoot = New-Item -Path "$(Pipeline.Workspace)/symbols" -ItemType Directory -Verbose + + $downloadedArtifacts | ForEach-Object { + $folderName = (Get-Item (Split-Path $_.FullName)).Name + Write-Verbose -Verbose "Expanding $($_.FullName) to $expandedRoot/$folderName/$($_.BaseName)" + $destFolder = New-Item -Path "$expandedRoot/$folderName/$($_.BaseName)/" -ItemType Directory -Verbose + Expand-Archive -Path $_.FullName -DestinationPath $destFolder -Force + + $symbolsToPublish = New-Item -Path "$symbolsRoot/$folderName/$($_.BaseName)" -ItemType Directory -Verbose + + Get-ChildItem -Path $destFolder -Recurse -Filter '*.pdb' | ForEach-Object { + Copy-Item -Path $_.FullName -Destination $symbolsToPublish -Verbose + } + } + + Write-Verbose -Verbose "Enumerating $symbolsRoot" + Get-ChildItem -Path $symbolsRoot -Recurse + $vstsCommandString = "vso[task.setvariable variable=SymbolsPath]$symbolsRoot" + Write-Verbose -Message "$vstsCommandString" -Verbose + Write-Host -Object "##$vstsCommandString" + displayName: Expand and capture symbols folders + + - task: PublishSymbols@2 + inputs: + symbolsFolder: '$(SymbolsPath)' + searchPattern: '**/*.pdb' + indexSources: false + publishSymbols: true + symbolServerType: teamServices + detailedLog: true diff --git a/PowerShell-master/.pipelines/templates/release-upload-buildinfo.yml b/PowerShell-master/.pipelines/templates/release-upload-buildinfo.yml new file mode 100644 index 0000000000000000000000000000000000000000..9e3d6a6accbbe5b349184924d6f6085047e2d469 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-upload-buildinfo.yml @@ -0,0 +1,164 @@ +parameters: + - name: skipPublish + default: false + type: boolean + +jobs: +- job: BuildInfoPublish + displayName: Publish BuildInfo + condition: succeeded() + pool: + name: PowerShell1ES + type: windows + isCustom: true + demands: + - ImageOverride -equals PSMMS2019-Secure + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: DOTNET_NOLOGO + value: 1 + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - group: 'Azure Blob variable group' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: false + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: release-SetReleaseTagandContainerName.yml + + - pwsh: | + Get-ChildItem Env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: 'Capture Environment Variables' + + - download: PSPackagesOfficial + artifact: BuildInfoJson + displayName: Download build info artifact + + - pwsh: | + $toolsDirectory = '$(Build.SourcesDirectory)/tools' + Import-Module "$toolsDirectory/ci.psm1" + $jsonFile = Get-Item "$ENV:PIPELINE_WORKSPACE/PSPackagesOfficial/BuildInfoJson/*.json" + $fileName = Split-Path $jsonFile -Leaf + # The build itself has already determined if it is preview or stable/LTS, + # we just need to check via the file name + $isPreview = $fileName -eq "preview.json" + $isStable = $fileName -eq "stable.json" + + $dateTime = [datetime]::UtcNow + $dateTime = [datetime]::new($dateTime.Ticks - ($dateTime.Ticks % [timespan]::TicksPerSecond), $dateTime.Kind) + + $metadata = Get-Content -LiteralPath "$toolsDirectory/metadata.json" -ErrorAction Stop | ConvertFrom-Json + # Note: version tags in metadata.json (e.g. StableReleaseTag) may not reflect the current release being + # published, so they must not be used to gate channel decisions. Use the explicit publish flags instead. + $stableRelease = $metadata.StableRelease.PublishToChannels + $ltsRelease = $metadata.LTSRelease.PublishToChannels + + Write-Verbose -Verbose "Writing $jsonFile contents:" + $buildInfoJsonContent = Get-Content $jsonFile -Encoding UTF8NoBom -Raw + Write-Verbose -Verbose $buildInfoJsonContent + + $buildInfo = $buildInfoJsonContent | ConvertFrom-Json + $buildInfo.ReleaseDate = $dateTime + $currentReleaseTag = $buildInfo.ReleaseTag -Replace 'v','' + + $targetFile = "$ENV:PIPELINE_WORKSPACE/$fileName" + ConvertTo-Json -InputObject $buildInfo | Out-File $targetFile -Encoding ascii + + if ($isPreview) { + Set-BuildVariable -Name UploadPreview -Value YES + } else { + Set-BuildVariable -Name UploadPreview -Value NO + } + + Set-BuildVariable -Name PreviewBuildInfoFile -Value $targetFile + + ## Create 'lts.json' if marked as a LTS release. + if ($isStable) { + if ($ltsRelease) { + $ltsFile = "$ENV:PIPELINE_WORKSPACE/lts.json" + Copy-Item -Path $targetFile -Destination $ltsFile -Force + Set-BuildVariable -Name LTSBuildInfoFile -Value $ltsFile + Set-BuildVariable -Name UploadLTS -Value YES + } else { + Set-BuildVariable -Name UploadLTS -Value NO + } + + ## Gate stable.json upload on the metadata publish flag. + if ($stableRelease) { + Set-BuildVariable -Name StableBuildInfoFile -Value $targetFile + Set-BuildVariable -Name UploadStable -Value YES + } else { + Set-BuildVariable -Name UploadStable -Value NO + } + + ## Always publish the version-specific {Major}-{Minor}.json for non-preview builds. + [System.Management.Automation.SemanticVersion] $currentVersion = $currentReleaseTag + $versionFile = "$ENV:PIPELINE_WORKSPACE/$($currentVersion.Major)-$($currentVersion.Minor).json" + Copy-Item -Path $targetFile -Destination $versionFile -Force + Set-BuildVariable -Name VersionSpecificBuildInfoFile -Value $versionFile + Set-BuildVariable -Name UploadVersionSpecific -Value YES + + } else { + Set-BuildVariable -Name UploadStable -Value NO + Set-BuildVariable -Name UploadVersionSpecific -Value NO + } + displayName: Create json files + + - task: AzurePowerShell@5 + displayName: Upload buildjson to blob + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + pwsh: true + inline: | + $containerName = '$web' + $storageAccount = '$(PSInfraStorageAccount)' + $prefix = "buildinfo" + + $storageContext = New-AzStorageContext -StorageAccountName $storageAccount -UseConnectedAccount + + #preview + if ($env:UploadPreview -eq 'YES') { + $jsonFile = "$env:PreviewBuildInfoFile" + $blobName = Get-Item $jsonFile | Split-Path -Leaf + Write-Verbose -Verbose "Uploading $jsonFile to $containerName/$prefix/$blobName" + Set-AzStorageBlobContent -File $jsonFile -Container $containerName -Blob "$prefix/$blobName" -Context $storageContext -Force + } + + #LTS + if ($env:UploadLTS -eq 'YES') { + $jsonFile = "$env:LTSBuildInfoFile" + $blobName = Get-Item $jsonFile | Split-Path -Leaf + Write-Verbose -Verbose "Uploading $jsonFile to $containerName/$prefix/$blobName" + Set-AzStorageBlobContent -File $jsonFile -Container $containerName -Blob "$prefix/$blobName" -Context $storageContext -Force + } + + #stable + if ($env:UploadStable -eq 'YES') { + $jsonFile = "$env:StableBuildInfoFile" + $blobName = Get-Item $jsonFile | Split-Path -Leaf + Write-Verbose -Verbose "Uploading $jsonFile to $containerName/$prefix/$blobName" + Set-AzStorageBlobContent -File $jsonFile -Container $containerName -Blob "$prefix/$blobName" -Context $storageContext -Force + } + + #version-specific + if ($env:UploadVersionSpecific -eq 'YES') { + $jsonFile = "$env:VersionSpecificBuildInfoFile" + $blobName = Get-Item $jsonFile | Split-Path -Leaf + Write-Verbose -Verbose "Uploading $jsonFile to $containerName/$prefix/$blobName" + Set-AzStorageBlobContent -File $jsonFile -Container $containerName -Blob "$prefix/$blobName" -Context $storageContext -Force + } + condition: and(succeeded(), or(eq(variables['UploadPreview'], 'YES'), eq(variables['UploadLTS'], 'YES'), eq(variables['UploadStable'], 'YES'), eq(variables['UploadVersionSpecific'], 'YES'))) diff --git a/PowerShell-master/.pipelines/templates/release-validate-fxdpackages.yml b/PowerShell-master/.pipelines/templates/release-validate-fxdpackages.yml new file mode 100644 index 0000000000000000000000000000000000000000..3f4f9a3bb6c82cce5c9b092d60ba673bd904853e --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-validate-fxdpackages.yml @@ -0,0 +1,118 @@ +parameters: + - name: jobName + type: string + default: "" + - name: displayName + type: string + default: "" + - name: jobtype + type: string + default: "" + - name: artifactName + type: string + default: "" + - name: packageNamePattern + type: string + default: "" + - name: arm64 + type: string + default: "no" + - name: enableCredScan + type: boolean + default: true + +jobs: +- job: ${{ parameters.jobName }} + displayName: ${{ parameters.displayName }} + variables: + - group: DotNetPrivateBuildAccess + - name: artifactName + value: ${{ parameters.artifactName }} + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_enabled + value: ${{ parameters.enableCredScan }} + + pool: + type: ${{ parameters.jobtype }} + ${{ if eq(parameters.arm64, 'yes') }}: + hostArchitecture: arm64 + + steps: + - checkout: self + clean: true + + - template: release-SetReleaseTagandContainerName.yml@self + + - download: PSPackagesOfficial + artifact: "${{ parameters.artifactName }}" + displayName: Download fxd artifact + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + + - pwsh: | + $artifactName = '$(artifactName)' + Get-ChildItem "$(Pipeline.Workspace)/PSPackagesOfficial/$artifactName" -Recurse + displayName: 'Capture Downloaded Artifacts' + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $artifactName = '$(artifactName)' + $rootPath = "$(Pipeline.Workspace)/PSPackagesOfficial/$artifactName" + + $destPath = New-Item "$rootPath/fxd" -ItemType Directory + $packageNameFilter = '${{ parameters.packageNamePattern }}' + + if ($packageNameFilter.EndsWith('tar.gz')) { + $package = @(Get-ChildItem -Path "$rootPath/*.tar.gz") + Write-Verbose -Verbose "Package: $package" + if ($package.Count -ne 1) { + throw 'Only 1 package was expected.' + } + tar -xvf $package.FullName -C $destPath + } + else { + $package = @(Get-ChildItem -Path "$rootPath/*.zip") + Write-Verbose -Verbose "Package: $package" + if ($package.Count -ne 1) { + throw 'Only 1 package was expected.' + } + Expand-Archive -Path $package.FullName -Destination "$destPath" -Verbose + } + displayName: Expand fxd package + + - pwsh: | + $repoRoot = "$(Build.SourcesDirectory)/PowerShell" + $artifactName = '$(artifactName)' + $rootPath = "$(Pipeline.Workspace)/PSPackagesOfficial/$artifactName" + + $env:DOTNET_NOLOGO=1 + Import-Module "$repoRoot/build.psm1" -Force + Find-Dotnet -SetDotnetRoot + Write-Verbose -Verbose "DOTNET_ROOT: $env:DOTNET_ROOT" + Write-Verbose -Verbose "Check dotnet install" + dotnet --info + Write-Verbose -Verbose "Start test" + $packageNameFilter = '${{ parameters.packageNamePattern }}' + $pwshExeName = if ($packageNameFilter.EndsWith('tar.gz')) { 'pwsh' } else { 'pwsh.exe' } + $pwshPath = Join-Path "$rootPath/fxd" $pwshExeName + + if ($IsLinux) { + chmod u+x $pwshPath + } + + $pwshDllPath = Join-Path "$rootPath/fxd" 'pwsh.dll' + + $actualOutput = & dotnet $pwshDllPath -c 'Start-ThreadJob -ScriptBlock { "1" } | Wait-Job | Receive-Job' + Write-Verbose -Verbose "Actual output: $actualOutput" + if ($actualOutput -ne 1) { + throw "Actual output is not as expected" + } + displayName: Test package diff --git a/PowerShell-master/.pipelines/templates/release-validate-globaltools.yml b/PowerShell-master/.pipelines/templates/release-validate-globaltools.yml new file mode 100644 index 0000000000000000000000000000000000000000..8c2031d5cc9cd5393c67180652818e045b3ff538 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-validate-globaltools.yml @@ -0,0 +1,127 @@ +parameters: + jobName: "" + displayName: "" + jobtype: "windows" + globalToolExeName: 'pwsh.exe' + globalToolPackageName: 'PowerShell.Windows.x64' + + +jobs: +- job: ${{ parameters.jobName }} + displayName: ${{ parameters.displayName }} + pool: + type: ${{ parameters.jobtype }} + variables: + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + + steps: + - checkout: self + clean: true + + - template: release-SetReleaseTagandContainerName.yml@self + + - download: PSPackagesOfficial + artifact: drop_nupkg_build_nupkg + displayName: Download nupkgs + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + + - pwsh: | + Get-ChildItem "$(Pipeline.Workspace)/PSPackagesOfficial/drop_nupkg_build_nupkg" -Recurse + displayName: 'Capture Downloaded Artifacts' + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $repoRoot = "$(Build.SourcesDirectory)/PowerShell" + + Import-Module "$repoRoot/build.psm1" -Force -Verbose + Start-PSBootstrap -Scenario Dotnet + + $toolPath = New-Item -ItemType Directory "$(System.DefaultWorkingDirectory)/toolPath" | Select-Object -ExpandProperty FullName + + Write-Verbose -Verbose "dotnet tool list -g" + dotnet tool list -g + + $packageName = '${{ parameters.globalToolPackageName }}' + Write-Verbose -Verbose "Installing $packageName" + + dotnet tool install --add-source "$ENV:PIPELINE_WORKSPACE/PSPackagesOfficial/drop_nupkg_build_nupkg" --tool-path $toolPath --version '$(OutputVersion.Version)' $packageName + + Get-ChildItem -Path $toolPath + + displayName: Install global tool + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - pwsh: | + $toolPath = "$(System.DefaultWorkingDirectory)/toolPath/${{ parameters.globalToolExeName }}" + + if (-not (Test-Path $toolPath)) + { + throw "Tool is not installed at $toolPath" + } + else + { + Write-Verbose -Verbose "Tool found at: $toolPath" + } + displayName: Validate tool is installed + + - pwsh: | + $repoRoot = "$(Build.SourcesDirectory)/PowerShell" + + Import-Module "$repoRoot/build.psm1" -Force -Verbose + Start-PSBootstrap -Scenario Dotnet + + $exeName = if ($IsWindows) { "pwsh.exe" } else { "pwsh" } + + $toolPath = "$(System.DefaultWorkingDirectory)/toolPath/${{ parameters.globalToolExeName }}" + + $source = (get-command -Type Application -Name dotnet | Select-Object -First 1 -ExpandProperty source) + $target = (Get-ChildItem $source).target + + # If we find a symbolic link for dotnet, then we need to split the filename off the target. + if ($target) { + Write-Verbose -Verbose "Splitting target: $target" + $target = Split-Path $target + } + + Write-Verbose -Verbose "target is set as $target" + + $env:DOTNET_ROOT = (resolve-path -Path (Join-Path (split-path $source) $target)).ProviderPath + + Write-Verbose -Verbose "DOTNET_ROOT: $env:DOTNET_ROOT" + Get-ChildItem $env:DOTNET_ROOT + + $versionFound = & $toolPath -c '$PSVersionTable.PSVersion.ToString()' + + if ( '$(OutputVersion.Version)' -ne $versionFound) + { + throw "Expected version of global tool not found. Installed version is $versionFound" + } + else + { + write-verbose -verbose "Found expected version: $versionFound" + } + + $dateYear = & $toolPath -c '(Get-Date).Year' + + if ( $dateYear -ne [DateTime]::Now.Year) + { + throw "Get-Date returned incorrect year: $dateYear" + } + else + { + write-verbose -verbose "Got expected year: $dateYear" + } + displayName: Basic validation + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) diff --git a/PowerShell-master/.pipelines/templates/release-validate-packagenames.yml b/PowerShell-master/.pipelines/templates/release-validate-packagenames.yml new file mode 100644 index 0000000000000000000000000000000000000000..7271ffc05a8e2a5fb44e40095b8486251a81214a --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-validate-packagenames.yml @@ -0,0 +1,184 @@ +jobs: +- job: validatePackageNames + displayName: Validate Package Names + pool: + type: windows + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - group: 'Azure Blob variable group' + + steps: + - checkout: self + clean: true + + - template: release-SetReleaseTagandContainerName.yml + + - pwsh: | + Get-ChildItem ENV: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + + - pwsh: | + $name = "{0}_{1:x}" -f '$(OutputReleaseTag.releaseTag)', (Get-Date).Ticks + Write-Host $name + Write-Host "##vso[build.updatebuildnumber]$name" + displayName: Set Release Name + + - task: AzurePowerShell@5 + displayName: Upload packages to blob + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + pwsh: true + inline: | + $storageAccount = Get-AzStorageAccount -ResourceGroupName '$(StorageResourceGroup)' -Name '$(StorageAccount)' + $ctx = $storageAccount.Context + $container = '$(OutputVersion.AzureVersion)' + + $destinationPath = '$(System.ArtifactsDirectory)' + $blobList = Get-AzStorageBlob -Container $container -Context $ctx + foreach ($blob in $blobList) { + $blobName = $blob.Name + $destinationFile = Join-Path -Path $destinationPath -ChildPath $blobName + Get-AzStorageBlobContent -Container $container -Blob $blobName -Destination $destinationFile -Context $ctx -Force + Write-Output "Downloaded $blobName to $destinationFile" + } + + - pwsh: | + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse | Select-Object -ExpandProperty Name + displayName: Capture Artifact Listing + + - pwsh: | + $message = @() + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -filter *.rpm | ForEach-Object { + if($_.Name -notmatch 'powershell\-(preview-|lts-)?\d+\.\d+\.\d+(_[a-z]*\.\d+)?-1.(rh|cm).(x86_64|aarch64)\.rpm') + { + $messageInstance = "$($_.Name) is not a valid package name" + $message += $messageInstance + Write-Warning $messageInstance + } + } + if($message.count -gt 0){throw ($message | out-string)} + displayName: Validate RPM package names + + - pwsh: | + $message = @() + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -filter *.tar.gz | ForEach-Object { + if($_.Name -notmatch 'powershell-(lts-)?\d+\.\d+\.\d+\-([a-z]*.\d+\-)?(linux|osx|linux-musl)+\-(x64\-fxdependent|x64|arm32|arm64|x64\-musl-noopt\-fxdependent)\.(tar\.gz)') + { + $messageInstance = "$($_.Name) is not a valid package name" + $message += $messageInstance + Write-Warning $messageInstance + } + } + if($message.count -gt 0){throw ($message | out-string)} + displayName: Validate Tar.Gz Package Names + + - pwsh: | + $message = @() + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -filter *.pkg | ForEach-Object { + if($_.Name -notmatch 'powershell-(lts-)?\d+\.\d+\.\d+\-([a-z]*.\d+\-)?osx\-(x64|arm64)\.pkg') + { + $messageInstance = "$($_.Name) is not a valid package name" + $message += $messageInstance + Write-Warning $messageInstance + } + } + if($message.count -gt 0){throw ($message | out-string)} + displayName: Validate PKG Package Names + + - pwsh: | + $message = @() + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -include *.zip | ForEach-Object { + if($_.Name -notmatch 'PowerShell-\d+\.\d+\.\d+\-([a-z]*.\d+\-)?win\-(fxdependent|x64|arm64|x86|fxdependentWinDesktop)\.(zip){1}') + { + $messageInstance = "$($_.Name) is not a valid package name" + $message += $messageInstance + Write-Warning $messageInstance + } + } + + if($message.count -gt 0){throw ($message | out-string)} + displayName: Validate Zip Package Names + + - pwsh: | + $message = @() + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -filter *.deb | ForEach-Object { + if($_.Name -notmatch 'powershell(-preview|-lts)?_\d+\.\d+\.\d+([\-~][a-z]*.\d+)?-\d\.deb_amd64\.deb') + { + $messageInstance = "$($_.Name) is not a valid package name" + $message += $messageInstance + Write-Warning $messageInstance + } + } + if($message.count -gt 0){throw ($message | out-string)} + displayName: Validate Deb Package Names + +# Move to 1ES SBOM validation tool +# - job: validateBOM +# displayName: Validate Package Names +# pool: +# type: windows +# variables: +# - name: ob_outputDirectory +# value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' +# - name: ob_sdl_credscan_suppressionsFile +# value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json +# - name: ob_sdl_tsa_configFile +# value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json +# - group: 'Azure Blob variable group' + +# steps: +# - checkout: self +# clean: true + +# - pwsh: | +# Get-ChildItem ENV: | Out-String -width 9999 -Stream | write-Verbose -Verbose +# displayName: Capture environment + +# - template: release-SetReleaseTagAndContainerName.yml + +# - pwsh: | +# $name = "{0}_{1:x}" -f '$(releaseTag)', (Get-Date).Ticks +# Write-Host $name +# Write-Host "##vso[build.updatebuildnumber]$name" +# displayName: Set Release Name + +# - task: DownloadPipelineArtifact@2 +# inputs: +# source: specific +# project: PowerShellCore +# pipeline: '696' +# preferTriggeringPipeline: true +# runVersion: latestFromBranch +# runBranch: '$(Build.SourceBranch)' +# artifact: finalResults +# path: $(System.ArtifactsDirectory) + + +# - pwsh: | +# Get-ChildItem $(System.ArtifactsDirectory)\* -recurse | Select-Object -ExpandProperty Name +# displayName: Capture Artifact Listing + +# - pwsh: | +# Install-module Pester -Scope CurrentUser -Force -MaximumVersion 4.99 +# displayName: Install Pester +# condition: succeededOrFailed() + +# - pwsh: | +# Import-module './build.psm1' +# Import-module './tools/packaging' +# $env:PACKAGE_FOLDER = '$(System.ArtifactsDirectory)' +# $path = Join-Path -Path $pwd -ChildPath './packageReleaseTests.xml' +# $results = invoke-pester -Script './tools/packaging/releaseTests' -OutputFile $path -OutputFormat NUnitXml -PassThru +# Write-Host "##vso[results.publish type=NUnit;mergeResults=true;runTitle=Package Release Tests;publishRunAttachments=true;resultFiles=$path;]" +# if($results.TotalCount -eq 0 -or $results.FailedCount -gt 0) +# { +# throw "Package Release Tests failed" +# } +# displayName: Run packaging release tests diff --git a/PowerShell-master/.pipelines/templates/release-validate-sdk.yml b/PowerShell-master/.pipelines/templates/release-validate-sdk.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b0442f65d653364dd7d1dfd853a86be1417b994 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/release-validate-sdk.yml @@ -0,0 +1,98 @@ +parameters: + jobName: "" + displayName: "" + poolName: "windows" + imageName: 'none' + +jobs: +- job: ${{ parameters.jobName }} + displayName: ${{ parameters.displayName }} + pool: + type: linux + isCustom: true + ${{ if eq( parameters.poolName, 'Azure Pipelines') }}: + name: ${{ parameters.poolName }} + vmImage: ${{ parameters.imageName }} + ${{ else }}: + name: ${{ parameters.poolName }} + demands: + - ImageOverride -equals ${{ parameters.imageName }} + + variables: + - group: mscodehub-feed-read-general + - group: mscodehub-feed-read-akv + - group: DotNetPrivateBuildAccess + + steps: + - checkout: self + clean: true + lfs: false + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: "$(Build.SourcesDirectory)" + + - template: release-SetReleaseTagandContainerName.yml@self + + - download: PSPackagesOfficial + artifact: drop_nupkg_build_nupkg + displayName: Download nupkgs + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + + - pwsh: | + Get-ChildItem "$(Pipeline.Workspace)/PSPackagesOfficial/drop_nupkg_build_nupkg" -Recurse + displayName: 'Capture Downloaded Artifacts' + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $repoRoot = "$(Build.SourcesDirectory)" + + Import-Module "$repoRoot/build.psm1" -Force -Verbose + Start-PSBootstrap -Scenario Dotnet + + $env:DOTNET_NOLOGO=1 + + $localLocation = "$(Pipeline.Workspace)/PSPackagesOfficial/drop_nupkg_build_nupkg" + $xmlElement = @" + + + + "@ + + $releaseVersion = '$(OutputVersion.Version)' + + Write-Verbose -Message "Release Version: $releaseVersion" -Verbose + + Set-Location -Path $repoRoot/test/hosting + + Get-ChildItem + + ## register the packages download directory in the nuget file + $nugetPath = './NuGet.Config' + if(!(test-path $nugetPath)) { + $nugetPath = "$repoRoot/nuget.config" + } + Write-Verbose -Verbose "nugetPath: $nugetPath" + $nugetConfigContent = Get-Content $nugetPath -Raw + $updateNugetContent = $nugetConfigContent.Replace("", $xmlElement) + + $updateNugetContent | Out-File $nugetPath -Encoding ascii + + Get-Content $nugetPath + + dotnet --info + dotnet restore + dotnet test /property:RELEASE_VERSION=$releaseVersion --test-adapter-path:. "--logger:xunit;LogFilePath=$(System.DefaultWorkingDirectory)/test-hosting.xml" + displayName: Restore and execute tests + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - task: PublishTestResults@2 + displayName: 'Publish Test Results **\test-hosting.xml' + inputs: + testResultsFormat: XUnit + testResultsFiles: '**\test-hosting.xml' diff --git a/PowerShell-master/.pipelines/templates/set-reporoot.yml b/PowerShell-master/.pipelines/templates/set-reporoot.yml new file mode 100644 index 0000000000000000000000000000000000000000..af7983afaa1df0d70ceecdbf5519f72b8e804a3a --- /dev/null +++ b/PowerShell-master/.pipelines/templates/set-reporoot.yml @@ -0,0 +1,35 @@ +parameters: +- name: ob_restore_phase + type: boolean + default: true + +steps: +- pwsh: | + $path = "./build.psm1" + if($env:REPOROOT){ + Write-Verbose "reporoot already set to ${env:REPOROOT}" -Verbose + exit 0 + } + if(Test-Path -Path $path) + { + Write-Verbose "reporoot detected at: ." -Verbose + $repoRoot = '.' + } + else{ + $path = "./PowerShell/build.psm1" + if(Test-Path -Path $path) + { + Write-Verbose "reporoot detected at: ./PowerShell" -Verbose + $repoRoot = './PowerShell' + } + } + if($repoRoot) { + $vstsCommandString = "vso[task.setvariable variable=repoRoot]$repoRoot" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + } else { + Write-Verbose -Verbose "repo not found" + } + displayName: 'Set repo Root' + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} diff --git a/PowerShell-master/.pipelines/templates/shouldSign.yml b/PowerShell-master/.pipelines/templates/shouldSign.yml new file mode 100644 index 0000000000000000000000000000000000000000..551297f3aaa737c315e66f00ee2ae845a853099d --- /dev/null +++ b/PowerShell-master/.pipelines/templates/shouldSign.yml @@ -0,0 +1,30 @@ +parameters: +- name: ob_restore_phase + type: boolean + default: true + +steps: +- powershell: | + $shouldSign = $true + $authenticodeCert = 'CP-230012' + $msixCert = 'CP-230012' + if($env:IS_DAILY -eq 'true') + { + $authenticodeCert = 'CP-460906' + } + if($env:SKIP_SIGNING -eq 'Yes') + { + $shouldSign = $false + } + $vstsCommandString = "vso[task.setvariable variable=SHOULD_SIGN]$($shouldSign.ToString().ToLowerInvariant())" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + $vstsCommandString = "vso[task.setvariable variable=MSIX_CERT]$($msixCert)" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + $vstsCommandString = "vso[task.setvariable variable=AUTHENTICODE_CERT]$($authenticodeCert)" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: 'Set SHOULD_SIGN Variable' + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} diff --git a/PowerShell-master/.pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml b/PowerShell-master/.pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml new file mode 100644 index 0000000000000000000000000000000000000000..cd0a4ebc065dfade3cfd9e49749a8f2235273155 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml @@ -0,0 +1,202 @@ +parameters: + - name: RUN_WINDOWS + type: boolean + default: true + - name: RUN_TEST_AND_RELEASE + type: boolean + default: true + - name: OfficialBuild + type: boolean + +stages: +- stage: prep + jobs: + - job: SetVars + displayName: Set Variables + pool: + type: linux + + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT/BuildJson' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_codeql_compiled_enabled + value: false + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_signing_setup_enabled + value: false + - name: ob_sdl_sbom_enabled + value: false + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - pwsh: | + Get-ChildItem Env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment variables + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: yes + +- stage: macos + displayName: macOS - build and sign + dependsOn: ['prep'] + variables: + - name: ps_official_build + value: ${{ parameters.OfficialBuild }} + jobs: + - template: /.pipelines/templates/mac.yml@self + parameters: + buildArchitecture: x64 + - template: /.pipelines/templates/mac.yml@self + parameters: + buildArchitecture: arm64 + +- stage: linux + displayName: linux - build and sign + dependsOn: ['prep'] + variables: + - name: ps_official_build + value: ${{ parameters.OfficialBuild }} + jobs: + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'linux-x64' + JobName: 'linux_x64' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'linux-x64' + JobName: 'linux_x64_minSize' + BuildConfiguration: 'minSize' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'linux-arm' + JobName: 'linux_arm' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'linux-arm64' + JobName: 'linux_arm64' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'fxdependent-linux-x64' + JobName: 'linux_fxd_x64_mariner' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'fxdependent-linux-arm64' + JobName: 'linux_fxd_arm64_mariner' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'fxdependent-noopt-linux-musl-x64' + JobName: 'linux_fxd_x64_alpine' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'fxdependent' + JobName: 'linux_fxd' + + - template: /.pipelines/templates/linux.yml@self + parameters: + Runtime: 'linux-musl-x64' + JobName: 'linux_x64_alpine' + +- stage: windows + displayName: windows - build and sign + dependsOn: ['prep'] + condition: and(succeeded(),eq('${{ parameters.RUN_WINDOWS }}','true')) + variables: + - name: ps_official_build + value: ${{ parameters.OfficialBuild }} + jobs: + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: x64 + BuildConfiguration: release + JobName: build_windows_x64_release + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: x64 + BuildConfiguration: minSize + JobName: build_windows_x64_minSize_release + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: x86 + JobName: build_windows_x86_release + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: arm64 + JobName: build_windows_arm64_release + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: fxdependent + JobName: build_windows_fxdependent_release + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: fxdependentWinDesktop + JobName: build_windows_fxdependentWinDesktop_release + +- stage: test_and_release_artifacts + displayName: Test and Release Artifacts + dependsOn: ['prep'] + condition: and(succeeded(),eq('${{ parameters.RUN_TEST_AND_RELEASE }}','true')) + jobs: + - template: /.pipelines/templates/testartifacts.yml@self + + - job: release_json + displayName: Create and Upload release.json + pool: + type: windows + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + steps: + - checkout: self + clean: true + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + - template: /.pipelines/templates/rebuild-branch-check.yml@self + - powershell: | + $metadata = Get-Content '$(Build.SourcesDirectory)/PowerShell/tools/metadata.json' -Raw | ConvertFrom-Json + + # Use the rebuild branch check from the template + $isRebuildBranch = '$(RebuildBranchCheck.IsRebuildBranch)' -eq 'true' + + # Don't mark as LTS release for rebuild branches + $LTS = $metadata.LTSRelease.Package -and -not $isRebuildBranch + + if ($isRebuildBranch) { + Write-Verbose -Message "Rebuild branch detected, not marking as LTS release" -Verbose + } + + @{ ReleaseVersion = "$(Version)"; LTSRelease = $LTS } | ConvertTo-Json | Out-File "$(Build.StagingDirectory)\release.json" + Get-Content "$(Build.StagingDirectory)\release.json" + + if (-not (Test-Path "$(ob_outputDirectory)\metadata")) { + New-Item -ItemType Directory -Path "$(ob_outputDirectory)\metadata" + } + + Copy-Item -Path "$(Build.StagingDirectory)\release.json" -Destination "$(ob_outputDirectory)\metadata" -Force + displayName: Create and upload release.json file to build artifact + retryCountOnTaskFailure: 2 + - template: /.pipelines/templates/step/finalize.yml@self diff --git a/PowerShell-master/.pipelines/templates/stages/PowerShell-Packages-Stages.yml b/PowerShell-master/.pipelines/templates/stages/PowerShell-Packages-Stages.yml new file mode 100644 index 0000000000000000000000000000000000000000..b1efb2a80973f16b5e0c3a063e8088c136d26f86 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/stages/PowerShell-Packages-Stages.yml @@ -0,0 +1,192 @@ +parameters: + - name: OfficialBuild + type: boolean + +stages: +- stage: prep + displayName: 'Prep BuildInfo+Az' + jobs: + - template: /.pipelines/templates/checkAzureContainer.yml@self + +- stage: mac_package + displayName: 'macOS Pkg+Sign' + dependsOn: [] + jobs: + - template: /.pipelines/templates/mac-package-build.yml@self + parameters: + buildArchitecture: x64 + + - template: /.pipelines/templates/mac-package-build.yml@self + parameters: + buildArchitecture: arm64 + +- stage: windows_package_build + displayName: 'Win Pkg (unsigned)' + dependsOn: [] + jobs: + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: x64 + + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: arm64 + + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: x86 + + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: fxdependent + + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: fxdependentWinDesktop + + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: minsize + +- stage: windows_package_sign + displayName: 'Win Pkg Sign' + dependsOn: [windows_package_build] + jobs: + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: x64 + + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: arm64 + + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: x86 + + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: fxdependent + + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: fxdependentWinDesktop + + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: minsize + +- stage: linux_package + displayName: 'Linux Pkg+Sign' + dependsOn: [] + jobs: + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_x64' + signedDrop: 'drop_linux_sign_linux_x64' + packageType: deb + jobName: deb + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_fxd_x64_mariner' + signedDrop: 'drop_linux_sign_linux_fxd_x64_mariner' + packageType: rpm-fxdependent #mariner-x64 + jobName: mariner_x64 + signingProfile: 'CP-459159-pgpdetached' + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_fxd_arm64_mariner' + signedDrop: 'drop_linux_sign_linux_fxd_arm64_mariner' + packageType: rpm-fxdependent-arm64 #mariner-arm64 + jobName: mariner_arm64 + signingProfile: 'CP-459159-pgpdetached' + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_x64' + signedDrop: 'drop_linux_sign_linux_x64' + packageType: rpm + jobName: rpm + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_arm' + signedDrop: 'drop_linux_sign_linux_arm' + packageType: tar-arm + jobName: tar_arm + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_arm64' + signedDrop: 'drop_linux_sign_linux_arm64' + packageType: tar-arm64 + jobName: tar_arm64 + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_x64_alpine' + signedDrop: 'drop_linux_sign_linux_x64_alpine' + packageType: tar-alpine + jobName: tar_alpine + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_fxd' + signedDrop: 'drop_linux_sign_linux_fxd' + packageType: fxdependent + jobName: fxdependent + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_x64' + signedDrop: 'drop_linux_sign_linux_x64' + packageType: tar + jobName: tar + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_fxd_x64_alpine' + signedDrop: 'drop_linux_sign_linux_fxd_x64_alpine' + packageType: tar-alpine-fxdependent + jobName: tar_alpine_fxd + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_x64_minSize' + signedDrop: 'drop_linux_sign_linux_x64_minSize' + packageType: min-size + jobName: minSize + +- stage: nupkg + displayName: 'NuGet Pkg+Sign' + dependsOn: [] + jobs: + - template: /.pipelines/templates/nupkg.yml@self + +- stage: msixbundle + displayName: 'MSIX Bundle+Sign' + dependsOn: [windows_package_build] # Only depends on unsigned packages + jobs: + - template: /.pipelines/templates/package-create-msix.yml@self + parameters: + OfficialBuild: ${{ parameters.OfficialBuild }} + +- stage: store_package + displayName: 'Store Package' + dependsOn: [msixbundle] + jobs: + - template: /.pipelines/templates/package-store-package.yml@self + +- stage: upload + displayName: 'Upload' + dependsOn: [prep, mac_package, windows_package_sign, linux_package, nupkg, msixbundle] # prep needed for BuildInfo JSON + jobs: + - template: /.pipelines/templates/uploadToAzure.yml@self + +- stage: validatePackages + displayName: 'Validate Packages' + dependsOn: [upload] + jobs: + - template: /.pipelines/templates/release-validate-packagenames.yml@self diff --git a/PowerShell-master/.pipelines/templates/stages/PowerShell-Release-Stages.yml b/PowerShell-master/.pipelines/templates/stages/PowerShell-Release-Stages.yml new file mode 100644 index 0000000000000000000000000000000000000000..52ce428a663f0af6df769f5960c2ac702459d505 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/stages/PowerShell-Release-Stages.yml @@ -0,0 +1,323 @@ +parameters: + - name: releaseEnvironment + type: string + - name: SkipPublish + type: boolean + - name: SkipPSInfraInstallers + type: boolean + - name: skipMSIXPublish + type: boolean + +stages: +- stage: setReleaseTagAndChangelog + displayName: 'Set Release Tag and Upload Changelog' + jobs: + - template: /.pipelines/templates/release-SetTagAndChangelog.yml@self + +- stage: validateSdk + displayName: 'Validate SDK' + dependsOn: [] + jobs: + - template: /.pipelines/templates/release-validate-sdk.yml@self + parameters: + jobName: "windowsSDK" + displayName: "Windows SDK Validation" + imageName: PSMMS2019-Secure + poolName: $(windowsPool) + + - template: /.pipelines/templates/release-validate-sdk.yml@self + parameters: + jobName: "MacOSSDK" + displayName: "MacOS SDK Validation" + imageName: macOS-latest + poolName: Azure Pipelines + + - template: /.pipelines/templates/release-validate-sdk.yml@self + parameters: + jobName: "LinuxSDK" + displayName: "Linux SDK Validation" + imageName: PSMMSUbuntu22.04-Secure + poolName: $(ubuntuPool) + +- stage: gbltool + displayName: 'Validate Global tools' + dependsOn: [] + jobs: + - template: /.pipelines/templates/release-validate-globaltools.yml@self + parameters: + jobName: "WindowsGlobalTools" + displayName: "Windows Global Tools Validation" + jobtype: windows + + - template: /.pipelines/templates/release-validate-globaltools.yml@self + parameters: + jobName: "LinuxGlobalTools" + displayName: "Linux Global Tools Validation" + jobtype: linux + globalToolExeName: 'pwsh' + globalToolPackageName: 'PowerShell.Linux.x64' + +- stage: fxdpackages + displayName: 'Validate FXD Packages' + dependsOn: [] + jobs: + - template: /.pipelines/templates/release-validate-fxdpackages.yml@self + parameters: + jobName: 'winfxd' + displayName: 'Validate Win Fxd Packages' + jobtype: 'windows' + artifactName: 'drop_windows_package_package_win_fxdependent' + packageNamePattern: '**/*win-fxdependent.zip' + + - template: /.pipelines/templates/release-validate-fxdpackages.yml@self + parameters: + jobName: 'winfxdDesktop' + displayName: 'Validate WinDesktop Fxd Packages' + jobtype: 'windows' + artifactName: 'drop_windows_package_package_win_fxdependentWinDesktop' + packageNamePattern: '**/*win-fxdependentwinDesktop.zip' + + - template: /.pipelines/templates/release-validate-fxdpackages.yml@self + parameters: + jobName: 'linuxfxd' + displayName: 'Validate Linux Fxd Packages' + jobtype: 'linux' + artifactName: 'drop_linux_package_fxdependent' + packageNamePattern: '**/*linux-x64-fxdependent.tar.gz' + + - template: /.pipelines/templates/release-validate-fxdpackages.yml@self + parameters: + jobName: 'linuxArm64fxd' + displayName: 'Validate Linux ARM64 Fxd Packages' + jobtype: 'linux' + artifactName: 'drop_linux_package_fxdependent' + # this is really an architecture independent package + packageNamePattern: '**/*linux-x64-fxdependent.tar.gz' + arm64: 'yes' + enableCredScan: false + +- stage: ManualValidation + dependsOn: [] + displayName: Manual Validation + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Validate Windows Packages + jobName: ValidateWinPkg + instructions: | + Validate zip package on windows + + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Validate OSX Packages + jobName: ValidateOsxPkg + instructions: | + Validate tar.gz package on osx-arm64 + +- stage: ReleaseAutomation + dependsOn: [] + displayName: 'Release Automation' + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Start Release Automation + jobName: StartRA + instructions: | + Kick off Release automation build at: https://dev.azure.com/powershell-rel/Release-Automation/_build?definitionId=10&_a=summary + + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Triage results + jobName: TriageRA + dependsOnJob: StartRA + instructions: | + Triage ReleaseAutomation results + + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Signoff Tests + dependsOnJob: TriageRA + jobName: SignoffTests + instructions: | + Signoff ReleaseAutomation results + +- stage: UpdateChangeLog + displayName: Update the changelog + dependsOn: + - ManualValidation + - ReleaseAutomation + - fxdpackages + - gbltool + - validateSdk + + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Make sure the changelog is updated + jobName: MergeChangeLog + instructions: | + Update and merge the changelog for the release. + This step is required for creating GitHub draft release. + +- stage: PublishGitHubReleaseAndNuget + displayName: Publish GitHub and Nuget Release + dependsOn: + - setReleaseTagAndChangelog + - UpdateChangeLog + variables: + ob_release_environment: ${{ parameters.releaseEnvironment }} + jobs: + - template: /.pipelines/templates/release-githubNuget.yml@self + parameters: + skipPublish: ${{ parameters.SkipPublish }} + +- stage: PushGitTagAndMakeDraftPublic + displayName: Push Git Tag and Make Draft Public + dependsOn: PublishGitHubReleaseAndNuget + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Push Git Tag + jobName: PushGitTag + instructions: | + Push the git tag to upstream + + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Make Draft Public + dependsOnJob: PushGitTag + jobName: DraftPublic + instructions: | + Make the GitHub Release Draft Public + +- stage: BlobPublic + displayName: Make Blob Public + dependsOn: + - UpdateChangeLog + - PushGitTagAndMakeDraftPublic + jobs: + - template: /.pipelines/templates/release-MakeBlobPublic.yml@self + parameters: + SkipPSInfraInstallers: ${{ parameters.SkipPSInfraInstallers }} + +- stage: PublishPMC + displayName: Publish PMC + dependsOn: PushGitTagAndMakeDraftPublic + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Publish to PMC + jobName: ReleaseToPMC + instructions: | + Run PowerShell-Release-Official-Azure.yml pipeline to publish to PMC + +- stage: UpdateDotnetDocker + dependsOn: PushGitTagAndMakeDraftPublic + displayName: Update DotNet SDK Docker images + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Update .NET SDK docker images + jobName: DotnetDocker + instructions: | + Create PR for updating dotnet-docker images to use latest PowerShell version. + 1. Fork and clone https://github.com/dotnet/dotnet-docker.git + 2. git checkout upstream/nightly -b updatePS + 3. dotnet run --project .\eng\update-dependencies\ specific --product-version powershell= --compute-shas + 4. create PR targeting nightly branch + +- stage: UpdateWinGet + dependsOn: PushGitTagAndMakeDraftPublic + displayName: Add manifest entry to winget + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Add manifest entry to winget + jobName: UpdateWinGet + instructions: | + This is typically done by the community 1-2 days after the release. + +- stage: PublishMsix + dependsOn: + - setReleaseTagAndChangelog + - PushGitTagAndMakeDraftPublic + displayName: Publish MSIX to store + variables: + ob_release_environment: ${{ parameters.releaseEnvironment }} + jobs: + - template: /.pipelines/templates/release-MSIX-Publish.yml@self + parameters: + skipMSIXPublish: ${{ parameters.skipMSIXPublish }} + +- stage: PublishVPack + dependsOn: PushGitTagAndMakeDraftPublic + displayName: Release vPack + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Start 2 vPack Release pipelines + jobName: PublishVPack + instructions: | + 1. Kick off PowerShell-vPack-Official pipeline + 2. Kick off PowerShell-MSIXBundle-VPack pipeline + +# Need to verify if the Az PS / CLI team still uses this. Skipping for this release. +# - stage: ReleaseDeps +# dependsOn: GitHubTasks +# displayName: Update pwsh.deps.json links +# jobs: +# - template: templates/release-UpdateDepsJson.yml + +- stage: UploadBuildInfoJson + dependsOn: PushGitTagAndMakeDraftPublic + displayName: Upload BuildInfo.json + jobs: + - template: /.pipelines/templates/release-upload-buildinfo.yml@self + +- stage: ReleaseSymbols + dependsOn: PushGitTagAndMakeDraftPublic + displayName: Release Symbols + jobs: + - template: /.pipelines/templates/release-symbols.yml@self + +- stage: ChangesToMaster + displayName: Ensure changes are in GH master + dependsOn: + - PublishPMC + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Make sure changes are in master + jobName: MergeToMaster + instructions: | + Make sure that changes README.md and metadata.json are merged into master on GitHub. + +- stage: ReleaseToMU + displayName: Release to MU + dependsOn: PushGitTagAndMakeDraftPublic # This only needs the blob to be available + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Release to MU + instructions: | + Notify the PM team to start the process of releasing to MU. + +- stage: ReleaseClose + displayName: Finish Release + dependsOn: + - ReleaseToMU + - ReleaseSymbols + jobs: + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Retain Build + jobName: RetainBuild + instructions: | + Retain the build + + - template: /.pipelines/templates/approvalJob.yml@self + parameters: + displayName: Delete release branch + jobName: DeleteBranch + instructions: | + Delete release branch diff --git a/PowerShell-master/.pipelines/templates/stages/PowerShell-vPack-Stages.yml b/PowerShell-master/.pipelines/templates/stages/PowerShell-vPack-Stages.yml new file mode 100644 index 0000000000000000000000000000000000000000..f0d49e8b4897f85b7fa670f3d5bc7d1f9500b9de --- /dev/null +++ b/PowerShell-master/.pipelines/templates/stages/PowerShell-vPack-Stages.yml @@ -0,0 +1,236 @@ +parameters: + - name: createVPack + type: boolean + - name: vPackName + type: string + +stages: +- stage: BuildStage + jobs: + - job: BuildJob + pool: + type: windows + + strategy: + matrix: + x86: + architecture: x86 + + x64: + architecture: x64 + + arm64: + architecture: arm64 + + variables: + ArtifactPlatform: 'windows' + ob_artifactBaseName: drop_build_$(architecture) + ob_outputDirectory: '$(BUILD.SOURCESDIRECTORY)\out' + ob_createvpack_enabled: ${{ parameters.createVPack }} + ob_createvpack_owneralias: tplunk + ob_createvpack_versionAs: parts + ob_createvpack_propsFile: true + ob_createvpack_verbose: true + ob_createvpack_packagename: '${{ parameters.vPackName }}.$(architecture)' + ob_createvpack_description: PowerShell $(architecture) $(version) + # I think the variables reload after we transition back to the host so this works. 🤷‍♂️ + ob_createvpack_majorVer: $(pwshMajorVersion) + ob_createvpack_minorVer: $(pwshMinorVersion) + ob_createvpack_patchVer: $(pwshPatchVersion) + ${{ if ne(variables['pwshPrereleaseVersion'], '') }}: + ob_createvpack_prereleaseVer: $(pwshPrereleaseVersion) + ${{ else }}: + ob_createvpack_prereleaseVer: $(Build.SourceVersion) + + steps: + - checkout: self + displayName: Checkout source code - during restore + clean: true + path: s + env: + ob_restore_phase: true + + - template: .pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: yes + + - pwsh: | + $version = '$(Version)' + Write-Verbose -Verbose "Version: $version" + if(!$version) { + throw "Version is not set." + } + + $mainVersionParts = $version -split '-' + + Write-Verbose -Verbose "mainVersionParts: $($mainVersionParts[0]) ; $($mainVersionParts[1])" + $versionParts = $mainVersionParts[0] -split '[.]'; + $major = $versionParts[0] + $minor = $versionParts[1] + $patch = $versionParts[2] + + $previewPart = $mainVersionParts[1] + Write-Verbose -Verbose "previewPart: $previewPart" + + Write-Host "major: $major; minor: $minor; patch: $patch;" + + $vstsCommandString = "vso[task.setvariable variable=pwshMajorVersion]$major" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + + $vstsCommandString = "vso[task.setvariable variable=pwshMinorVersion]$minor" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + + $vstsCommandString = "vso[task.setvariable variable=pwshPatchVersion]$patch" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + if($previewPart) { + $vstsCommandString = "vso[task.setvariable variable=pwshPrereleaseVersion]$previewPart" + } else { + Write-Verbose -Verbose "No prerelease part found in version string." + } + displayName: Set ob_createvpack_*Ver + env: + ob_restore_phase: true + + # Validate pwsh*Version variables + - pwsh: | + $variables = @("pwshMajorVersion", "pwshMinorVersion", "pwshPatchVersion") + foreach ($var in $variables) { + if (-not (get-item "Env:\$var" -ErrorAction SilentlyContinue).value) { + throw "Required variable '`$env:$var' is not set." + } + } + displayName: Validate pwsh*Version variables + env: + ob_restore_phase: true + + - pwsh: | + if($env:RELEASETAGVAR -match '-') { + throw "Don't release a preview build without coordinating with Windows Engineering Build Tools Team" + } + displayName: Stop any preview release + env: + ob_restore_phase: true + + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + packageType: sdk + version: 3.1.x + installationPath: $(Agent.ToolsDirectory)/dotnet + + ### BUILD ### + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(repoRoot) + + - task: CodeQL3000Init@0 # Add CodeQL Init task right before your 'Build' step. + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + inputs: + Enabled: true + AnalyzeInPipeline: false # Do not upload results + Language: csharp + + - task: UseDotNet@2 + displayName: 'Install .NET based on global.json' + inputs: + useGlobalJson: true + workingDirectory: $(repoRoot) + env: + ob_restore_phase: true + + - pwsh: | + # Need to set PowerShellRoot variable for obp-file-signing template + $vstsCommandString = "vso[task.setvariable variable=PowerShellRoot]$(repoRoot)" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + + $Architecture = '$(Architecture)' + $runtime = switch ($Architecture) + { + "x64" { "win7-x64" } + "x86" { "win7-x86" } + "arm64" { "win-arm64" } + } + + $params = @{} + if ($env:BuildConfiguration -eq 'minSize') { + $params['ForMinimalSize'] = $true + } + + $vstsCommandString = "vso[task.setvariable variable=Runtime]$runtime" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + + Write-Verbose -Message "Building PowerShell with Runtime: $runtime for '$env:BuildConfiguration' configuration" + Import-Module -Name $(repoRoot)/build.psm1 -Force + $buildWithSymbolsPath = New-Item -ItemType Directory -Path "$(Pipeline.Workspace)/Symbols_$Architecture" -Force + + Start-PSBootstrap -Scenario Package + $null = New-Item -ItemType Directory -Path $buildWithSymbolsPath -Force -Verbose + + $ReleaseTagParam = @{} + + if ($env:RELEASETAGVAR) { + $ReleaseTagParam['ReleaseTag'] = $env:RELEASETAGVAR + } + + Start-PSBuild -Runtime $runtime -Configuration Release -Output $buildWithSymbolsPath -Clean -PSModuleRestore @params @ReleaseTagParam + + $refFolderPath = Join-Path $buildWithSymbolsPath 'ref' + Write-Verbose -Verbose "refFolderPath: $refFolderPath" + $outputPath = Join-Path '$(ob_outputDirectory)' 'psoptions' + $null = New-Item -ItemType Directory -Path $outputPath -Force + $psOptPath = "$outputPath/psoptions.json" + Save-PSOptions -PSOptionsPath $psOptPath + + Write-Verbose -Verbose "Completed building PowerShell for '$env:BuildConfiguration' configuration" + displayName: Build Windows Universal - $(Architecture) -$(BuildConfiguration) Symbols folder + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - task: CodeQL3000Finalize@0 # Add CodeQL Finalize task right after your 'Build' step. + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 + displayName: 'Component Detection' + inputs: + sourceScanPath: '$(repoRoot)\src' + ob_restore_phase: true + + - template: /.pipelines/templates/obp-file-signing.yml@self + parameters: + binPath: '$(Pipeline.Workspace)/Symbols_$(Architecture)' + SigningProfile: $(windows_build_tools_cert_id) + OfficialBuild: false + vPackScenario: true + + ### END OF BUILD ### + + - pwsh: | + Get-ChildItem env:/ob_createvpack_*Ver + Get-ChildItem -Path "$(Pipeline.Workspace)\Symbols_$(Architecture)\*" -Recurse + Get-Content "$(Pipeline.Workspace)\PowerShell\preview.json" -ErrorAction SilentlyContinue | Write-Host + displayName: Debug Output Directory and Version + condition: succeededOrFailed() + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - pwsh: | + $vpackFiles = Get-ChildItem -Path "$(Pipeline.Workspace)\Symbols_$(Architecture)\*" -Recurse + if($vpackFiles.Count -eq 0) { + throw "No files found in $(Pipeline.Workspace)\Symbols_$(Architecture)" + } + $vpackFiles + displayName: Debug Output Directory and Version + condition: succeededOrFailed() diff --git a/PowerShell-master/.pipelines/templates/step/finalize.yml b/PowerShell-master/.pipelines/templates/step/finalize.yml new file mode 100644 index 0000000000000000000000000000000000000000..78e0341c829d8abbe646e46de8ff0ab2e4161c75 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/step/finalize.yml @@ -0,0 +1,6 @@ +# This was used before migrating to OneBranch to deal with one of the SDL taks from failing with a warning instead of an error. +steps: +- pwsh: | + throw "Jobs with an Issue will not work for release. Please fix the issue and try again." + displayName: Check for SucceededWithIssues + condition: eq(variables['Agent.JobStatus'],'SucceededWithIssues') diff --git a/PowerShell-master/.pipelines/templates/testartifacts.yml b/PowerShell-master/.pipelines/templates/testartifacts.yml new file mode 100644 index 0000000000000000000000000000000000000000..3a6bec4a8591152369ef44b4207c85b6e76a9eb0 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/testartifacts.yml @@ -0,0 +1,134 @@ +jobs: +- job: build_testartifacts_win + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_codeSignValidation_excludes + value: '-|**\*.ps1;-|**\*.psm1;-|**\*.ps1xml;-|**\*.psd1;-|**\*.exe;-|**\*.dll;-|**\*.cdxml' + + displayName: Build windows test artifacts + condition: succeeded() + pool: + type: windows + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(RepoRoot) + ob_restore_phase: true + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + New-Item -Path '$(ob_outputDirectory)' -ItemType Directory -Force + Import-Module $(Build.SourcesDirectory)/PowerShell/build.psm1 + function BuildTestPackage([string] $runtime) + { + Write-Verbose -Verbose "Starting to build package for $runtime" + New-TestPackage -Destination $(System.ArtifactsDirectory) -Runtime $runtime + if (-not (Test-Path $(System.ArtifactsDirectory)/TestPackage.zip)) + { + throw "Test Package was not found at: $(System.ArtifactsDirectory)" + } + switch ($runtime) + { + win7-x64 { $packageName = "TestPackage-win-x64.zip" } + win7-x86 { $packageName = "TestPackage-win-x86.zip" } + win-arm64 { $packageName = "TestPackage-win-arm64.zip" } + } + Rename-Item $(System.ArtifactsDirectory)/TestPackage.zip $packageName + ## Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" + + Copy-Item -Path $(System.ArtifactsDirectory)/$packageName -Destination $(ob_outputDirectory) -Force -Verbose + } + BuildTestPackage -runtime win7-x64 + BuildTestPackage -runtime win7-x86 + BuildTestPackage -runtime win-arm64 + displayName: Build test package and upload + retryCountOnTaskFailure: 1 + env: + ob_restore_phase: true + + - pwsh: | + Write-Host "This doesn't do anything but make the build phase run." + displayName: Dummy build task + + +- job: build_testartifacts_nonwin + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: DotNetPrivateBuildAccess + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + displayName: Build non-windows test artifacts + condition: succeeded() + pool: + type: linux + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(Build.SourcesDirectory)/PowerShell + ob_restore_phase: true + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + New-Item -Path '$(ob_outputDirectory)' -ItemType Directory -Force + Import-Module $(Build.SourcesDirectory)/PowerShell/build.psm1 + function BuildTestPackage([string] $runtime) + { + Write-Verbose -Verbose "Starting to build package for $runtime" + New-TestPackage -Destination $(System.ArtifactsDirectory) -Runtime $runtime + if (-not (Test-Path $(System.ArtifactsDirectory)/TestPackage.zip)) + { + throw "Test Package was not found at: $(System.ArtifactsDirectory)" + } + switch ($runtime) + { + linux-x64 { $packageName = "TestPackage-linux-x64.zip" } + linux-arm { $packageName = "TestPackage-linux-arm.zip" } + linux-arm64 { $packageName = "TestPackage-linux-arm64.zip" } + osx-x64 { $packageName = "TestPackage-macOS.zip" } + linux-musl-x64 { $packageName = "TestPackage-alpine-x64.zip"} + } + Rename-Item $(System.ArtifactsDirectory)/TestPackage.zip $packageName + Copy-Item -Path $(System.ArtifactsDirectory)/$packageName -Destination $(ob_outputDirectory) -Force -Verbose + } + BuildTestPackage -runtime linux-x64 + BuildTestPackage -runtime linux-arm + BuildTestPackage -runtime linux-arm64 + BuildTestPackage -runtime osx-x64 + BuildTestPackage -runtime linux-musl-x64 + displayName: Build test package and upload + retryCountOnTaskFailure: 1 + env: + ob_restore_phase: true + + - pwsh: | + Write-Host "This doesn't do anything but make the build phase run." + displayName: Dummy build task diff --git a/PowerShell-master/.pipelines/templates/uploadToAzure.yml b/PowerShell-master/.pipelines/templates/uploadToAzure.yml new file mode 100644 index 0000000000000000000000000000000000000000..de6f8e0d7fde2f85378cf828a3880904faaddebb --- /dev/null +++ b/PowerShell-master/.pipelines/templates/uploadToAzure.yml @@ -0,0 +1,425 @@ +jobs: +- job: upload_packages + displayName: Upload packages + condition: succeeded() + pool: + type: windows + variables: + - name: ob_sdl_sbom_enabled + value: true + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: DOTNET_NOLOGO + value: 1 + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: false + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: ob_sdl_codeql_compiled_enabled + value: false + - group: 'Azure Blob variable group' + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: no + + - template: /.pipelines/templates/release-SetReleaseTagandContainerName.yml@self + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - pwsh: | + Get-ChildItem Env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: 'Capture Environment Variables' + + - pwsh: | + New-Item -Path '$(Build.ArtifactStagingDirectory)/downloads' -ItemType Directory -Force + displayName: Create downloads directory + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_deb + itemPattern: '**/*.deb' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download deb package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_fxdependent + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux fxd package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_mariner_arm64 + itemPattern: '**/*.rpm' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux mariner arm64 package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_mariner_x64 + itemPattern: '**/*.rpm' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux mariner x64 package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_minSize + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux minSize package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_rpm + itemPattern: '**/*.rpm' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux rpm package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_tar + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux tar package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_tar_alpine + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux alpine tar package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_tar_alpine_fxd + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux alpine fxd tar package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_tar_arm + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux arm32 tar package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_tar_arm64 + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux arm64 tar package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_nupkg_build_nupkg + itemPattern: '**/*.nupkg' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download nupkgs + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_arm64 + itemPattern: | + **/*.msix + **/*.zip + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows arm64 packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_fxdependent + itemPattern: '**/*.zip' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows fxdependent packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_fxdependentWinDesktop + itemPattern: '**/*.zip' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows fxdependentWinDesktop packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_minsize + itemPattern: '**/*.zip' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows minsize packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_x64 + itemPattern: | + **/*.msix + **/*.zip + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows x64 packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_x86 + itemPattern: | + **/*.msix + **/*.zip + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows x86 packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: macos-pkgs + itemPattern: | + **/*.tar.gz + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download macos tar packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_mac_package_sign_package_macos_arm64 + itemPattern: | + **/*.pkg + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download macos arm packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_mac_package_sign_package_macos_x64 + itemPattern: | + **/*.pkg + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download macos x64 packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_msixbundle_CreateMSIXBundle + itemPattern: | + **/*.msixbundle + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download MSIXBundle + + - pwsh: | + Get-ChildItem '$(Build.ArtifactStagingDirectory)/downloads' | Select-Object -ExpandProperty FullName + displayName: 'Capture downloads' + + - pwsh: | + Write-Verbose -Verbose "Copying Github Release files in $(Build.ArtifactStagingDirectory)/downloads to use in Release Pipeline" + + Write-Verbose -Verbose "Creating output directory for GitHub Release files: $(ob_outputDirectory)/GitHubPackages" + New-Item -Path $(ob_outputDirectory)/GitHubPackages -ItemType Directory -Force + Get-ChildItem -Path "$(Build.ArtifactStagingDirectory)/downloads/*" -Recurse | + Where-Object { $_.Extension -notin '.msix', '.nupkg' -and $_.Name -notmatch '-gc'} | + Copy-Item -Destination $(ob_outputDirectory)/GitHubPackages -Recurse -Verbose + + Write-Verbose -Verbose "Creating output directory for NuGet packages: $(ob_outputDirectory)/NuGetPackages" + New-Item -Path $(ob_outputDirectory)/NuGetPackages -ItemType Directory -Force + Get-ChildItem -Path "$(Build.ArtifactStagingDirectory)/downloads/*" -Recurse | + Where-Object { $_.Extension -eq '.nupkg' } | + Copy-Item -Destination $(ob_outputDirectory)/NuGetPackages -Recurse -Verbose + displayName: Copy downloads to Artifacts + + - pwsh: | + # Create output directory for packages which have been uploaded to blob storage + New-Item -Path $(Build.ArtifactStagingDirectory)/uploaded -ItemType Directory -Force + displayName: Create output directory for packages + + - task: AzurePowerShell@5 + displayName: Upload packages to blob + inputs: + azureSubscription: az-blob-cicd-infra + scriptType: inlineScript + azurePowerShellVersion: LatestVersion + pwsh: true + inline: | + $downloadsDirectory = '$(Build.ArtifactStagingDirectory)/downloads' + $uploadedDirectory = '$(Build.ArtifactStagingDirectory)/uploaded' + $storageAccountName = "pscoretestdata" + $containerName = $env:AZUREVERSION + + Write-Verbose -Verbose "Uploading packages to blob storage account: $storageAccountName container: $containerName" + + $context = New-AzStorageContext -StorageAccountName $storageAccountName -UseConnectedAccount + + # Create the blob container if it doesn't exist + $containerExists = Get-AzStorageContainer -Name $containerName -Context $context -ErrorAction SilentlyContinue + if (-not $containerExists) { + $null = New-AzStorageContainer -Name $containerName -Context $context + Write-Host "Blob container $containerName created successfully." + } + + $gcPackages = Get-ChildItem -Path $downloadsDirectory -Filter "powershell*gc.*" + Write-Verbose -Verbose "gc files to upload." + $gcPackages | Write-Verbose -Verbose + $gcContainerName = "$containerName-gc" + # Create the blob container if it doesn't exist + $containerExists = Get-AzStorageContainer -Name $gcContainerName -Context $context -ErrorAction SilentlyContinue + if (-not $containerExists) { + $null = New-AzStorageContainer -Name $gcContainerName -Context $context + Write-Host "Blob container $gcContainerName created successfully." + } + + $gcPackages | ForEach-Object { + $blobName = "${_.Name}" + Write-Verbose -Verbose "Uploading $($_.FullName) to $gcContainerName/$blobName" + $null = Set-AzStorageBlobContent -File $_.FullName -Container $gcContainerName -Blob $blobName -Context $context + # Move to folder to we wont upload again + Move-Item -Path $_.FullName -Destination $uploadedDirectory -Force -Verbose + } + + $nupkgFiles = Get-ChildItem -Path $downloadsDirectory -Filter "*.nupkg" | Where-Object { $_.Name -notlike "powershell*.nupkg" } + + # create a SHA512 checksum file for each nupkg files + + $checksums = $nupkgFiles | + ForEach-Object { + Write-Verbose -Verbose "Generating checksum file for $($_.FullName)" + $packageName = $_.Name + $hash = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash.ToLower() + # the '*' before the packagename signifies it is a binary + "$hash *$packageName" + } + + $checksums | Out-File -FilePath "$downloadsDirectory\SHA512SUMS" -Force + $fileContent = Get-Content -Path "$downloadsDirectory\SHA512SUMS" -Raw | Out-String + Write-Verbose -Verbose -Message $fileContent + + Write-Verbose -Verbose "nupkg files to upload." + $nupkgFiles += (Get-Item "$downloadsDirectory\SHA512SUMS") + $nupkgFiles | Write-Verbose -Verbose + $nugetContainerName = "$containerName-nuget" + # Create the blob container if it doesn't exist + $containerExists = Get-AzStorageContainer -Name $nugetContainerName -Context $context -ErrorAction SilentlyContinue + if (-not $containerExists) { + $null = New-AzStorageContainer -Name $nugetContainerName -Context $context + Write-Host "Blob container $nugetContainerName created successfully." + } + + $nupkgFiles | ForEach-Object { + $blobName = $_.Name + Write-Verbose -Verbose "Uploading $($_.FullName) to $nugetContainerName/$blobName" + $null = Set-AzStorageBlobContent -File $_.FullName -Container $nugetContainerName -Blob $blobName -Context $context + # Move to folder to we wont upload again + Move-Item -Path $_.FullName -Destination $uploadedDirectory -Force -Verbose + } + + $globaltoolFiles = Get-ChildItem -Path $downloadsDirectory -Filter "powershell*.nupkg" + # create a SHA512 checksum file for each nupkg files + + $checksums = $globaltoolFiles | + ForEach-Object { + Write-Verbose -Verbose "Generating checksum file for $($_.FullName)" + $packageName = $_.Name + $hash = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash.ToLower() + # the '*' before the packagename signifies it is a binary + "$hash *$packageName" + } + + New-Item -Path "$downloadsDirectory\globaltool" -ItemType Directory -Force + $checksums | Out-File -FilePath "$downloadsDirectory\globaltool\SHA512SUMS" -Force + $fileContent = Get-Content -Path "$downloadsDirectory\globaltool\SHA512SUMS" -Raw | Out-String + Write-Verbose -Verbose -Message $fileContent + + Write-Verbose -Verbose "globaltool files to upload." + $globaltoolFiles += Get-Item ("$downloadsDirectory\globaltool\SHA512SUMS") + $globaltoolFiles | Write-Verbose -Verbose + $globaltoolContainerName = "$containerName-nuget" + $globaltoolFiles | ForEach-Object { + $blobName = "globaltool/" + $_.Name + $globaltoolContainerName = "$containerName-nuget" + Write-Verbose -Verbose "Uploading $($_.FullName) to $globaltoolContainerName/$blobName" + $null = Set-AzStorageBlobContent -File $_.FullName -Container $globaltoolContainerName -Blob $blobName -Context $context + # Move to folder to we wont upload again + Move-Item -Path $_.FullName -Destination $uploadedDirectory -Force + } + + # To use -Include parameter, we need to use \* to get all files + $privateFiles = Get-ChildItem -Path $downloadsDirectory\* -Include @("*.msix", "*.exe") + Write-Verbose -Verbose "private files to upload." + $privateFiles | Write-Verbose -Verbose + $privateContainerName = "$containerName-private" + # Create the blob container if it doesn't exist + $containerExists = Get-AzStorageContainer -Name $privateContainerName -Context $context -ErrorAction SilentlyContinue + if (-not $containerExists) { + $null = New-AzStorageContainer -Name $privateContainerName -Context $context + Write-Host "Blob container $privateContainerName created successfully." + } + + $privateFiles | ForEach-Object { + $blobName = $_.Name + Write-Verbose -Verbose "Uploading $($_.FullName) to $privateContainerName/$blobName" + $null = Set-AzStorageBlobContent -File $_.FullName -Container $privateContainerName -Blob $blobName -Context $context + # Move to folder to we wont upload again + Move-Item -Path $_.FullName -Destination $uploadedDirectory -Force -Verbose + } + + # To use -Include parameter, we need to use \* to get all files + $files = Get-ChildItem -Path $downloadsDirectory\* -Include @("*.deb", "*.tar.gz", "*.rpm", "*.zip", "*.pkg") + Write-Verbose -Verbose "files to upload." + $files | Write-Verbose -Verbose + + $files | ForEach-Object { + $blobName = $_.Name + Write-Verbose -Verbose "Uploading $($_.FullName) to $containerName/$blobName" + $null = Set-AzStorageBlobContent -File $_.FullName -Container $containerName -Blob $blobName -Context $context + Write-Host "File $blobName uploaded to $containerName container." + Move-Item -Path $_.FullName -Destination $uploadedDirectory -Force -Verbose + } + + $msixbundleFiles = Get-ChildItem -Path $downloadsDirectory -Filter "*.msixbundle" + + $containerName = '$(OutputVersion.AzureVersion)-private' + $storageAccount = '$(StorageAccount)' + + $storageContext = New-AzStorageContext -StorageAccountName $storageAccount -UseConnectedAccount + + if ($msixbundleFiles) { + $bundleFile = $msixbundleFiles[0].FullName + $blobName = $msixbundleFiles[0].Name + + $existing = Get-AzStorageBlob -Container $containerName -Blob $blobName -Context $storageContext -ErrorAction Ignore + if ($existing) { + Write-Verbose -Verbose "MSIX bundle already exists at '$storageAccount/$containerName/$blobName', removing first." + $existing | Remove-AzStorageBlob -ErrorAction Stop -Verbose + } + + Write-Verbose -Verbose "Uploading $bundleFile to $containerName/$blobName" + Set-AzStorageBlobContent -File $bundleFile -Container $containerName -Blob $blobName -Context $storageContext -Force + } else { + throw "MSIXBundle not found in $downloadsDirectory" + } diff --git a/PowerShell-master/.pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml b/PowerShell-master/.pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml new file mode 100644 index 0000000000000000000000000000000000000000..dd67d509a8addb891ca8c379d308c38fe3233a6c --- /dev/null +++ b/PowerShell-master/.pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml @@ -0,0 +1,67 @@ +parameters: + - name: InternalSDKBlobURL + type: string + default: ' ' + - name: ReleaseTagVar + type: string + default: 'fromBranch' + - name: SKIP_SIGNING + type: string + default: 'NO' + - name: ENABLE_MSBUILD_BINLOGS + type: boolean + default: false + - name: FORCE_CODEQL + type: boolean + default: false + +variables: + - name: PS_RELEASE_BUILD + value: 1 + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - name: branchCounterKey + value: $[format('{0:yyyyMMdd}-{1}', pipeline.startTime,variables['Build.SourceBranch'])] + - name: branchCounter + value: $[counter(variables['branchCounterKey'], 1)] + - name: BUILDSECMON_OPT_IN + value: true + - name: __DOTNET_RUNTIME_FEED + value: ${{ parameters.InternalSDKBlobURL }} + - name: LinuxContainerImage + value: mcr.microsoft.com/onebranch/azurelinux/build:3.0 + - name: WindowsContainerImage + value: onebranch.azurecr.io/windows/ltsc2022/vse2022:latest + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] + - name: ReleaseTagVar + value: ${{ parameters.ReleaseTagVar }} + - name: SKIP_SIGNING + value: ${{ parameters.SKIP_SIGNING }} + - group: mscodehub-feed-read-general + - group: mscodehub-feed-read-akv + - name: ENABLE_MSBUILD_BINLOGS + value: ${{ parameters.ENABLE_MSBUILD_BINLOGS }} + - ${{ if eq(parameters['FORCE_CODEQL'],'true') }}: + # Cadence is hours before CodeQL will allow a re-upload of the database + - name: CodeQL.Cadence + value: 1 + - name: CODEQL_ENABLED + ${{ if or(eq(variables['Build.SourceBranch'], 'refs/heads/master'), eq(parameters['FORCE_CODEQL'],'true')) }}: + value: true + ${{ else }}: + value: false + # Fix for BinSkim ICU package error in Linux containers + - name: DOTNET_SYSTEM_GLOBALIZATION_INVARIANT + value: true + # Disable BinSkim at job level to override NonOfficial template defaults + - name: ob_sdl_binskim_enabled + value: false diff --git a/PowerShell-master/.pipelines/templates/variables/PowerShell-Packages-Variables.yml b/PowerShell-master/.pipelines/templates/variables/PowerShell-Packages-Variables.yml new file mode 100644 index 0000000000000000000000000000000000000000..7d1818909b5b9f7c19fcc49dcbc87c29420f4379 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/variables/PowerShell-Packages-Variables.yml @@ -0,0 +1,50 @@ +parameters: + - name: debug + type: boolean + default: false + - name: ForceAzureBlobDelete + type: string + default: 'false' + - name: ReleaseTagVar + type: string + default: 'fromBranch' + - name: disableNetworkIsolation + type: boolean + default: false + +variables: + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] # needed for onebranch.pipeline.version task + - name: system.debug + value: ${{ parameters.debug }} + - name: ENABLE_PRS_DELAYSIGN + value: 1 + - name: ROOT + value: $(Build.SourcesDirectory) + - name: ForceAzureBlobDelete + value: ${{ parameters.ForceAzureBlobDelete }} + - name: NUGET_XMLDOC_MODE + value: none + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - name: ReleaseTagVar + value: ${{ parameters.ReleaseTagVar }} + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: WindowsContainerImage + value: 'onebranch.azurecr.io/windows/ltsc2022/vse2022:latest' # Docker image which is used to build the project + - name: LinuxContainerImage + value: mcr.microsoft.com/onebranch/azurelinux/build:3.0 + - group: mscodehub-feed-read-general + - group: mscodehub-feed-read-akv + - name: branchCounterKey + value: $[format('{0:yyyyMMdd}-{1}', pipeline.startTime,variables['Build.SourceBranch'])] + - name: branchCounter + value: $[counter(variables['branchCounterKey'], 1)] + - group: MSIXSigningProfile + - name: disableNetworkIsolation + value: ${{ parameters.disableNetworkIsolation }} diff --git a/PowerShell-master/.pipelines/templates/variables/PowerShell-Release-Azure-Variables.yml b/PowerShell-master/.pipelines/templates/variables/PowerShell-Release-Azure-Variables.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b47e5eff2b044ef8262536936cb656e6419481d --- /dev/null +++ b/PowerShell-master/.pipelines/templates/variables/PowerShell-Release-Azure-Variables.yml @@ -0,0 +1,35 @@ +parameters: + - name: debug + type: boolean + default: false + +variables: + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] + - name: system.debug + value: ${{ parameters.debug }} + - name: ENABLE_PRS_DELAYSIGN + value: 1 + - name: ROOT + value: $(Build.SourcesDirectory) + - name: REPOROOT + value: $(Build.SourcesDirectory) + - name: OUTPUTROOT + value: $(REPOROOT)\out + - name: NUGET_XMLDOC_MODE + value: none + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\.config\tsaoptions.json + - name: WindowsContainerImage + value: 'onebranch.azurecr.io/windows/ltsc2022/vse2022:latest' + - name: LinuxContainerImage + value: mcr.microsoft.com/onebranch/azurelinux/build:3.0 + - group: PoolNames diff --git a/PowerShell-master/.pipelines/templates/variables/PowerShell-Release-Variables.yml b/PowerShell-master/.pipelines/templates/variables/PowerShell-Release-Variables.yml new file mode 100644 index 0000000000000000000000000000000000000000..930c559eafebbe47198d627344bbc514573bf965 --- /dev/null +++ b/PowerShell-master/.pipelines/templates/variables/PowerShell-Release-Variables.yml @@ -0,0 +1,41 @@ +parameters: + - name: debug + type: boolean + default: false + - name: ReleaseTagVar + type: string + default: 'fromBranch' + +variables: + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] + - name: system.debug + value: ${{ parameters.debug }} + - name: ENABLE_PRS_DELAYSIGN + value: 1 + - name: ROOT + value: $(Build.SourcesDirectory) + - name: REPOROOT + value: $(Build.SourcesDirectory) + - name: OUTPUTROOT + value: $(REPOROOT)\out + - name: NUGET_XMLDOC_MODE + value: none + - name: nugetMultiFeedWarnLevel + value: none + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipNugetSecurityAnalysis + value: true + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: WindowsContainerImage + value: 'onebranch.azurecr.io/windows/ltsc2022/vse2022:latest' + - name: LinuxContainerImage + value: mcr.microsoft.com/onebranch/azurelinux/build:3.0 + - name: ReleaseTagVar + value: ${{ parameters.ReleaseTagVar }} + - group: PoolNames + # Fix for BinSkim ICU package error in Linux containers + - name: DOTNET_SYSTEM_GLOBALIZATION_INVARIANT + value: true diff --git a/PowerShell-master/.pipelines/templates/variables/PowerShell-vPack-Variables.yml b/PowerShell-master/.pipelines/templates/variables/PowerShell-vPack-Variables.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f00a5e0e2a55c745b92cd89e056a60dbfce59ba --- /dev/null +++ b/PowerShell-master/.pipelines/templates/variables/PowerShell-vPack-Variables.yml @@ -0,0 +1,39 @@ +parameters: + - name: debug + type: boolean + default: false + - name: ReleaseTagVar + type: string + default: 'fromBranch' + - name: netiso + type: string + default: 'R1' + +variables: + - name: CDP_DEFINITION_BUILD_COUNT + value: $[counter('', 0)] + - name: system.debug + value: ${{ parameters.debug }} + - name: BuildSolution + value: $(Build.SourcesDirectory)\dirs.proj + - name: BuildConfiguration + value: Release + - name: WindowsContainerImage + value: 'onebranch.azurecr.io/windows/ltsc2022/vse2022:latest' + - name: Codeql.Enabled + value: false # pipeline is not building artifacts; it repackages existing artifacts into a vpack + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + - name: nugetMultiFeedWarnLevel + value: none + - name: ReleaseTagVar + value: ${{ parameters.ReleaseTagVar }} + - group: Azure Blob variable group + - group: certificate_logical_to_actual # used within signing task + - group: DotNetPrivateBuildAccess + - name: netiso + value: ${{ parameters.netiso }} +# We shouldn't be using PATs anymore +# - group: mscodehub-feed-read-general diff --git a/PowerShell-master/.pipelines/templates/variables/release-shared.yml b/PowerShell-master/.pipelines/templates/variables/release-shared.yml new file mode 100644 index 0000000000000000000000000000000000000000..70d3dd2df97af8aa14c43375cf4317495475849f --- /dev/null +++ b/PowerShell-master/.pipelines/templates/variables/release-shared.yml @@ -0,0 +1,40 @@ +parameters: + - name: REPOROOT + type: string + default: $(Build.SourcesDirectory)\PowerShell + - name: SBOM + type: boolean + default: false + - name: RELEASETAG + type: string + default: 'Not Initialized' + - name: VERSION + type: string + default: 'Not Initialized' + +variables: + - name: ob_signing_setup_enabled + value: false + - name: ob_sdl_sbom_enabled + value: ${{ parameters.SBOM }} + - name: DOTNET_NOLOGO + value: 1 + - group: 'mscodehub-code-read-akv' + - group: 'Azure Blob variable group' + - group: 'GitHubTokens' + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: false + - name: ob_sdl_tsa_configFile + value: ${{ parameters.REPOROOT }}\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: ${{ parameters.REPOROOT }}\.config\suppress.json + - name: ob_sdl_codeql_compiled_enabled + value: false + - name: ReleaseTag + value: ${{ parameters.RELEASETAG }} + - name: Version + value: ${{ parameters.VERSION }} diff --git a/PowerShell-master/.pipelines/templates/windows-hosted-build.yml b/PowerShell-master/.pipelines/templates/windows-hosted-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..a2933e90817e1ca3c00ca73306093da48c4231ec --- /dev/null +++ b/PowerShell-master/.pipelines/templates/windows-hosted-build.yml @@ -0,0 +1,323 @@ +parameters: + Architecture: 'x64' + BuildConfiguration: 'release' + JobName: 'build_windows' + +jobs: +- job: build_windows_${{ parameters.Architecture }}_${{ parameters.BuildConfiguration }} + displayName: Build_Windows_${{ parameters.Architecture }}_${{ parameters.BuildConfiguration }} + condition: succeeded() + pool: + type: windows + variables: + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: DOTNET_NOLOGO + value: 1 + - group: DotNetPrivateBuildAccess + - group: certificate_logical_to_actual + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + - name: ob_sdl_codeSignValidation_enabled + value: false + - name: ob_sdl_binskim_enabled + value: true + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)\PowerShell\.config\tsaoptions.json + - name: ob_sdl_credscan_suppressionsFile + value: $(Build.SourcesDirectory)\PowerShell\.config\suppress.json + - name: Architecture + value: ${{ parameters.Architecture }} + - name: BuildConfiguration + value: ${{ parameters.BuildConfiguration }} + - name: ob_sdl_sbom_packageName + value: 'Microsoft.Powershell.Windows.${{ parameters.Architecture }}' + # We add this manually, so we need it disabled the OneBranch auto-injected one. + - name: ob_sdl_codeql_compiled_enabled + value: false + + steps: + - checkout: self + clean: true + env: + ob_restore_phase: true # This ensures checkout is done at the beginning of the restore phase + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: /.pipelines/templates/cloneToOfficialPath.yml@self + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + parameters: + repoRoot: $(PowerShellRoot) + + - task: CodeQL3000Init@0 # Add CodeQL Init task right before your 'Build' step. + condition: eq(variables['CODEQL_ENABLED'], 'true') + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + inputs: + Enabled: true + # AnalyzeInPipeline: false = upload results + # AnalyzeInPipeline: true = do not upload results + AnalyzeInPipeline: false + Language: csharp + + - template: /.pipelines/templates/install-dotnet.yml@self + + - pwsh: | + $runtime = switch ($env:Architecture) + { + "x64" { "win7-x64" } + "x86" { "win7-x86" } + "arm64" { "win-arm64" } + "fxdependent" { "fxdependent" } + "fxdependentWinDesktop" { "fxdependent-win-desktop" } + } + + $params = @{} + if ($env:BuildConfiguration -eq 'minSize') { + $params['ForMinimalSize'] = $true + } + + $vstsCommandString = "vso[task.setvariable variable=Runtime]$runtime" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + + Write-Verbose -Message "Building PowerShell with Runtime: $runtime for '$env:BuildConfiguration' configuration" + Import-Module -Name $(PowerShellRoot)/build.psm1 -Force + $buildWithSymbolsPath = New-Item -ItemType Directory -Path $(Pipeline.Workspace)/Symbols_$(Architecture) -Force + + Start-PSBootstrap -Scenario Package + $null = New-Item -ItemType Directory -Path $buildWithSymbolsPath -Force -Verbose + + $ReleaseTagParam = @{} + + if ($env:RELEASETAGVAR) { + $ReleaseTagParam['ReleaseTag'] = $env:RELEASETAGVAR + } + + Start-PSBuild -Runtime $runtime -Configuration Release -Output $buildWithSymbolsPath -Clean -PSModuleRestore @params @ReleaseTagParam + + $refFolderPath = Join-Path $buildWithSymbolsPath 'ref' + Write-Verbose -Verbose "refFolderPath: $refFolderPath" + $outputPath = Join-Path '$(ob_outputDirectory)' 'psoptions' + $null = New-Item -ItemType Directory -Path $outputPath -Force + $psOptPath = "$outputPath/psoptions.json" + Save-PSOptions -PSOptionsPath $psOptPath + + Write-Verbose -Verbose "Verifying pdbs exist in build folder" + $pdbs = Get-ChildItem -Path $buildWithSymbolsPath -Recurse -Filter *.pdb + if ($pdbs.Count -eq 0) { + Write-Error -Message "No pdbs found in build folder" + } + else { + Write-Verbose -Verbose "Found $($pdbs.Count) pdbs in build folder" + $pdbs | ForEach-Object { + Write-Verbose -Verbose "Pdb: $($_.FullName)" + } + + $pdbs | Compress-Archive -DestinationPath "$(ob_outputDirectory)/symbols.zip" -Update + } + + Write-Verbose -Verbose "Completed building PowerShell for '$env:BuildConfiguration' configuration" + displayName: 'Build Windows Universal - $(Architecture)-$(BuildConfiguration) Symbols folder' + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - pwsh: | + $runtime = switch ($env:Architecture) + { + "x64" { "win7-x64" } + "x86" { "win7-x86" } + "arm64" { "win-arm64" } + "fxdependent" { "fxdependent" } + "fxdependentWinDesktop" { "fxdependent-win-desktop" } + } + + Import-Module -Name $(PowerShellRoot)/build.psm1 -Force + Find-Dotnet + + ## Build global tool + Write-Verbose -Message "Building PowerShell global tool for Windows.x64" -Verbose + $globalToolCsProjDir = Join-Path $(PowerShellRoot) 'src' 'GlobalTools' 'PowerShell.Windows.x64' + Push-Location -Path $globalToolCsProjDir -Verbose + + $globalToolArtifactPath = Join-Path $(Build.SourcesDirectory) 'GlobalTool' + $vstsCommandString = "vso[task.setvariable variable=GlobalToolArtifactPath]${globalToolArtifactPath}" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + + if ($env:RELEASETAGVAR) { + $ReleaseTagToUse = $env:RELEASETAGVAR -Replace '^v' + } + + Write-Verbose -Verbose "Building PowerShell global tool for Windows.x64 with cmdline: dotnet publish --no-self-contained --artifacts-path $globalToolArtifactPath /property:PackageVersion=$(Version) --configuration 'Release' /property:ReleaseTag=$ReleaseTagToUse" + dotnet publish --no-self-contained --artifacts-path $globalToolArtifactPath /property:PackageVersion=$(Version) --configuration 'Release' /property:ReleaseTag=$ReleaseTagToUse + $globalToolBuildModulePath = Join-Path $globalToolArtifactPath 'publish' 'PowerShell.Windows.x64' 'release' + Pop-Location + # do this to ensure everything gets signed. + Restore-PSModuleToBuild -PublishPath $globalToolBuildModulePath + + $buildWithSymbolsPath = Get-Item -Path "$(Pipeline.Workspace)/Symbols_$(Architecture)" + $refFolderPath = Join-Path $buildWithSymbolsPath 'ref' + Write-Verbose -Verbose "refFolderPath: $refFolderPath" + + # Copy reference assemblies + Copy-Item -Path $refFolderPath -Destination $globalToolBuildModulePath -Recurse -Force + + Write-Verbose -Verbose "clean unnecessary files in obj directory" + $objDir = Join-Path $globalToolArtifactPath 'obj' 'PowerShell.Windows.x64' 'release' + + $filesToKeep = @("apphost.exe", "PowerShell.Windows.x64.pdb", "PowerShell.Windows.x64.dll", "project.assets.json") + + # only four files are needed in obj folder for global tool packaging + Get-ChildItem -Path $objDir -File -Recurse | + Where-Object { -not $_.PSIsContainer } | + Where-Object { $_.name -notin $filesToKeep } | + Remove-Item -Verbose + + + displayName: 'Build Winx64 Global tool' + condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) + env: + __DOTNET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - task: CodeQL3000Finalize@0 # Add CodeQL Finalize task right after your 'Build' step. + condition: eq(variables['CODEQL_ENABLED'], 'true') + env: + ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. + + - pwsh: | + $platform = 'windows' + $vstsCommandString = "vso[task.setvariable variable=ArtifactPlatform]$platform" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: Set artifact platform + + - template: /.pipelines/templates/obp-file-signing.yml@self + parameters: + binPath: '$(Pipeline.Workspace)/Symbols_$(Architecture)' + OfficialBuild: $(ps_official_build) + + ## first we sign all the files in the bin folder + - ${{ if eq(variables['Architecture'], 'fxdependent') }}: + - template: /.pipelines/templates/obp-file-signing.yml@self + parameters: + binPath: '$(GlobalToolArtifactPath)/publish/PowerShell.Windows.x64/release' + globalTool: 'true' + OfficialBuild: $(ps_official_build) + + - pwsh: | + Get-ChildItem '$(GlobalToolArtifactPath)/obj/PowerShell.Windows.x64/release' + displayName: Capture obj files + condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) + + ## Now we sign couple of file from the obj folder which are needed for the global tool packaging + - task: onebranch.pipeline.signing@1 + displayName: Sign obj files + inputs: + command: 'sign' + signing_profile: external_distribution + files_to_sign: '**\*.dll;**\*.exe' + search_root: '$(GlobalToolArtifactPath)/obj/PowerShell.Windows.x64/release' + condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) + + - pwsh: | + <# The way the packaging works is a bit tricky as when it is built, we cannot add the modules that come from gallery. + We have to use dotnet pack to build the nupkg and then expand it as a zip. + After expanding we restore the signed files for the modules from the gallery. + We also delete pdbs, content and contentFiles folder which are not necessary. + After that, we repack using Compress-Archive and rename it back to a nupkg. + #> + + Import-Module -Name $(PowerShellRoot)/build.psm1 -Force + Find-Dotnet + + $packagingStrings = Import-PowerShellDataFile "$(PowerShellRoot)\tools\packaging\packaging.strings.psd1" + + $outputPath = Join-Path '$(ob_outputDirectory)' 'globaltool' + $null = New-Item -ItemType Directory -Path $outputPath -Force + $globalToolCsProjDir = Join-Path $(PowerShellRoot) 'src' 'GlobalTools' 'PowerShell.Windows.x64' + Push-Location -Path $globalToolCsProjDir -Verbose + + if ($env:RELASETAGVAR) { + $ReleaseTagToUse = $env:RELASETAGVAR -Replace '^v' + } + + Write-Verbose -Verbose "Packing PowerShell global tool for Windows.x64 with cmdline: dotnet pack --output $outputPath --no-build --artifacts-path '$(GlobalToolArtifactPath)' /property:PackageVersion=$(Version) /property:PackageIcon=Powershell_64.png /property:Version=$(Version) /property:ReleaseTag=$ReleaseTagToUse" + + dotnet pack --output $outputPath --no-build --artifacts-path '$(GlobalToolArtifactPath)' /property:PackageVersion=$(Version) /property:PackageIcon=Powershell_64.png /property:Version=$(Version) /property:ReleaseTag=$ReleaseTagToUse + + Write-Verbose -Verbose "Deleting content and contentFiles folders from the nupkg" + + $nupkgs = Get-ChildItem -Path $outputPath -Filter powershell*.nupkg + + $nupkgName = $nupkgs.Name + $newName = $nupkgName -replace '(\.nupkg)$', '.zip' + Rename-Item -Path $nupkgs.FullName -NewName $newName + + $zipPath = Get-ChildItem -Path $outputPath -Filter powershell*.zip + + # Expand zip and remove content and contentFiles folders + Expand-Archive -Path $zipPath -DestinationPath "$outputPath\temp" -Force + + $modulesToCopy = @( + 'PowerShellGet' + 'PackageManagement' + 'Microsoft.PowerShell.PSResourceGet' + 'Microsoft.PowerShell.Archive' + 'PSReadLine' + 'Microsoft.PowerShell.ThreadJob' + ) + + $sourceModulePath = Join-Path '$(GlobalToolArtifactPath)' 'publish' 'PowerShell.Windows.x64' 'release' 'Modules' + $destModulesPath = Join-Path "$outputPath" 'temp' 'tools' 'net11.0' 'any' 'modules' + + $modulesToCopy | ForEach-Object { + $modulePath = Join-Path $sourceModulePath $_ + Copy-Item -Path $modulePath -Destination $destModulesPath -Recurse -Force + } + + # Copy ref assemblies + Copy-Item '$(Pipeline.Workspace)/Symbols_$(Architecture)/ref' "$outputPath\temp\tools\net11.0\any\ref" -Recurse -Force + + $contentPath = Join-Path "$outputPath\temp" 'content' + $contentFilesPath = Join-Path "$outputPath\temp" 'contentFiles' + + Remove-Item -Path $contentPath,$contentFilesPath -Recurse -Force + + # remove PDBs to reduce the size of the nupkg + Remove-Item -Path "$outputPath\temp\tools\net11.0\any\*.pdb" -Recurse -Force + + # create powershell.config.json + $config = [ordered]@{} + $config.Add("Microsoft.PowerShell:ExecutionPolicy", "RemoteSigned") + $config.Add("WindowsPowerShellCompatibilityModuleDenyList", @("PSScheduledJob", "BestPractices", "UpdateServices")) + + $configPublishPath = Join-Path "$outputPath" 'temp' 'tools' 'net11.0' 'any' "powershell.config.json" + Set-Content -Path $configPublishPath -Value ($config | ConvertTo-Json) -Force -ErrorAction Stop + + Compress-Archive -Path "$outputPath\temp\*" -DestinationPath "$outputPath\$nupkgName" -Force + + Remove-Item -Path "$outputPath\temp" -Recurse -Force + Remove-Item -Path $zipPath -Force + + if (-not (Test-Path "$outputPath\powershell.windows.x64.*.nupkg")) { + throw "Global tool package not found at $outputPath" + } + displayName: 'Pack Windows.x64 global tool' + condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) + + - task: onebranch.pipeline.signing@1 + displayName: Sign nupkg files + inputs: + command: 'sign' + cp_code: 'CP-401405' + files_to_sign: '**\*.nupkg' + search_root: '$(ob_outputDirectory)\globaltool' + condition: and(succeeded(), eq(variables['Architecture'], 'fxdependent')) + + - template: /.pipelines/templates/step/finalize.yml@self diff --git a/PowerShell-master/.prettierrc b/PowerShell-master/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..222861c341540db6785e10c2b6461d5cbc94a6eb --- /dev/null +++ b/PowerShell-master/.prettierrc @@ -0,0 +1,4 @@ +{ + "tabWidth": 2, + "useTabs": false +} diff --git a/PowerShell-master/.spelling b/PowerShell-master/.spelling new file mode 100644 index 0000000000000000000000000000000000000000..cc711f0aa5a4ddf56979c15aff3e9125b7d57daa --- /dev/null +++ b/PowerShell-master/.spelling @@ -0,0 +1,1757 @@ +# markdown-spellcheck spelling configuration file +# Format - lines beginning # are comments +# global dictionary is at the start, file overrides afterwards +# one word per line, to define a file override use ' - filename' +# where filename is relative to this configuration file +-title +0-powershell-crossplatform +0xfeeddeadbeef +100ms +1redone +1.final +2.x +2ae5d07 +32-bit +4.final +64-bit +AAATechGuy +about_ +about_debuggers +about_jobs +about_Telemetry +about_PSDesiredStateConfiguration +acl +adamdriscoll +add-localgroupmember +add-ons +AddType.cs +adelton +adhoc +aditya +adityapatwardhan +ADOPTERS.md +aetos382 +aiello +Aishat452 +al-cheb +alepauly +alexandair +alexjordan6 +alpha.10 +alpha.11 +alpha.12 +alpha.13 +alpha.14 +alpha.15 +alpha.16 +alpha.17 +alpha.18 +alpha.7 +alpha.8 +alpha.9 +alternatestream +alvarodelvalle +amd64 +ananya26-vishnoi +andschwa +anmenaga +api +apis +APIScan +appimage +applocker +appveyor +appx +ArchitectureSensitiveAttribute +args +argumentlist +arm32 +arm64 +asp.net +ast.cs +assemblyloadcontext +AssemblyInfo +assessibility +AtariDreams +authenticode +authenticodesignature +azdevops +AzFileCopy +AzureFileCopy +azurerm.netcore.preview +azurerm.profile.netcore.preview +azurerm.resources.netcore.preview +backgrounded +backgrounding +backport +beatcracker +bergmeister +beta.1 +beta.2 +beta.3 +beta.4 +beta.5 +beta.6 +beta.7 +beta.8 +beta.9 +beta.406 +beta.507 +beta2 +bgelens +Bhaal22 +BinaryFormatter +bjh7242 +bnot +bool +bpayette +brcrista +breakpoint +brianbunke +britishben +brotli +brucepay +bugfix +build.json +build.psm1 +bulid +buildInfoJson +callmejoebob +CarloToso +catchable +cdxml +celsius +CentOS +CimDscParser +codeql-action +CGManifest +cgmanifest.json +cgmanifest +changelog +changelog.md +changelogs +changeset +changesets +channel9 +charltonstanley +charset +checkbox +checksum +chibi +childitem +ChuckieChen945 +ChrisLGardner +chrullrich +cimsession +cimsupport +ci.psm1 +cgmanifest +classlib +clear-itemproperty +cloudydino +cls +cmake +cmd +cmdlet +cmdletproviderclasses +cmdlets +codebase +codecov.io +codecoverage.zip +codefactor +CodeFormatter +codeowner +codepage +commanddiscovery +CommandInvocationIntrinsics +commandsearch +CommandSearcher +comobject +Compiler.cs +composability +computerinfo +ComRuntimeHelpers.cs +config +connect-pssession +consolehost +consolehostrunspaceinit +consolehostuserinterface +consolelineoutput +contenttype +convertfrom-csv +convertfrom-json +convertfrom-sddlstring +convertfrom-securestring +convertfrom-stringdata +convertto-csv +convertto-html +convertto-json +convertto-securestring +convertto-xml +copy-itemproperty +CopyItem.Tests.ps1 +corbob +coreclr +coreconsolehost +corefx +CorePsAssemblyLoadContext.cs +coveralls.exe +coveralls.io. +coveralls.net +CreateFile +CreateFileW +credssp +cron +crontab +crossgen +crossgen'ing +crossplatform +csharp +csmacnz +csphysicallyinstalledmemory +ctrl +CurrentCulture +CustomShellCommands.cs +DamirAinullin +DarylGraves +darquewarrior +darwinjs +DateTime +DateTime.UnixEpoch +daxian-dbw +dayofweek +dchristian3188 +ddwr +debughandler +dee-see +defaultRefAssemblies +dependabot +deps +deserialization +deserialize +deserialized +deserializing +dest +dest.txt +dev +devblackops +devcontainer +deviceguard +devlead +devops +dgoldman-msft +Dictionary.TryAdd +diddledan +disable-localuser +disable-psbreakpoint +disable-pstrace +disable-pswsmancombinedtrace +disable-runspacedebug +disable-wsmantrace +disconnect-pssession +displaydataquery +Distribution_Request.md +distro +distros +dkaszews +dll +DllImport +dlls +dlwyatt +dockerbasedbuild +dockerfile +dockerfiles +learn.microsoft.com +doctordns +don'ts +dongbo +dotcover +dotnet +dotnetcore +dotnetmetadata.json +DotnetRutimeMetadata.json +DotnetRuntimeMetadata.json +dottedscopes +downlevel +dropdown +dwtaber +e.g. +ebook +ebooks +ece-jacob-scott +editorconfig +edyoung +enable-localuser +enable-psbreakpoint +enable-pstrace +enable-pswsmancombinedtrace +enable-runspacedebug +enable-wsmantrace +encodings +endian +enter-pshostprocess +enter-pssession +enum +enums +Environment.NewLine +ergo3114 +errorrecord +etl +eugenesmlv +EventLogLogProvider +excludeversion +exe +executables +executionpolicy +exit-pshostprocess +exit-pssession +export-binarymilog +export-clixml +export-csv +export-formatdata +export-modulemember +fabricbot.json +failurecode +failurecount +farmerau +fbehrens +felixfbecker +ffeldhaus +ffi +fflaten +File.OpenHandle +filecatalog +filename +filesystem +filesystemprovider +files.wxs +filterhashtable +find-dscresource +find-packageprovider +find-rolecapability +findMissingNotices.ps1 +firefox +folderName +foreach +formatfileloading +formatviewbinding +FormatWideCommand +Francisco-Gamino +frontload +fullclr +FunctionInfo +functionprovider +FunctionTable +fxdependent +gabrielsroka +GAC_Arm64 +gamified +gc.regions.xml +Generic.SortedList +get-apachemodule +get-apachevhost +get-childitem +get-cimassociatedinstance +get-cimclass +get-ciminstance +get-computerinfo +get-cronjob +get-eventsubscriber +Get-ExperimentalFeature +get-filehash +get-formatdata +get-installedmodule +get-installedscript +get-itemproperty +get-itempropertyvalue +get-localgroup +get-localgroupmember +get-localuser +get-logproperties +get-packageprovider +get-packagesource +get-psbreakpoint +get-pscallstack +get-pshostprocessinfo +get-psprovider +get-psreadlinekeyhandler +get-psreadlineoption +get-psrepository +get-pssession +get-pssessioncapability +get-runspacedebug +get-systemdjournal +get-typedata +get-uiculture +get-winevent +get-wsmaninstance +Get-WSManSupport +GetExceptionForHR +getparentprocess +gettype +Geweldig +GigaScratch +gitcommitid +github +githug +gitter +glachancecmaisonneuve +global.json +globbing +GoogleTest +gregsdennis +GUIs +gzip +hackathons +HashData +HashSet +hashtable +hashtables +hayhay27 +helloworld.ps1 +helpproviderwithcache +helpproviderwithfullcache +helpsystem +hemant +hemantmahawar +Higinbotham +himura2la +hololens +homebrew +hostifaces +hostname +hotfix +httpbin.org +httpbin's +https +hubuk +hvitved +i3arnon +i.e. +ico +idera +IDictionary +ifdef'ed +iisresetme +ilya +import-binarymilog +import-clixml +import-csv +import-localizeddata +import-packageprovider +import-powershelldatafile +includeide +includeusername +informationrecord +initializers +InitialSessionState.cs +InlineAsTypeCheck +install-packageprovider +IntelliSense +interactivetesting +interop +interoperation +interlocked.read +invoke-cimmethod +Invoke-DSCResource +invoke-restmethod +invoke-wsmanaction +InvokeRestMethodCommand.Common +iot +isazonov +iscore +iscoreclr +isError +isnot +itemtype +itpro +jackdcasey +jameswtruher +Jawz84 +jazzdelightsme +jeffbi +jellyfrog +jen +joandrsn +joeltankam +joeyaiello +jokajak +JohnLBevan +josea +joshuacooper +journalctl +jpsnover +json +jsonconfigfileaccessor +JsonSchema.Net +judgement +jumplist +jwmoss +kanjibates +kasper3 +katacoda +Kellen-Stuart +kevinmarquette +kevinoid +KevRitchie +keyfileparameter +keyhandler +khansen00 +kiazhi +kirkmunro +kittholland +korygill +kpis +krishnayalavarthi +kvprasoon +kwiknick +kwkam +kylesferrazza +labelling +LabhanshAgrawal +lastwritetime +launch.json +ldspits +lee303 +Leonhardt +Libera.Chat +libicu +LibraryImport +libpsl +libpsl-native +libunwind8 +license.rtf +linux +locationglobber +lockdown +loopback +lossless +louistio +LucaFilipozzi +lukexjeremy +lupino3 +lynda.com +lzybkr +m1k0net +M1kep +mababio +macos +macports +maertendmsft +mahawar +mailmap +Markdig.Signed +markdown.yml +manifest.spdx.json +markekraus +marktiedemann +Marusyk +MarvTheRobot +mattifestation +matt9ucci +mcbobke +mcr.microsoft.com +md +meir017 +memberresolution +Menagarishvili +messageanalyzer +metadata +metadata.json +miaromero +michaeltlombardi +microsoft +Microsoft.ApplicationInsights +Microsoft.CodeAnalysis.CSharp +Microsoft.CodeAnalysis.NetAnalyzers +microsoft.com +Microsoft.Management +microsoft.management.infrastructure.cimcmdlets +microsoft.management.infrastructure.native +Microsoft.Management.Infrastructure.Runtime.Win +microsoft.net.test.sdk +microsoft.powershell.archive +Microsoft.PowerShell.Commands +microsoft.powershell.commands.diagnostics +microsoft.powershell.commands.management +microsoft.powershell.commands.utility +microsoft.powershell.consolehost +microsoft.powershell.core +microsoft.powershell.coreclr.assemblyloadcontext +microsoft.powershell.coreclr.eventing +microsoft.powershell.diagnostics +microsoft.powershell.localaccounts +microsoft.powershell.management +microsoft.powershell.markdownrender +microsoft.powershell.psreadline +microsoft.powershell.security +microsoft.powershell.utility +Microsoft.Security.Extensions +Microsoft.WSMan +microsoft.wsman.management +microsoft.wsman.runtime +mikeTWC1984 +mirichmo +mjanko5 +mkdir +mkht +mklement0 +ModuleCmdletBase.cs +MohiTheFish +Molkree +move-itemproperty +ms-psrp +msbuild +msftrncs +mshexpression.cs +mshsnapinloadunload +msi +multiline +multipart +mv +mvps +mwrock +myget +namedpipe +nameof +NameObscurerTelemetryInitializer +namespace +nano +nanoserver +NativeCommandProcessor.cs +NativeCultureResolver +nativeexecution +net5.0 +net10.0 +netcoreapp5.0 +netip.ps1. +netstandard.dll +new-apachevhost +new-ciminstance +new-cimsessionoption +new-cronjob +New-DockerTestBuild +new-guid +new-itemproperty +new-localgroup +new-localuser +new-modulemanifest +new-psrolecapabilityfile +new-pssession +new-pssessionconfigurationfile +new-pssessionoption +new-pstransportoption +new-scriptfileinfo +new-temporaryfile +new-timespan +new-winevent +new-wsmaninstance +new-wsmansessionoption +NextTurn +ngharo +Newtonsoft.Json +NJsonSchema +nohwnd +NoMoreFood +non-22 +non-cim +non-https +non-nullable +non-r2 +noresume +notcontains +nuget +nuget.config +nuget.exe +nugetfeed +Nullable +numberbytes +numberOfPowershellRefAssemblies +nupkg +oauth +object.ReferenceEquals +offthewoll +oising +omi +omnisharp +OneDrive +oneget.org +OneScripter +opencover +opencover.zip +openssh +openssl +opensuse +oss +OutputType +p1 +packagemanagement +PackageVersion +parameshbabu +parameterbinderbase +parameterbindercontroller +parameterbinding +ParenExpression +ParseError.ToString +Path.Join +pathresolution +PathResolvedToMultiple +patochun +patwardhan +paulhigin +pawamoy +payette +perf +perfview +perfview.exe +peter-evans +petseral +PingPathCommand.cs +pinvoke +pinvokes +plaintext +pluggable +pluralsight +poshcode +pougetat +powerbi +powercode +powershell +powershell-unix +powershell.6 +powershell.com +PowerShell.Common.props +powershell.core.instrumentation +powershell.exe +powershell.org +powershellcore +powershellgallery +powershellget +powershellmagazine.com +powershellninja +powershellpr0mpt +powershellproperties +ppadmavilasom +pre-build +pre-compiled +pre-defined +pre-generated +pre-installed +pre-parse +pre-release +pre-releases +pre-requisites +prepend +preprocessor +preview.1 +preview.2 +preview.2.22153.17 +preview.3 +preview.4 +preview.5 +preview.5.20279.10 +preview.5.20278.13 +preview.5.20269.29 +preview.5.20268.9 +preview.5.20272.6 +preview.5.22307.18 +preview.6 +preview.6.20318.15 +preview.6.21355.2 +preview.7 +preview.7.20356.2 +preview.7.20358.6 +preview.7.20364.3 +preview.7.20366.2 +preview.7.20366.15 +preview.7.22377.5 +preview.4.20258.7 +preview.4.20229.10 +preview.4.22252.9 +preview.8 +preview1-24530-04 +preview1.22217.1 +preview7 +ProcessorArchitecture +ProductCode +productversion +program.cs +prototyyppi +providername +proxycommand +ps1 +ps1xml +pscore +pscredential +psd1 +psdrive +psdriveinfo +pseudoparameterbinder +psgallery +PSGalleryModules +psm1 +psobject +psobjects +psoptions.json +psproxyjobs +psreadline +psresourceget +psrp.windows +psscriptanalyzer +pssessionconfiguration +pssnapinloadunload +pssnapins +psversion +psversiontable +PSWindowsPowerShellCompatibility +PublishReadyToRun +pvs-studio +pwd +pwrshplughin.dll +pwsh +pwsh.deps.json +qmfrederik +raghav710 +Random.Shared +RandomNoun7 +RandomNumberGenerator.Fill +raspbian +rc +rc.1 +rc.1.21455.2 +rc.1.21458.32 +rc.2 +rc.2.22477.20 +rc.3 +rc2-24027 +rc3-24011 +rcedit +readme +readme.md +readonly +ReadyToRun +rebase +rebase.yml +rebasing +receive-pssession +recurse +reddit +redhat +redirections +redistributable +redistributables +register-argumentcompleter +register-cimindicationevent +register-engineevent +register-objectevent +register-packagesource +register-psrepository +registryprovider +relationlink +releaseTools.psm1 +RemoteSessionNamedPipe +remotesigned +remoting +remove-ciminstance +remove-cronjob +remove-itemproperty +remove-localgroup +remove-localgroupmember +remove-localuser +remove-psbreakpoint +remove-psreadlinekeyhandler +remove-pssession +remove-typedata +remove-wsmaninstance +rename-itemproperty +rename-localgroup +rename-localuser +renehernandez +reparse +replicaJunction +repo +reportgenerator +resgen +responseheaders +REST +rest.ps1 +restart-apachehttpserver +resx +Rethrow +reynoldsbd +richardszalay +Rin +rjmholt +rkeithhill +rkitover +robo210 +ronn +rpalo +rpolley +runas +runspace +runspaceinit +runspaces +runtime +runtimes +Ryan-Hutchison-USAF +SA1026CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation +Saancreed +SafeRegistryHandle +sample-dotnet1 +sample-dotnet2 +sarithsutha +sarthakmalik +savehelp +sazonov +sba923 +schvartzman +schwartzmeyer +scriptblock +securestring +seemethere +select-xml +SemanticChecks +semver +serverless +sessionid +sessionstate +sessionstatecontainer +sessionstateitem +set-ciminstance +set-itemproperty +set-localgroup +set-localuser +set-logproperties +set-packagesource +set-psbreakpoint +set-psdebug +set-psreadlinekeyhandler +set-psreadlineoption +set-psrepository +set-strictmode +set-wsmaninstance +set-wsmanquickconfig +sethvs +setversionvariables +sha256 +ShaydeNofziger +shellexecute +shouldbeerrorid +showcommandinfo +Shriram0908 +silijon +simonwahlin +singleline +sles15 +smes +snapcraft +snapin +snover +sometext +SortedList +source.txt +spongemike2 +src +ss64.com +st0le +stackoverflow +stanzilla +start-codecoveragerun +start-pspester +stdin +stevel-msft +StevenLiekens +stevend811 +stknohg +strawgate +streamdescribecifeaturescenariodescribecontextitcontextcontextbeforeallafterallbeforeeachaftereachshould +StrictMode +string.split +stringbuilder +stuntguy3000 +StyleCop +subfolder +submodule +submodules +sudo +superproject +svg +swarfegagit +SwitchParameter +sxs +sydneyhsmith +symlink +symlinks +syscall +syslog +System.IO.Packaging +System.InvalidOperationException +system.manage +system.management.automation +System.Management.Automation.utils +systemd +SytzeAndr +tabcompletion +tadas +tandasat +tasnimzotder +TargetFramework +test-modulemanifest +test-pssessionconfigurationfile +test-scriptfileinfo +tar.gz +test.ps1 +test.txt. +Tests.ps1 +test1.txt +test2.txt +testcase +testdrive +TestPathCommand.cs +tests.zip +tgz +theflyingcorpse +thenewstellw +thezim +thlac +ThomasNieto +threadjob +ThreadStatic +throttlelimit +throw-testcasesitmockdescribe +ThrowExceptionForHR +timcurwick +timestamp +timothywlewis +TKey +tobias +tokenizer.cs +tokenizing +tomconte +tommymaynard +toolchain +toolset +tracesource +travisez13 +travisty +trossr32 +truher +TSAUpload +turbedi +TValue +tylerleonhardt +typecataloggen +typeconversion +typegen +typematch +t_ +ubuntu +ubuntu22.04 +uint +un-versioned +unicode +UnixSocket +unregister-event +unregister-packagesource +unregister-psrepository +unregister-pssessionconfiguration +unregistering +untracked +unvalidated +UpdateDotnetRuntime.ps1 +update-formatdata +update-modulemanifest +update-scriptfileinfo +update-typedata +uri +urizen-source +urls +UseMU +userdata +uservoice +utf-8 +utf8 +utf8nobom +utils +utils.cs +v0.1.0 +v0.2.0 +v0.3.0 +v0.4.0 +v0.5.0 +v0.6.0 +v141 +v2 +v3 +v4 +v5 +v5.0 +v6 +v6.0. +v6.0.0 +v6.0.1 +v6.0.2 +v6.0.4 +v6.0.5 +v6.1.0 +v6.1.1 +v6.1.2 +v6.2.0 +v6.2.1 +v6.2.2 +v6.2.3 +v6.2.4 +v7.0.0 +v7.0.3 +v7.0.4 +v7.0.9 +v7.1.0 +v7.1.6 +v7.1.7 +v7.2.2 +v7.2.6 +v7.3.0 +v7.4.0 +v7.0.12 +v7.0.13 +validatenotnullorempty +ValidateSet +varunsh-coder +versioned +versioning +vexx32 +Virtualization +visualstudio +vmsilvamolina +vorobev +vors +vpondala +vscode +vstsbuild.ps1 +walkthrough +webcmdlets +weblistener +webrequest +webrequestpscmdlet.common.cs +webresponseobject.common +weltner +wesholton84 +wget +whitespace +wildcard +wildcarded +wildcards +win32 +win32-openssh +win7 +win8 +windos +windows.json +windowspsmodulepath +windowsversion +winrm +wix +wmentha +WNetGetConnection +WNetAddConnection2 +worrenb +wpr +wprui.exe +writingpestertests.md +wsl +wsman +wsmancredssp +wsmansessionoption.cs +www.github.com +x64 +x86 +xpath +xtqqczze +xunit +xunit.runner.visualstudio +Xunit.SkippableFact +yaml +yashrajbharti +yecril71pl +yml +youtube +Youssef1313 +Yulv-git +zackjknight +ComInterop +ryneandal +runtime#33060 +vexx32 +perf +britishben +felixfbecker +vpondala +dependabot +jellyfrog +1redone +tommymaynard +vmsilvamolina +fbehrens +lockdown +lukexjeremy +deserializing +kiazhi +v6.1.2 +Menagarishvili +anmenaga +fxdependent +sba923 +replicaJunction +lupino3 +hvitved +unvalidated +Geweldig +mjanko5 +v7.0.0 +v7.0.10 +renehernandez +ece-jacob-scott +st0le +MohiTheFish +CodeFormatter +StyleCop +SytzeAndr +yashrajbharti +Leonhardt +tylerleonhardt +nuget.config +libmi +rpms +authenticode +env +MarianoAlipi +Microsoft.PowerShell.Native +davidBar-On +parameterized +misconfigured +hez2010 +ZhiZe-ZG +SecureStringHelper.FromPlainTextString +ProcessBaseCommand.AllProcesses +Parser.cs +MultipleServiceCommandBase.AllServices +JustinGrote +Newtonsoft.Json +minSize +WGs +wg-definitions +thejasonhelmick +winps +componentization +CimCmdlets +Microsoft.PowerShell.Host +PSDiagnostics +nightlies +wg +Visio +triaged +lifecycle +v2.0.5 +mutex +gukoff +dinhngtu +globbed +octos4murai +PSCommand +System.Management.Automation.ICommandRuntime +AppDomain.CreateDomain +AppDomain.Unload +ProcessModule.FileName +Environment.ProcessPath +PSUtils.GetMainModule +schuelermine +SupportsShouldProcess +Start-PSBootstrap +DotnetMetadataRuntime.json +deps.json +Jaykul +eltociear +consolehost.proto +IDisposable +ConvertToJsonCommand +CommandPathSearch +UseCoalesceExpression +UseSystemHashCode +UseCoalesceExpressionForNullable +substring +RemoveAll +MakeFieldReadonly +Microsoft.Management.UI.Internal +StringComparison +osx-arm64 +crossgen2 +MartinGC94 +BrannenGH +SergeyZalyadeev +KiwiThePoodle +Thomas-Yu +cgmanifest.json +mcr.microsoft.com +global.json +tar.gz +psoptions.json +manifest.spdx.json +buildinfo +SKUs +vmImage +InternalCommands.cs +CommonCommandParameters.cs +preview.6.22352.1 +v2.2.6 +ResultsComparer +pre-defined +System.Runtime.CompilerServices.Unsafe +TabExpansion +PSv2 +System.Data.SqlClient +Microsoft.CSharp +v7.2.10 +7.2.x +v7.3.3 +http +webcmdlet +argumentexception.throwifnullorempty +bitconverter.tostring +convert.tohexstring +requires.notnullorempty +argumentoutofrangeexception.throwifnegativeorzero +callerargumentexpression +requires.notnull +argumentnullexception +throwifnull +process.cs +setrequestcontent +streamhelper.cs +invokerestmethodcommand.common.cs +gethttpmethod +httpmethod +removenulls +notnull +argumentnullexception.throwifnull +disable_telemetry +langversion +microsoft.extensions.objectpool +microsoft.codeanalysis.analyzers +benchmarkdotnet +winforms +MicrosoftDocs +about_Scripts +debugging-from-commandline +about_Object_Creation +about_Functions_Advanced +Microsoft.PowerShell.SDK +NuGet.org. + - CHANGELOG.md +aavdberg +asrosent +azkarmoulana +chucklu +Claustn +CVE-2018-8256 +CVE-2018-8415 +daviddreher2 +honour +iGotenz +jeis2497052 +Jocapear +lassehastrup +markwragg +nbkalex +NeoBeum +nycjan +paalbra +robdy +SeeminglyScience +StingyJack +ThreeFive-O +tobvil +uninstallation +vongrippen +yurko7 +zhenggu +davinci26 +vedhasp +SeeminglyScience +eugenesmlv +steviecoaster +machgo +derek-xia +weltkante +kilasuit +tnieto88 +Orca88 +OrderBy +centreboard +romero126 +Greg-Smulko +danstur +vdamewood +MJECloud +DamirAinullin +NoMoreFood +silijon +NextTurn +mikeTWC1984 +Marusyk +M1kep +doctordns +alvarodelvalle +devlead +RandomNoun7 +edyoung +stevend811 +LabhanshAgrawal +ShaydeNofziger +alepauly +bpayette +joeltankam +OneScripter +Francisco-Gamino +adamdriscoll +analytics +deserialized +string.Join +string.Split +StringSplitOptions.TrimEntries +Dictionary.TryAdd +Environment.NewLine +ParseError.ToString +EditorConfig +GetExceptionForHR +ThrowExceptionForHR +Get-ExperimentalFeature +PSWindowsPowerShellCompatibility +currentculture +NJsonSchema +Microsoft.CodeAnalysis.CSharp +NJsonSchema +StrictMode +devcontainer +AzFileCopy +metadata.json +ADOPTERS.md +powershell.exe +SetVersionVariables +yml +DateTime +DeploymentScripts +GetValues +GetNames +SessionStateStrings +Enum.HasFlags +ConsoleInfoErrorStrings.resx +ContentHelper.Common.cs +FusionAssemblyIdentity +GlobalAssemblyCache +StringManipulationHelper +testexe.exe +echocmdline +MemoryExtensions.IndexOfAny +PSv2CompletionCompleter +RemoteRunspacePoolInternal.cs +PSVersionInfo +WildcardPattern +UTF8Encoding +PowerShell.Core.Instrumentation.man +Encoding.Default +WinTrust +System.Runtime.CompilerServices.Unsafe +azCopy +APISets +ApiScan +System.Data.SqlClient +minimatch +2.final +SessionStateInternal +Microsoft.PowerShell.SDK +Markdig.Signed + - docs/debugging/README.md +corehost + - docs/learning-powershell/README.md +PSKoans + - docs/testing-guidelines/CodeCoverageAnalysis.md +de5f69c + - docs/testing-guidelines/TestRoadmap.md +_no_ + - docs/testing-guidelines/WritingPesterTests.md +nGet-ContentOut-String +nGet-MultiLineString +PSDefaultParameterValues-skip +ShouldShouldIt + - tools/performance/README.md +Invoke-PerfviewPS +JIT.Regions.xml +PowerShell.Regions.xml +PowerShell.stacktags +PowerShell.wpaProfile +PowerShell.wprp +wpa +wpaProfile + - demos/WindowsPowerShellModules/README.md +2.x. + - CHANGELOG/7.1.md +ThomasNieto +spongemike2 +davidseibel +HumanEquivalentUnit +hemisphera +tamasvajk +boolean +bitwise +StringUtil +StringUtil.Format +CommandLineParameterParser +jackerr3 +preview.8.20407.11 +pre-check +davidreis97 +soccypowa +nologo +InstallLocation +PkgES +Microsoft.PowerShell.Native +rtm.20526.5 +ini +package.json +jcotton42 +RPMs +PSDesiredStateConfiguration +dotnet5 + - CHANGELOG/7.2.md +Gimly +jborean93 +mkswd +PatLeong +paul-cheung +georgettica +ProcessId +CurrentManagedThreadId +System.Environment +LongCount +nullable +Guid +accessor +CancellationToken +struct +IsEmpty +StringBuilder.Append +String.Concat +String.Substring +NoLanguage +kyanha +accessors +matthewjdegarmo +Reset-PWSHSystemPath +StyleCop.Analyzers +UseIsNullCheck +ConvertTypeOfToNameOf +usings +PriorityAttribute +System.Management.Automation.Interpreter.IBoxableInstruction +System.Management.Automation.Provider.IDynamicPropertyProvider +System.Management.Automation.Language.IScriptExtent +System.Management.Automation.Language.ICustomAstVisitor2 +System.Management.Automation.LanguagePrimitives.IConversionData +System.Automation.Remoting.Client.IWSManNativeApiFacade +System.Management.Automation.Language.ISupportsAssignment +System.Management.Automation.ICommandRuntime2 +System.Management.Automation.IOutputProcessingState +System.Management.Automation.IJobDebugger +System.Management.Automation.Interpreter.IInstructionProvider +System.Management.Automation.IHasSessionStateEntryVisibility +System.Management.Automation.Tracing.IEtwEventCorrelator +AclCommands +System.Management.Automation.Language.IAstPostVisitHandler +System.Management.Automation.IModuleAssemblyInitializer +nuget.org +GetFiles +TestModuleManifestCommand +System.Management.Automation.Provider.IContentWriter +TranscriptionOption.FlushContentToDisk +structs +System.Management.Automation.IArgumentCompleter +GetDirectories +System.Management.Automation.Host.IHostSupportsInteractiveSession +System.Management.Automation.Provider.IPropertyCmdletProvider +SimplifyConditionalExpression +MarkdownLint +AsSpan +AsMemory +xml +finalizer +finalizers +const +UseAutoProperty +SuppressFinalize +string.Empty +LoadBinaryModule +GetListOfFilesFromData +RPMs +NullableAttribute +PSDesiredStateConfiguration +brianary +Fs00 +MartinGC94 +jakekerr +strikethrough +string.Contains +imba-tjd +url +ArrayList +SDKs +XunitXml.TestLogger +Backport +v7.1.1 +about_PSDesiredStateConfiguration +hbuckle +preview.2.21155.3 +3.final +codesign +powershell.config.json +romero126 +boolean +rtm.20526.5 +dbaileyut +un-localized +awakecoding +bcwood +ThrowTerminatingError +DoesNotReturn +GetValueOrDefault +PSLanguageMode +adamsitnik +msixbundle +PowerShell-Native#70 +AppxManifest.xml +preview.9 +preview.10 +ArmaanMcleod +entrypoint +lselden +SethFalco +CodeQL +slowy07 +rc.2.21505.57 +ThirdPartyNotices +ThirdPartyNotices.txt +cgmanifest.json +buildinfo +tar.gz +psoptions.json +manifest.spdx.json +vPack +kondratyev-nv +v7.2.0 +v7.2.3 +cgmanifest.json +pwsh.exe +6.0.100-rtm.21527.11 +6.0.100-rc.2.21505.57 +ThirdPartyNotices.txt +rtm.21527.11 +SKUs +vmImage +Ubuntu22.04 + - CHANGELOG/7.0.md +codesign +release-BuildJson +yml +dotnet5 +buildinfo +SKUs +CGManifest +vmImage +ci.psm1 +centos-7 +PSDesiredStateConfiguration +NoLanguage +createdump +vPack +PkgES + - test/perf/benchmarks/README.md +benchmarked +BenchmarkDotNet + - docs/community/working-group-definitions.md +gaelcolas +jdhitsolutions +jhoneill +kilasuit +michaeltlombardi +SeeminglyScience +TobiasPSP + - CHANGELOG/7.3.md +ayousuf23 +AzCopy.exe +hammy3502 +PowerShellExecutionHelper.cs +ClientRemotePowerShell +DOTNET_ROOT +SkipExperimentalFeatureGeneration +AzCopy +Start-PSBootStrap +precheck +SKUs +powershell.config.json +Microsoft.PowerShell.GlobalTool.Shim.csproj +InvokeCommand +UseDotNet +vmImage +NoLanguage +GetValueOrDefault +kondratyev-nv +penimc_cor3.dll +PkgES +v7.2.0 +preview.9 +pwsh.exe +XunitXml.TestLogger +rtm.21527.11 +ThirdPartyNotices.txt +buildinfo +tar.gz +rc.2.21505.57 +psoptions.json +manifest.spdx.json +AzureFileCopy +vPack +dotnet5 +buildinfo +SKUs +CGManifest +vmImage +ci.psm1 +jcotton42 +centos-7 +Security.types.ps1xml +optout + - ADOPTERS.md +MicrosoftPowerBIMgmt + - tools/clearlyDefined/readme.md +ClearlyDefined + - CHANGELOG/preview.md +stevenebutler +spaette +syntax-tm +URIs +typeDataXmlLoader.cs +GetResponseObject +ContentHelper +BasicHtmlWebResponseObject +WebRequestSession.cs +dkattan +preview.3.23178.7 +PoolNames +techguy16 +sdwheeler +MicrosoftDocs +about_Scripts +about_Object_Creation +about_Functions_Advanced +Microsoft.PowerShell.SDK +NuGet.org. diff --git a/PowerShell-master/.vscode/extensions.json b/PowerShell-master/.vscode/extensions.json new file mode 100644 index 0000000000000000000000000000000000000000..fa227cd9944557b2a49d2718d69a9ad0ac8ad7ae --- /dev/null +++ b/PowerShell-master/.vscode/extensions.json @@ -0,0 +1,14 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "editorconfig.editorconfig", + "ms-azure-devops.azure-pipelines", + "ms-vscode.cpptools", + "ms-dotnettools.csharp", + "ms-vscode.PowerShell", + "twxs.cmake", + "DavidAnson.vscode-markdownlint", + "vitaliymaz.vscode-svg-previewer" + ] +} diff --git a/PowerShell-master/.vscode/launch.json b/PowerShell-master/.vscode/launch.json new file mode 100644 index 0000000000000000000000000000000000000000..4ba261df08cd0f07959baf1aa229016684fd7bb7 --- /dev/null +++ b/PowerShell-master/.vscode/launch.json @@ -0,0 +1,41 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch", + "type": "coreclr", + "request": "launch", + "justMyCode": false, + "stopAtEntry": true, + "program": "${workspaceRoot}/debug/pwsh", + "preLaunchTask": "Build", + "externalConsole": true, + "cwd": "${workspaceRoot}" + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "justMyCode": false, + "processId": "${command:pickProcess}" + }, + { + "type": "PowerShell", + "request": "launch", + "name": "PowerShell Launch Current File", + "script": "${file}", + "args": [], + "cwd": "${file}" + }, + { + "type": "PowerShell", + "request": "launch", + "name": "PowerShell Launch Current File w/Args Prompt", + "script": "${file}", + "args": [ + "${command:SpecifyScriptArgs}" + ], + "cwd": "${file}" + } + ] +} diff --git a/PowerShell-master/.vscode/settings.json b/PowerShell-master/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..ad298823d1037b90ee5134081c190b5dd7bc4d8f --- /dev/null +++ b/PowerShell-master/.vscode/settings.json @@ -0,0 +1,40 @@ +// Place your settings in this file to overwrite default and user settings. +{ + "editor.tabSize": 4, + "editor.insertSpaces": true, + + "files.insertFinalNewline": true, + + // Based on current .markdownlist.json settings: + // https://github.com/PowerShell/PowerShell/blob/master/.markdownlint.json + "markdownlint.config": { + "MD004": false, + "MD024": false, + "MD033": false, + "MD034": false, + "MD038": false, + "MD042": false + }, + + "[powershell]": { + "files.trimTrailingWhitespace": true + }, + + // Sets the codeformatting options to follow the given indent style in a way that is compatible with PowerShell syntax. For more information about the brace styles please refer to https://github.com/PoshCode/PowerShellPracticeAndStyle/issues/81. + "powershell.codeFormatting.preset": "OTBS", + + // Adds a space between a keyword and its associated scriptblock expression. + "powershell.codeFormatting.whitespaceBeforeOpenBrace": true, + + // Adds a space between a keyword (if, elseif, while, switch, etc) and its associated conditional expression. + "powershell.codeFormatting.whitespaceBeforeOpenParen": true, + + // Adds spaces before and after an operator ('=', '+', '-', etc.). + "powershell.codeFormatting.whitespaceAroundOperator": true, + + // Adds a space after a separator (',' and ';'). + "powershell.codeFormatting.whitespaceAfterSeparator": true, + + // Omnisharp : Enable EditorConfig support + "omnisharp.enableEditorConfigSupport": true +} diff --git a/PowerShell-master/.vscode/tasks.json b/PowerShell-master/.vscode/tasks.json new file mode 100644 index 0000000000000000000000000000000000000000..b92aaddeb0d619f4b584453d490aecd8f0047a44 --- /dev/null +++ b/PowerShell-master/.vscode/tasks.json @@ -0,0 +1,64 @@ +{ + "version": "2.0.0", + + "windows": { + "options": { + "shell": { + "executable": "pwsh.exe", + "args": [ + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-Command" + ] + } + } + }, + "linux": { + "options": { + "shell": { + "executable": "/usr/bin/pwsh", + "args": [ + "-NoProfile", + "-Command" + ] + } + } + }, + "osx": { + "options": { + "shell": { + "executable": "/usr/local/bin/pwsh", + "args": [ + "-NoProfile", + "-Command" + ] + } + } + }, + + "tasks": [ + { + "label": "Bootstrap", + "type": "shell", + "command": "Import-Module '${workspaceFolder}/build.psm1'; Start-PSBootstrap", + "problemMatcher": [] + }, + { + "label": "Clean Build", + "type": "shell", + "command": "Import-Module '${workspaceFolder}/build.psm1'; Start-PSBuild -Clean -Output (Join-Path '${workspaceFolder}' debug)", + "problemMatcher": "$msCompile" + }, + { + "label": "Build", + "type": "shell", + "command": "Import-Module '${workspaceFolder}/build.psm1'; Start-PSBuild -Output (Join-Path '${workspaceFolder}' debug)", + "group": { + "kind": "build", + "isDefault": true + }, + "problemMatcher": "$msCompile" + } + ] +} diff --git a/PowerShell-master/.vsts-ci/install-ps.yml b/PowerShell-master/.vsts-ci/install-ps.yml new file mode 100644 index 0000000000000000000000000000000000000000..7190e2285785d153b8defd67d8e0744b41e1c8fc --- /dev/null +++ b/PowerShell-master/.vsts-ci/install-ps.yml @@ -0,0 +1,161 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - /tools/install-powershell.* + - /tools/installpsh-*.sh + - /.vsts-ci/install-ps.yml +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - /tools/install-powershell.sh + - /tools/installpsh-*.sh + - /tools/install-powershell.ps1 + - /.vsts-ci/install-ps.yml + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + +resources: +- repo: self + clean: true +phases: +- template: templates/install-ps-phase.yml + parameters: + scriptName: sudo ./tools/install-powershell.sh + jobName: InstallPowerShellUbuntu + pool: ubuntu-latest + verification: | + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + +- template: templates/install-ps-phase.yml + parameters: + scriptName: sudo ./tools/install-powershell.sh + jobName: InstallPowerShellMariner2 + pool: ubuntu-latest + container: mcr.microsoft.com/powershell/test-deps:mariner-2.0 + verification: | + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + +- template: templates/install-ps-phase.yml + parameters: + scriptName: sudo ./tools/install-powershell.sh + jobName: InstallPowerShellAmazonLinux + pool: ubuntu-latest + container: pshorg/powershellcommunity-test-deps:amazonlinux-2.0 + verification: | + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + +- template: templates/install-ps-phase.yml + parameters: + scriptName: sudo ./tools/installpsh-amazonlinux.sh + jobName: InstallPSHAmazonLinux + pool: ubuntu-latest + container: pshorg/powershellcommunity-test-deps:amazonlinux-2.0 + verification: | + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + continueOnError: false + +# TODO: add sudo to script and use image with sudo +- template: templates/install-ps-phase.yml + parameters: + scriptName: ./tools/install-powershell.sh + jobName: InstallPowerShellCentOS + pool: ubuntu-latest + container: mcr.microsoft.com/powershell/test-deps:centos-7 + +- template: templates/install-ps-phase.yml + parameters: + scriptName: ./tools/install-powershell.sh + jobName: InstallPowerShellDebian9 + pool: ubuntu-latest + container: mcr.microsoft.com/powershell/test-deps:debian-9 + + +# VSTS could not find pwsh in: +# mcr.microsoft.com/powershell:opensuse-42.3 +# could not repo locally + +# sudo is not needed on macOS +- template: templates/install-ps-phase.yml + parameters: + scriptName: ./tools/install-powershell.sh + jobName: InstallPowerShellMacOS + pool: macOS-latest + verification: | + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + # The script does not upgrade on mac os https://github.com/PowerShell/PowerShell/issues/9322 + Write-Warning "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + +- template: templates/install-ps-phase.yml + parameters: + scriptName: pwsh -c ./tools/install-powershell.ps1 -AddToPath + jobName: InstallPowerShellPS1Ubuntu + pool: ubuntu-latest + +- template: templates/install-ps-phase.yml + parameters: + scriptName: pwsh -c ./tools/install-powershell.ps1 -AddToPath -Daily + jobName: InstallPowerShellPS1UbuntuDaily + pool: ubuntu-latest + verification: | + Write-Verbose $PSVersionTable.PSVersion -verbose + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + +- template: templates/install-ps-phase.yml + parameters: + scriptName: pwsh -c ./tools/install-powershell.ps1 -AddToPath -Daily + jobName: InstallPowerShellMacOSDaily + pool: macOS-latest + verification: | + Write-Verbose $PSVersionTable.PSVersion -verbose + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.0.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + +- template: templates/install-ps-phase.yml + parameters: + scriptName: | + pwsh -c ./tools/install-powershell.ps1 -AddToPath -Daily + jobName: InstallPowerShellWindowsDaily + pool: windows-latest + verification: | + $newVersion = &$env:LOCALAPPDATA\Microsoft\powershell-daily\pwsh -v + $newVersion -match '^PowerShell ((\d*\.\d*\.\d*)(-\w*(\.\d*)?)?){1}' + $versionOnly = $Matches[2] + Write-verbose "$newVersion; versionOnly: $versionOnly" -verbose + if ([Version]$versionOnly -lt [version]"7.0.0") + { + throw "powershell was not upgraded: $newVersion" + } diff --git a/PowerShell-master/.vsts-ci/linux-daily.yml b/PowerShell-master/.vsts-ci/linux-daily.yml new file mode 100644 index 0000000000000000000000000000000000000000..10effadd1e32c153899ee00b7d217dbd5180cb77 --- /dev/null +++ b/PowerShell-master/.vsts-ci/linux-daily.yml @@ -0,0 +1,149 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - /.vsts-ci/misc-analysis.yml + - /.github/ISSUE_TEMPLATE/* + - /.dependabot/config.yml +pr: + branches: + include: + - master + paths: + include: + - .vsts-ci/linux-daily.yml + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + __SuppressAnsiEscapeSequences: 1 + +resources: +- repo: self + clean: true + +stages: +- stage: BuildLinux + displayName: Build for Linux + jobs: + - template: templates/ci-build.yml + parameters: + pool: ubuntu-20.04 + jobName: linux_build + displayName: linux Build + +- stage: TestLinux + displayName: Test for Linux + jobs: + - job: linux_test + timeoutInMinutes: 90 + pool: + vmImage: ubuntu-20.04 + displayName: Linux Test + + steps: + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - task: DownloadBuildArtifacts@0 + displayName: 'Download Build Artifacts' + inputs: + downloadType: specific + itemPattern: | + build/**/* + xunit/**/* + downloadPath: '$(System.ArtifactsDirectory)' + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture Artifacts Directory' + continueOnError: true + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\build.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + $output = (Get-PSOptions).Output + $rootPath = Split-Path (Split-Path $output) + Expand-Archive -Path '$(System.ArtifactsDirectory)\build\build.zip' -DestinationPath $rootPath -Force + + ## Fix permissions + Get-ChildItem $rootPath -Recurse | ForEach-Object { + if ($_ -is [System.IO.DirectoryInfo]) { + chmod +rwx $_.FullName + } else { + chmod +rw $_.FullName + } + } + chmod a+x $output + + Write-Host "=== Capture Unzipped Directory ===" + Get-ChildItem $rootPath -Recurse + displayName: 'Unzip Build and Fix Permissions' + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose UnelevatedPesterTests -TagSet CI + displayName: Test - UnelevatedPesterTests - CI + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose ElevatedPesterTests -TagSet CI + displayName: Test - ElevatedPesterTests - CI + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose UnelevatedPesterTests -TagSet Others + displayName: Test - UnelevatedPesterTests - Others + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose ElevatedPesterTests -TagSet Others + displayName: Test - ElevatedPesterTests - Others + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\build.psm1 + $xUnitTestResultsFile = "$(System.ArtifactsDirectory)\xunit\xUnitTestResults.xml" + Test-XUnitTestResults -TestResultsFile $xUnitTestResultsFile + displayName: Verify xUnit Test Results + condition: succeededOrFailed() + +- stage: CodeCovTestPackage + displayName: CodeCoverage and Test Packages + dependsOn: [] # by specifying an empty array, this stage doesn't depend on the stage before it + jobs: + - job: CodeCovTestPackage + displayName: CodeCoverage and Test Packages + pool: + vmImage: ubuntu-20.04 + steps: + - pwsh: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + displayName: CodeCoverage and Test Package diff --git a/PowerShell-master/.vsts-ci/linux-internal.yml b/PowerShell-master/.vsts-ci/linux-internal.yml new file mode 100644 index 0000000000000000000000000000000000000000..b90ab0d9eb4ea84319ff7fe1f9f1bd3d4b70cd5e --- /dev/null +++ b/PowerShell-master/.vsts-ci/linux-internal.yml @@ -0,0 +1,115 @@ +# Pipeline to run Linux CI internally +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - .pipelines/* + - test/perf/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .dependabot/config.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .vsts-ci/misc-analysis.yml + - .vsts-ci/windows.yml + - .vsts-ci/windows/* + - tools/cgmanifest/* + - LICENSE.txt + - test/common/markdown/* + - test/perf/* + - tools/releaseBuild/* + - tools/install* + - tools/releaseBuild/azureDevOps/templates/* + - README.md + - .spelling + - .pipelines/* + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + +resources: + repositories: + - repository: Docker + type: github + endpoint: PowerShell + name: PowerShell/PowerShell-Docker + ref: master + +stages: +- stage: BuildLinuxStage + displayName: Build for Linux + jobs: + - template: templates/ci-build.yml + parameters: + pool: ubuntu-20.04 + jobName: linux_build + displayName: linux Build + +- stage: TestUbuntu + displayName: Test for Ubuntu + dependsOn: [BuildLinuxStage] + jobs: + - template: templates/nix-test.yml + parameters: + name: Ubuntu + pool: ubuntu-20.04 + purpose: UnelevatedPesterTests + tagSet: CI + + - template: templates/nix-test.yml + parameters: + name: Ubuntu + pool: ubuntu-20.04 + purpose: ElevatedPesterTests + tagSet: CI + + - template: templates/nix-test.yml + parameters: + name: Ubuntu + pool: ubuntu-20.04 + purpose: UnelevatedPesterTests + tagSet: Others + + - template: templates/nix-test.yml + parameters: + name: Ubuntu + pool: ubuntu-20.04 + purpose: ElevatedPesterTests + tagSet: Others + + - template: templates/verify-xunit.yml + parameters: + pool: ubuntu-20.04 + +- stage: PackageLinux + displayName: Package Linux + dependsOn: ["BuildLinuxStage"] + jobs: + - template: linux/templates/packaging.yml + parameters: + pool: ubuntu-20.04 diff --git a/PowerShell-master/.vsts-ci/linux.yml b/PowerShell-master/.vsts-ci/linux.yml new file mode 100644 index 0000000000000000000000000000000000000000..5d9dc663e1ca7c625a91cb8a5d090ab56b0c7242 --- /dev/null +++ b/PowerShell-master/.vsts-ci/linux.yml @@ -0,0 +1,79 @@ +parameters: + - name: ContainerPattern + displayName: | + Pattern to match JobName of the container. + Update this to force a container. + `.` will match everything + type: string + default: . + +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - .pipelines/* + - test/perf/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - .vsts-ci/linux.yml + - .vsts-ci/linux/templates/packaging.yml + - assets/manpage/* + - build.psm1 + - global.json + - nuget.config + - PowerShell.Common.props + - src/*.csproj + - tools/ci.psm1 + - tools/packaging/* + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + +resources: + repositories: + - repository: Docker + type: github + endpoint: PowerShell + name: PowerShell/PowerShell-Docker + ref: master + +stages: +- stage: BuildLinuxStage + displayName: Build for Linux + jobs: + - template: templates/ci-build.yml + parameters: + pool: ubuntu-latest + jobName: linux_build + displayName: linux Build + +- stage: PackageLinux + displayName: Package Linux + dependsOn: ["BuildLinuxStage"] + jobs: + - template: linux/templates/packaging.yml + parameters: + pool: ubuntu-latest diff --git a/PowerShell-master/.vsts-ci/linux/templates/packaging.yml b/PowerShell-master/.vsts-ci/linux/templates/packaging.yml new file mode 100644 index 0000000000000000000000000000000000000000..8f77b8e24a090c57c9287243363425a1b0f33612 --- /dev/null +++ b/PowerShell-master/.vsts-ci/linux/templates/packaging.yml @@ -0,0 +1,99 @@ +parameters: + pool: 'ubuntu-20.04' + parentJobs: [] + name: 'Linux' + +jobs: +- job: ${{ parameters.name }}_packaging + dependsOn: + ${{ parameters.parentJobs }} + pool: + vmImage: ${{ parameters.pool }} + + displayName: ${{ parameters.name }} packaging + + steps: + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + useGlobalJson: true + packageType: 'sdk' + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - task: DownloadBuildArtifacts@0 + displayName: 'Download build artifacts' + inputs: + downloadType: specific + itemPattern: | + build/**/* + downloadPath: '$(System.ArtifactsDirectory)' + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture Artifacts Directory' + continueOnError: true + + - pwsh: | + Import-Module .\build.psm1 + Start-PSBootstrap -Scenario Package + displayName: Bootstrap + + - pwsh: | + Import-Module ./build.psm1 + displayName: 'Capture Artifacts Directory' + continueOnError: true + + - task: ExtractFiles@1 + displayName: 'Extract Build ZIP' + inputs: + archiveFilePatterns: '$(System.ArtifactsDirectory)/build/build.zip' + destinationFolder: '$(System.ArtifactsDirectory)/bins' + + - bash: | + find "$(System.ArtifactsDirectory)/bins" -type d -exec chmod +rwx {} \; + find "$(System.ArtifactsDirectory)/bins" -type f -exec chmod +rw {} \; + displayName: 'Fix permissions' + continueOnError: true + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\bins\*" -Recurse -ErrorAction SilentlyContinue + displayName: 'Capture Extracted Build ZIP' + continueOnError: true + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + $options = (Get-PSOptions) + $rootPath = '$(System.ArtifactsDirectory)\bins' + $originalRootPath = Split-Path -path $options.Output + $path = Join-Path -path $rootPath -ChildPath (split-path -leaf -path $originalRootPath) + $pwshPath = Join-Path -path $path -ChildPath 'pwsh' + chmod a+x $pwshPath + $options.Output = $pwshPath + Set-PSOptions $options + Invoke-CIFinish + displayName: Packaging Tests + condition: succeeded() + + - pwsh: | + Get-ChildItem "${env:BUILD_ARTIFACTSTAGINGDIRECTORY}\*.deb" -Recurse | ForEach-Object { + $packagePath = $_.FullName + Write-Host "Uploading $packagePath" + Write-Host "##vso[artifact.upload containerfolder=deb;artifactname=deb]$packagePath" + } + Get-ChildItem "${env:BUILD_ARTIFACTSTAGINGDIRECTORY}\*.rpm" -Recurse | ForEach-Object { + $packagePath = $_.FullName + Write-Host "Uploading $packagePath" + Write-Host "##vso[artifact.upload containerfolder=rpm;artifactname=rpm]$packagePath" + } + Get-ChildItem "${env:BUILD_ARTIFACTSTAGINGDIRECTORY}\*.tar.gz" -Recurse | ForEach-Object { + $packagePath = $_.FullName + Write-Host "Uploading $packagePath" + Write-Host "##vso[artifact.upload containerfolder=rpm;artifactname=rpm]$packagePath" + } + displayName: Upload packages + retryCountOnTaskFailure: 2 diff --git a/PowerShell-master/.vsts-ci/mac.yml b/PowerShell-master/.vsts-ci/mac.yml new file mode 100644 index 0000000000000000000000000000000000000000..678ded65259f80eca78f79f16c9eb4b515b1f545 --- /dev/null +++ b/PowerShell-master/.vsts-ci/mac.yml @@ -0,0 +1,114 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - tools/releaseBuild/**/* + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - .pipelines/* + - test/perf/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .dependabot/config.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .vsts-ci/misc-analysis.yml + - .vsts-ci/windows.yml + - .vsts-ci/windows/* + - tools/cgmanifest/* + - LICENSE.txt + - test/common/markdown/* + - test/perf/* + - tools/packaging/* + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* + - README.md + - .spelling + - .pipelines/* + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + # Turn off Homebrew analytics + HOMEBREW_NO_ANALYTICS: 1 + __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none + +resources: +- repo: self + clean: true + +stages: +- stage: BuildMac + displayName: Build for macOS + jobs: + - template: templates/ci-build.yml + parameters: + pool: macOS-latest + jobName: mac_build + displayName: macOS Build + +- stage: TestMac + displayName: Test for macOS + jobs: + - template: templates/nix-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: CI + + - template: templates/nix-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: CI + + - template: templates/nix-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: Others + + - template: templates/nix-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: Others + + - template: templates/verify-xunit.yml + parameters: + pool: macOS-latest + +- stage: PackageMac + dependsOn: ['BuildMac'] + displayName: Package macOS (bootstrap only) + jobs: + - job: macos_packaging + pool: + vmImage: macOS-latest + + displayName: macOS packaging (bootstrap only) + steps: + - checkout: self + clean: true + - pwsh: | + import-module ./build.psm1 + start-psbootstrap -Scenario package + displayName: Bootstrap packaging + condition: succeededOrFailed() diff --git a/PowerShell-master/.vsts-ci/misc-analysis/generateMarkdownMatrix.yml b/PowerShell-master/.vsts-ci/misc-analysis/generateMarkdownMatrix.yml new file mode 100644 index 0000000000000000000000000000000000000000..56a43accd552ace6ebf3c530897a431f110849a0 --- /dev/null +++ b/PowerShell-master/.vsts-ci/misc-analysis/generateMarkdownMatrix.yml @@ -0,0 +1,46 @@ +parameters: + - name: jobName + - name: taskName + +jobs: +- job: ${{ parameters.jobName }} + displayName: Generate Markdown Matrix + + pool: + vmImage: ubuntu-20.04 + + variables: + - name: repoPath + value: $(Agent.BuildDirectory)/$(repoFolder) + + steps: + - checkout: self + clean: true + path: $(repoFolder) + + - powershell: | + $matrix = @{} + $matrix += @{ + 'root' = @{ + markdown_folder = "$(repoPath)" + markdown_recurse = $false + } + } + Get-ChildItem -path '$(repoPath)' -Directory | Foreach-Object { + $folder = $_ + $matrix += @{ + $_.Name = @{ + markdown_folder = $_.fullName + markdown_recurse = $true + } + } + } + + $matrixJson = $matrix | ConvertTo-Json -Compress + $variableName = "matrix" + $command = "vso[task.setvariable variable=$variableName;isoutput=true]$($matrixJson)" + Write-Verbose "sending command: '$command'" + Write-Host "##$command" + displayName: Create Matrix + condition: succeededOrFailed() + name: ${{ parameters.taskName }} diff --git a/PowerShell-master/.vsts-ci/psresourceget-acr.yml b/PowerShell-master/.vsts-ci/psresourceget-acr.yml new file mode 100644 index 0000000000000000000000000000000000000000..225e2699533ae1d4bffe1c559ff941a1d1fd149a --- /dev/null +++ b/PowerShell-master/.vsts-ci/psresourceget-acr.yml @@ -0,0 +1,155 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - test/perf/* + - .pipelines/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .dependabot/config.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .vsts-ci/misc-analysis.yml + - tools/cgmanifest/* + - LICENSE.txt + - test/common/markdown/* + - test/perf/* + - tools/packaging/* + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* + - README.md + - .spelling + - .pipelines/* + +variables: + GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + __SuppressAnsiEscapeSequences: 1 + NugetSecurityAnalysisWarningLevel: none + nugetMultiFeedWarnLevel: none + +resources: +- repo: self + clean: true + +stages: +- stage: BuildWin + displayName: Build for Windows + jobs: + - template: templates/ci-build.yml + +- stage: TestWin + displayName: Test PSResourceGetACR + jobs: + - job: win_test_ACR + displayName: PSResourceGet ACR Tests + pool: + vmImage: 'windows-latest' + + steps: + - pwsh: | + Get-ChildItem -Path env: + displayName: Capture Environment + condition: succeededOrFailed() + + - task: DownloadBuildArtifacts@0 + displayName: 'Download Build Artifacts' + inputs: + downloadType: specific + itemPattern: | + build/**/* + downloadPath: '$(System.ArtifactsDirectory)' + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture Artifacts Directory' + continueOnError: true + + - pwsh: | + # Remove "Program Files\dotnet" from the env variable PATH, so old SDKs won't affect us. + Write-Host "Old Path:" + Write-Host $env:Path + + $dotnetPath = Join-Path $env:SystemDrive 'Program Files\dotnet' + $paths = $env:Path -split ";" | Where-Object { -not $_.StartsWith($dotnetPath) } + $env:Path = $paths -join ";" + + Write-Host "New Path:" + Write-Host $env:Path + + # Bootstrap + Import-Module .\tools\ci.psm1 + Invoke-CIInstall + displayName: Bootstrap + + - pwsh: | + Install-Module -Name 'Microsoft.PowerShell.SecretManagement' -force -SkipPublisherCheck -AllowClobber + Install-Module -Name 'Microsoft.PowerShell.SecretStore' -force -SkipPublisherCheck -AllowClobber + $vaultPassword = ConvertTo-SecureString $("a!!"+ (Get-Random -Maximum ([int]::MaxValue))) -AsPlainText -Force + Set-SecretStoreConfiguration -Authentication None -Interaction None -Confirm:$false -Password $vaultPassword + Register-SecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault + displayName: 'Install Secret store' + + - task: AzurePowerShell@5 + inputs: + azureSubscription: PSResourceGetACR + azurePowerShellVersion: LatestVersion + ScriptType: InlineScript + pwsh: true + inline: | + Write-Verbose -Verbose "Getting Azure Container Registry" + Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * + Write-Verbose -Verbose "Setting up secret for Azure Container Registry" + $azt = Get-AzAccessToken + $tenantId = $azt.TenantID + Set-Secret -Name $tenantId -Secret $azt.Token -Verbose + $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: 'Setup Azure Container Registry secret' + + - pwsh: | + Import-Module .\build.psm1 -force + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + $options = (Get-PSOptions) + $path = split-path -path $options.Output + $rootPath = split-Path -path $path + Expand-Archive -Path '$(System.ArtifactsDirectory)\build\build.zip' -DestinationPath $rootPath -Force + + $pwshExe = Get-ChildItem -Path $rootPath -Recurse -Filter pwsh.exe | Select-Object -First 1 + + $outputFilePath = "$(Build.SourcesDirectory)\test\powershell\Modules\Microsoft.PowerShell.PSResourceGet\ACRTests.xml" + $cmdline = "`$env:ACRTESTS = 'true'; Invoke-Pester -Path '$(Build.SourcesDirectory)\test\powershell\Modules\Microsoft.PowerShell.PSResourceGet\Microsoft.PowerShell.PSResourceGet.Tests.ps1' -TestName 'PSResourceGet - ACR tests' -OutputFile $outputFilePath -OutputFormat NUnitXml" + Write-Verbose -Verbose "Running $cmdline" + + & $pwshExe -Command $cmdline + + Publish-TestResults -Title "PSResourceGet - ACR tests" -Path $outputFilePath -Type NUnit + displayName: 'PSResourceGet ACR functional tests using AzAuth' diff --git a/PowerShell-master/.vsts-ci/sshremoting-tests.yml b/PowerShell-master/.vsts-ci/sshremoting-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..72c5710016bc518f629a8511d9c6c8a4e508b4ff --- /dev/null +++ b/PowerShell-master/.vsts-ci/sshremoting-tests.yml @@ -0,0 +1,97 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '/src/System.Management.Automation/engine/*' + - '/test/SSHRemoting/*' +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '/src/System.Management.Automation/engine/*' + - '/test/SSHRemoting/*' + +variables: + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + - name: DOTNET_NOLOGO + value: 1 + - name: __SuppressAnsiEscapeSequences + value: 1 + - name: NugetSecurityAnalysisWarningLevel + value: none +# Prevents auto-injection of nuget-security-analysis@0 + - name: skipNugetSecurityAnalysis + value: true + + +resources: +- repo: self + clean: true +jobs: +- job: SSHRemotingTests + pool: + vmImage: ubuntu-20.04 + container: mcr.microsoft.com/powershell/test-deps:ubuntu-18.04 + displayName: SSH Remoting Tests + + steps: + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - pwsh: Write-Host "##vso[build.updatebuildnumber]$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))" + displayName: Set Build Name for Non-PR + condition: ne(variables['Build.Reason'], 'PullRequest') + + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + + - pwsh: | + sudo apt-get update + sudo apt-get install -y git + displayName: Install Github + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIBuild + displayName: Build + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions + $options = (Get-PSOptions) + Import-Module .\test\tools\Modules\HelpersRemoting + Install-SSHRemoting -PowerShellFilePath $options.Output + displayName: Install SSH Remoting + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions + $options = (Get-PSOptions) + Import-Module .\build.psm1 + Start-PSPester -Path test/SSHRemoting -powershell $options.Output -OutputFile "$PWD/sshTestResults.xml" + displayName: Test + condition: succeeded() diff --git a/PowerShell-master/.vsts-ci/templates/ci-build.yml b/PowerShell-master/.vsts-ci/templates/ci-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ec458c3c5a916333b0c6e2b502c482ab0e751cc --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/ci-build.yml @@ -0,0 +1,87 @@ +parameters: + - name: pool + default: 'windows-latest' + - name: imageName + default: 'PSWindows11-ARM64' + - name: jobName + default: 'win_build' + - name: displayName + default: Windows Build + - name: PoolType + default: AzDoHosted + type: string + values: + - AzDoHosted + - 1esHosted + +jobs: +- job: ${{ parameters.jobName }} + pool: + ${{ if eq( parameters.PoolType, 'AzDoHosted') }}: + vmImage: ${{ parameters.pool }} + ${{ else }}: + name: ${{ parameters.pool }} + demands: + - ImageOverride -equals ${{ parameters.imageName }} + + displayName: ${{ parameters.displayName }} + + steps: + - powershell: | + [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 + $pwsh = Get-Command pwsh -ErrorAction SilentlyContinue -CommandType Application + + if ($null -eq $pwsh) { + $powerShellPath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'powershell' + Invoke-WebRequest -Uri https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/install-powershell.ps1 -outfile ./install-powershell.ps1 + ./install-powershell.ps1 -Destination $powerShellPath + $vstsCommandString = "vso[task.setvariable variable=PATH]$powerShellPath;$env:PATH" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + } + + displayName: Install PowerShell + + - checkout: self + fetchDepth: 1000 + + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - pwsh: Write-Host "##vso[build.updatebuildnumber]$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))" + displayName: Set Build Name for Non-PR + condition: ne(variables['Build.Reason'], 'PullRequest') + + - ${{ if ne(variables['UseAzDevOpsFeed'], '') }}: + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + useGlobalJson: true + packageType: 'sdk' + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + Write-Verbose -Verbose "Start Sync-PSTags" + Sync-PSTags -AddRemoteIfMissing + Write-Verbose -Verbose "End Sync-PSTags" + displayName: Bootstrap + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIBuild + displayName: Build + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions + Invoke-CIxUnit -SkipFailing + displayName: xUnit Tests + condition: succeeded() + continueOnError: true diff --git a/PowerShell-master/.vsts-ci/templates/credscan.yml b/PowerShell-master/.vsts-ci/templates/credscan.yml new file mode 100644 index 0000000000000000000000000000000000000000..60094ff3d7773480727a733a956ef68ecf8dd4be --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/credscan.yml @@ -0,0 +1,29 @@ +parameters: + pool: 'windows-latest' + jobName: 'credscan' + displayName: Secret Scan + +jobs: +- job: ${{ parameters.jobName }} + pool: + vmImage: ${{ parameters.pool }} + + displayName: ${{ parameters.displayName }} + + steps: + - task: securedevelopmentteam.vss-secure-development-tools.build-task-credscan.CredScan@2 + displayName: 'Scan for Secrets' + inputs: + suppressionsFile: tools/credScan/suppress.json + toolMajorVersion: V2 + debugMode: false + + - task: securedevelopmentteam.vss-secure-development-tools.build-task-publishsecurityanalysislogs.PublishSecurityAnalysisLogs@2 + displayName: 'Publish Secret Scan Logs to Build Artifacts' + continueOnError: true + + - task: securedevelopmentteam.vss-secure-development-tools.build-task-postanalysis.PostAnalysis@1 + displayName: 'Check for Failures' + inputs: + CredScan: true + ToolLogsNotFoundAction: Error diff --git a/PowerShell-master/.vsts-ci/templates/install-ps-phase.yml b/PowerShell-master/.vsts-ci/templates/install-ps-phase.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e650273264045485fc17eabf093d7566b83ce99 --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/install-ps-phase.yml @@ -0,0 +1,42 @@ +parameters: + pool: 'ubuntu-latest' + jobName: 'none' + scriptName: '' + container: '' + verification: '' + continueOnError: false + +jobs: + +- job: ${{ parameters.jobName }} + variables: + scriptName: ${{ parameters.scriptName }} + + ${{ if ne(parameters.container, '') }}: + container: ${{ parameters.container }} + + pool: + vmImage: ${{ parameters.pool }} + + displayName: ${{ parameters.jobName }} + + steps: + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - powershell: Write-Host "##vso[build.updatebuildnumber]$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))" + displayName: Set Build Name for Non-PR + condition: ne(variables['Build.Reason'], 'PullRequest') + + - bash: | + $(scriptName) + displayName: Run Script - $(scriptName) + condition: succeededOrFailed() + continueOnError: ${{ parameters.continueOnError }} + + - ${{ if ne(parameters.verification, '') }}: + - pwsh: ${{ parameters.verification }} + displayName: Verification + continueOnError: ${{ parameters.continueOnError }} diff --git a/PowerShell-master/.vsts-ci/templates/nix-test.yml b/PowerShell-master/.vsts-ci/templates/nix-test.yml new file mode 100644 index 0000000000000000000000000000000000000000..214ae14b2c63b2872364a34fc207be9667a64c1c --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/nix-test.yml @@ -0,0 +1,25 @@ +parameters: + pool: 'macOS-latest' + purpose: '' + tagSet: 'CI' + name: 'mac' + +jobs: +- job: ${{ parameters.name }}_test_${{ parameters.purpose }}_${{ parameters.tagSet }} + + pool: + vmImage: ${{ parameters.pool }} + + displayName: ${{ parameters.name }} Test - ${{ parameters.purpose }} - ${{ parameters.tagSet }} + + steps: + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + useGlobalJson: true + packageType: 'sdk' + + - template: ./test/nix-test-steps.yml + parameters: + purpose: ${{ parameters.purpose }} + tagSet: ${{ parameters.tagSet }} diff --git a/PowerShell-master/.vsts-ci/templates/test/nix-container-test.yml b/PowerShell-master/.vsts-ci/templates/test/nix-container-test.yml new file mode 100644 index 0000000000000000000000000000000000000000..37c60a4c53b4a1ae161023ce8f09d9b124600744 --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/test/nix-container-test.yml @@ -0,0 +1,36 @@ +parameters: + pool: 'macOS-latest' + purpose: '' + tagSet: 'CI' + name: 'mac' + +jobs: +- job: ${{ parameters.name }}_test_${{ parameters.purpose }}_${{ parameters.tagSet }} + + dependsOn: + - getContainerJob + + variables: + __INCONTAINER: 1 + getContainerJob: $[ dependencies.getContainerJob.outputs['getContainerTask.containerName'] ] + containerBuildName: $[ dependencies.getContainerJob.outputs['getContainerTask.containerBuildName'] ] + + container: $[ variables.getContainerJob ] + + pool: + vmImage: ${{ parameters.pool }} + + displayName: ${{ parameters.name }} Test - ${{ parameters.purpose }} - ${{ parameters.tagSet }} + + steps: + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + useGlobalJson: true + packageType: 'sdk' + + - template: ./nix-test-steps.yml + parameters: + purpose: ${{ parameters.purpose }} + tagSet: ${{ parameters.tagSet }} + buildName: $(containerBuildName) diff --git a/PowerShell-master/.vsts-ci/templates/test/nix-test-steps.yml b/PowerShell-master/.vsts-ci/templates/test/nix-test-steps.yml new file mode 100644 index 0000000000000000000000000000000000000000..f15d59ea73aff70fcbe3e9cd66c4aba1ab076e61 --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/test/nix-test-steps.yml @@ -0,0 +1,60 @@ +parameters: + purpose: '' + tagSet: 'CI' + buildName: 'Ubuntu' + +steps: + - pwsh: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture Environment + condition: succeededOrFailed() + + - task: DownloadBuildArtifacts@0 + displayName: 'Download build artifacts' + inputs: + downloadType: specific + itemPattern: | + build/**/* + downloadPath: '$(System.ArtifactsDirectory)' + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture Artifacts Directory' + continueOnError: true + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + + - task: ExtractFiles@1 + displayName: 'Extract Build ZIP' + inputs: + archiveFilePatterns: '$(System.ArtifactsDirectory)/build/build.zip' + destinationFolder: '$(System.ArtifactsDirectory)/bins' + + - bash: | + find "$(System.ArtifactsDirectory)/bins" -type d -exec chmod +rwx {} \; + find "$(System.ArtifactsDirectory)/bins" -type f -exec chmod +rw {} \; + displayName: 'Fix permissions' + continueOnError: true + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\bins\*" -Recurse -ErrorAction SilentlyContinue + displayName: 'Capture Extracted Build ZIP' + continueOnError: true + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + $options = (Get-PSOptions) + $rootPath = '$(System.ArtifactsDirectory)\bins' + $originalRootPath = Split-Path -path $options.Output + $path = Join-Path -path $rootPath -ChildPath (split-path -leaf -path $originalRootPath) + $pwshPath = Join-Path -path $path -ChildPath 'pwsh' + chmod a+x $pwshPath + $options.Output = $pwshPath + Set-PSOptions $options + Invoke-CITest -Purpose '${{ parameters.purpose }}' -TagSet '${{ parameters.tagSet }}' -TitlePrefix '${{ parameters.buildName }}' + displayName: Test + condition: succeeded() diff --git a/PowerShell-master/.vsts-ci/templates/verify-xunit.yml b/PowerShell-master/.vsts-ci/templates/verify-xunit.yml new file mode 100644 index 0000000000000000000000000000000000000000..b43cb9339f974ec9a31a7c6c5d56769752f8b713 --- /dev/null +++ b/PowerShell-master/.vsts-ci/templates/verify-xunit.yml @@ -0,0 +1,33 @@ +parameters: + parentJobs: [] + pool: 'windows-latest' + jobName: 'xunit_verify' + +jobs: +- job: verify_xunit + displayName: Verify xUnit Results + pool: + vmImage: ${{ parameters.pool }} + dependsOn: + ${{ parameters.parentJobs }} + steps: + - task: DownloadBuildArtifacts@0 + displayName: 'Download build artifacts' + inputs: + downloadType: specific + itemPattern: | + xunit/**/* + downloadPath: '$(System.ArtifactsDirectory)' + + - pwsh: | + dir "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture artifacts directory' + continueOnError: true + + - pwsh: | + Import-Module .\tools\ci.psm1 + $xUnitTestResultsFile = "$(System.ArtifactsDirectory)\xunit\xUnitTestResults.xml" + + Test-XUnitTestResults -TestResultsFile $xUnitTestResultsFile + displayName: Test + condition: succeeded() diff --git a/PowerShell-master/.vsts-ci/windows-arm64.yml b/PowerShell-master/.vsts-ci/windows-arm64.yml new file mode 100644 index 0000000000000000000000000000000000000000..1c4bc2ee8afc5bfc975f52f09ea6305459cea9a1 --- /dev/null +++ b/PowerShell-master/.vsts-ci/windows-arm64.yml @@ -0,0 +1,94 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .dependabot/config.yml + - test/perf/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .dependabot/config.yml + - .github/ISSUE_TEMPLATE/* + - .vsts-ci/misc-analysis.yml + - tools/cgmanifest/* + - LICENSE.txt + - test/common/markdown/* + - test/perf/* + - tools/packaging/* + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* + - README.md + - .spelling + +variables: + - name: GIT_CONFIG_PARAMETERS + value: "'core.autocrlf=false'" + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + - name: DOTNET_NOLOGO + value: 1 + - name: __SuppressAnsiEscapeSequences + value: 1 + - group: PoolNames + +resources: +- repo: self + clean: true + +stages: +- stage: BuildWin + displayName: Build for Windows + jobs: + - template: templates/ci-build.yml + parameters: + pool: $(armPool) + PoolType: 1esHosted + +- stage: TestWin + displayName: Test for Windows + jobs: + - template: templates/windows-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: CI + pool: $(armPool) + + - template: templates/windows-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: CI + pool: $(armPool) + + - template: templates/windows-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: Others + pool: $(armPool) + + - template: templates/windows-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: Others + pool: $(armPool) + + - template: templates/verify-xunit.yml diff --git a/PowerShell-master/.vsts-ci/windows.yml b/PowerShell-master/.vsts-ci/windows.yml new file mode 100644 index 0000000000000000000000000000000000000000..4171d09643d083ef0f947e8874db9269a9a1299d --- /dev/null +++ b/PowerShell-master/.vsts-ci/windows.yml @@ -0,0 +1,83 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - test/perf/* + - .pipelines/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - .vsts-ci/templates/* + - .vsts-ci/windows.yml + - '*.props' + - build.psm1 + - src/* + - test/* + - tools/buildCommon/* + - tools/ci.psm1 + - tools/WindowsCI.psm1 + exclude: + - test/common/markdown/* + - test/perf/* + +variables: + GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + __SuppressAnsiEscapeSequences: 1 + NugetSecurityAnalysisWarningLevel: none + nugetMultiFeedWarnLevel: none + +resources: +- repo: self + clean: true + +stages: +- stage: BuildWin + displayName: Build for Windows + jobs: + - template: templates/ci-build.yml + +- stage: TestWin + displayName: Test for Windows + jobs: + - template: templates/windows-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: CI + + - template: templates/windows-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: CI + + - template: templates/windows-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: Others + + - template: templates/windows-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: Others + + - template: templates/verify-xunit.yml diff --git a/PowerShell-master/.vsts-ci/windows/templates/windows-packaging.yml b/PowerShell-master/.vsts-ci/windows/templates/windows-packaging.yml new file mode 100644 index 0000000000000000000000000000000000000000..d23b745c30f24b4463b79f457db8a5cc08914ebb --- /dev/null +++ b/PowerShell-master/.vsts-ci/windows/templates/windows-packaging.yml @@ -0,0 +1,111 @@ +parameters: + - name: pool + default: 'windows-latest' + - name: jobName + default: 'win_packaging' + - name: runtimePrefix + default: 'win7' + - name: architecture + default: 'x64' + - name: channel + default: 'preview' + +jobs: +- job: ${{ parameters.jobName }}_${{ parameters.channel }}_${{ parameters.architecture }} + + variables: + - name: repoFolder + value: PowerShell + - name: repoPath + value: $(Agent.BuildDirectory)\$(repoFolder) + - name: complianceRepoFolder + value: compliance + - name: complianceRepoPath + value: $(Agent.BuildDirectory)\$(complianceRepoFolder) + + pool: + vmImage: ${{ parameters.pool }} + + displayName: Windows Packaging - ${{ parameters.architecture }} - ${{ parameters.channel }} + + steps: + - checkout: self + clean: true + path: $(repoFolder) + + - checkout: ComplianceRepo + clean: true + path: $(complianceRepoFolder) + + - powershell: | + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose + displayName: Capture environment + condition: succeededOrFailed() + + - pwsh: | + $PSVersionTable + displayName: Capture PowerShell Version Table + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Switch-PSNugetConfig -Source Public + displayName: Switch to public feeds + condition: succeeded() + workingDirectory: $(repoPath) + + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + useGlobalJson: true + packageType: 'sdk' + workingDirectory: $(repoPath) + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeeded() + workingDirectory: $(repoPath) + + - pwsh: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + Invoke-CIFinish -Runtime ${{ parameters.runtimePrefix }}-${{ parameters.architecture }} -channel ${{ parameters.channel }} -Stage Build + displayName: Build + workingDirectory: $(repoPath) + + - template: Sbom.yml@ComplianceRepo + parameters: + BuildDropPath: '$(System.ArtifactsDirectory)/mainBuild' + Build_Repository_Uri: $(build.repository.uri) + displayName: SBOM + sourceScanPath: '$(repoPath)\tools' + signSBOM: false + + # This is needed as SBOM task removed the installed .NET and installs .NET 3.1 + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeeded() + workingDirectory: $(repoPath) + + - pwsh: | + $manifestFolder = Join-Path -Path '$(System.ArtifactsDirectory)/mainBuild' -ChildPath '_manifest' + + if (-not (Test-Path $manifestFolder)) { + throw "_manifest folder does not exist under $(System.ArtifactsDirectory)/mainBuild" + } + + $null = New-Item -Path "$manifestFolder/spdx_2.2/bsi.json" -Verbose -Force + $null = New-Item -Path "$manifestFolder/spdx_2.2/manifest.cat" -Verbose -Force + + displayName: Create fake SBOM manifest signed files + + - pwsh: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + Invoke-CIFinish -Runtime ${{ parameters.runtimePrefix }}-${{ parameters.architecture }} -channel ${{ parameters.channel }} -Stage Package + displayName: Package and Test + workingDirectory: $(repoPath) diff --git a/PowerShell-master/.vsts-ci/windows/windows-packaging.yml b/PowerShell-master/.vsts-ci/windows/windows-packaging.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b73ca0572323d5dbc65960500b35690642d94fa --- /dev/null +++ b/PowerShell-master/.vsts-ci/windows/windows-packaging.yml @@ -0,0 +1,87 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + exclude: + - tests/* + - docs/* + - demos/* + - CHANGELOG/* + - .devcontainer/* + - .github/* + - .poshchan/* + - .vscode/* + - code-server/* + - docker/* + +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - .vsts-ci/windows/*.yml + - assets/wix/* + - build.psm1 + - global.json + - nuget.config + - PowerShell.Common.props + - src/*.csproj + - test/packaging/windows/* + - tools/ci.psm1 + - tools/packaging/* + - tools/wix/* + +variables: + - name: GIT_CONFIG_PARAMETERS + value: "'core.autocrlf=false'" + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + - name: DOTNET_NOLOGO + value: 1 + - name: __SuppressAnsiEscapeSequences + value: 1 + - group: fakeNugetKey + - name: SBOMGenerator_Formats + value: spdx:2.2 + - name: nugetMultiFeedWarnLevel + value: none + +resources: + repositories: + - repository: ComplianceRepo + type: github + endpoint: PowerShell + name: PowerShell/compliance + ref: master + +stages: +- stage: PackagingWin + displayName: Packaging for Windows + dependsOn: [] # by specifying an empty array, this stage doesn't depend on the stage before it + jobs: + # Unlike daily builds, we do not upload nuget package to MyGet so we do not wait on tests to finish. + - template: templates/windows-packaging.yml + - template: templates/windows-packaging.yml + parameters: + channel: stable + architecture: x86 + - template: templates/windows-packaging.yml + parameters: + channel: preview + architecture: x86 + - template: templates/windows-packaging.yml + parameters: + channel: preview + architecture: arm64 + runtimePrefix: win diff --git a/PowerShell-master/ADOPTERS.md b/PowerShell-master/ADOPTERS.md new file mode 100644 index 0000000000000000000000000000000000000000..186b99dd09352cafa57d0a1b0af6431a4ea8aa0d --- /dev/null +++ b/PowerShell-master/ADOPTERS.md @@ -0,0 +1,39 @@ +# Adopters + + + +This is a list of adopters using PowerShell in production or in their products (in alphabetical order): + +* [Azure Cloud Shell](https://shell.azure.com/) provides a battery-included browser-based PowerShell environment used by Azure administrators to manage their environment. + It includes up-to-date PowerShell modules for `Azure`, `AzureAD`, `Exchange`, `Teams`, and many more. + More information about Azure Cloud Shell is available at [Azure Cloud Shell Overview.](https://learn.microsoft.com/azure/cloud-shell/overview) +* [Azure Functions - PowerShell](https://github.com/Azure/azure-functions-powershell-worker) is a serverless compute service to execute PowerShell scripts on the cloud without worrying about managing resources. + In addition, Azure Functions provides client tools such as [`Az.Functions`](https://www.powershellgallery.com/packages/Az.Functions), a cross-platform PowerShell module for managing function apps and service plans in the cloud. + For more information about Functions, please visit [functions overview](https://learn.microsoft.com/azure/azure-functions/functions-overview). +* [PowerShell Universal](https://ironmansoftware.com/powershell-universal) is a cross-platform web framework for PowerShell. + It provides the ability to create robust, interactive sites, REST APIs, and Electron-based desktop apps with PowerShell script. + More information about PowerShell Universal Dashboard is available at the [PowerShell Universal Dashboard Docs](https://docs.universaldashboard.io). +* [System Frontier](https://systemfrontier.com/solutions/powershell/) provides dynamically generated web GUIs and REST APIs for PowerShell and other scripting languages. + Enable non-admins like help desk and tier 1 support teams to execute secure web based tools on any platform `without admin rights`. + Configure flexible RBAC permissions from an intuitive interface, without a complex learning curve. + Script output along with all actions are audited. Manage up to 5,000 nodes for free with the [Community Edition](https://systemfrontier.com/solutions/community-edition/). +* [Amazon AWS](https://aws.com) supports PowerShell in a wide variety of its products including [AWS tools for PowerShell](https://github.com/aws/aws-tools-for-powershell), + [AWS Lambda Support For PowerShell](https://github.com/aws/aws-lambda-dotnet/tree/master/PowerShell) and [AWS PowerShell Tools for `CodeBuild`](https://docs.aws.amazon.com/powershell/latest/reference/items/CodeBuild_cmdlets.html) + as well as supporting PowerShell Core in both Windows and Linux EC2 Images. +* [Azure Resource Manager Deployment Scripts](https://learn.microsoft.com/azure/azure-resource-manager/templates/deployment-script-template) Complete the "last mile" of your Azure Resource Manager (ARM) template deployments with a Deployment Script, which enables you to run an arbitrary PowerShell script in the context of a deployment. + It is designed to let you complete tasks that should be part of a deployment, but are not possible in an ARM template today — for example, creating a Key Vault certificate or querying an external API for a new CIDR block. +* [Azure Pipelines Hosted Agents](https://learn.microsoft.com/azure/devops/pipelines/agents/hosted?view=azure-devops) Windows, Ubuntu, and macOS Agents used by Azure Pipelines customers have PowerShell pre-installed so that customers can make use of it for all their CI/CD needs. +* [GitHub Actions Virtual Environments for Hosted Runners](https://help.github.com/actions/reference/virtual-environments-for-github-hosted-runners) Windows, Ubuntu, and macOS virtual environments are used by customers of GitHub Actions include PowerShell out of the box. +* [GitHub Actions Python builds](https://github.com/actions/python-versions) GitHub Actions uses PowerShell to automate building Python from source for its runners. +* [Microsoft HoloLens](https://www.microsoft.com/hololens) makes extensive use of PowerShell 7+ throughout the development cycle to automate tasks such as firmware assembly and automated testing. +* [Power BI](https://powerbi.microsoft.com/) provides PowerShell users a set of cmdlets in [MicrosoftPowerBIMgmt](https://learn.microsoft.com/powershell/power-bi) module to manage and automate the Power BI service. + This is in addition to Power BI leveraging PowerShell, internally for various engineering systems and infrastructure for its service. +* [Windows 10 IoT Core](https://learn.microsoft.com/windows/iot-core/windows-iot-core) is a small form factor Windows edition for IoT devices and now you can easily include the [PowerShell package](https://github.com/ms-iot/iot-adk-addonkit/blob/master/Tools/IoTCoreImaging/Docs/Import-PSCoreRelease.md#Import-PSCoreRelease) in your imaging process. diff --git a/PowerShell-master/Analyzers.props b/PowerShell-master/Analyzers.props new file mode 100644 index 0000000000000000000000000000000000000000..6f906496c734b0aaf548aa34871be3ca1d882162 --- /dev/null +++ b/PowerShell-master/Analyzers.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/PowerShell-master/CHANGELOG.md b/PowerShell-master/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..73ffd17cdb6c2c5dd465d2deb0892b391d0c49ff --- /dev/null +++ b/PowerShell-master/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +The change logs have been split by version and moved to [CHANGELOG](./CHANGELOG). diff --git a/PowerShell-master/CHANGELOG/6.0.md b/PowerShell-master/CHANGELOG/6.0.md new file mode 100644 index 0000000000000000000000000000000000000000..52db53afabf57ed857486a0fd0b9d14ec9045153 --- /dev/null +++ b/PowerShell-master/CHANGELOG/6.0.md @@ -0,0 +1,1180 @@ +# 6.0 Changelog + +## [6.0.0] - 2018-01-10 + +### Breaking changes + +- Remove `sc` alias which conflicts with `sc.exe` (#5827) +- Separate group policy settings and enable policy controlled logging in PowerShell Core (#5791) + +### Engine updates and fixes + +- Handle `DLLImport` failure of `libpsrpclient` in PowerShell Remoting on Unix platforms (#5622) + +### Test + +- Replace `lee.io` Tests with `WebListener` (#5709) (Thanks @markekraus!) +- Update the docker based release package tests due to the removal of `Pester` module and other issues (#5692) +- Replace Remaining `HttpBin.org` Tests with `WebListener` (#5665) (Thanks @markekraus!) + +### Build and Packaging Improvements + +- Update x86 and x64 `MSI` packages to not overwrite each other (#5812) (Thanks @bergmeister!) +- Update `Restore-PSPester` to include the fix for nested describe errors (#5771) +- Automate the generation of release change log draft (#5712) + +### Documentation and Help Content + +- Updated help Uri to point to latest help content for `Microsoft.PowerShell.Core` module (#5820) +- Update the installation doc for `Raspberry-Pi` about supported devices (#5773) +- Fix a typo and a Markdown linting error in the Pull Request Template (#5807) (Thanks @markekraus!) +- Update submodule documentation for pester removal (#5786) (Thanks @bergmeister!) +- Change `Github` to `GitHub` in `CONTRIBUTING.md` (#5697) (Thanks @stuntguy3000!) +- Fix incorrect release date on the changelog (#5698) (Thanks @SwarfegaGit!) +- Add instructions to deploy `win-arm` build on Windows IoT (#5682) + +## [6.0.0-rc.2] - 2017-12-14 + +### Breaking changes + +- Skip null-element check for collections with a value-type element type (#5432) +- Make `AllSigned` execution policy require modules under `$PSHome` to be signed (#5511) + +### Engine updates and fixes + +- Update PowerShell to use `2.0.4` dotnet core runtime. (#5677) +- Remove references to the old executable `powershell` or `powershell.exe` (#5408) + +### General cmdlet updates and fixes + +- Remove unnecessary check for `Paths.count > 0`, in the `*-FileCatalog` CmdLets (#5596) +- Use explicit `libpsl-native` binary name for `dllimport`. (#5580) + +### Build and Packaging Improvements + +- Fix `Get-EnvironmentInformation` to properly check for CoreCLR (#5592) (Thanks @markekraus!) +- Make Travis CI use `libcurl+openssl+gssapi` (#5629) (Thanks @markekraus!) +- Disambiguate icon for daily builds on Windows (#5467) (Thanks @bergmeister!) +- Fix `Import-CliXml` tests which still use `powershell` instead of `pwsh` and make sure it fails if it regresses (#5521) (Thanks @markekraus!) +- Update port number used for WebCmdlets tests which broke due to a change in AppVeyor (#5520) (Thanks @markekraus!) +- Clean up use of `Runspaceconfiguration` from comments and xUnit test code (#5569) (Thanks @Bhaal22!) +- Replace `HttpListener` Response Tests with WebListener (#5540, #5605) (Thanks @markekraus!) +- Fix the path to `powershell_xxx.inc` in Start-Build (#5538) (Thanks @iSazonov!) +- Remove Pester as a module include with the PowerShell Packages. + You should be able to add it by running `Install-Module Pester`. (#5623, #5631) +- Refactor `New-UnixPackaging` into functions to make the large function more readable. (#5625) +- Make the experience better when `Start-PSPester` doesn't find Pester (#5673) +- Update packaging and release build scripts to produce zip packages for `win-arm` and `win-arm64` (#5664) +- Enable `Install-Debian` to work with VSTS Hosted Linux Preview (#5659) +- Add `linux-arm` tarball package to release build (#5652, #5660) +- Enable building for `win-arm` and `win-arm64` (#5524) +- Make macOS package require 10.12 or newer (#5649, #5654) +- Update signing subjects to something meaningful (#5650) +- Make `New-UnixPackage` more readable (#5625) +- Update `PowerShellGet` tests to validate the new install location of `AllUsers` scope. (#5633) +- Increase reliability of flaky test that fails intermittently in CI (#5641) +- Exclude markdown files from `Pester` folder from the Markdown meta test (#5636) +- Run tests for Windows installer only on Windows (#5619) +- Suppress the expected errors from `Select-Xml` tests (#5591) +- Add retry logic to prerequisite URL and output URL on failure so you can more easily troubleshoot (#5601, #5570) +- Make sure submodule are initialized when running Mac release build (#5496) +- Remove duplicate files in Windows packages in a folder called `signed` (#5527) +- Add PowerShell VSCode style settings (#5529) (Thanks @bergmeister) +- Add Travis CI matrix for improved job tagging (#5547) +- Remove community docker files from official docker image validation (#5508) + +### Documentation and Help Content + +- XML documentation fix for `CompletionResult` (#5550) (Thanks @bergmeister!) +- Change synopsis of `install-powershell.ps1` to reflect that it works cross-platform (#5465) (Thanks @bergmeister!) +- Add more helpful message for `AmbiguousParameterSet` exception (#5537) (Thanks @kvprasoon!) +- Update the contribution guideline to note that updating the changelog is required. (#5586) +- Updated doc to build arm/arm64 versions of `psrp.windows` and `PowerShell.Core.Instrumentation.dll` libraries (#5668) +- Update Contribution guidelines with work in progress guidance (#5655) +- Update code coverage tests to get GitCommitId using the ProductVersion from Assembly (#5651) +- Remove requirement to updating changelog update in PR (#5644, #5586) +- Minor refactoring of the release build scripts (#5632) +- Update PowerShell executable name in `using-vscode.md` (#5593) +- Fix xUnit test for PS (#4780) +- Update install link and instructions for R-Pi (#5495) + +### Compliance Work + +[Compliance](https://github.com/PowerShell/PowerShell/blob/master/docs/maintainers/issue-management.md#miscellaneous-labels) +work is required for Microsoft to continue to sign and release packages from the project as official Microsoft packages. + +- Remove `PerformWSManPluginReportCompletion`, which was not used, from `pwrshplugin.dll` (#5498) (Thanks @bergmeister!) +- Remove exclusion for unresponsive condition and add context exception for remaining instances (#5595) +- Replace `strlen` with `strnlen` in native code (#5510) + +## [6.0.0-rc] - 2017-11-16 + +### Breaking changes + +- Fix `-Verbose` to not override `$ErrorActionPreference`. (#5113) +- Fix `Get-Item -LiteralPath a*b` to return error if `a*b` doesn't actually exist. (#5197) +- Remove `AllScope` from most default aliases to reduce overhead on creating new scopes. (#5268) +- Change `$OutputEncoding` default to be `UTF8` without `BOM` rather than `ASCII`. (#5369) +- Add error on legacy credential over non-HTTPS for Web Cmdlets. (#5402) (Thanks @markekraus!) +- Fix single value JSON `null` in `Invoke-RestMethod`. (#5338) (Thanks @markekraus!) +- Add `PSTypeName` Support for `Import-Csv` and `ConvertFrom-Csv`. (#5389) (Thanks @markekraus!) + +### Engine updates and fixes + +- Add char range overload to the `..` operator, so `'a'..'z'` returns characters from 'a' to 'z'. (#5026) (Thanks @IISResetMe!) +- Remove `CommandFactory` because it serves no real purpose. (#5266) +- Change to not insert line breaks at console window width to output (except for tables). (#5193) +- Use `Ast` for context in parameter binding and fix to glob the native command argument only when it's not quoted. (#5188) +- Fix dynamic class assembly name. (#5292) +- Update PowerShell to use `2.0.4-servicing` dotnet core runtime. (#5295) +- Fix `ExecutionContext.LoadAssembly` to load with name when file cannot be found. (#5161) +- Speed up the check for suspicious content in script texts. (#5302) +- Use native `os_log` APIs on macOS for PowerShell Core logging. (#5310) +- Redirect `ETW` logging to `Syslog` on Linux. (#5144) +- Improve how we pass the array literal to native commands. (#5301) +- Make `SemanticVersion` compatible with `SemVer 2.0`. (#5037) (Thanks @iSazonov!) +- Revert refactoring changes that broke remoting to Windows PowerShell 5.1. (#5321) +- Port some fixes in `Job` for an issue that causes PowerShell to not respond. (#5258) +- Multiple improvements by `CodeRush` static analysis. (#5132) (Thanks @Himura2la!) +- Fix the Runspace cleanup issue that causes PowerShell to not respond on exit. (#5356) +- Update PowerShell to depend on new version of `psrp` and `libmi` nuget packages on Unix platforms. (#5469) + +### General cmdlet updates and fixes + +- Add `-AsHashtable` to `ConvertFrom-Json` to return a `Hashtable` instead. (#5043) (Thanks @bergmeister!) +- Fix `Import-module` to not report a loaded module was not found. (#5238) +- Fix performance issues in `Add-Type`. (#5243) (Thanks @iSazonov!) +- Fix `PSUserAgent` generation for Web Cmdlets on Windows 7. (#5256) (Thanks @markekraus!) +- Remove `DCOM` support from `*-Computer` cmdlets. (#5277) +- Add multiple link header support to Web Cmdlets. (#5265) (Thanks @markekraus!) +- Use wider columns for process id and user. (#5303) +- Add `Remove-Alias` Command. (#5143) (Thanks @PowershellNinja!) +- Update `installpsh-suse.sh` to work with the `tar.gz` package. (#5309) +- Add `Jobject` serialization support to `ConvertTo-Json`. (#5141) +- Display full help with 'help' function. (#5195) (Thanks @rkeithhill!) +- Fix `help` function to not pipe to `more` if objects are returned instead of help text. (#5395) +- Fix `Unblock-File` to not write an error if the file is already unblocked. (#5362) (Thanks @iSazonov!) +- Clean up FullCLR code from Web Cmdlets. (#5376) (Thanks @markekraus!) +- Exclude cmdlets that are not supported on Unix platforms. (#5083) +- Make `Import-Csv` support `CR`, `LF` and `CRLF` as line delimiters. (#5363) (Thanks @iSazonov!) +- Fix spelling in Web Cmdlet errors. (#5427) (Thanks @markekraus!) +- Add `SslProtocol` support to Web Cmdlets. (#5329) (Thanks @markekraus!) + +### Build and Packaging Improvements + +- Use `RCEdit` to embed icon and version information into `pwsh.exe`. (#5178) +- Update Docker file for Nano Server 1709 release. (#5252) +- Change VSCode build task to use `pwsh`. (#5255) +- Refactor building and packaging scripts for signing in release build workflow. (#5300) +- Always build with `-CrossGen` in CI to verify a fix in `CrossGen` tool. (#5315) +- Separate `Install-PowerShellRemoting.ps1` from `psrp.windows` nuget package. (#5330) +- Include symbols folder an embedded zip when packaging symbols. (#5333) +- Add Uniform Type Identifier conforming with Apple standards using a reverse DNS style prefix. (#5323) +- Update `Wix` toolset download link to newer version 3.11 (#5339) (Thanks @bergmeister!) +- Re-enable macOS launcher after fixing an issue that blocked macOS package generation. (#5291) (Thanks @thezim!) +- Set expected binaries and variable name for folder for symbols build. (#5357) +- Rename and update PowerShell `ETW` manifest to remove the Windows PowerShell dependency. (#5360) +- Add ability to produce `tar.gz` package for Raspbian. (#5387) +- Update `Find-Dotnet` to find dotnet with the compatible SDK. (#5341) (Thanks @rkeithhill!) +- Add signing manifest and script to update it with production values. (#5397) +- Add `install-powershell.ps1` to install PowerShell Core on windows. (#5383) +- Make `-Name` a dynamic parameter in `Start-PSPackage`. (#5415) +- Support `[package]` tag in PR CI and fix nightly build on macOS. (#5410) +- Enhance `install-powershell.ps1` to work on Linux and macOS. (#5411) +- Move the `RCEdit` step to the build phase rather than the packaging phase. (#5404) +- Allow packaging from a zip package to allow for signing. (#5418) +- Add automation to validate PowerShell Core packages using Docker containers. (#5401) +- Fix the `brew update` issue in bootstrap script. (#5400) +- Enable `install-powershell.ps1` to update the current running PowerShell Core. (#5429) +- Add standard set of VSCode workspace setting files. (#5457) (Thanks @rkeithhill!) +- Add support for installing PowerShell Core on Amazon Linux via `install-powershell.sh`. (#5461) (Thanks @DarwinJS!) +- Get `PowerShellGet` and `PackageManagement` from the PowerShell Gallery. (#5452) +- Fix `Start-PSBuild` on `WSL` if repository was already built on Windows. (#5346) (Thanks @bergmeister!) +- Fix build in VSCode and use an improved version of `tasks.json` from @rkeithhill. (#5453) +- Add scripts for signing packages in the release build workflow. (#5463) + +### Documentation and Help Content + +- Fix the codebase to use the consistent copyright string. (#5210) +- Add documentation about how to create `libpsl` and `psrp.windows` nuget packages. (#5278) +- Add help strings in PowerShell banner. (#5275) (Thanks @iSazonov!) +- Change all links in `README.md` to absolute as they are being used in other places outside of GitHub. (#5354) +- Update instructions to build on VSCode based on `pwsh`. (#5368) +- Update `FAQ.md` about how to use PowerShell Core nuget packages. (#5366) +- Correct the Fedora documentation (#5384) (Thanks @offthewoll!) +- Add instructions about how to create the `PowerShell.Core.Instrumentation` nuget package. (#5396) +- Updated PowerShell to use the latest help package. (#5454) + +### Compliance Work + +[Compliance](https://github.com/PowerShell/PowerShell/blob/master/docs/maintainers/issue-management.md#miscellaneous-labels) +work is required for Microsoft to continue to sign and release packages from the project as official Microsoft packages. + +- Replace the word `hang` with something more appropriate and add rules about other terms. (#5213, #5297, #5358) +- Use simplified names for compliance folders (#5388) +- Add compliance label description (#5355) +- Set `requestedExecutionLevel` to `asInvoker` for `pwsh.exe` on Windows. (#5285) +- Add `HighEntropyVA` to building pwsh. (#5455) + +## [6.0.0-beta.9] - 2017-10-24 + +### Breaking changes + +- Fix `ValueFromRemainingArguments` to have consistent behavior between script and C# cmdlets. (#2038) (Thanks @dlwyatt) +- Remove parameters `-importsystemmodules` and `-psconsoleFile` from `powershell.exe`. (#4995) +- Removed code to show a GUI prompt for credentials as PowerShell Core prompts in console. (#4995) +- Remove `-ComputerName` from `Get/Set/Remove-Service`. (#5094) +- Rename the executable name from `powershell` to `pwsh`. (#5101) +- Remove `RunspaceConfiguration` support. (#4942) +- Remove `-ComputerName` support since .NET Core `Process.GetProcesses(computer)` returns local processes. (#4960) +- Make `-NoTypeInformation` the default on `Export-Csv` and `ConvertTo-Csv`. (#5164) (Thanks @markekraus) +- Unify cmdlets with parameter `-Encoding` to be of type `System.Text.Encoding`. (#5080) + +### Engine updates and fixes + +- Fix PowerShell to update the `PATH` environment variable only if `PATH` exists. (#5021) +- Enable support of folders and files with colon in name on Unix. (#4959) +- Fix detection of whether `-LiteralPath` was used to suppress wildcard expansion for navigation cmdlets. (#5038) +- Enable using filesystem from a UNC location. (#4998) +- Escape trailing backslash when dealing with native command arguments. (#4965) +- Change location of `ModuleAnalysisCache` so it isn't shared with Windows PowerShell. (#5133) +- Put command discovery before scripts for Unix. (#5116) + +### General cmdlet updates and fixes + +- Correct comma position in `SecureStringCommands.resx`. (#5033) (Thanks @markekraus) +- User Agent of Web Cmdlets now reports the OS platform (#4937) (Thanks @LDSpits) +- Add the positional parameter attribute to `-InputObject` for `Set-Service`. (#5017) (Thanks @travisty-) +- Add `ValidateNotNullOrEmpty` attribute to `-UFormat` for `Get-Date`. (#5055) (Thanks @DdWr) +- Add `-NoNewLine` switch for `Out-String`. (#5056) (Thanks @raghav710) +- Improve progress messages written by Web Cmdlets. (#5078) (Thanks @markekraus) +- Add verb descriptions and alias prefixes for `Get-Verb`. (#4746) (Thanks @Tadas) +- Fix `Get-Content -Raw` to not miss the last line feed character. (#5076) +- Add authentication parameters to Web Cmdlets. (#5052) (Thanks @markekraus) + - Add `-Authentication` that provides three options: Basic, OAuth, and Bearer. + - Add `-Token` to get the bearer token for OAuth and Bearer options. + - Add `-AllowUnencryptedAuthentication` to bypass authentication that is provided for any transport scheme other than HTTPS. +- Fix `MatchInfoContext` clone implementation (#5121) (Thanks @dee-see) +- Exclude `PSHostProcess` cmdlets from Unix platforms. (#5105) +- Fix `Add-Member` to fetch resource string correctly. (#5114) +- Enable `Import-Module` to be case insensitive. (#5097) +- Add exports for `syslog` APIs in `libpsl-native`. (#5149) +- Fix `Get-ChildItem` to not ignore `-Depth` parameter when using with `-Include` or `-Exclude`. (#4985) (Thanks @Windos) +- Added properties `UserName`, `Description`, `DelayedAutoStart`, `BinaryPathName` and `StartupType` to the `ServiceController` objects returned by `Get-Service`. (#4907) (Thanks @joandrsn) + +### Build and Packaging Improvements + +- Treat `.rtf` files as binary so EOL don't get changed. (#5020) +- Improve the output of `tools/installpsh-osx.sh` and update Travis-CI to use Ruby 2.3.3. (#5065) +- Improve `Start-PSBootstrap` to locate dotnet SDK before installing it. (#5059) (Thanks @PetSerAl) +- Fix the prerequisite check of the MSI package. (#5070) +- Support creating `tar.gz` package for Linux and macOS. (#5085) +- Add release builds that produce symbols for compliance scans. (#5086) +- Update existing Docker files for the Linux package changes. (#5102) +- Add compiler switches and replace dangerous function with safer ones. (#5089) +- Add macOS launcher. (#5138) (Thanks @thezim) +- Replace `httpbin.org/response-headers` Tests with WebListener. (#5058) (Thanks @markekraus) +- Update `appimage.sh` to reflect the new name `pwsh`. (#5172) +- Update the man help file used in packaging. (#5173) +- Update to use `pwsh` in macOS launcher. (#5174) (Thanks @thezim) +- Add code to send web hook for Travis-CI daily build. (#5183) +- Add `global.json` to pick correct SDK version. (#5118) (Thanks @rkeithhill) +- Update packaging to only package PowerShell binaries when packaging symbols. (#5145) +- Update Docker files and related due to the name change. (#5156) + +### Code Cleanup + +- Clean up Json cmdlets. (#5001) (Thanks @iSazonov) +- Remove code guarded by `RELATIONSHIP_SUPPORTED` and `SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER`, which has never been used. (#5066) +- Remove PSMI code that has never been used. (#5075) +- Remove unreachable code for `Stop-Job`. (#5091) (Thanks @travisty-) +- Removed font and codepage handling code that is only applicable to Windows PowerShell. (#4995) + +### Test + +- Fix a race condition between `WebListener` and Web Cmdlets tests. (#5035) (Thanks @markekraus) +- Add warning to `Start-PSPester` if Pester module is not found (#5069) (Thanks @DdWr) +- Add tests for DSC configuration compilation on Windows. (#5011) +- Test fixes and code coverage automation fixes. (#5046) + +### Documentation and Help Content + +- Update Pi demo instructions about installing libunwind8. (#4974) +- Add links on best practice guidelines in coding guideline. (#4983) (Thanks @iSazonov) +- Reformat command line help for `powershell -help` (#4989) (Thanks @iSazonov) +- Change logo in readme to current black icon. (#5030) +- Fix RPM package name in `README.md`. (#5044) +- Update `docs/building/linux.md` to reflect the current status of powershell build. (#5068) (Thanks @dee-see) +- Add black version of `.icns` file for macOS. (#5073) (Thanks @thezim) +- Update Arch Linux installation instructions. (#5048) (Thanks @kylesferrazza) +- Add submodule reminder to `testing-guidelines.md`. (#5061) (Thanks @DdWr) +- Update instructions in `docs/building/internals.md` for building from source. (#5072) (Thanks @kylesferrazza) +- Add UserVoice link to Issue Template. (#5100) (Thanks @markekraus) +- Add `Get-WebListenerUrl` Based Examples to WebListener `README.md`. (#4981) (Thanks @markekraus) +- Add document about how to create cmdlet with dotnet CLI. (#5117) (Thanks @rkeithhill) +- Update the help text for PowerShell executable with the new name `pwsh`. (#5182) +- Add new forward links for PowerShell 6.0.0 help content. (#4978) +- Fix VSCode `launch.json` to point to `pwsh`. (#5189) +- Add example of how to create .NET Core cmdlet with Visual Studio. (#5096) + +## [6.0.0-beta.8] - 2017-10-05 + +### Breaking changes + +* Changed `New-Service` to return error when given unsupported `-StartupType` and fixed `Set-Service` icon failing test. (#4802) +* Allow `*` to be used in registry path for `Remove-Item`. (#4866) +* Remove unsupported `-ShowWindow` switch from `Get-Help`. (#4903) +* Fix incorrect position of a parameter which resulted in the args passed as input instead of as args for `InvokeScript()`. (#4963) + +### Engine updates and fixes + +* Make calls to `void CodeMethod` work. (#4850) (Thanks @powercode) +* Get `PSVersion` and `GitCommitId` from the `ProductVersion` attribute of assembly (#4863) (Thanks @iSazonov) +* Fix `powershell -version` and built-in help for `powershell.exe` to align with other native tools. (#4958 & #4931) (Thanks @iSazonov) +* Load assemblies with `Assembly.LoadFrom` before `Assembly.Load` when the file path is given. (#4196) +* Add a generic file watcher function in `HelpersCommon.psm1`. (#4775) +* Update old links and fix broken links in `docs/host-powershell/README.md`. (#4877) +* Fix when importing remote modules using version filters (and added tests). (#4900) +* Enable transcription of native commands on non-Windows platforms. (#4871) +* Add a new line to `CommandNotFoundException` error string. (#4934 & #4991) +* Fix bug where PowerShell would exit with an error within an SSH remoting connection on Linux. (#4993) +* Fix issues with expression redirected to file. (#4847) + +### General cmdlet updates and fixes + +* Added `Remove-Service` to Management module. (#4858) (Thanks @joandrsn) +* Added functionality to set credentials on `Set-Service` command. (#4844) (Thanks @joandrsn) +* Fix `Select-String` to exclude directories (as opposed to individual files) discovered from `-Path`. (#4829) (Thanks @iSazonov) +* `Get-Date` now supports more argument completion scenarios by adding `ArgumentCompletionsAttribute`. (#4835) (Thanks @iSazonov) +* Exclude `-ComObject` parameter of `New-Object` on unsupported (currently non-Windows) platforms. (#4922) (Thanks @iSazonov) +* Updated default `ModuleVersion` in `New-ModuleManifest` to `0.0.1` to align with SemVer. (#4842) (Thanks @LDSpits) +* Add Multipart support to web cmdlets. (#4782) (Thanks @markekraus) +* Add `-ResponseHeadersVariable` to `Invoke-RestMethod` to enable the capture of response headers. (#4888) (Thanks @markekraus) +* Initialize web cmdlets headers dictionary only once. (#4853) (Thanks @markekraus) +* Change web cmdlets `UserAgent` from `WindowsPowerShell` to `PowerShell`. (#4914) (Thanks @markekraus) + +### Build and Packaging Improvements + +* Make the build output the WiX compilation log if it failed. (#4831) (Thanks @bergmeister) +* Use a simple file based check in the MSI for the VC++ 2015 redistributables. (#4745) (Thanks @bergmeister) +* New icon for PowerShell Core. (#4848) +* Build Powershell Core using the generic RID `linux-x64`. (#4841) +* Create generic Linux-x64 packages that are portable to all supported RPM Linux distros (and more similar for Debian based distros). (#4902 & #4994) +* Suppress the output of building test tools in `Compress-TestContent`. (#4957) +* Remove unnecessary error messages from output. (#4954) +* Update Travis CI script so that PRs can fail due to Pester tests. (#4830) +* Move release build definition into PowerShell. (#4884) +* Fix credential scan issues. (#4927 & #4935) +* Enable security flags in native compiler. (#4933) +* Add VS 2017 solution file for `powershell-win-core`. (#4748) + +### Code Cleanup + +* Remove remainder of `Utility.Activities` (Workflow code). (#4880) +* Remove `Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll`. (#4868) +* Enable auto EOL on Git repo side, fix some character encoding issues. (#4912) +* Updated EOL for all files to be LF in the repository. (#4943 & #4956) +* Removed leading whitespace. (#4991) + +### DSC Language + +* Update version of `PSDesiredStateConfiguration` in project files to fix complication of MOF files with the `Configuration` keyword. (#4979) + +### Test + +* Replace httpbin.org tests with `WebListener`. (Thanks @markekraus) + * headers (#4799) + * user-agent (#4798) + * redirect (#4852) + * encoding (#4869) + * delay (#4905) + * gzip & enable deflate (#4948) + * related changes and fixes (#4920) +* Port tests for constrained language mode. (#4816) +* Enable `Select-String` test from a network path. (#4921) (Thanks @iSazonov) +* Reformat `Measure-Object` test. (#4972) (Thanks @iSazonov) +* Mitigate intermittent failures in access denied tests. (#4788) +* Fix tests that incorrectly use `ShouldBeErrorId`. (#4793) +* Fix a test issue that causes tests to be skipped in Travis CI run (#4891) +* Skip web cmdlet certificate authentication tests on CentOS and Mac. (#4822) +* Validate product resource strings against resx files. (#4811 & #4861) +* Add source files for coverage run. (#4925) +* Add the UTC offset correctly in tests for CDXML cmdlets. (#4867) +* Be sure to change `PSDefaultParameterValue` in the global scope. (#4977 & #4892) +* Reduce output of Pester for CI. (#4855) +* Add tests for + * `Get-Content` (#4723) (Thanks @sarithsutha) + * Remoting and Jobs (#4928) + * `Get-Help` (#4895) + * `Get-Command -ShowCommandInfo` (#4906) + * `Get-Content -Tail` (#4790) + * `Get-Module` over remoting (#4787) + * `Start/Stop/Suspend/Resume/Restart-Service` cmdlets (#4774) + * WSMan Config provider tests (#4756) + * CDXML CIM `DateTime` test (#4796) + +### Documentation and Graphics + +* Sort `.spelling` (Thanks @markekraus) +* Improve the guideline for performance consideration. (#4824) +* Add setup steps for MacOS to use PSRP over SSH. (#4872) +* Instructions to demo PowerShell Core on Raspbian. (#4882) +* Added instructions to get permission to use PowerShell image assets. (#4938) +* Added demo for using Windows PowerShell modules. (#4886) + +## [6.0.0-beta.7] - 2017-09-13 + +### Breaking change + +* Fix `Get-Content -Delimiter` to not include the delimiter in the array elements returned (#3706) (Thanks @mklement0) +* Rename `$IsOSX` to `$IsMacOS` (#4757) + +### Engine updates and fixes + +* Use stricter rules when unwrapping a PSObject that wraps a COM object (#4614) +* Remove appended Windows PowerShell `PSModulePath` on Windows. (#4656) +* Ensure `GetNetworkCredential()` returns null if PSCredential has null or empty user name (#4697) +* Push locals of automatic variables to 'DottedScopes' when dotting script cmdlets (#4709) +* Fix `using module` when module has non-terminating errors handled with `SilentlyContinue` (#4711) (Thanks @iSazonov) +* Enable use of 'Singleline,Multiline' option in split operator (#4721) (Thanks @iSazonov) +* Fix error message in `ValidateSetAttribute.ValidateElement()` (#4722) (Thanks @iSazonov) + +### General cmdlet updates and fixes + +* Add Meta, Charset, and Transitional parameters to `ConvertTo-HTML` (#4184) (Thanks @ergo3114) +* Prevent `Test-ModuleManifest` from loading unnecessary modules (#4541) +* Remove AlternateStream code and `-Stream` from provider cmdlets on non-Windows (#4567) +* Add explicit ContentType detection to `Invoke-RestMethod` (#4692) +* Fix an error on `Enter-PSSession` exit (#4693) +* Add `-WhatIf` switch to `Start-Process` cmdlet (#4735) (Thanks @sarithsutha) +* Remove double spaces in .cs, .ps1, and .resx files (#4741 & #4743) (Thanks @korygill) +* Replace 'Windows PowerShell' with 'PowerShell' in resx files (#4758) (Thanks @iSazonov) + +### Build and Packaging Improvements + +* Refactor MSBuild project files to get PowerShell version from git tag (#4182) (Thanks @iSazonov) +* Create a single package for each Windows supported architecture (x86 and amd64) (#4540) +* Set the default windows RID to win7- (#4701) +* Enable cross-compiling for Raspberry-PI arm32 (#4742) +* Fix macOS brew reinstall command (#4627) (Thanks @TheNewStellW) +* Improvements to the Travis-CI script (#4689, #4731, #4807) +* Update OpenSUSE docker image to 42.2 (#4737) +* Confirm `Start-PSPackage` produces a package (#4795) + +### Code Cleanup + +* Remove Workflow code (#4777) +* Clean up CORECLR preprocessor directives in TraceSource (#4684) + +### Test + +* Add test WebListener module and tests for Web Cmdlet Certificate Authentication (#4622) (Thanks @markekraus) +* Move WebCmdlets HTTPS tests to WebListener (#4733) (Thanks @markekraus) +* Replace httpbin.org/get tests With WebListener (#4738) (Thanks @markekraus) +* Use `-PassThru` on Pester tests to reliably catch failures (#4644) +* Display the same number of tests regardless of platform (#4728) +* Improve comparison of code coverage values for a file (#4764) +* Silence PSSessionConfiguration test warning messages in the log (#4794) +* Add tests for + * `Get-Service` (#4773) + * `Set-Service` and `New-Service` (#4785) + * `Trace-Command` (#4288) + * `StaticParameter` (#4779) + * `Test-Wsman` (#4771) + * `New-Object -ComObject` (#4776) + * ProxyCommand APIs (#4791) +* Disable tests + * 'VC++ Redistributable'(#4673 & #4729) + * "Test 01. Standard Property test - all properties ()" due to missing CsPhysicallyInstalledMemory (#4763) + * `New-Service` failing test (#4806) + +### Documentation + +* Update WritingPesterTests.md to recommend ShouldBeErrorId (#4637) +* Clarify the Pull Request process, roles, and responsibilities (#4710) +* Add absolute URLs in the issue template and pull request template (#4718) (Thanks @chucklu) +* Add new approved Build and Deploy verbs (#4725) +* Update using-vscode.md to use the new exe path (#4736) +* Update coding guidelines to make it more concrete and useful in a review process (#4754) + +## [6.0.0-beta.6] - 2017-08-24 + +### Breaking change + +* Make invalid argument error messages for `-File` and `-Command` consistent and make exit codes consistent with Unix standards (#4573) + +### Engine updates and fixes + +* Make resource loading to work with PowerShell SxS installation (#4139) +* Add missing assemblies to TPA list to make Pwrshplughin.dll work (#4502) +* Make sure running `powershell` starts instance of the current version of PowerShell. (#4481) +* Make sure we only use Unicode output by default on Nano and IoT systems (#4074) +* Enable `powershell -WindowStyle` to work on Windows. (#4573) +* Enable enumeration of COM collections. (#4553) + +### General cmdlet updates and fixes + +* Fix Web CmdLets `-SkipHeaderValidation` to work with non-standard User-Agent headers. (#4479 & #4512) (Thanks @markekraus) +* Add Certificate authentication support for Web CmdLets. (#4646) (Thanks @markekraus) +* Add support for content headers to Web CmdLets. (#4494 & #4640) (Thanks @markekraus) +* Add support for converting enums to string (#4318) (Thanks @KirkMunro) +* Ignore casing when binding PSReadline KeyHandler functions (#4300) (Thanks @oising) +* Fix `Unblock-File` for the case of a read-only file. (#4395) (Thanks @iSazonov) +* Use supported API to set Central Access Policy ID (CAPID) in SACL. (#4496) +* Make `Start-Trace` support paths that require escaping in the underlying APIs (#3863) +* Removing `#if CORECLR` enabled, `Enable-PSRemoting` and `Disable-PSRemoting` (#2671) +* Enable WSManCredSSP cmdlets and add tests. (#4336) +* Use .NET Core's implementation for ShellExecute. (#4523) +* Fix SSH Remoting handling of KeyFileParameter when the path must be quoted. (#4529) +* Make Web CmdLets use HTML meta charset attribute value, if present (#4338) +* Move to .NET Core 2.0 final (#4603) + +### Build/test and code cleanup + +* Add Amazon Linux Docker image and enable related tests. (#4393) (Thanks @DarwinJS) +* Make MSI verify pre-requisites are installed. (#4602) (Thank @bergmeister) +* Fixed formatting issues in build files. (#4630) (Thanks @iSazonov) +* Make sure `install-powershell.sh` installs latest powershell on macOS, even if an old version is cached in brew. (#4509) (Thanks @richardszalay for reporting.) +* Fixes install scripts issue for macOS. (#4631) (Thanks @DarwinJS) +* Many stability improvements to our nightly code coverage automation. (#4313 & #4550) +* Remove hash validation from nanoserver-insider Docker file, due to frequent changes. (#4498) +* Update to make Travis-CI daily build badge more reliable. (#4522) +* Remove unused build files, build code, and product code. (#4532, #4580, #4590, #4589, #4588, #4587, #4586, #4583, #4582, #4581) +* Add additional acceptance tests for PowerShellGet. (#4531) +* Only publish a NuGet of the full PowerShell core package on daily builds and not merge. (#4517) +* Update nanoserver-insider Docker file due to breaking changes in the base image. (#4555) +* Cleanup engine tests (#4551) +* Fix intermittent failures in filesystem tests (#4566) +* Add tests for + * `New-WinEvent`. (#4384) + * tab completion. (#4560) + * various types. (#4503) + * CDXML CmdLets. (#4537) +* Only allow packaging of powershell, if it was built from a repo at the root of the file system named powershell. (#4569 & #4600) +* Update `Format-Hex` test cases to use -TestCase instead of foreach loops. (#3800) +* Added functionality to get code coverage for a single file locally. (#4556) + +### Documentation + +* Added Ilya (@iSazonov) as a Maintainer. (#4365) +* Grammar fix to the Pull Request Guide. (#4322) +* Add homebrew for macOS to install documentation. (#3838) +* Added a CodeOwner file. (#4565 & #4597) + +### Cleanup `#if CORECLR` code + +PowerShell 6.0 will be exclusively built on top of CoreCLR, +so we are removing a large amount of code that's built only for FullCLR. +To read more about this, check out [this blog post](https://devblogs.microsoft.com/powershell/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). + +## [6.0.0-beta.5] - 2017-08-02 + +### Breaking changes + +* Remove the `*-Counter` cmdlets in `Microsoft.PowerShell.Diagnostics` due to the use of unsupported APIs until a better solution is found. (#4303) +* Remove the `Microsoft.PowerShell.LocalAccounts` due to the use of unsupported APIs until a better solution is found. (#4302) + +### Engine updates and fixes + +* Fix the issue where PowerShell Core wasn't working on Windows 7 or Windows Server 2008 R2/2012 (non-R2). (#4463) +* `ValidateSetAttribute` enhancement: support set values to be dynamically generated from a custom `ValidateSetValueGenerator`. (#3784) (Thanks to @iSazonov!) +* Disable breaking into debugger on Ctrl+Break when running non-interactively. (#4283) (Thanks to @mwrock!) +* Give error instead of crashing if WSMan client library is not available. (#4387) +* Allow passing `$true`/`$false` as a parameter to scripts using `powershell.exe -File`. (#4178) +* Enable `DataRow`/`DataRowView` adapters in PowerShell Core to fix an issue with `DataTable` usage. (#4258) +* Fix an issue where PowerShell class static methods were being shared across `Runspace`s/`SessionState`s. (#4209) +* Fix array expression to not return null or throw error. (#4296) +* Fixes a CIM deserialization bug where corrupted CIM classes were instantiating non-CIM types. (#4234) +* Improve error message when `HelpMessage` property of `ParameterAttribute` is set to empty string. (#4334) +* Make `ShellExecuteEx` run in a STA thread. (#4362) + +### General cmdlet updates and fixes + +* Add `-SkipHeaderValidation` switch to `Invoke-WebRequest` and `Invoke-RestMethod` to support adding headers without validating the header value. (#4085) +* Add support for `Invoke-Item -Path `. (#4262) +* Fix `ConvertTo-Html` output when using a single column header. (#4276) +* Fix output of `Length` for `FileInfo` when using `Format-List`. (#4437) +* Fix an issue in implicit remoting where restricted sessions couldn't use `Get-FormatData �PowerShellVersion`. (#4222) +* Fix an issue where `Register-PSSessionConfiguration` fails if `SessionConfig` folder doesn't exist. (#4271) + +### Installer updates + +* Create script to install latest PowerShell from Microsoft package repositories (or Homebrew) on non-Windows platforms. (#3608) (Thanks to @DarwinJS!) +* Enable MSI upgrades rather than a side-by-side install. (#4259) +* Add a checkbox to open PowerShell after the Windows MSI installer has finished. (#4203) (Thanks to @bergmeister!) +* Add Amazon Linux compatibility to `install-powershell.sh`. (#4360) (Thanks to @DarwinJS!) +* Add ability to package PowerShell Core as a NuGet package. (#4363) + +### Build/test and code cleanup + +* Add build check for MFC for Visual C++ during Windows builds. + This fixes a long-standing (and very frustrating!) issue with missing build dependencies! (#4185) (Thanks to @KirkMunro!) +* Move building Windows PSRP binary out of `Start-PSBuild`. + Now `Start-PSBuild` doesn't build PSRP binary on windows. Instead, we consume the PSRP binary from a NuGet package. (#4335) +* Add tests for built-in type accelerators. (#4230) (Thanks to @dchristian3188!) +* Increase code coverage of `Get-ChildItem` on file system. (#4342) (Thanks to @jeffbi!) +* Increase test coverage for `Rename-Item` and `Move-Item`. (#4329) (Thanks to @jeffbi!) +* Add test coverage for Registry provider. (#4354) (Thanks to @jeffbi!) +* Fix warnings and errors thrown by PSScriptAnalyzer. (#4261) (Thanks to @bergmeister!) +* Fix regressions that cause implicit remoting tests to fail. (#4326) +* Disable legacy UTC and SQM Windows telemetry by enclosing the code in '#if LEGACYTELEMETRY'. (#4190) + +### Cleanup `#if CORECLR` code + +PowerShell 6.0 will be exclusively built on top of CoreCLR, +so we are removing a large amount of code that's built only for FullCLR. +To read more about this, check out [this blog post](https://devblogs.microsoft.com/powershell/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). + +## [6.0.0-beta.4] - 2017-07-12 + +## Windows PowerShell backwards compatibility + +In the `beta.4` release, we've introduced a change to add the Windows PowerShell `PSModulePath` to the default `PSModulePath` in PowerShell Core on Windows. (#4132) + +Along with the introduction of .NET Standard 2.0 in `6.0.0-beta.1` and a GAC probing fix in `6.0.0-beta.3`, +**this change will enable a large number of your existing Windows PowerShell modules/scripts to "just work" inside of PowerShell Core on Windows**. +(Note: We have also fixed the CDXML modules on Windows that were regressed in `6.0.0-beta.2` as part of #4144). + +So that we can further enable this backwards compatibility, +we ask that you tell us more about what modules or scripts do and don't work in Issue #4062. +This feedback will also help us determine if `PSModulePath` should include the Windows PowerShell values by default in the long run. + +For more information on this, we invite you to read [this blog post explaining PowerShell Core and .NET Standard in more detail](https://blogs.msdn.microsoft.com/powershell/?p=13355). + +### Engine updates and fixes + +- Add Windows PowerShell `PSModulePath` by default on Windows. (#4132) +- Move PowerShell to `2.0.0-preview3-25426-01` and using the .NET CLI version `2.0.0-preview2-006502`. (#4144) +- Performance improvement in PSReadline by minimizing writing ANSI escape sequences. (#4110) +- Implement Unicode escape parsing so that users can use Unicode characters as arguments, strings or variable names. (#3958) (Thanks to @rkeithhill!) +- Script names or full paths can have commas. (#4136) (Thanks to @TimCurwick!) +- Added `semver` as a type accelerator for `System.Management.Automation.SemanticVersion`. (#4142) (Thanks to @oising!) +- Close `eventLogSession` and `EventLogReader` to unlock an ETL log. (#4034) (Thanks to @iSazonov!) + +### General cmdlet updates and fixes + +- `Move-Item` cmdlet honors `-Include`, `-Exclude`, and `-Filter` parameters. (#3878) +- Add a parameter to `Get-ChildItem` called `-FollowSymlink` that traverses symlinks on demand, with checks for link loops. (#4020) +- Change `New-ModuleManifest` encoding to UTF8NoBOM on non-Windows platforms. (#3940) +- `Get-AuthenticodeSignature` cmdlets can now get file signature timestamp. (#4061) +- Add tab completion for `Export-Counter` `-FileFormat` parameter. (#3856) +- Fixed `Import-Module` on non-Windows platforms so that users can import modules with `NestedModules` and `RootModules`. (#4010) +- Close `FileStream` opened by `Get-FileHash`. (#4175) (Thanks to @rkeithhill!) + +### Remoting + +- Fixed PowerShell not responding when the SSH client abruptly terminates. (#4123) + +### Documentation + +- Added recommended settings for VS Code. (#4054) (Thanks to @iSazonov!) + +## [6.0.0-beta.3] - 2017-06-20 + +### Breaking changes + +- Remove the `BuildVersion` property from `$PSVersionTable`. + This property was strongly tied to the Windows build version. + Instead, we recommend that you use `GitCommitId` to retrieve the exact build version of PowerShell Core. + (#3877) (Thanks to @iSazonov!) +- Change positional parameter for `powershell.exe` from `-Command` to `-File`. + This fixes the usage of `#!` (aka as a shebang) in PowerShell scripts that are being executed from non-PowerShell shells on non-Windows platforms. + This also means that you can now do things like `powershell foo.ps1` or `powershell fooScript` without specifying `-File`. + However, this change now requires that you explicitly specify `-c` or `-Command` when trying to do things like `powershell.exe Get-Command`. + (#4019) +- Remove `ClrVersion` property from `$PSVersionTable`. + (This property is largely irrelevant for .NET Core, + and was only preserved in .NET Core for specific legacy purposes that are inapplicable to PowerShell.) + (#4027) + +### Engine updates and fixes + +- Add support to probe and load assemblies from GAC on Windows platform. + This means that you can now load Windows PowerShell modules with assembly dependencies which reside in the GAC. + If you're interested in running your traditional Windows PowerShell scripts and cmdlets using the power of .NET Standard 2.0, + try adding your Windows PowerShell module directories to your PowerShell Core `$PSModulePath`. + (E.g. `$env:PSModulePath += ';C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules'`) + Even if the module isn't owned by the PowerShell Team, please tell us what works and what doesn't by leaving a comment in [issue #4062][issue-4062]! (#3981) +- Enhance type inference in tab completion based on runtime variable values. (#2744) (Thanks to @powercode!) + This enables tab completion in situations like: + + ```powershell + $p = Get-Process + $p | Foreach-Object Prio + ``` + +- Add `GitCommitId` to PowerShell Core banner. + Now you don't have to run `$PSVersionTable` as soon as you start PowerShell to get the version! (#3916) (Thanks to @iSazonov!) +- Fix a bug in tab completion to make `native.exe --` call into native completer. (#3633) (Thanks to @powercode!) +- Fix PowerShell Core to allow use of long paths that are more than 260 characters. (#3960) +- Fix ConsoleHost to honour `NoEcho` on Unix platforms. (#3801) +- Fix transcription to not stop when a Runspace is closed during the transcription. (#3896) + +[issue-4062]: https://github.com/PowerShell/PowerShell/issues/4062 + +### General cmdlet updates and fixes + +- Enable `Send-MailMessage` in PowerShell Core. (#3869) +- Fix `Get-Help` to support case insensitive pattern matching on Unix platforms. (#3852) +- Fix tab completion on `Get-Help` for `about_*` topics. (#4014) +- Fix PSReadline to work in Windows Server Core container image. (#3937) +- Fix `Import-Module` to honour `ScriptsToProcess` when `-Version` is specified. (#3897) +- Strip authorization header on redirects with web cmdlets. (#3885) +- `Start-Sleep`: add the alias `ms` to the parameter `-Milliseconds`. (#4039) (Thanks to @Tadas!) + +### Developer experience + +- Make hosting PowerShell Core in your own .NET applications much easier by refactoring PowerShell Core to use the default CoreCLR loader. (#3903) +- Update `Add-Type` to support `CSharpVersion7`. (#3933) (Thanks to @iSazonov) + +## [6.0.0-beta.2] - 2017-06-01 + +### Support backgrounding of pipelines with ampersand (`&`) (#3360) + +- Putting `&` at the end of a pipeline will cause the pipeline to be run as a PowerShell job. +- When a pipeline is backgrounded, a job object is returned. +- Once the pipeline is running as a job, all of the standard `*-Job` cmdlets can be used to manage the job. +- Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so `Copy-Item $foo $bar &` just works. +- The job is also run in the current directory instead of the user's home directory. +- For more information about PowerShell jobs, see [about_Jobs](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_jobs). + +### Engine updates and fixes + +- Crossgen more of the .NET Core assemblies to improve PowerShell Core startup time. (#3787) +- Enable comparison between a `SemanticVersion` instance and a `Version` instance that is constructed only with `Major` and `Minor` version values. + This will fix some cases where PowerShell Core was failing to import older Windows PowerShell modules. (#3793) (Thanks to @mklement0!) + +### General cmdlet updates and fixes + +- Support Link header pagination in web cmdlets (#3828) + - For `Invoke-WebRequest`, when the response includes a Link header we create a RelationLink property as a Dictionary representing the URLs and `rel` attributes and ensure the URLs are absolute to make it easier for the developer to use. + - For `Invoke-RestMethod`, when the response includes a Link header we expose a `-FollowRelLink` switch to automatically follow `next` `rel` links until they no longer exist or once we hit the optional `-MaximumFollowRelLink` parameter value. +- Update `Get-ChildItem` to be more in line with the way that the *nix `ls -R` and the Windows `DIR /S` native commands handle symbolic links to directories during a recursive search. + Now, `Get-ChildItem` returns the symbolic links it encountered during the search, but it won't search the directories those links target. (#3780) +- Fix `Get-ChildItem` to continue enumeration after throwing an error in the middle of a set of items. + This fixes some issues where inaccessible directories or files would halt execution of `Get-ChildItem`. (#3806) +- Fix `ConvertFrom-Json` to deserialize an array of strings from the pipeline that together construct a complete JSON string. + This fixes some cases where newlines would break JSON parsing. (#3823) +- Enable `Get-TimeZone` for macOS/Linux. (#3735) +- Change to not expose unsupported aliases and cmdlets on macOS/Linux. (#3595) (Thanks to @iSazonov!) +- Fix `Invoke-Item` to accept a file path that includes spaces on macOS/Linux. (#3850) +- Fix an issue where PSReadline was not rendering multi-line prompts correctly on macOS/Linux. (#3867) +- Fix an issue where PSReadline was not working on Nano Server. (#3815) + +## [6.0.0-beta.1] - 2017-05-08 + +### Move to .NET Core 2.0 (.NET Standard 2.0 support) + +PowerShell Core has moved to using .NET Core 2.0 so that we can leverage all the benefits of .NET Standard 2.0. (#3556) +To learn more about .NET Standard 2.0, there's some great starter content [on Youtube](https://www.youtube.com/playlist?list=PLRAdsfhKI4OWx321A_pr-7HhRNk7wOLLY) +and on [the .NET blog](https://devblogs.microsoft.com/dotnet/introducing-net-standard/). +We'll also have more content soon in our [repository documentation](https://github.com/PowerShell/PowerShell/tree/master/docs) (which will eventually make its way to [official documentation](https://github.com/powershell/powershell-docs)). +In a nutshell, .NET Standard 2.0 allows us to have universal, portable modules between Windows PowerShell (which uses the full .NET Framework) and PowerShell Core (which uses .NET Core). +Many modules and cmdlets that didn't work in the past may now work on .NET Core, so import your favorite modules and tell us what does and doesn't work in our GitHub Issues! + +### Telemetry + +- For the first beta of PowerShell Core 6.0, telemetry has been to the console host to report two values (#3620): + - the OS platform (`$PSVersionTable.OSDescription`) + - the exact version of PowerShell (`$PSVersionTable.GitCommitId`) + +If you want to opt-out of this telemetry, simply delete `$PSHome\DELETE_ME_TO_DISABLE_CONSOLEHOST_TELEMETRY`. +Even before the first run of Powershell, deleting this file will bypass all telemetry. +In the future, we plan on also enabling a configuration value for whatever is approved as part of [RFC0015](https://github.com/PowerShell/PowerShell-RFC/blob/master/Archive/Rejected/RFC0015-PowerShell-StartupConfig.md). +We also plan on exposing this telemetry data (as well as whatever insights we leverage from the telemetry) in [our community dashboard](https://devblogs.microsoft.com/powershell/powershell-open-source-community-dashboard/). + +If you have any questions or comments about our telemetry, please file an issue. + +### Engine updates and fixes + +- Add support for native command globbing on Unix platforms. (#3643) + - This means you can now use wildcards with native binaries/commands (e.g. `ls *.txt`). +- Fix PowerShell Core to find help content from `$PSHome` instead of the Windows PowerShell base directory. (#3528) + - This should fix issues where about_* topics couldn't be found on Unix platforms. +- Add the `OS` entry to `$PSVersionTable`. (#3654) +- Arrange the display of `$PSVersionTable` entries in the following way: (#3562) (Thanks to @iSazonov!) + - `PSVersion` + - `PSEdition` + - alphabetical order for rest entries based on the keys +- Make PowerShell Core more resilient when being used with an account that doesn't have some key environment variables. (#3437) +- Update PowerShell Core to accept the `-i` switch to indicate an interactive shell. (#3558) + - This will help when using PowerShell as a default shell on Unix platforms. +- Relax the PowerShell `SemanticVersion` constructors to not require 'minor' and 'patch' portions of a semantic version name. (#3696) +- Improve performance to security checks when group policies are in effect for ExecutionPolicy. (#2588) (Thanks to @powercode) +- Fix code in PowerShell to use `IntPtr(-1)` for `INVALID_HANDLE_VALUE` instead of `IntPtr.Zero`. (#3544) (Thanks to @0xfeeddeadbeef) + +### General cmdlet updates and fixes + +- Change the default encoding and OEM encoding used in PowerShell Core to be compatible with Windows PowerShell. (#3467) (Thanks to @iSazonov!) +- Fix a bug in `Import-Module` to avoid incorrect cyclic dependency detection. (#3594) +- Fix `New-ModuleManifest` to correctly check if a URI string is well formed. (#3631) + +### Filesystem-specific updates and fixes + +- Use operating system calls to determine whether two paths refer to the same file in file system operations. (#3441) + - This will fix issues where case-sensitive file paths were being treated as case-insensitive on Unix platforms. +- Fix `New-Item` to allow creating symbolic links to file/directory targets and even a non-existent target. (#3509) +- Change the behavior of `Remove-Item` on a symbolic link to only removing the link itself. (#3637) +- Use better error message when `New-Item` fails to create a symbolic link because the specified link path points to an existing item. (#3703) +- Change `Get-ChildItem` to list the content of a link to a directory on Unix platforms. (#3697) +- Fix `Rename-Item` to allow Unix globbing patterns in paths. (#3661) + +### Interactive fixes + +- Add Hashtable tab completion for `-Property` of `Select-Object`. (#3625) (Thanks to @powercode) +- Fix tab completion with `@{` to avoid crash in PSReadline. (#3626) (Thanks to @powercode) +- Use ` - ` as `ToolTip` and `ListItemText` when tab completing process ID. (#3664) (Thanks to @powercode) + +### Remoting fixes + +- Update PowerShell SSH remoting to handle multi-line error messages from OpenSSH client. (#3612) +- Add `-Port` parameter to `New-PSSession` to create PowerShell SSH remote sessions on non-standard (non-22) ports. (#3499) (Thanks to @Lee303) + +### API Updates + +- Add the public property `ValidRootDrives` to `ValidateDriveAttribute` to make it easy to discover the attribute state via `ParameterMetadata` or `PSVariable` objects. (#3510) (Thanks to @indented-automation!) +- Improve error messages for `ValidateCountAttribute`. (#3656) (Thanks to @iSazonov) +- Update `ValidatePatternAttribute`, `ValidateSetAttribute` and `ValidateScriptAttribute` to allow users to more easily specify customized error messages. (#2728) (Thanks to @powercode) + +## [6.0.0-alpha.18] - 2017-04-05 + +### Progress Bar + +We made a number of fixes to the progress bar rendering and the `ProgressRecord` object that improved cmdlet performance and fixed some rendering bugs on non-Windows platforms. + +- Fix a bug that caused the progress bar to drift on Unix platforms. (#3289) +- Improve the performance of writing progress records. (#2822) (Thanks to @iSazonov!) +- Fix the progress bar rendering on Unix platforms. (#3362) (#3453) +- Reuse `ProgressRecord` in Web Cmdlets to reduce the GC overhead. (#3411) (Thanks to @iSazonov!) + +### Cmdlet updates + +- Use `ShellExecute` with `Start-Process`, `Invoke-Item`, and `Get-Help -Online` so that those cmdlets use standard shell associations to open a file/URI. + This means you `Get-Help -Online` will always use your default browser, and `Start-Process`/`Invoke-Item` can open any file or path with a handler. + (Note: there are still some problems with STA threads.) (#3281, partially fixes #2969) +- Add `-Extension` and `-LeafBase` switches to `Split-Path` so that you can split paths between the filename extension and the rest of the filename. (#2721) (Thanks to @powercode!) +- Implement `Format-Hex` in C# along with some behavioral changes to multiple parameters and the pipeline. (#3320) (Thanks to @MiaRomero!) +- Add `-NoProxy` to web cmdlets so that they ignore the system-wide proxy setting. (#3447) (Thanks to @TheFlyingCorpse!) +- Fix `Out-Default -Transcript` to properly revert out of the `TranscribeOnly` state, so that further output can be displayed on Console. (#3436) (Thanks to @PetSerAl!) +- Fix `Get-Help` to not return multiple instances of the same help file. (#3410) + +### Interactive fixes + +- Enable argument auto-completion for `-ExcludeProperty` and `-ExpandProperty` of `Select-Object`. (#3443) (Thanks to @iSazonov!) +- Fix a tab completion bug that prevented `Import-Module -n` from working. (#1345) + +### Cross-platform fixes + +- Ignore the `-ExecutionPolicy` switch when running PowerShell on non-Windows platforms because script signing is not currently supported. (#3481) +- Standardize the casing of the `PSModulePath` environment variable. (#3255) + +### JEA fixes + +- Fix the JEA transcription to include the endpoint configuration name in the transcript header. (#2890) +- Fix `Get-Help` in a JEA session. (#2988) + +## [6.0.0-alpha.17] - 2017-03-08 + +- Update PSRP client libraries for Linux and Mac. + - We now support customer configurations for Office 365 interaction, as well as NTLM authentication for WSMan based remoting from Linux (more information [here](https://github.com/PowerShell/psl-omi-provider/releases/tag/v1.0.0.18)). (#3271) +- We now support remote step-in debugging for `Invoke-Command -ComputerName`. (#3015) +- Use prettier formatter with `ConvertTo-Json` output. (#2787) (Thanks to @kittholland!) +- Port `*-CmsMessage` and `Get-PfxCertificate` cmdlets to Powershell Core. (#3224) +- `powershell -version` now returns version information for PowerShell Core. (#3115) +- Add the `-TimeOut` parameter to `Test-Connection`. (#2492) +- Add `ShouldProcess` support to `New-FileCatalog` and `Test-FileCatalog` (fixes `-WhatIf` and `-Confirm`). (#3074) (Thanks to @iSazonov!) +- Fix `Test-ModuleManifest` to normalize paths correctly before validating. + - This fixes some problems when using `Publish-Module` on non-Windows platforms. (#3097) +- Remove the `AliasProperty "Count"` defined for `System.Array`. + - This removes the extraneous `Count` property on some `ConvertFrom-Json` output. (#3231) (Thanks to @PetSerAl!) +- Port `Import-PowerShellDatafile` from PowerShell script to C#. (#2750) (Thanks to @powercode!) +- Add `-CustomMethod` parameter to web cmdlets to allow for non-standard method verbs. (#3142) (Thanks to @Lee303!) +- Fix web cmdlets to include the HTTP response in the exception when the response status code is not success. (#3201) +- Expose a process' parent process by adding the `CodeProperty "Parent"` to `System.Diagnostics.Process`. (#2850) (Thanks to @powercode!) +- Fix crash when converting a recursive array to a bool. (#3208) (Thanks to @PetSerAl!) +- Fix casting single element array to a generic collection. (#3170) +- Allow profile directory creation failures for Service Account scenarios. (#3244) +- Allow Windows' reserved device names (e.g. CON, PRN, AUX, etc.) to be used on non-Windows platforms. (#3252) +- Remove duplicate type definitions when reusing an `InitialSessionState` object to create another Runspace. (#3141) +- Fix `PSModuleInfo.CaptureLocals` to not do `ValidateAttribute` check when capturing existing variables from the caller's scope. (#3149) +- Fix a race bug in WSMan command plug-in instance close operation. (#3203) +- Fix a problem where newly mounted volumes aren't available to modules that have already been loaded. (#3034) +- Remove year from PowerShell copyright banner at start-up. (#3204) (Thanks to @kwiknick!) +- Fixed spelling for the property name `BiosSerialNumber` for `Get-ComputerInfo`. (#3167) (Thanks to @iSazonov!) + +## [6.0.0-alpha.16] - 2017-02-15 + +- Add `WindowsUBR` property to `Get-ComputerInfo` result +- Cache padding strings to speed up formatting a little +- Add alias `Path` to the `-FilePath` parameter of `Out-File` +- Fix the `-InFile` parameter of `Invoke-WebRequest` +- Add the default help content to powershell core +- Speed up `Add-Type` by crossgen'ing its dependency assemblies +- Convert `Get-FileHash` from script to C# implementation +- Fix lock contention when compiling the code to run in interpreter +- Avoid going through WinRM remoting stack when using `Get-ComputerInfo` locally +- Fix native parameter auto-completion for tokens that begin with a single "Dash" +- Fix parser error reporting for incomplete input to allow defining class in interactive host +- Add the `RoleCapabilityFiles` keyword for JEA support on Windows + +## [6.0.0-alpha.15] - 2017-01-18 + +- Use parentheses around file length for offline files +- Fix issues with the Windows console mode (terminal emulation) and native executables +- Fix error recovery with `using module` +- Report `PlatformNotSupported` on IoT for Get/Import/Export-Counter +- Add `-Group` parameter to `Get-Verb` +- Use MB instead of KB for memory columns of `Get-Process` +- Add new escape character for ESC: `` `e`` +- Fix a small parsing issue with a here string +- Improve tab completion of types that use type accelerators +- `Invoke-RestMethod` improvements for non-XML non-JSON input +- PSRP remoting now works on CentOS without addition setup + +## [6.0.0-alpha.14] - 2016-12-14 + +- Moved to .NET Core 1.1 +- Add Windows performance counter cmdlets to PowerShell Core +- Fix try/catch to choose the more specific exception handler +- Fix issue reloading modules that define PowerShell classes +- `Add ValidateNotNullOrEmpty` to approximately 15 parameters +- `New-TemporaryFile` and `New-Guid` rewritten in C# +- Enable client side PSRP on non-Windows platforms +- `Split-Path` now works with UNC roots +- Implicitly convert value assigned to XML property to string +- Updates to `Invoke-Command` parameters when using SSH remoting transport +- Fix `Invoke-WebRequest` with non-text responses on non-Windows platforms +- `Write-Progress` performance improvement from `alpha13` reverted because it introduced crash with a race condition + +## [6.0.0-alpha.13] - 2016-11-22 + +- Fix `NullReferenceException` in binder after turning on constrained language mode +- Enable `Invoke-WebRequest` and `Invoke-RestMethod` to not validate the HTTPS certificate of the server if required. +- Enable binder debug logging in PowerShell Core +- Add parameters `-Top` and `-Bottom` to `Sort-Object` for Top/Bottom N sort +- Enable `Update-Help` and `Save-Help` on Unix platforms +- Update the formatter for `System.Diagnostics.Process` to not show the `Handles` column +- Improve `Write-Progress` performance by adding timer to update a progress pane every 100 ms +- Enable correct table width calculations with ANSI escape sequences on Unix +- Fix background jobs for Unix and Windows +- Add `Get-Uptime` to `Microsoft.PowerShell.Utility` +- Make `Out-Null` as fast as `> $null` +- Add DockerFile for 'Windows Server Core' and 'Nano Server' +- Fix WebRequest failure to handle missing ContentType in response header +- Make `Write-Host` fast by delay initializing some properties in InformationRecord +- Ensure PowerShell Core adds an initial `/` rooted drive on Unix platforms +- Enable streaming behavior for native command execution in pipeline, so that `ping | grep` doesn't block +- Make `Write-Information` accept objects from pipeline +- Fixes deprecated syscall issue on macOS 10.12 +- Fix code errors found by the static analysis using PVS-Studio +- Add support to W3C Extended Log File Format in `Import-Csv` +- Guard against `ReflectionTypeLoadException` in type name auto-completion +- Update build scripts to support win7-x86 runtime +- Move PackageManagement code/test to oneget.org + +## [6.0.0-alpha.12] - 2016-11-03 + +- Fix `Get-ChildItem -Recurse -ErrorAction Ignore` to ignore additional errors +- Don't block pipeline when running Windows EXE's +- Fix for PowerShell SSH remoting with recent Win32-OpenSSH change. +- `Select-Object` with `-ExcludeProperty` now implies `-Property *` if -Property is not specified. +- Adding ValidateNotNullOrEmpty to `-Name` parameter of `Get-Alias` +- Enable Implicit remoting commands in PowerShell Core +- Fix GetParentProcess() to replace an expensive WMI query with Win32 API calls +- Fix `Set-Content` failure to create a file in PSDrive under certain conditions. +- Adding ValidateNotNullOrEmpty to `-Name` parameter of `Get-Service` +- Adding support in `Get-WinEvent -FilterHashtable` +- Adding WindowsVersion to `Get-ComputerInfo` +- Remove the unnecessary use of lock in PseudoParameterBinder to avoid deadlock +- Refactor `Get-WinEvent` to use StringBuilder for XPath query construction +- Clean up and fix error handling of libpsl-native +- Exclude Registry and Certificate providers from UNIX PS +- Update PowerShell Core to consume .Net Core preview1-24530-04 + +## [6.0.0-alpha.11] - 2016-10-17 + +- Add '-Title' to 'Get-Credential' and unify the prompt experience +- Update dependency list for PowerShell Core on Linux and OS X +- Fix 'powershell -Command -' to not stop responding and to not ignore the last command +- Fix binary operator tab completion +- Enable 'ConvertTo-Html' in PowerShell Core +- Remove most Maximum* capacity variables +- Fix 'Get-ChildItem -Hidden' to work on system hidden files on Windows +- Fix 'JsonConfigFileAccessor' to handle corrupted 'PowerShellProperties.json' + and defer creating the user setting directory until a write request comes +- Fix variable assignment to not overwrite read-only variables +- Fix 'Get-WinEvent -FilterHashtable' to work with named fields in UserData of event logs +- Fix 'Get-Help -Online' in PowerShell Core on Windows +- Spelling/grammar fixes + +## [6.0.0-alpha.10] - 2016-09-15 + +- Fix passing escaped double quoted spaces to native executables +- Add DockerFiles to build each Linux distribution +- `~/.config/PowerShell` capitalization bug fixed +- Fix crash on Windows 7 +- Fix remote debugging on Windows client +- Fix multi-line input with redirected stdin +- Add PowerShell to `/etc/shells` on installation +- Fix `Install-Module` version comparison bug +- Spelling fixes + +## [6.0.0-alpha.9] - 2016-08-15 + +- Better man page +- Added third-party and proprietary licenses +- Added license to MSI + +## [6.0.0-alpha.8] - 2016-08-11 + +- PowerShell packages pre-compiled with crossgen +- `Get-Help` content added +- `Get-Help` null reference exception fixed +- Ubuntu 16.04 support added +- Unsupported cmdlets removed from Unix modules +- PSReadline long prompt bug fixed +- PSReadline custom key binding bug on Linux fixed +- Default terminal colors now respected +- Semantic Version support added +- `$env:` fixed for case-sensitive variables +- Added JSON config files to hold some settings +- `cd` with no arguments now behaves as `cd ~` +- `ConvertFrom-Json` fixed for multiple lines +- Windows branding removed +- .NET CoreCLR Runtime patched to version 1.0.4 +- `Write-Host` with unknown hostname bug fixed +- `powershell` man-page added to package +- `Get-PSDrive` ported to report free space +- Desired State Configuration MOF compilation ported to Linux +- Windows 2012 R2 / Windows 8.1 remoting enabled + +## [6.0.0-alpha.7] - 2016-07-26 + +- Invoke-WebRequest and Invoke-RestMethod ported to PowerShell Core +- Set PSReadline default edit mode to Emacs on Linux +- IsCore variable renamed to IsCoreCLR +- Microsoft.PowerShell.LocalAccounts and other Windows-only assemblies excluded on Linux +- PowerShellGet fully ported to Linux +- PackageManagement NuGet provider ported +- Write-Progress ported to Linux +- Get-Process -IncludeUserName ported +- Enumerating symlinks to folders fixed +- Bugs around administrator permissions fixed on Linux +- ConvertFrom-Json multi-line bug fixed +- Execution policies fixed on Windows +- TimeZone cmdlets added back; excluded from Linux +- FileCatalog cmdlets added back for Windows +- Get-ComputerInfo cmdlet added back for Windows + +## [0.6.0] - 2016-07-08 + +- Targets .NET Core 1.0 release +- PowerShellGet enabled +- [system.manage] completion issues fixed +- AssemblyLoadContext intercepts dependencies correctly +- Type catalog issues fixed +- Invoke-Item enabled for Linux and OS X +- Windows ConsoleHost reverted to native interfaces +- Portable ConsoleHost redirection issues fixed +- Bugs with pseudo (and no) TTY's fixed +- Source Depot synced to baseline changeset 717473 +- SecureString stub replaced with .NET Core package + +## [0.5.0] - 2016-06-16 + +- Paths given to cmdlets are now slash-agnostic (both / and \ work as directory separator) +- Lack of cmdlet support for paths with literal \ is a known issue +- .NET Core packages downgraded to build rc2-24027 (Nano's build) +- XDG Base Directory Specification is now respected and used by default +- Linux and OS X profile path is now `~/.config/powershell/profile.ps1` +- Linux and OS X history save path is now `~/.local/share/powershell/PSReadLine/ConsoleHost_history.txt` +- Linux and OS X user module path is now `~/.local/share/powershell/Modules` +- The `~/.powershell` folder is deprecated and should be deleted +- Scripts can be called within PowerShell without the `.ps1` extension +- `Trace-Command` and associated source cmdlets are now available +- `Ctrl-C` now breaks running cmdlets correctly +- Source Depot changesets up to 715912 have been merged +- `Set-PSBreakPoint` debugging works on Linux, but not on Windows +- MSI and APPX packages for Windows are now available +- Microsoft.PowerShell.LocalAccounts is available on Windows +- Microsoft.PowerShell.Archive is available on Windows +- Linux xUnit tests are running again +- Many more Pester tests are running + +## [0.4.0] - 2016-05-17 + +- PSReadline is ported and included by default +- Original Windows ConsoleHost is ported and replaced CoreConsoleHost +- .NET Core packages set to the RC2 release at build 24103 +- OS X 10.11 added to Continuous Integration matrix +- Third-party C# cmdlets can be built with .NET CLI +- Improved symlink support on Linux +- Microsoft.Management.Infrastructure.Native replaced with package +- Many more Pester tests + +## [0.3.0] - 2016-04-11 + +- Supports Windows, Nano, OS X, Ubuntu 14.04, and CentOS 7.1 +- .NET Core packages are build rc3-24011 +- Native Linux commands are not shadowed by aliases +- `Get-Help -Online` works +- `more` function respects the Linux `$PAGER`; defaults to `less` +- `IsWindows`, `IsLinux`, `IsOSX`, `IsCore` built-in PowerShell variables added +- `Microsoft.PowerShell.Platform` removed for the above +- Cross-platform core host is now `CoreConsoleHost` +- Host now catches exceptions in `--command` scripts +- Host's shell ID changed to `Microsoft.PowerShellCore` +- Modules that use C# assemblies can be loaded +- `New-Item -ItemType SymbolicLink` supports arbitrary targets +- PSReadline implementation supports multi-line input +- `Ctrl-R` provides incremental reverse history search +- `$Host.UI.RawUI` now supported +- `Ctrl-K` and `Ctrl-Y` for kill and yank implemented +- `Ctrl-L` to clear screen now works +- Documentation was completely overhauled +- Many more Pester and xUnit tests added + +## [0.2.0] - 2016-03-08 + +- Supports Windows, OS X, Ubuntu 14.04, and CentOS 7.1 +- .NET Core packages are build 23907 +- `System.Console` PSReadline is fully functional +- Tests pass on OS X +- `Microsoft.PowerShell.Platform` module is available +- `New-Item` supports symbolic and hard links +- `Add-Type` now works +- PowerShell code merged with upstream `rs1_srv_ps` + +## 0.1.0 - 2016-02-23 + +- Supports Windows, OS X, and Ubuntu 14.04 + +[6.0.0]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-rc.2...v6.0.0 +[6.0.0-rc.2]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-rc...v6.0.0-rc.2 +[6.0.0-rc]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.9...v6.0.0-rc +[6.0.0-beta.9]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.8...v6.0.0-beta.9 +[6.0.0-beta.8]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.7...v6.0.0-beta.8 +[6.0.0-beta.7]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.6...v6.0.0-beta.7 +[6.0.0-beta.6]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.5...v6.0.0-beta.6 +[6.0.0-beta.5]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.4...v6.0.0-beta.5 +[6.0.0-beta.4]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.3...v6.0.0-beta.4 +[6.0.0-beta.3]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.2...v6.0.0-beta.3 +[6.0.0-beta.2]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-beta.1...v6.0.0-beta.2 +[6.0.0-beta.1]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.18...v6.0.0-beta.1 +[6.0.0-alpha.18]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.17...v6.0.0-alpha.18 +[6.0.0-alpha.17]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.16...v6.0.0-alpha.17 +[6.0.0-alpha.16]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.15...v6.0.0-alpha.16 +[6.0.0-alpha.15]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.14...v6.0.0-alpha.15 +[6.0.0-alpha.14]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.13...v6.0.0-alpha.14 +[6.0.0-alpha.13]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.12...v6.0.0-alpha.13 +[6.0.0-alpha.12]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.11...v6.0.0-alpha.12 +[6.0.0-alpha.11]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.10...v6.0.0-alpha.11 +[6.0.0-alpha.10]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.9...v6.0.0-alpha.10 +[6.0.0-alpha.9]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.8...v6.0.0-alpha.9 +[6.0.0-alpha.8]: https://github.com/PowerShell/PowerShell/compare/v6.0.0-alpha.7...v6.0.0-alpha.8 +[6.0.0-alpha.7]: https://github.com/PowerShell/PowerShell/compare/v0.6.0...v6.0.0-alpha.7 +[0.6.0]: https://github.com/PowerShell/PowerShell/compare/v0.5.0...v0.6.0 +[0.5.0]: https://github.com/PowerShell/PowerShell/compare/v0.4.0...v0.5.0 +[0.4.0]: https://github.com/PowerShell/PowerShell/compare/v0.3.0...v0.4.0 +[0.3.0]: https://github.com/PowerShell/PowerShell/compare/v0.2.0...v0.3.0 +[0.2.0]: https://github.com/PowerShell/PowerShell/compare/v0.1.0...v0.2.0 diff --git a/PowerShell-master/CHANGELOG/6.1.md b/PowerShell-master/CHANGELOG/6.1.md new file mode 100644 index 0000000000000000000000000000000000000000..59cf2842d78a7f5e7f74a4acd296e7d5de65c6e7 --- /dev/null +++ b/PowerShell-master/CHANGELOG/6.1.md @@ -0,0 +1,797 @@ +# 6.1 Changelog + +## [6.1.6] - 2019-09-12 + +### Build and Packaging Improvements + +- Update DotNet SDK and runtime framework version (Internal 9945) + +## [6.1.5] - 2019-07-16 + +### Breaking changes + +- Disable `Enter-PSHostProcess` cmdlet when system in lock down mode (Internal 8968) + +### Build and Packaging Improvements + +- Update DotNet SDK and runtime framework version (Internal 9087) +- Add automated RPM signing to release build (#10013) +- Update copyright symbol for NuGet packages (#9936) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.3` to `4.5.4` (#9790) +- Integrate building NuGet package in the coordinated build (#8947) (#9708) +- Bump `Newtonsoft.Json` (#9662) + +## [6.1.4] - 2019-05-21 + +### Build and Packaging Improvements + +- Disable debugger in System Lock down mode (Internal 8430) +- Port changes for release automation to `6.1` (Internal 8402) +- Fix `MSI` `WIX` generation (#9013) (Internal 8385) +- Update `Microsoft.PowerShell.Archive` version (Internal 8380) +- Update package version in hosting test (Internal 8374) +- Bump to `dotnet` `2.1.11` release +- Remove update build table logic from release build (Internal 8364) +- Add `AccessToken` variable to jobs that perform signing (#9351) +- Support release branches based on the forward slash separator (#8903) + +## [6.1.3] - 2019-02-14 + +### Engine Updates and Fixes + +- Add security mitigation for 6.1.3 release (Internal 6561) + +### Tools + +- Change the feed URL to feed name due to changes in Azure DevOps (#8664) + +### Tests + +- Updating test gallery URL in PackageManagement tests (#7879) + +### Build and Packaging Improvements + +- Get PowerShellGet tests working (#7831) +- Start tracking release build information in an azure storage table (#8850) +- Remove `PDBs` from `fxdependent` package (#8006) +- Make every `csproj` files have its own folder (#8750) +- Update packaging script to build reference assembly targeting `netcoreapp2.1` and use actual `.csproj` files (#8729) +- Move Final artifacts from coordinated build to `finalResults` folder (#8806) +- Refactor Unified Release Build (#8804) +- Add compliance to Coordinated build (#8798) +- Switch to 1.11 of FPM to fix FPM install issue (#8797) +- Update the coordinated build with framework dependent package for dotnet SDK (#8773) +- Add Windows build to coordinated release build YAML (#8695) +- Build package build using Ubuntu 18.04 image (#8666) +- Adding `yml` for Windows Release builds (#8374) +- Update `SignType` in `signing.xml` (#8223) +- Update DotNet SDK and Runtime version (Internal 7004) +- Add `binskim` to coordinated build and increase timeout (#8834) + +## [6.1.2] - 2019-01-15 + +### Tests + +- Fix test failures (Internal 6310) + +### Build and Packaging Improvements + +- Moved the cleanup logic to `Restore-PSModuleToBuild` (Internal 6442) +- Update dependency versions (Internal 6421) +- Create unified release build for macOS and Linux packages (#8399) +- Build Alpine `tar.gz` package in release builds (Internal 6027) + +### Documentation and Help Content + +- Update version for README, Alpine docker file and hosting tests (Internal 6438) + +## [6.1.1] - 2018-11-13 + +### Engine Updates and Fixes + +- Fix issue with logging the null character in `ScriptBlock` logging (Internal 5607) +- Consolidation of all Windows PowerShell work ported to 6.1 (Internal 5233) + +### General Cmdlet Updates and Fixes + +- Use `ZipFile` and `ExtractToDirectory` APIs to extract zip file (Internal 5608) + +## [6.0.5] - 2018-11-13 + +### Engine updates and fixes + +- Fix issue with logging the null character in `ScriptBlock` logging (Internal 5605) + +### General cmdlet updates and fixes + +- Use `ZipFile` and `ExtractToDirectory` APIs to extract zip file (Internal 4802) + +### Build and Packaging Improvements + +- Update `SignType` in `signing.xml` (Internal 5721) +- Port changes to pull PowerShell Gallery modules from Modules `csproj` (Internal 5713) +- Port macOS Release build changes changes from GitHub (#8189, #8188, #8185) +- Fix script path for `PowerShellPackageVsts.ps1` (#8189) +- Workaround for accessing `AzDevOps` Artifacts (#8188) +- Bump various packages to latest patch version (Internal 5675) +- Update PowerShell SDK NuGet various metadata description (Internal 4527, 4510, 4505) + +## [6.0.4] - 2018-08-10 + +### Build and Packaging Improvements + +- Update the Archive module version (Internal 5671) +- Update to .NET Core `2.1.5` with SDK `2.1.403` (#7936) (Thanks @iSazonov!) +- Disable package major upgrade tests for release branch (Internal 5209) +- Bump versions for dependencies (Internal 5612) +- Port changes to allow `AzDevOps` NuGet feeds for macOS build (Internal 5716) +- Port macOS changes from GitHub (#8189, #8188, #8185) +- Add function to create a new `nuget.config` file (#8170) +- Updated `wxs` file to match published packages (Internal 5660) + +### Tests + +- Change API to match cmdlet which is more reliable in `AzDevOps` Pipelines Windows (#8003) +- Fix conflict with `Get-AdlStoreChildItem` from `az` module in tab completion tests (#8167) + +## [6.1.0] - 2018-09-13 + +### Engine Updates and Fixes + +- Enable indexing operations on `System.Tuple` and `System.ValueTuple` (#7633) (Thanks @SeeminglyScience!) +- Use non-virtual call to invoke 'family or assembly' methods on base class from PowerShell class (#7624) (Thanks @yurko7!) +- Handle operations with `ByRef-like` types gracefully in PowerShell (#7533) +- Make the `-settingfile` flag on `pwsh` work for `ScriptBlock` logging on windows (#7631) +- Ensure the `SSHClientSessionTransportManager` stream writer and reader fields are cleared after disposing (#7746) +- Add `LocationChangedAction` handler to support the Windows Compatibility module (#7552) + +### General Cmdlet Updates and Fixes + +- Fix `Set-Service -Status Stopped` to stop services with dependencies (#5525) (Thanks @zhenggu!) +- Add the `Duration` property to `HistoryInfo` (#5208) (Thanks @powercode!) +- Fix null reference in `ConvertFrom-Markdown` when the markdown content is empty (#7463) +- Fix file blocking issue with WebCmdlets (#7676) (Thanks @Claustn!) +- Fix performance issue in `WSMan` provider by using `Refresh()` to update the status rather than instantiating `ServiceController` (#7680) + +### Code Cleanup + +- Remove `Suspend-Job` and `Resume-Job` cmdlets from compilation on Unix platforms (#7650) +- Remove extra spaces in error messages in `Modules.resx` (#7662) (Thanks @sethvs!) +- Cleanup the platform runtime checks from `FileSystemProvider` (#7655) (Thanks @iSazonov!) +- Improve code style of `Send-MailMessage` cmdlet (#7723) (Thanks @ThreeFive-O!) + +### Tools + +- Add tools for PowerShell performance analysis (#7595) (Thanks @lzybkr!) +- Update code coverage module to download zip files based on job ID (#7653) + +### Tests + +- Update test which assumes all previews have the name preview in the version (#7625) +- Update Pester syntax in `Set-Location` test (#7615) (Thanks @iSazonov!) +- Add `ScriptBlock` logging test for Linux and macOS (#7599) (#7586) +- Add tests to report when package references are out of date (#7661) +- Fix `ModuleSpecification.Tests.ps1` (#7663) (Thanks @sethvs!) +- Updates Docker package tests (#7667) + +### Build and Packaging Improvements + +- Update to the latest package references, dotnet core SDK and framework (#7646) (Thanks @iSazonov!) +- Make the artifact upload only occur for non-PR builds (#7657) +- Change to not upload artifacts during pull request due to missing VSTS feature (#7588) +- Remove workaround on VSTS that is no longer needed (#7666) +- Update docker files to use MCR (#7656) +- Add symbolic links for `libssl` and `libcrypto` to Debian 9 build to make remoting work (#7609) +- Simplify the `StartupInfo` type used in Jumplist creation for faster `P/Invoke` (#7580) (Thanks @powercode!) +- Add VSTS CI for Windows (#7536) +- Update the version of `PowerShellGet` module to `1.6.7` (#7564) +- update the version of `PSReadLine` module to `2.0.0-beta3` (#7711) +- Make sure MSI build works for non-preview builds (#7752) +- Build and package framework dependent package (#7729) +- Change locale of `mdspell` to `en-US` (#7671) +- Add daily build on non-windows platforms (#7683) +- Fix Windows MSI to remove the `Uninstall` shortcut during an uninstall when more than one version is installed (#7701) (Thanks @bergmeister!) +- Fix docker image names for release build (#7726) + +### Documentation and Help Content + +- Update the version of .NET Core in docs (#7467) (Thanks @bergmeister!) +- Fix links in `README.md` (#7619) (Thanks @iSazonov!) +- Add VSTS CI build badges for master branch to `README.md` (#7691) (Thanks @bergmeister!) +- Add a paragraph in `CONTRIBUTING.md` about updating `files.wxs` (#7695) (Thanks @iSazonov!) + +# [6.1.0-rc.1]- 2018-08-22 + +### Engine Updates and Fixes + +- Fix to not duplicate the `System32` module path when starting `pwsh` from `pwsh` (#7414) +- Fix sequence point update for `switch/if/for/while/do-while/do-until` statements (#7305) +- Set the cursor to the place where a user hits tab key (#7299) +- Adding `LanguagePrimitives.TryCompare` to provide faster comparisons (#7438) (Thanks @powercode!) +- Improving performance of `LanguagePrimitives.TryConvertTo` (#7418) (Thanks @powercode!) +- Set `PowerShellVersion` to `3.0` for built-in modules to make Windows PowerShell work when starting from PowerShell Core (#7365) +- Avoid extra unnecessary allocations in `PSMemberInfoInternalCollection` (#7435) (Thanks @iSazonov!) +- Enforce the `CompatiblePSEditions` check for modules from the legacy `System32` module path (#7183) +- Make sure that `SettingFile` argument is parsed before we load the settings (#7449) +- Default to `DefaultConsoleWidth` when DotNet says `WindowWidth` is 0 (#7465) + +### General Cmdlet Updates and Fixes + +- Fix parameter name in the `Get-Variable` cmdlet error message (#7384) (Thanks @sethvs!) +- Fix `Move-Item -Path` with wildcard character (#7397) (Thanks @kwkam!) +- Ignore `Newtonsoft.Json` metadata properties in `ConvertFrom-Json` (#7308) (Thanks @louistio!) +- Fix several issues in Markdown cmdlets (#7329) +- Add support for parsing Link Header with variable whitespace (#7322) +- Change parameter order in `Get-Help` and help in order to get first `-Full` and + then `-Functionality` when using Get-Help `-Fu` followed by pressing tab and help `-Fu` followed by pressing tab (#7370) (Thanks @sethvs!) +- Add support for passing files and Markdown directly to `Show-Markdown` (#7354) +- Add `-SkipIndex` parameter to `Select-Object` (#7483) (Thanks @powercode!) +- Improve performance of `Import-CSV` up to 10 times (#7413) (Thanks @powercode!) +- Update `Enable-PSRemoting` so configuration name is unique for Preview releases (#7202) +- Improve performance on JSON to PSObject conversion (#7482) (Thanks @powercode!) +- Fix error message for `Add-Type` when `-AssemblyName` with wildcard is not found (#7444) +- Make native globbing on Unix return an absolute path when it is given an absolute path (#7106) +- Improve the performance of `Group-Object` (#7410) (Thanks @powercode!) +- Remove one unneeded verbose output from `ConvertTo-Json` (#7487) (Thanks @devblackops!) +- Enable `Get-ChildItem` to produce `Mode` property even if cannot determine if hard link (#7355) + +### Code Cleanup + +- Remove empty XML comment lines (#7401) (Thanks @iSazonov!) +- Cleanup Docker files (#7328) +- Correct the comment for `WSManReceiveDataResult.Unmarshal` (#7364) +- Format Utility `csproj` with updated `codeformatter` (#7263) (Thanks @iSazonov!) +- Bulk update format for files in Management folder with `codeformatter` (#7346) (Thanks @iSazonov!) +- Cleanup: replace `Utils.FileExists()/DirectoryExists()/ItemExists()` with DotNet methods (#7129) (Thanks @iSazonov!) +- Update `Utils.IsComObject` to use `Marshal.IsComObject` since CAS is no longer supported in DotNet Core (#7344) +- Fix some style issues in engine code (#7246) (Thanks @iSazonov!) + +### Test + +- Use `-BeExactly` and `-HaveCount` instead of `-Be` in `BugFix.Tests.ps1` (#7386) (Thanks @sethvs!) +- Use `-BeExactly` and `-HaveCount` instead of `-Be` in `TabCompletion.Tests.ps1` (#7380) (Thanks @sethvs!) +- Update CI scripts to support running tests for experimental features (#7419) +- Use `-HaveCount` instead of `-Be` in `Where-Object.Tests.ps1` (#7379) (Thanks @sethvs!) +- Fix ThreadJob tests so that they will run more reliably (#7360) +- Make logging tests for macOS pending (#7433) + +### Build and Packaging Improvements + +- Update Build script owners (#7321) +- Make `MUSL` NuGet package optional (#7316) +- Enable `pwsh-preview` to work on Windows (#7345) +- Fix SDK dependencies +- Add back the `powershell-core` NuGet source for hosting tests +- Fix typo in environment checker (#7547 & #7549) +- Only remove the revision if it is `0` from module version when restoring modules (#7538) +- Update `WCF` and `NJsonSchema` NuGet packages to latest released patch version (#7411) (Thanks @bergmeister!) +- Add Linux and macOS VSTS CI (#7490, #7527, #7535, #7515 & #7516) +- Updated ThreadJob to version `1.1.2` (#7522) +- Add xUnit project to `PowerShell.sln` and make it runnable from within VisualStudio (#7254) (Thanks @bergmeister!) +- Update NuGet packaging code for the new markdown assembly (#7431) +- Update version of modules shipped with PowerShell (#7531) +- Retry restore on failure (#7544 & #7550) +- Update `PowerShellGet` version +- Update NuGet package metadata (#7517) +- Update reference to use packages from `NuGet.org` (#7525) +- `Start-DevPowerShell`: add `-Configuration` and handle `-ArgumentList` more properly (#7300) (Thanks @jazzdelightsme!) +- Add preview icon to macOS launcher (#7448) (Thanks @thezim!) +- Add `Microsoft.PowerShell.MarkdownRender` to `signing.xml` (#7472) +- Fix building on RedHat Enterprise Linux (#7489) +- Build: Also search PATH for `rcedit` (#7503) (Thanks @kwkam!) +- Save modules to un-versioned folder to enable servicing (#7518 & #7523) +- Fix macOS launcher app to allow release and preview versions (#7306) (Thanks @thezim!) + +### Documentation and Help Content + +- Fix docs comments in utility folder (#7192) (Thanks @iSazonov!) +- Fix a typo in `issue-management.md` (#7393) (Thanks @alexandair!) +- Fix casing of `GitHub` in `best-practice.md` (#7392) (Thanks @alexandair!) +- Fix typos in `docs/maintainers/README.md` (#7390) (Thanks @alexandair!) +- Add maintainer's best practice document and update maintainer list (#7311) +- Update Docker link to `PowerShell-Docker` (#7351) (Thanks @JoshuaCooper!) +- Add `Snapcraft` to spelling dictionary (#7318) +- Update `README.md` and `metadata.json` for release `v6.0.4` (#7497) +- Add `Former Repository Maintainers` section in `maintainers/README.md` (#7475) +- Update the `HelpUri` for `Get-ExperimentalFeature` (#7466) + +# [6.1.0-preview.4]- 2018-07-19 + +### Breaking Changes + +- Remove the `VisualBasic` support from Add-Type (#7284) +- Update PowerShell Direct to try `pwsh` then fallback to `powershell` (#7241) +- Make pwsh able to start in a directory with wildcards in the name (#7240) +- Update `Enable-PSRemoting` so configuration name is unique for Preview releases (#7202) +- Enforce the `CompatiblePSEditions` check for modules from the legacy `System32` module path (#7183) + +### Engine Updates and Fixes + +- Add support to experimental features (#7242) +- Fix error when using `Get-ChildItem c:` (#7033) (Thanks @sethvs!) +- Add location history for `Set-Location` to enable `cd -` scenario (issue #2188) (#5051) (Thanks @bergmeister!) +- Fix padding for right aligned column in table formatting (#7136) +- Fix a performance regression to the `-replace` operator after adding `ScriptBlock` support (#7135) +- Fix tab expansion for `Get-Process` on macOS (#7176) +- When using PSRP, if we receive text instead of XML, output it as error to help troubleshoot (#7168) +- Fix trimming of whitespace when table is wrapped (#7184) +- Modified the `Group-Object -AsHashTable` to use the base object of `PSObject` as the key for the `Hashtable` (#7123) +- Add back ADSI and WMI type accelerators (#7085) +- Add `CompatiblePSEditions` to PowerShell Core built-in modules (#7083) +- Make `Start-Process -ArgumentList` to accept `@()` or `$null` (#6597) +- Avoid calling native APIs to check for existence of FileSystem items (#6929) (Thanks @iSazonov!) +- Add copy environment variables from `ProcessStartInfo` to key/pair array used in creating SSH process (#7070) +- Add markdown rendering feature assemblies to the trusted assembly list (#7280) +- Don't fail if `SaferPolicy` API is not available on Windows 10 IoT or NanoServer (#7075) +- Fix conditions for transcription of `Write-Information` command. (#6917) (Thanks @hubuk!) +- Fix a parsing error when `break` and `continue` are used in a switch statement in a finally block (#7273) +- Fix prompt string to be platform agnostic and keep its trailing spaces (#7255) +- Make progress panel display correctly on UNIX when the user is typing. (#6972) +- Revert change to have `SetLocation()` treat wildcarded path as literal if it exists (#7101) +- Make `Select-Object`/`ForEach-Object`/`Where-Object` see dynamic properties (#6898) (Thanks @jazzdelightsme!) +- Fix class searcher to ignore hidden properties (#7188) +- Update remote prompt when using SSH to show username if different (#7191) +- Remove `SemanticVersion` from `knowntypes` list in serialization code to enable interop between Windows PowerShell and PowerShell Core (#7016) +- Add more information to job process failure error (#7251) +- Use .Net Core `File.Delete()` method to remove symbolic links and alternate streams (#7017) (Thanks @iSazonov!) +- Enable `UseShellExecute` on all platforms (#7198) +- Methods with return type `[object]` should return `null` for an empty result (#7138) + +### General Cmdlet Updates and Fixes + +- Add Markdown rendering cmdlets (#6926) +- `Send-MailMessage`: Update all parameters to support `ValueFromPipelineByPropertyName`. (#6911) (Thanks @sethvs!) +- Allow Basic Auth over HTTPS (#6890) +- Add `ThreadJob` module package and tests (#7169) +- Fix Windows Event Log channel isolation semantics (#6956) (Thanks @Robo210!) +- Make `Measure-Object` handle `scriptblock` properties. (#6934) +- Added functionality to retry in `Invoke-RestMethod` and `Invoke-WebRequest`. (#5760) +- Add type inference for `Select-Object` command (#7171) (Thanks @powercode!) +- Add `-AllStats` Switch parameter for `Measure-Object` cmdlet (#7220) (Thanks @kvprasoon!) + +### Code Cleanup + +- Remove unneeded code that forces ARM platforms to run PowerShell in CL mode (#7046) +- Bulk update code base to put `null` on the right-hand-side of a comparison expression (#6949) (Thanks @iSazonov!) +- Remove `MapSecurityZoneWithUrlmon` method and related code (#7103) +- Cleanup: remove the unneeded type `RemotingCommandUtils` (#7029) +- Remove unneeded "Windows-Full" modules (#7030) +- CodeFactor code style cleanup: replace literal empty strings with `string.Empty` (#6950) (Thanks @iSazonov!) +- Remove dummy comments in Utility module files (#7224) (Thanks @iSazonov!) +- Use empty array for Functions/Cmdlets/`AliasesToExport` to follow the best practice (#7108) +- Refactor module code related to `Get-Module -ListAvailable` (#7145) +- Refactor module specification logic (#7126) + +### Test + +- Add tests for module specifications (#7140) +- Update test string for better clarity in `Send-MailMessage.Tests.ps1` (#7195) (Thanks @sethvs!) +- Add test to verify filesystem provider isn't used when accessing root path in `PSDrive` (#7173) +- Fix to address `ThreadJob` tests reliability and speed (#7270) +- Add additional checks for test that passes inconsistently (#7051) + +### Build and Packaging Improvements + +- `install-powershell.sh` filter pre-releases (when available), `params` documentation (#6849) (Thanks @DarwinJS!) +- Fedora 28 was released, Fedora 26 and 25 went end of life. (#7079) (Thanks @adelton!) +- Disambiguate icon on Windows for preview builds/installers to use `Powershell_av_colors` and + make daily build use `Powershell_avatar` instead (#7086) (Thanks @bergmeister!) +- Update to build for Alpine (#7139) +- Update build and packaging modules for Alpine (#7149) +- Add ability to install previews side-by-side with production releases (#7194) (Thanks @DarwinJS!) +- Enable NuGet Package Registration for compliance (#7053) +- Fix the preview macOS package link (#7061) +- Remove PSReadLine from then `PowerShell.sln` file (#7137) +- Fix the file `PowerShell.sln` that was corrupted by accident (#7288) +- Fix the encoding of `PowerShell.sln` to be `utf-8` (#7289) +- Make sure all references to the Package ID for previews packages is powershell-preview (#7066) +- Update `internals.md` with the latest build changes (#7058) +- When installing using MSI, set the working directory of the shortcut to the user home directory (#7072) +- Move to dotnet core 2.1.1 (#7161) (Thanks @iSazonov!) +- Update to latest package references, runtime framework, and SDK (#7272) +- AppVeyor build matrix: more efficient build job split to reduce total time by another 5 minutes (#7021) (Thanks @bergmeister!) +- Build: Fix the source location of `PowerShell.Core.Instrumentation.dll` (#7226) +- Add Andrew to the default reviewers of the build related files (#7019) +- Build: Fix a check to avoid null argument in case `vcvarsall.bat` is absent (#7218) (Thanks @PetSerAl!) +- Update `releaseTag` in `tools/metadata.json` (#7214) +- Update `Start-PSPester` to make it more user friendly (#7210) (Thanks @bergmeister!) +- Make `Start-PSBuild -Clean` not prompt due to locked files when Visual Studio is open by excluding `sqlite3` folder and use `-x` instead of `-X` option on `git clean` (#7235) (Thanks @bergmeister!) + +### Documentation and Help Content + +- Fix typos in `DOCSMIGRATION.md` (#7094) (Thanks @alexandair!) +- Add instructions to update Homebrew formula for the preview version PowerShell (#7067) (Thanks @vors!) +- Merge Third Party Notices and License updates (#7203) +- Update third party notices (#7042) +- Fix Markdown and spelling errors in `CHANGELOG.md` (#7064) +- Fix `New-TemporaryFile` online help URI (#6608) +- Fix links to PowerShell install docs (#7001) (Thanks @jokajak!) +- Update links that contain `en-us` culture (#7013) (Thanks @bergmeister!) +- Update docs for `ArgumentCompleterAttribute` class (#7227) (Thanks @Meir017!) +- Fix the name of a `Register-EngineEvent` test (#7222) (Thanks @alexjordan6!) +- Update README files for native code for migration (#7248) +- Comment about dynamic members for the `DotNetAdapter`, `GetMember` and `GetMembers` (#7087) +- Update the PowerShell executable location in building guide docs (#7205) (Thanks @louistio!) + +# [6.1.0-preview.3]- 2018-06-07 + +### Breaking Changes + +- Clean up uses of `CommandTypes.Workflow` and `WorkflowInfo` (#6708) +- Disallow Basic Auth over HTTP in PowerShell Remoting on Unix (#6787) +- Change packaging to differentiate only between major versions and previews (#6968) +- Enhance and refactor `Add-Type` cmdlet (#6141) (Thanks @iSazonov!) + - A few error strings were removed and thus the corresponding fully qualified error ids are no longer in use. + +### Engine Updates and Fixes + +- Fix crash when terminal is reset (#6777) +- Fix a module-loading regression that caused an infinite loop (#6843) +- Further improve `PSMethod` to `Delegate` conversion (#6851) +- Block list `System.Windows.Forms` from loading to prevent a crash (#6822) +- Fix `Format-Table` where rows were being trimmed unnecessarily if there's only one row of headers (#6772) +- Fix `SetDate` function in `libpsl-native` to avoid corrupting memory during `P/Invoke` (#6881) +- Fix tab completions for hash table (#6839) (Thanks @iSazonov!) +- Fix parser to continue parsing key-value pairs after an `If-Statement` value in a `HashExpression` (#7002) +- Add error handling for `#requires` in an interactive session (#6469) + +### General Cmdlet Updates and Fixes + +- Improve parameter validation in `ExportCsvHelper` (#6816) (Thanks @sethvs!) +- Quote `Multipart` form-data field names (#6782) (Thanks @markekraus!) +- Fix Web Cmdlets for .NET Core 2.1 (#6806) (Thanks @markekraus!) +- Fix `Set-Location DriveName:` to restore current working directory in the drive (#6774) (Thanks @mcbobke!) +- Add the alias `-lp` for `-LiteralPath` parameters #6732 (#6770) (Thanks @kvprasoon!) +- Remove `more` function and move the `$env:PAGER` capability into the `help` function (#6059) (Thanks @iSazonov!) +- Add line break to the error message for `Set-ExecutionPolicy` (#6803) (Thanks @wesholton84!) + +### Code Cleanup + +- Clean up `#if SILVERLIGHT` (#6907) (Thanks @iSazonov!) +- Clean up the unused method `NonWindowsGetDomainName()` (#6948) (Thanks @iSazonov!) +- Clean up FileSystem provider (#6909) (Thanks @iSazonov!) + +### Test + +- Add tests for PowerShell hosting API to verify MyGet packages (#6737) +- Remove Web Cmdlets tests using proxy environment variables (#6808) (Thanks @iSazonov!) +- Enable Web Cmdlets tests for greater platform support (#6836) (Thanks @markekraus!) +- Convert `ShouldBeErrorId` to `Should -Throw -ErrorId` in PowerShell tests (#6682) +- Fix CIM cmdlets tests (#6755) (Thanks @sethvs!) +- Add tests for PowerShell classes inheriting from abstract .NET classes (#6752) +- Fix `Select-Object.Tests.ps1` which previously failed intermittently on Unix platforms. (#6747) +- Update docker package tests to fix error on OpenSUSE 42 (#6783) +- Fix test and infrastructure that block code coverage runs (#6790) +- Update Tests `Isfile` to correct response for `"/"` (#6754) (Thanks @Patochun!) +- Improve code coverage in `Export-Csv.Tests.ps1` (#6795) (Thanks @sethvs!) +- Change `-Quiet` parameter of `Invoke-Pester` to `-Show None` in `OpenCover.psm1` (#6798) (Thanks @sethvs!) +- Replace `Dbg.Assert` with `if () throw` in `CSVCommands.cs` (#6910) (Thanks @sethvs!) +- Fix xUnit test `GetTempFileName` (#6943) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +- Add Windows Compatibility Pack 2.0.0 to PowerShell Core and adopt the official .NET Core 2.1 (#6958) +- Add Jumplist 'Run as Administrator' to Taskbar on Windows (#6913, #6985) (Thanks @bergmeister!) +- Use AppVeyor matrix for faster Pull Request builds (#6945) (Thanks @bergmeister!) +- Fix `build.psm1` to not add tool path to $PATH twice (#6834) +- Add script to create a container manifest (#6735) +- Fix docker manifest creation script to work with more complex tags and with repeated use (#6852) +- Add functions to merge Pester and xUnit logs (#6854) +- Enable generating full symbols for the Windows debug build (#6853) +- Add functions into `build.psm1` to save and restore `PSOptions` between different sessions. (#6884) +- Update signing XML based on new signing guidelines (#6893) +- Update the release docker files to allow specifying the version of to-be-installed PowerShell and the version of image to use (#6835) +- Updates docker files for Fedora 27 and Kali Linux (#6819) +- Change packaging to support Ubuntu 17.10 and 18.04 (#6769) +- Update `Get-ChangeLog` to make it more accurate (#6764) +- Fix comparison to see if sudo test is needed in `install-*.sh` (#6771) (Thanks @bjh7242!) +- Packaging: Add registry keys to support library folder background for explorer context menu (#6784) (Thanks @bergmeister!) +- Skip `dotnet-cli` initialization and stop caching the `dotnet` folder for Travis CI (#7007) +- Skip compiling the non-supported cmdlets on Unix in `System.Management.Automation.dll` to fix the crash in Unix debug build (#6939) +- Use `PSReadLine` 2.0.0-beta2 from PSGallery (#6998) +- Update `PSRP` Linux NuGet package version to 1.4.2-* (#6711) +- Add path cleanup utility `Reset-PWSHSystemPath.ps1` (#6892) (Thanks @DarwinJS!) +- Add logic to create signing XML for NuGet packages (#6921) +- Add and config the `Settings.StyleCop` file (#6930, #6986) (Thanks @iSazonov!) +- Fix the double curly bracket typo in a docker file (#6960) (Thanks @adelton!) +- Remove dependencies on `libcurl` and `libunwind` in packaging to match the .NET Core behavior (#6964) (Thanks @qmfrederik!) +- Make the docker build fail when the curl operation fails. (#6961) (Thanks @adelton!) + +### Documentation and Help Content + +- Update installation doc about Raspbian (#6859) +- Add code coverage report generation instructions (#6515) +- Migrate docs from PowerShell repository to Docs repository (#6899) +- Fix broken links due to migrating GitHub docs on Installation, Known Issues and Breaking Changes to `docs.microsoft.com` (#6981) (Thanks @bergmeister!) +- Update documentation on how to write tests verifying errors conditions (#6687) +- Fix preview download links in `README.md` (#6762) + +# [6.1.0-preview.2]- 2018-04-27 + +### Breaking Changes + +- Remove support for file to opt-out of telemetry, only support environment variable (#6601) +- Simplify the installation paths the MSI uses (#6442) + +### Engine Updates and Fixes + +- Fix running `pwsh` produced from `dotnet build` (#6549) +- Remove the `FullCLR-only` symbol-info related code from `EventManager.cs` (#6563) +- Improve `PSMethod-to-Delegate` conversion (#6570) +- Fix `PsUtils.GetManModule()` to avoid infinite loop when there was no main module (#6358) +- Fix error in windows environment provider when the environment variable has duplicates that differ only by case (#6489) (Thanks @mklement0!) +- Make sure that the width of the header is at least the size of the label (or property name) (#6487) +- Enable `[Environment]::OSVersion` to return current OS rather than compatible version (#6457) +- Change the `SaveError` method in Parser to use `nameof` for error ids (#6498) +- Fix error when `Format-Wide -AutoSize | Out-String` is called (#6491) (Thanks @stknohg!) +- Make `LanguagePrimitive.GetEnumerable` treat `DataTable` as Enumerable (#6511) +- Fix formatting of tables where headers span multiple rows (#6504) +- Improve performance of parsing `RegexOption` for `-split` by using `if` branches (#6605) (Thanks @iSazonov!) +- Enable specifying `sshd` subsystem to use via `-Subsystem` (#6603) +- Add some optimizations in formatting subsystem (#6678) (Thanks @iSazonov!) +- Throw better parsing error when statements should be put in named block (#6434) +- Use `Unregister-Event` to remove an event subscriber when removing `PSEdit` function (#6449) +- Make the `PSISERemoteSessionOpenFile` a support event (#6582) +- Add `-WorkingDirectory` parameter to `pwsh` (#6612) +- Support importing module paths that end in trailing directory separator (#6602) +- Formatting: Use cache for dash padding strings for tables (#6625) (Thanks @iSazonov!) +- Port Windows PowerShell AppLocker and DeviceGuard `UMCI` application white listing support (#6133) +- Reduce allocations in `TableWriter` (#6648) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Add `-Resume` Feature to WebCmdlets (#6447) (Thanks @markekraus!) +- Support `user@host:port` syntax for `SSH` transport (#6558) +- Add ported `Test-Connection` cmdlet (#5328) (Thanks @iSazonov!) +- Added line break to Access-Denied error message (#6607) +- Some fixes in `Get-Date -UFormat` (#6542) (Thanks @iSazonov!) +- Added check for existence of Location HTTP header before using it (#6560) (Thanks @ffeldhaus!) +- Enable `Update-Help` to save help content in user scope by default (#6352) +- Update `Enable-PSRemoting` to create PowerShell.6 endpoint and version specific endpoint (#6519, #6630) +- Update error message that `Disconnect-PSSession` is only supported with `WSMan` (#6689) +- Make `Export-FormatData` print pretty XML output (#6691) (Thanks @iSazonov!) +- Add `-AsArray` parameter to `ConvertoTo-Json` command (#6438) +- Add `Test-Json` cmdlet (`NJsonSchema`) (#5229) (Thanks @iSazonov!) +- Correct a typo in comment for `Invoke-WebRequest` (#6700) (Thanks @gabrielsroka!) +- Re-order `UFormat` options in `Get-Date` (#6627) (Thanks @iSazonov!) +- Add the parameter `-Not` to `Where-Object` (#6464) (Thanks @SimonWahlin!) + +### Code Cleanup + +- Engine: Fix several code cleanup issues (#6552, #6609) +- Clean up workflow logic in the module loading component (#6523) +- Engine: Clean up unneeded `GetTypeInfo()` calls (#6613, #6636, #6633, #6635, #6634) + +### Test + +- Fix line ending in `DefaultCommands.Tests.ps1` from `CRLF` to `LF` (#6553) +- Use new Pester parameter syntax in tests (#6490, #6574, #6535, #6536, #6488, #6366, #6351, #6349, #6256, #6250) (Thanks @KevinMarquette, @sethvs, @bergmeister!) +- Fix `Copy.Item.Tests.ps1` (#6596) (Thanks @sethvs!) +- Fix typos or formatting in some test files (#6595, #6593, #6594, #6592, #6591) (Thanks @sethvs!) +- Add missing `Start-WebListener` to WebCmdlets tests (#6604) (Thanks @markekraus!) +- Update Dockerfile test to use Ubuntu 17.10 as the base image (#6503) +- Add PowerShell logging tests for macOS and Linux (#6025) +- Add tests for `Format-Table -Wrap` (#6670) (Thanks @iSazonov!) +- Reformat `Format-Table` tests (#6657) (Thanks @iSazonov!) +- Add new reliable tests for `Get-Date -UFormat` (#6614) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +- Use C# latest language in `.csproj` files (#6559) (Thanks @iSazonov!) +- Update `installpsh-.sh` installers to handle "preview" in version number (#6573) (Thanks @DarwinJS!) +- Enable `PowerShell.sln` to work in VisualStudio (#6546) +- Remove duplicate `Restore-PSPackage` (#6544) +- Use `-WorkingDirectory` parameter to handle context menu when path contains single quotes (#6660) (Thanks @bergmeister!) +- Make `-CI` not depend on `-PSModuleRestore` in `Start-PSBuild` (#6450) +- Restore for official Linux arm builds (#6455) +- Fix error about setting readonly variable in `install-powershell.sh` (#6617) +- Make release macOS build work better (#6619, #6610) +- MSI: add function to generate a `MSP` package (#6445) + +### Documentation and Help Content + +- Doc: Update Ubuntu source creation commands to use `curl -o` (#6510) (Thanks @M-D-M!) +- Update stale bot message (#6462) (Thanks @iSazonov!) +- Remove extraneous SSH and install docs from the 'demos' folder (#6628) + +# [6.1.0-preview.1]- 2018-03-23 + +### Breaking Changes + +- Throw terminating error in `New-TemporaryFile` and make it not rely on the presence of the `TEMP` environment variable (#6182) (Thanks @bergmeister!) +- Remove the unnecessary `AddTypeCommandBase` class from `Add-Type` (#5407) (Thanks @iSazonov!) +- Remove unsupported members from the enum `Language` in `Add-Type` (#5829) (Thanks @iSazonov!) +- Fix range operator to work better with character ranges (#5732) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Fix `ValidateSet` with generator in a module (#5702) +- Update `SAL` annotation and fix warnings (#5617) +- Add `ForEach` and `Where` methods to `PSCustomobject` (#5756) (Thanks @iSazonov!) +- Add `Count` and `Length` properties to `PSCustomobject` (#5745) (Thanks @iSazonov!) +- Make minor fixes in compiler to properly handle void type expression (#5764) +- Logging: Fix the escaped characters when generating `.resx` file from PowerShell `ETW` manifest. (#5892) +- Remove `PSv2` only code from `Types_Ps1Xml.cs` and `HostUtilities.cs` (#5907) (Thanks @iSazonov!) +- Enable passing arrays to `pwsh -EncodedArguments` on debug builds. (#5836) +- Logging: Handle path that contains spaces in `RegisterManifest.ps1` (#5859) (Thanks @tandasat!) +- Add `-settingsfile` to `pwsh` to support loading a custom powershell config file. (#5920) +- Return better error for `pwsh -WindowStyle` on unsupported platforms. (#5975) (Thanks @thezim!) +- Enable conversions from `PSMethod` to `Delegate` (#5287) (Thanks @powercode!) +- Minor code clean-up changes in tab completion code (#5737) (Thanks @kwkam!) +- Add lambda support to `-replace` operator (#6029) (Thanks @IISResetMe!) +- Fix retrieval of environment variables on Windows in cases where variable names differ only by case. (#6320) +- Fix the `NullRefException` when using `-PipelineVariable` with `DynamicParam` block (#6433) +- Add `NullReference` checks to two code paths related to `PseudoParameterBinder` (#5738) (Thanks @kwkam!) +- Fix `PropertyOnlyAdapter` to allow calling base methods (#6394) +- Improve table view for `Certs` and `Signatures` by adding `EnhancedKeyUsageList` and `StatusMessage` (#6123) +- Fix the filtering of analytic events on Unix platforms. (#6086) +- Update copyright and license headers (#6134) +- Set pipeline thread stack size to 10MB (#6224) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Fix the `NullRefException` in `Enter-PSHostProcess` (#5995) +- Merge and Sort `BasicHtmlWebResponseObject` and `ContentHelper` in Web Cmdlets (#5720) (Thanks @markekraus!) +- Encoding for `New-ModuleManifest` on all platforms should be `UTF-8 NoBOM` (#5923) +- Make `Set-Location` use path with wildcard characters as literal if it exists (#5839) +- Combine Web Cmdlets partial class files (#5612) (Thanks @markekraus!) +- Change `Microsoft.PowerShell.Commands.SetDateCommand.SystemTime` to `struct`. (#6006) (Thanks @stknohg!) +- Add Simplified `multipart/form-data` support to Web Cmdlets through `-Form` parameter (#5972) (Thanks @markekraus!) +- Make a relative redirect URI absolute when `Authorization` header present (#6325) (Thanks @markekraus!) +- Make relation-link handling in Web Cmdlets case-insensitive (#6338) +- Make `Get-ChildItem -LiteralPath` accept `Include` or `Exclude` filter (#5462) +- Stop `ConvertTo-Json` when `Ctrl+c` is hit (#6392) +- Make `Resolve-Path -Relative` return useful path when `$PWD` and `-Path` is on different drive (#5740) (Thanks @kwkam!) +- Correct the `%c`, `%l`, `%k`, `%s` and `%j` formats in `Get-Date -UFormat` (#4805) (Thanks @iSazonov!) +- Add standard deviation implementation on `Measure-Object` (#6238) (Thanks @CloudyDino!) +- Make `Get-ChildItem /* -file` include `` as search directory (#5431) +- Enable setting `PSSession` Name when using `SSHTransport` and add `Transport` property (#5954) +- Add `Path` alias to `-FilePath` parameters and others for several commands (#5817) (Thanks @KevinMarquette!) +- Add the parameter `-Password` to `Get-PfxCertificate` (#6113) (Thanks @maybe-hello-world!) +- Don't add trailing spaces to last column when using `Format-Table` (#5568) +- Fix table alignment and padding. (#6230) +- Add `-SkipHeaderValidation` Support to `ContentType` on Web Cmdlets (#6018) (Thanks @markekraus!) +- Add common aliases for all `write-*` commands default message parameter (#5816) (Thanks @KevinMarquette!) +- Make `UTF-8` the default encoding for `application/json` (#6109) (Thanks @markekraus!) +- Enable `$env:PAGER` to work correctly if arguments are used (#6144) + +### Test + +- Convert Web Cmdlets test to `one-true-brace-style` formatting (#5716) (Thanks @markekraus!) +- Add a test for `IValidateSetValuesGenerator` in a module (#5830) (Thanks @iSazonov!) +- Fix function to test for docker OS due to change to use `linuxkit` for macOS (#5843) +- Replace `HttpListener` tests with `WebListener` (#5806, #5840, #5872) (Thanks @markekraus!) +- Stop `HttpListener` from running in Web Cmdlets tests (#5921) (Thanks @markekraus!) +- Fix `PSVersion` in `PSSessionConfiguration` tests (#5554) (Thanks @iSazonov!) +- Update test framework to support Pester v4 (#6064) +- Update tests to use Pester v4 Syntax. (#6294, #6257, #6306, #6304, #6298) +- Add negative tests for `Copy-Item` over remote sessions (#6231) +- Markdown test: Use strict in JavaScript (#6328) +- Add tests for `Get-Process` about the `-Module` and `-FileVersion` parameters (#6272) +- Add test for the `OsLocalDateTime` property of `Get-ComputerInfo`. (#6253) +- Change `Get-FileHash` tests to use raw bytes (#6430) +- Remove `runas.exe` from tests as we have tags to control this behavior (#6432) +- Refactor the `Get-Content` tests to use `-TestCases`. (#6082) +- Use `RequireAdminOnWindows` tag in `Set-Date` tests (#6034) (Thanks @stknohg!) +- Remove `-TimeOutSec` from non timeout related tests (#6055) (Thanks @markekraus!) +- Add verbosity and more accurate timeout implementation for `Start-WebListener` (#6013) (Thanks @markekraus!) +- Skip tests that use `ExecutionPolicy` cmdlets on Unix (#6021) +- Change Web Cmdlet tests to use `127.0.0.1` instead of `Localhost` (#6069) (Thanks @markekraus!) +- Fix `Start-PSPester` to include or exclude `RequireSudoOnUnix` tag smartly on Unix (#6241) +- Fix the terse output on Windows for test runs without admin privilege (#6252) +- Add `RequireSudoOnUnix` tag for `Get-Help` tests. (#6223) +- Add tests for `*-Item` Cmdlets in function provider (#6172) +- Support running tests in root privilege on Linux. (#6145) + +### Build and Packaging Improvements + +- Add option to add explorer shell context menu in Windows installer (#5774) (Thanks @bergmeister!) +- Make the explorer shell context menu registry entries platform specific to allow side by side of `x86` and `x64`. (#5824) (Thanks @bergmeister!) +- Fix start menu folder clash of shortcut when `x86` and `x64` are both installed by appending ` (x86)` for `x86` installation. (#5826) (Thanks @bergmeister!) +- Reduce image file sizes using lossless compression with `imgbot` (#5808) (Thanks @bergmeister!) +- Windows installer: Allow `Launch PowerShell` checkbox to be toggled using the space bar. (#5792) (Thanks @bergmeister!) +- Fix release packaging build (#6459) +- Fail `AppVeyor` Build if `MSI` does not build (#5755) (Thanks @bergmeister!) +- Cleanup temporarily created `WiX` files after compilation to be able to have a clean re-build (#5757) (Thanks @bergmeister!) +- Fix `install-powershell.ps1` for running during window setup (#5727) +- Start using `Travis-CI` cache (#6003) +- Fix build, packaging and installation scripts for `SLES` (#5918) (Thanks @tomconte!) +- Update recommended `WiX` toolset link to be generic to `WiX 3.x` but mention that latest version of 3.11 has to be taken (#5926) (Thanks @bergmeister!) +- Add service point manager call in `Install-PowerShell.ps1` to force `TLS1.2`. (#6310) (Thanks @DarqueWarrior!) +- Add `-Restore` when build `win-arm` and `win-arm64` (#6353) +- Make sure package verification failure fails the `AppVeyor` build (#6337) +- Specify the runtime when running `dotnet restore` in `Start-PSBuild` (#6345) +- Rename `log` and `logerror` to `Write-Log [$message] [-error]` (#6333) +- Make Linux packages use correct version scheme for preview releases (#6318) +- Add support for Debian in `installpsh-debian.sh` (#6314) (Thanks @Pawamoy!) +- MSI: Make preview builds to install Side by side with release builds (#6301) +- Add `TLS1.2` workaround for code coverage script (#6299) +- Cleanup after Powershell install for `CentOS` and `Fedora` Docker images (#6264) (Thanks @strawgate!) +- MSI: Update the environment variable PATH with proper value (#6441) +- MSI: Remove the version from the product name (#6415) +- Support non-GitHub commits in the change log generation script (#6389) +- Fix secret and JavaScript compliance issues (#6408) +- Remove `AppVeyor` specific cmdlet from `Start-NativeExecution` (#6263) +- Restore modules from the `NuGet` package cache by using `dotnet restore` (#6111) +- CI Build: Use `TRAVIS_PULL_REQUEST_SHA` to accurately get the commit message (#6024) +- Use `TLS1.2` on Windows during `Start-PSBootstrap` (#6235) (Thanks @CallmeJoeBob!) +- Use `TLS1.2` in `Start-PSBootStrap` without breaking `HTTPS` (#6236) (Thanks @markekraus!) +- Add options to enable `PSRemoting` and register Windows Event Logging Manifest to MSI installer (#5999) (Thanks @bergmeister!) + +### Documentation and Help Content + +- Separate macOS from Linux install instructions. (#5823) (Thanks @thezim!) +- Show usage (short) help if command line parameter is wrong (#5780) (Thanks @iSazonov!) +- Add the breaking changes doc for 6.0.0 release. (#5620) (Thanks @maertendMSFT!) +- Remove DockerFile for Fedora 25 and add DockerFile for Fedora 27 (#5984) (Thanks @seemethere!) +- Add a missing step to prepare the build environment on Mac. (#5901) (Thanks @zackJKnight!) +- Update `BREAKINGCHANGES.md` to include WebCmdlets breaking changes (#5852) (Thanks @markekraus!) +- Fix typos in `BREAKINGCHANGES.md` (#5913) (Thanks @brianbunke!) +- Update `macos.md` to use `brew cask upgrade` for upgrading powershell (#5875) (Thanks @timothywlewis!) +- Add verification step to macOS install docs (#5860) (Thanks @rpalo!) +- Fix links in macOS install docs (#5861) (Thanks @kanjibates!) +- Update docs with test guidelines with the `RequireSudoOnUnix` tag. (#6274) +- Add `Alpine` Linux support (#6367) (Thanks @kasper3!) +- Update to Governance doc to reflect current working model (#6323) +- Add guidance on adding copyright and license header to new source files (#6140) +- Fix the command to build type catalog in `internals.md` (#6084) (Thanks @ppadmavilasom!) +- Fix `Pull Request Process` dead link (#6066) (Thanks @IISResetMe!) +- Update processes to allow for coordinated vulnerability disclosure (#6042) +- Rework Windows Start menu folder name (#5891) (Thanks @Stanzilla!) +- Update `Raspbian` installation instructions to create `symlink` for `pwsh` (#6122) +- Fix various places that still refer to old versions of `pwsh` (#6179) (Thanks @bergmeister!) +- Correct a Linux installation typo (#6219) (Thanks @mababio!) +- Change synopsis of `install-powershell.ps1` to reflect that it works cross-platform (#5465) (Thanks @bergmeister!) + +## [6.0.2] - 2018-03-15 + +### Engine updates and fixes + +- Update PowerShell to use `2.0.6` dotnet core runtime and packages (#6403) + - This change addresses this vulnerability: [Microsoft Security Advisory `CVE-2018-0875`: Hash Collision can cause Denial of Service](https://github.com/PowerShell/Announcements/issues/4) + +### Build and Packaging Improvements + +- Add Ubuntu build without `AppImage` (#6380) +- Add scripts to set and or update the release tag in `VSTS` (#6107) +- Fix `DSC` Configuration compilation (#6225) +- Fix errors in `Start-PSBootStrap` during release builds (#6159) +- Fix spelling failures in `CI` (#6191) +- Use PowerShell `windowsservercore` Docker image for release builds (#6226) +- Use `ADD` instead of `Invoke-WebRequest` in `nanoserver` Docker file (#6255) +- When doing daily/test build in a non-release branch use the branch name as the preview name (#6355) +- Add Environment Variable override of telemetry (#6063) (Thanks @diddledan!) +- Build: Remove two unneeded lines from `Invoke-AppveyorFinish` (#6344) +- MSI: Refactor `New-MsiPackage` into `packaging.psm1` + and various fixes to enable patching + (#5871, #6221, #6254, #6303, #6356, #6208, #6334, #6379, #6094, #6192) +- MSI: Use `HKLM` instead of `HKCU` registry keys since the current installation scope is per-machine. (#5915) (Thanks @bergmeister!) + +## [6.0.1] - 2018-01-25 + +### Engine updates and fixes + +- Update PowerShell to use `2.0.5` dotnet core runtime and packages. (#5903, #5961) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +- Re-release of `v6.0.0` as `v6.0.1` due to issues upgrading from pre-release versions + +### Test + +- Update regular expression to validate `GitCommitId` in `$PSVersionTable` to not require a pre-release tag (#5893) + +[6.1.6]: https://github.com/PowerShell/PowerShell/compare/v6.1.5...v6.1.6 +[6.1.5]: https://github.com/PowerShell/PowerShell/compare/v6.1.4...v6.1.5 +[6.1.4]: https://github.com/PowerShell/PowerShell/compare/v6.1.3...v6.1.4 +[6.1.3]: https://github.com/PowerShell/PowerShell/compare/v6.1.2...v6.1.3 +[6.1.2]: https://github.com/PowerShell/PowerShell/compare/v6.1.1...v6.1.2 +[6.1.1]: https://github.com/PowerShell/PowerShell/compare/v6.1.0...v6.1.1 +[6.1.0]: https://github.com/PowerShell/PowerShell/compare/v6.1.0-rc.1...v6.1.0 +[6.1.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v6.1.0-preview.4...v6.1.0-rc.1 +[6.1.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v6.1.0-preview.3...v6.1.0-preview.4 +[6.1.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v6.1.0-preview.2...v6.1.0-preview.3 +[6.1.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v6.1.0-preview.1...v6.1.0-preview.2 +[6.1.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v6.0.2...v6.1.0-preview.1 +[6.0.2]: https://github.com/PowerShell/PowerShell/compare/v6.0.1...v6.0.2 +[6.0.1]: https://github.com/PowerShell/PowerShell/compare/v6.0.0...v6.0.1 diff --git a/PowerShell-master/CHANGELOG/6.2.md b/PowerShell-master/CHANGELOG/6.2.md new file mode 100644 index 0000000000000000000000000000000000000000..bf54f978eba1cdcc92bc688d5e190d717c220ea4 --- /dev/null +++ b/PowerShell-master/CHANGELOG/6.2.md @@ -0,0 +1,875 @@ +# 6.2 Changelog + +## [6.2.7] - 2020-07-16 + +### Build and Packaging Improvements + +
+ +
    +
  • Fix Azure file copy issues in release build by fixing the path to upload directory content (#13182)
  • +
  • Update .NET Core to version 2.1.808 (Internal 12003)
  • +
  • Fix Azure file copy break in AzDevOps by updating task version to latest (#13173)
  • +
+ +
+ +## [6.2.6] - 2020-06-11 + +### Engine Updates and Fixes + +- Restrict loading of `amsi.dll` to `system32` folder (#12730) + +### Tools + +- Update the PowerShell team list to correct changelog generation (#12927) + +### Tests + +- Pin major Pester version to 4 to prevent breaking changes caused by upcoming release of `v5` (#12262) (Thanks @bergmeister!) + +### Build and Packaging Improvements + +
+ + + +

Update to `.NET Core 2.1.807`

+ +
+ +
    +
  • update to dotnet 2.1.807 (Internal 11697)
  • +
  • update hosting tests
  • +
  • Check if Azure Blob exists before overwriting (#12921)
  • +
  • Upgrade APIScan version (#12876)
  • +
  • Fix break in package build by pinning ffi version to 1.12 (#12889)
  • +
  • Update the build to sign any unsigned files as 3rd party Dlls (#12581)
  • +
+ +
+ +## [6.2.5] - 2020-05-14 + +### Build and Packaging Improvements + +
+ +
    +
  • Port back the code for new changelog format.
  • +
  • Work around FPM issue with a specific version on macOS
  • +
  • Update the combined package build to release the daily builds (#10449)
  • +
  • Refactor packaging pipeline (#11852)
  • +
  • Bump .NET SDK version to the version 2.1.18
  • +
  • Move to standard internal pool for building (#12119)
  • +
+ +
+ +## [6.2.4] - 2020-01-27 + +### General Cmdlet Updates and Fixes + +- Enable `Start-Process` to work on Windows 7 (#10417) (Thanks @iSazonov!) +- Fix global tool issues around exit code, command line parameters, and paths with spaces (#10461) +- Make `Add-Type` usable in applications that host PowerShell (#10587) + +### Build and Packaging Improvements + +- Update to use `TSAv2` (#9914) +- Update the dotnet SDK install script URL in `build.psm1` (#10927) +- Update dependencies needed by Azure PowerShell and patch for `Newtonsoft.Json` (Internal 10798) +- Fix path for getting reference assemblies (Internal 10792) + +## [6.2.3] - 2019-09-12 + +### Engine Updates and Fixes + +- Fix debugger performance regression in system lock down mode (#10269) + +### Tests + +- Remove `markdownlint` tests due to security issues (#10163) + +### Build and Packaging Improvements + +- Update DotNet SDK and runtime framework version (Internal 9946) +- Fix macOS build break (#10207) + +## [6.2.2] - 2019-07-16 + +### Breaking Changes + +- Disable `Enter-PSHostProcess` cmdlet when system in lock down mode (Internal 8969) + +### Engine Updates and Fixes + +- Create `JumpList` in STA thread as some COM APIs are strictly STA only to avoid sporadic CLR crashes (#10057, #9928) (Thanks @bergmeister!) + +### Build and Packaging Improvements + +- Update DotNet SDK and runtime framework version (Internal 9082, 9088, 9092) +- Make `Hashtable` case insensitivity test use current culture rather than shell to set culture (Internal 8529) +- Add automated RPM signing to release build (#10013) +- Update copyright symbol for NuGet packages (#9936) +- Bump `Microsoft.ApplicationInsights` from `2.9.1` to `2.10.0` (#9757) +- Switch from BMP to PNG for graphical MSI installer assets (#9606) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.3` to `4.5.4` (#9789) +- Enable building of MSIX package (#9289, #9715) + +## [6.2.1] - 2019-05-21 + +### Engine Updates and Fixes + +- Re-enable tab completion for functions (#9383) +- Disable debugger in System Lock down mode (Internal 8428) + +### Code Cleanup + +- Update repo for Ubuntu 14.04 EOL (#9324) + +### Tests + +- Fix skipping of tests in `RemoteSession.Basic.Tests.ps1` (#9304) +- Update tests to account for when `$PSHOME` is read only (#9279) +- Mark tests in macOS CI which use `applescript` as pending/inconclusive (#9352) +- Make sure non-Windows CI fails when a test fails (#9303) + +### Build and Packaging Improvements + +- Partially revert "Fix the failed test and update `Publish-TestResults` to make `AzDO` fail the task when any tests failed (#9457)" +- Bump `Markdig.Signed` from `0.16.0` to `0.17.0` (#9595) +- Bump `Microsoft.PowerShell.Archive` from `1.2.2.0` to `1.2.3.0` in `/src/Modules` (#9594) +- Enable building on Kali Linux (#9471) +- Fix the failed test and update `Publish-TestResults` to make `AzDO` fail the task when any tests failed (#9457) +- Add Preview assets for `msix` (#9375) +- Create code coverage and test packages for non-windows (#9373) +- Fix publishing daily `nupkg` to MyGet (#9269) +- Bump `PackageManagement` from `1.3.1` to `1.3.2` in `/src/Modules` (#9568) +- Bump `NJsonSchema` from `9.13.27` to `9.13.37` (#9524) +- Bump `gulp` from `4.0.0` to `4.0.2` in `/test/common/markdown` (#9443) +- Bump `Newtonsoft.Json` from `12.0.1` to `12.0.2` (#9433) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.2` to `4.5.3` (#9367) +- Add `AccessToken` variable to jobs that perform signing (#9351) +- Create test package for macOS on release builds (#9344) +- Add component detection to all jobs (#8964) +- Move artifacts to artifact staging directory before uploading (#9273) + +## [6.2.0] - 2019-03-28 + +### Breaking Changes + +- Fix `-NoEnumerate` behavior in `Write-Output` to be consistent with Windows PowerShell (#9069) (Thanks @vexx32!) + +### Engine Updates and Fixes + +- Add PowerShell remoting enable/disable cmdlet warning messages (#9203) +- Fix for `FormatTable` remote deserialization regression (#9116) +- Update the task-based `async` APIs added to PowerShell to return a Task object directly (#9079) +- Add 5 `InvokeAsync` overloads and `StopAsync` to the `PowerShell` type (#8056) (Thanks @KirkMunro!) + +### General Cmdlet Updates and Fixes + +- Enable `SecureString` cmdlets for non-Windows by storing the plain text (#9199) +- Add Obsolete message to `Send-MailMessage` (#9178) +- Fix `Restart-Computer` to work on `localhost` when WinRM is not present (#9160) +- Make `Start-Job` throw terminating error when PowerShell is being hosted (#9128) +- Update version for `PowerShell.Native` and hosting tests (#8983) + +### Tools + +- Adding `CmdletsToExport` and `AliasesToExport` to test module manifests. (#9108) (Thanks @powercode!) +- Comment cleanup in `releaseTools.psm1` (#9064) (Thanks @RDIL!) + +### Tests + +- Fix `Enter-PSHostProcess` tests flakiness (#9007) +- Add tests for command globbing (#9180) +- Add source for `Install-package` to install `netDumbster` (#9081) (Thanks @Geweldig!) +- Fix tab completion test to handle multiple matches (#8891) +- Refactor macOS and Linux CI so that tests run in parallel (#9056, #9209) +- Added `RequireSudoOnUnix` tags to `PowerShellGet` tests and remove `-pending` parameter (#8954) (Thanks @RDIL!) +- Pending `NamedPipeConnectionInfo` test (#9003) (Thanks @iSazonov!) +- Add test for `-WhatIf` for `New-FileCatalog` (#8966) (Thanks @mjanko5!) + +### Build and Packaging Improvements + +- Performance improvements for release build (#9179) +- Add `tsaVersion` property as `TsaV1` for compliance build phase (#9176) +- Publish global tool packages to `pwshtool` blob and bug fixes (#9163) +- Translate Skipped test results into something Azure DevOps does **not** understand (#9124) +- Disable Homebrew analytics in macOS VSTS builds (#9130) (Thanks @RDIL!) +- Remove AppVeyor references from packaging tools (#9117) (Thanks @RDIL!) +- Fixed Dockerfile syntax highlighting (#8991) (Thanks @RDIL!) +- Fix dependencies of NuGet build to wait on DEB uploads to finish (#9118) +- Fix artifact download issue in release build (#9095) +- Publish test package on release builds (#9063) +- Bump `Microsoft.PowerShell.Native` from `6.2.0-rc.1` to `6.2.0` (#9200) +- Bump `NJsonSchema` from `9.13.19` to `9.13.27` (#9044, #9136, #9166, #9172, #9184 #9196) +- Bump `PowerShellGet` from `2.0.4` to `2.1.2` in /src/Modules (#9110, #9145) +- Bump `SelfSignedCertificate` in `/test/tools/Modules` (#9055) + +### Documentation and Help Content + +- Update docs for `6.2.0-rc.1` release (#9022) + +## [6.2.0-rc.1] - 2019-03-05 + +### Breaking Changes + +- Make `Join-String -InputObject 1,2,3` result equal to `1,2,3 | Join-String` result (#8611) (Thanks @sethvs!) + +### Engine Updates and Fixes + +- Improve check for developer mode by checking minimum required build number (#8749) +- Simplify the declaration of new experimental features (#8726) +- Remove AMSI uninitialized assert and replace with call to uninitialized (#8713) +- Port Security bypass fixes from 6.1.3 (#8915) +- Enable discovering modules that have names same as a culture (e.g. `Az`) (#8777) +- Flatten interface hierarchy when generating properties that implement interface properties (#8382) (Thanks @IISResetMe!) +- Don't use Win32 native APIs on non-Windows for cryptography of secure string over remoting (#8746) +- Allow `.exe` files to be used as IL binary modules (#7281) +- Remove unused cached types (#9015) + +### Experimental Features + +- Add the experimental feature for creating `Temp:\` drive when `FileSystemProvider` initializes (#8696) +- Move `CommandNotFoundException` suggestion to an experimental feature (#8805) + +### General Cmdlet Updates and Fixes + +- Correctly Report impact level when `SupportsShouldProcess` is not set to 'true' (#8209) (Thanks @vexx32!) +- Fix Request Charset Issues in Web Cmdlets (#8742) (Thanks @markekraus!) +- Refactor `ConvertTo-Json` to expose `JsonObject.ConvertToJson` as a public API (#8682) +- Add `-CustomPipeName` to `pwsh` and `Enter-PSHostProcess` (#8889) +- Add configurable maximum depth in `ConvertFrom-Json` with `-Depth` (#8199) (Thanks @louistio!) +- Enable creating relative symbolic links on Windows with `New-Item` (#8783) +- Parse numeric strings as numbers again during conversions (#8681) (Thanks @vexx32!) +- Expose file attributes of `OneDrive` placeholders (#8745) (Thanks @sba923!) +- Enable `Write-Information` to accept `$null` (#8774) +- Adding parameter `ReplyTo` to `Send-MailMessage` (#8727) (Thanks @replicaJunction!) +- Fix `Get-Help` `PSTypeName` issue with `-Parameter` when only one parameter is declared (#8754) (Thanks @pougetat!) + +### Code Cleanup + +- Use HTTPS in URLs where available (#8622) (Thanks @xtqqczze!) +- Update code to use single method to check if path is UNC (#8680) +- Fix typo: `aganist` ➜ `against` (#8943) (Thanks @lupino3!) +- Use the `OperationCancellationException` to replace the `StoppingException` in `ConvertToJson` (#8920) +- Fix style issues in CSV cmdlets (#8894) (Thanks @iSazonov!) +- Fix `LGTM` issues (#8843) (Thanks @iSazonov!) +- Fix length check in `PSSnapinQualifiedName.GetInstance()` (#8837) (Thanks @hvitved!) +- Reduce string allocations when formatting file system objects. (#8831) (Thanks @powercode!) +- Fix many instances of CodeFactor style issue `A single-line comment must not be followed by a blank line` (#8825) (Thanks @RDIL!) +- Refactor `appveyor.psm1` to `ci.psm1` (#8733, #8854, #8709, #8756, #8867) (Thanks @RDIL!) +- Refactor `travis.ps1` into `ci.psm1` (#8822, #8888) (Thanks @RDIL!) +- Fix Markdown lint issues (#8929) +- Fix code-of-conduct linting (#8896) (Thanks @RDIL!) + +### Tools + +- Fix broken reference (#8753) (Thanks @RDIL!) +- Remove `GitKracken` files from `.gitignore` (#8743) (Thanks @RDIL!) +- Update path of `test\xUnit\xUnit.tests.csproj` in `PowerShell.sln` (#8730) (Thanks @markekraus!) +- Ignore files added by `SelfSignedCertificate` (#8728) (Thanks @markekraus!) +- Build Global tool for PowerShell and SDK container (#8984) +- Add Experimental Features to change log creation (#8827) +- Remove unneeded `Invoke-Expression` on unvalidated input (#8826) +- Update CLA pull request labeling info (#8820) (Thanks @RDIL!) +- Update some info in `md-link-checks` (#8757) (Thanks @RDIL!) + +### Tests + +- Fix `Enter-PSHostProcess` test to wait until runspace is ready before attempting to enter (#8725) +- Package validation tests updates (#8714) +- Make xUnit tests run sequentially to avoid race conditions caused by manipulating `powershell.config.json` in tests (#8945) +- Use verbatim string literals for paths (#8937) (Thanks @iSazonov!) +- Parallelize the Windows CI to enable us to run all tests all the time (#8868) +- Fixes for Scheduled release build (#8887) +- Remove references to uninitialized variable (#8849) +- Remove directory causing static analysis failure (#8812) +- Update Pester version to 4.4.4 (#8739) +- Change xUnit Runspace tests to run sequentially (#8796) +- Fix cleanup config files for the csharp xUnit tests (#8761) (Thanks @iSazonov!) +- Moved `fxdependent-dotnetsdk-latest/Dockerfile` (#8738) + +### Build and Packaging Improvements + +- Make every `csproj` files have its own folder (#8750) +- Update packaging script to build reference assembly targeting `netcoreapp2.1` and use actual `.csproj` files (#8729) +- Generate and deploy reference assembly for `Microsoft.PowerShell.Commands.Utility.dll` (#8716) +- Make test file result names unique (#8979) +- Add variable to control the version of the signing task we use (#8982) +- Publish test and code coverage artifacts for daily builds (#8955) +- Integrate building NuGet package in the coordinated build (#8947) +- Support release branches based on the forward slash separator (#8903) +- Port DotNet fixes from 6.1.3 (#8914) +- Start tracking release build information in an azure storage table (#8850) +- Make license a link in the MSI (#8846) +- Use `-ErrorAction Ignore` instead of `SilentlyContinue` with `Get-Command` in build.psm1 (#8832) +- Add `binskim` to coordinated build and increase timeout (#8834) +- Fix daily CI builds to publish tar package as artifacts (#8775) +- Add instrumentation for `Start-PSPackage` (#8811) +- Fix passing credential to the `SyncGalleryToAzArtifacts.psm1` script (#8808) +- Move Final artifacts from coordinated build to `finalResults` folder (#8806) +- Refactor coordinated release build (#8804) +- Add compliance to Coordinated build (#8798) +- Switch to 1.11 of FPM to fix FPM install issue (#8797) +- Update the coordinated build with framework dependent package for dotnet SDK (#8773) +- Fix MSI upgrade failure for preview builds (#9013) +- Build(deps): Bump `Microsoft.ApplicationInsights` from `2.8.1` to `2.9.1` (#8807,#8848) +- Build(deps): Bump `Microsoft.PowerShell.Native` (#8712) +- Build(deps): Bump `NJsonSchema` from `9.13.15` to `9.13.19` (#8732, #8747, #8881, #8952) +- Build(deps): Bump `PackageManagement` from `1.2.4` to `1.3.1` (#8800) +- Build(deps): Bump `XunitXml.TestLogger` from `2.0.0` to `2.1.26` (#8731) +- Build(deps): Bump `Markdig.Signed` from `0.15.7` to `0.16.0` (#8981) + +### Documentation and Help Content + +- Updating README.md for supported openSUSE version and updating link to OS versions supported by CoreFx (#8701) (Thanks @stknohg!) +- Add complete XML docs for `ConvertToJsonContext` constructors (#8737) +- Update README.md for ARM to include both 32-bit and 64-bit PS package links (#8677) (Thanks @slide!) +- Update issue templates with new supported values (#8718) (Thanks @RDIL!) +- Update maintainer docs about the CLA PR labels (#8734) (Thanks @RDIL!) +- Add Andrew to the maintainer list (#8722) +- Update release process template (#8711) +- Change label in doc issue template (#8895) (Thanks @iSazonov!) +- Update the `dir -recurse` example (#8939) (Thanks @vmsilvamolina!) +- Update CHANGELOG for release `6.1.3` (#8918) +- Update stable version to `6.1.3` (#8902) +- Fix broken link (#8905) +- Update Coding Guidelines (#8844) (Thanks @iSazonov!) +- Update governance documentation (#8776) (Thanks @RDIL!) +- Fix broken python method (#8821) (Thanks @RDIL!) +- Changing docs issue template to new docs repo location (#8818) +- Fix spelling in `releaseTool/README.md` (#8810) +- Update GitHub templates (#8792) (Thanks @iSazonov!) +- Fix broken link in `FAQs.md` (#8803) +- Updated `basics.md` to add a link for showing example for installing git on all package managers (#8735) (Thanks @RDIL!) +- Update `README.md` for `preview.4` (#8772) + +## [6.2.0-preview.4] - 2019-01-28 + +### Breaking Changes + +- Add `-Stable` to `Sort-Object` and related tests (#7862) (Thanks @KirkMunro!) +- Improve `Start-Sleep` cmdlet to accept fractional seconds (#8537) (Thanks @Prototyyppi!) +- Change hashtable to use `OrdinalIgnoreCase` to be case-insensitive in all Cultures (#8566) +- Fix `LiteralPath` in `Import-Csv` to bind to `Get-ChildItem` output (#8277) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Allow user-specified underlying type for enums (#8329) (Thanks @IISResetMe!) +- Handle case where AppLocker test script fails to delete (#8627) +- Update `CommandNotFound` fuzzy suggestion to only return unique results (#8640) +- Add support to show suggestions on `CommandNotFound` exception (#8458) +- Make `S.M.A.PowerShell.GetSteppablePipeline` method public (#8055) (Thanks @KirkMunro!) +- Add `S.M.A.PowerShell.Create` method overload with Runspace argument (#8057) (Thanks @KirkMunro!) +- Fix mistake on deserialization (#8502) +- Fix formatting of header of table when center aligned (#8497) +- Add `-RepeatHeader` to `Format-Table` to enable repeating header for each screen full (#8481) +- Fix `Debug-Runspace` for Unix platforms and properly enable Windows identity impersonation code (#8451) +- Reset output attributes if column had `ESC` char when using `Format-Table`; Replace `...` with unicode ellipsis (#8326) + +### Experimental Features + +- Add the experimental feature `PSUseAbbreviationExpansion` to support tab completion on abbreviated command names (#8109) + +### General Cmdlet Updates and Fixes + +- Fix code page parsing issue in `Invoke-RestMethod` (#8694) (Thanks @markekraus!) +- Fix `Expect 100-continue` issue with Web Cmdlets (#8679) (Thanks @markekraus!) +- Allow 'name' as an alias key for 'label' in `ConvertTo-Html`, allow the 'width' entry to be an integer (#8426) (Thanks @mklement0!) +- Resolve `:PAGER` if its path contains spaces (#8571) (Thanks @pougetat!) +- Add support enum and char types in `Format-Hex` cmdlet (#8191) (Thanks @iSazonov!) +- Change `Get-Help` cmdlet `-Parameter` parameter so it accepts string arrays (#8454) (Thanks @sethvs!) +- Fix `FixupFileName` to not load resolved assembly during module discovery (#8634) +- Change `Clear-Host` back to using `$RAWUI` and `clear` to work over remoting (#8609) +- Fix `LiteralPath` in `Import-Csv` to bind to `Get-ChildItem` output (#8277) (Thanks @iSazonov!) +- Make scriptblock based calculated properties work again in `ConvertTo-Html` (#8427) (Thanks @mklement0!) +- Fix `Join-String` cmdlet `FormatString` parameter logic (#8449) (Thanks @sethvs!) +- Allow Windows users in developer mode to create symlinks without elevation (#8534) +- `Help` function should only pass content to pager if content was found (#8528) +- Change `Clear-Host` to simply called `[console]::clear` and remove `clear` alias from Unix (#8603) +- `help` function shouldn't use pager for `AliasHelpInfo` (#8552) +- Fix XML nesting bug in `CustomSerializer.WriteMemberInfoCollection()` (#8476) (Thanks @IISResetMe!) +- Add `-UseMinimalHeader` to `Start-Transcript` to minimize transcript header (#8402) (Thanks @lukexjeremy!) + +### Code Cleanup + +- Remove the no longer used `RunspaceConfigurationEntry` types (#8424) +- Remove unneeded catch/throw from `mkdir` and `oss` functions (#8425) +- Remove comments after closing brackets (#8344) (Thanks @Meir017!) +- Cleanup `Format-Hex` (#8683) (Thanks @vexx32!) +- Delete `appveyor.yml` (#8639) (Thanks @RDIL!) +- Revise use of `Start-Sleep` cmdlet (#8633) (Thanks @xtqqczze!) +- Style: Change first char to upper in summary comments (#8597) (Thanks @iSazonov!) +- Style: Use the type aliases `char` and `bool` instead of `Char` and `Boolean` (#8572) (Thanks @iSazonov!) +- Style: Use the type alias `string` instead of `String` in places that are appropriate (#8573) (Thanks @iSazonov!) +- Correctly capitalize the `ForEach` operator in `*.ps1` (#8583) (Thanks @xtqqczze!) +- Remove unnecessary trim of passed-in command line in interactive debugging (#8594) +- Style: Add a space after "//" in comments and remove unneeded comments after "}" (#8576) (Thanks @iSazonov!) +- Style: Add the ending period to the XML document texts (#8577) (Thanks @iSazonov!) +- Avoid use of `mkdir` alias in `*.ps1` and `*.psm1` (#8582) (Thanks @xtqqczze!) +- Regularize redirection operator spacing in `*.ps1` and `*.psm1` (#8581) (Thanks @xtqqczze!) +- Style: Change 'String.' to 'string.' (#8568) (Thanks @iSazonov!) +- Style: Replace `String.IsNullOrEmpty` with `string.IsNullOrEmpty` (#8557) (Thanks @iSazonov!) +- Fix typo in AMSI test (#8561) (Thanks @iSazonov!) +- Style: Convert to upper first char in `` and `` doc tags (#8556) (Thanks @iSazonov!) +- Style: Add period before `` and `` doc tags (#8553) (Thanks @iSazonov!) +- Remove use of cmdlet aliases from `.\test\powershell` (#8546) (Thanks @xtqqczze!) +- Style: Remove extra spaces after `` and before `` docs tags (#8547) (Thanks @iSazonov!) +- Style: Remove preceding spaces from C# `preprocessor-type` keywords (#8540) (Thanks @xtqqczze!) +- Style: remove ` ` (#8538) (Thanks @iSazonov!) +- Style: Add period before returns doc tag (#8535) (Thanks @iSazonov!) +- Style: Change `Object[]` to `object[]` (#8526) (Thanks @iSazonov!) +- Style: Change `Object` to `object` (#8522) (Thanks @iSazonov!) +- Style: Change `UInt64?` to `ulong?` (#8527) (Thanks @iSazonov!) +- Style: Change `Byte{}` to `byte[]` (#8525) (Thanks @iSazonov!) +- Code cleanup: Add space after closing brace where needed (#8530) +- Style: Change `System.Boolean` to `bool` (#8521) (Thanks @iSazonov!) +- Change `String` to `string` for simple references (#8519) +- Change `Int32` to `int` for simple references in variable declaration (#8518) +- Style: Member access symbols should be followed with member name (#8517) +- Style: Remove extra space before colon in named parameters (#8504) +- Style: Use the shorthand of the `nullable` type (#8501) +- Remove empty lines; correct space on closing square brackets, negative signs, and generic brackets (#8508) +- Remove space after new keyword in implicitly typed array allocation (#8505) +- The static keyword should be right after access modifier (#8506) +- Remove comments after closing bracket (#8503) +- Remove space character after `'!'` (#8507) +- Style: Remove extra space before colon in named parameters (#8504) + +### Tools + +- Recommend Azure DevOps extension inside VS-Code for better `YAML` editing. (#8403) (Thanks @bergmeister!) +- `-AddToPath` re-implementation in `install-powershell.ps1` (#8081) (Thanks @glachancecmaisonneuve!) +- Change the feed `URL` to feed name due to changes in `AzDevOps` (#8664) +- Batch merge builds together while a merge build is running (#8668) +- Fix grammar in stale bot message (#8660) (Thanks @RDIL!) +- Add macOS files to `.gitignore` (#8456) (Thanks @RDIL!) +- Name the spelling yaml something more appropriate (#8601) (Thanks @RDIL!) +- Add script to create `icns` files. (#7456) (Thanks @thezim!) +- Pass `nugetkey` as parameter (#8461) +- Add `gitkracken` files to `gitignore` (#8434) (Thanks @RDIL!) +- Create release process issue template (#8417) +- Support for `linuxmint` in `installpsh-debian.sh` (#8440) (Thanks @DarwinJS!) +- Enable `install-powershell.ps1` to use `MSI` (#8418) + +### Tests + +- Remove broken `HelpUri` from `CimTest` (#8688) (Thanks @xtqqczze!) +- Remove appveyor environment checks (#8669) (Thanks @RDIL!) +- Adding tests for `PSDiagnostics Module` (#8431) (Thanks @kvprasoon!) +- Increase diagnose-ability of Link Checker failures (#8667) +- Fix broken urls (#8653) +- Update fuzzy test to fix daily build (#8629) +- Create link check task (#8471) (Thanks @RDIL!) +- Add Tests for `ConfirmImpact` Ratings (#8214) (Thanks @vexx32!) +- Fix style issues in xUnit tests (#8465) (Thanks @iSazonov!) +- Move `xUnit` tests in new folder (#8356) (Thanks @iSazonov!) +- Fix environment variable test and add missing null check in `CommandHelpProvider` (#8408) +- Remove `dotnet` dependency to start WebListener (#8390) + +### Build and Packaging Improvements + +- Update Third Party Notices (#8415) +- Adding yaml for Windows Release builds (#8374) +- Bump `NJsonSchema` from `9.13.1` to `9.13.2` (#8422) +- Do not ship fullclr binaries of `PackageManagement` (#8700) (Thanks @bergmeister!) +- Fix the build for `fxdependent` build for `dotnet sdk` (#8670) +- Add Windows build to universal release build YAML (#8695) +- Remove `Debian 8` references as it is EOL (#8678) +- Build(deps): Bump `NJsonSchema` from `9.13.14` to `9.13.15` (#8671) +- Build package build using ubuntu 18.04 image (#8666) +- Fix a typo in `packaging.psm1` (#8647) (Thanks @sethvs!) +- Add function to create a framework dependent package `dotnet-sdk` containers (#8644) +- Build(deps): Bump `NJsonSchema` from `9.13.13` to `9.13.14` (#8648) +- Build(deps): Bump `PowerShellGet` from `2.0.3` to `2.0.4` (#8649) +- Fix installing `fpm` and `ronn` in macOS CI by avoid installing docs for them (#8656) +- Build(deps): Bump `Markdig.Signed` from `0.15.6` to `0.15.7` (#8637) +- Build(deps): Bump `System.Security.Cryptography.Pkcs` from `4.5.1` to `4.5.2` (#8614) +- Build(deps): Bump `System.Net.Http.WinHttpHandler` from `4.5.1` to `4.5.2` (#8615) +- Build(deps): Bump `NJsonSchema` from `9.13.11` to `9.13.13` (#8616) +- Build(deps): Bump `System.Text.Encoding.CodePages` from `4.5.0` to `4.5.1` (#8613) +- Enable install of Preview MSI release side-by-side with Stable release (#8513) +- Get macOS to publish daily build to nugetfeed (#8464) +- Build(deps): Bump `Markdig.Signed` from `0.15.5` to `0.15.6` (#8558) +- Build(deps): Bump `NJsonSchema` from `9.13.10` to `9.13.11` (#8569) +- Remove duplicate `Open Here` context menu item upgrading to newer Preview release (#8496) +- Bump `NJsonSchema` from `9.13.9` to `9.13.10` (#8511) +- Bump `NJsonSchema` from `9.13.7` to `9.13.9` (#8498) +- Bump `NJsonSchema` from `9.13.4` to `9.13.7` (#8493) +- Bump `NJsonSchema` from `9.13.3` to `9.13.4` (#8462) +- Fix daily NuGet publishing (#8460) +- Bump `NJsonSchema` from `9.13.2` to `9.13.3` (#8457) +- Bump `Markdig.Signed` from `0.15.4` to `0.15.5` (#8444) + +### Documentation and Help Content + +- Remove unused `AppVeyor` links from `README.md` (#8685) (Thanks @RDIL!) +- Update `README.md` (#8684) +- Update Package Management license to MIT (#8676) (Thanks @RDIL!) +- Create Support File (#8618) (Thanks @RDIL!) +- Update git clone URL (#8673) (Thanks @RDIL!) +- docs(contributing): add link check information (#8659) (Thanks @RDIL!) +- Update License and Third Party Notice (#8646) +- Update README, `metadata.json` and changelog for release `6.1.2` (#8658) +- Fix typo in `README.md` (#8642) (Thanks @MarkTiedemann!) +- Fix some typos in the README (#8623) (Thanks @RDIL!) +- Remove `en-us` from `docs.microsoft.com` URL (#8628) (Thanks @xtqqczze!) +- Update examples for hosting PSCore and remove old outdated examples (#8472) (Thanks @bergmeister!) +- Update the pull request template (#8624) (Thanks @RDIL!) +- Contributing guidelines: Remove references to Travis CI and AppVeyor (#8617) (Thanks @RDIL!) +- Update code coverage analysis document (#8543) (Thanks @xtqqczze!) +- Remove `en-us` from our doc links (#8602) +- Document `First-time-issue` and `Hackathon`/`Hacktoberfest` labels (#8575) +- Updated linux build link (#8579) (Thanks @jwmoss!) +- Update contributing guidelines doc to run spellchecking in English (#8473) (Thanks @RDIL!) +- Updating links to point to new VS Code docs (#8468) + +## [6.2.0-preview.3] - 2018-12-10 + +### Breaking Changes + +- `Get-ExperimentalFeature` no longer has `-ListAvailable` switch (#8318) +- `Debug` parameter now sets `DebugPreference` to `Continue` instead of `Inquire` (#8195) (Thanks @KirkMunro!) + +### Engine Updates and Fixes + +- Improve PowerShell startup time by 24% (#8341) (#8396) +- Remove extra newlines from formatting which resulted in unnecessary double newlines (#8247) +- Add `Enable-ExperimentalFeature` and `Disable-ExperimentalFeature` cmdlets (#8318) +- Fix `Export-ModuleMember` bug for a `ScriptBlock` having no context (#8363) +- Fix race condition to access `powershell.config.json` (#8249) (Thanks @iSazonov!) +- Add `SkipCA` and `SkipCN` check requirement to WinRM/OMI HTTPS connection (#8279) +- Add fix for `Start-Job` initialization script which should not be executed as trusted in system lockdown (#8284) + +### General Cmdlet Updates and Fixes + +- Add `Enable-ExperimentalFeature` and `Disable-ExperimentalFeature` cmdlets (#8318) +- Add cmdlet `Join-String` for creating text from pipeline input (#7660) (Thanks @powercode!) +- Expose all cmdlets from `PSDiagnostics` if `logman.exe` is available (#8366) +- Fix `Get-Help` for advanced functions with MAML help content (#8353) +- Conditionally mark getter/setter implementations as virtual in generated classes (#8303) (Thanks @IISResetMe!) +- Fix for `PSDrive` creation with a UNC path with a trailing backslash or forward slash when combined with `-Persist` (#8305) (Thanks @kvprasoon!) +- Remove `Persist` parameter from `New-PSDrive` on non-Windows platform (#8291) (Thanks @lukexjeremy!) +- `Test-Path`: Return `$false` when given an empty or `$null` `-Path`/`-LiteralPath` value (#8080) (Thanks @vexx32!) +- Token calculation fix for `Get-Help` executed on `ScriptBlock` for comment help. (#8238) (Thanks @hubuk!) +- Support `Get-PSHostProcessInfo` and `Enter-PSHostProcess` on Unix platforms (#8232) + +### Code Cleanup + +- Update `resgen`, `typegen` to use .Net Core 2.1 (#8369) (Thanks @bergmeister!) +- Change `Newtonsoft` deserializing bug comment to link to the new issue (#8377) (Thanks @louistio!) +- Cleanup `#if !CORECLR` code (#8337) (Thanks @iSazonov!) +- Cleanup `UpdatableHelpSystem` and enable XSD validation on MAML help content (#8335) (Thanks @iSazonov!) +- Remove old `customPSSnapInType` parameter from `PSSnapInInfo()` (#8333) (Thanks @iSazonov!) +- Cleanup `#if CORECLR` from some files (#8332) (Thanks @iSazonov!) +- Cleanup `AssemblyInfo` (#8190) (Thanks @iSazonov!) +- Fix `GetLocationCommand` output type parameter set and style issues (#8324) (Thanks @Meir017!) + +### Tools + +- Remove `dependabot` attribution and generate changelog sections using `CL-*` labels (#8386) + +### Tests + +- Update folder path for storing optimization profile and add test to validate loaded assemblies and libraries on startup (#8406) +- Fix an intermittent failure in macOS logging tests (#8385) +- Created a `csproj` to pin test modules and updated `build.psm1` accordingly (#8350) +- Update help content for `TabCompletion` tests only if it does not exist (#8355) +- Skip `Enter-PSHostProcess` tests on `AppVeyor` due to `PSReadline` issue (#8317) + +### Build and Packaging Improvements + +- Remove `AmazonLinux` Dockerfile (#8271) (Thanks @kiazhi!) +- Make `install-powershell.sh` auto-detect if it should use `wget` or `curl` (#8225) (Thanks @DarwinJS!) +- Bump `NJsonSchema` from `9.12.2` to `9.13.1` (#8319) (#8328) (#8412) (#8371) (#8384) +- Bump `Microsoft.PowerShell.Native` from `6.2.0-preview.2` to `6.2.0-preview.3` (#8411) +- Update the name of the artifact to be unique per artifact (#8405) +- Create unified release build for macOS and Linux packages (#8399) +- Add Linux `ARM64` build support (#8016) (Thanks @slide!) +- Update the timeout of CI builds (#8398) +- Bump `PackageManagement` from `1.2.2` to `1.2.4` in `/src/Modules` (#8320) (#8383) +- Bump `Newtonsoft.Json` from `11.0.2` to `12.0.1` (#8348) +- Enable pipeline to sync `PSGallery` modules to `AzArtifacts` feed (#8316) +- Build Alpine `tar.gz` package in release builds (#8340) +- Publish test package to `AppVeyor` daily build (#8273) +- Bump `Microsoft.CodeAnalysis.CSharp` from `2.9.0` to `2.10.0` (#8294) +- Bump `PowerShellGet` from `2.0.1` to `2.0.3` in `/src/Modules` (#8321) +- Enable `Open Here` context menu on Windows to work with root of a drive (#8287) +- Bump `System.Data.SqlClient` from `4.5.1` to `4.6.0` (#8266) + +### Documentation and Help Content + +- Merge `changelogs` from `6.1.1` and `6.0.5` into master (#8283) +- Remove all reference to `AppVeyor` and `Travis CI` from docs (#8376) +- Change default issue template to use different categories (#8203) + +## [6.2.0-preview.2] - 2018-11-15 + +### Breaking Changes + +- Honor `-OutputFormat` if specified in non-interactive, redirected, encoded command used with `pwsh` (#8115) +- Load assembly from module base path before trying to load from the `GAC` (#8073) +- Remove tilde from Linux preview packages (#8244) +- Move processing of `-WorkingDirectory` before processing of profiles (#8079) + +### Known Issues + +- PowerShell WSMan remoting does not work on Debian 9 due to missing symbolic links. + For more information and a workaround see issue [#7598](https://github.com/PowerShell/PowerShell/issues/7598) + +### Engine Updates and Fixes + +- Enable case-insensitive tab completion for files and folders on case-sensitive filesystem (#8128) +- Experimental feature: Implicit remoting batching performance improvements (#8038) +- Add a path for checking `ZoneInformation` without throwing an exception (#8025) (Thanks @powercode!) +- Fix [CVE-2018-8256](https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2018-8256), + issues with expanding `ZIP` files with relative paths (#8252) +- Fix [CVE-2018-8415](https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2018-8415), + issue logging when the `scriptblock` has a null character (#8253) +- Make `PSVersionInfo.PSVersion` and `PSVersionInfo.PSEdition` public (#8054) (Thanks @KirkMunro!) +- Enable distinct `ModuleAnalysisCache` files for each installation of `pwsh` (#8174) +- Consolidation of all Windows PowerShell work ported to PowerShell Core (#8257) +- Fix incorrect name check when auto-loading required modules (#8218) +- Adding verbose output for experimental implicit remoting batching feature (#8166) +- Add Type Inference for `$_ / $PSItem in catch{ }` blocks (#8020) (Thanks @vexx32!) +- Fix static method invocation type inference (#8018) (Thanks @SeeminglyScience!) + +### General Cmdlet Updates and Fixes + +- Reduce allocations in `Get-Content` cmdlet (#8103) (Thanks @iSazonov!) +- Enable `Set-Location -LiteralPath` to work with folders named `-` and `+` (#8089) +- Enable `Add-Content` to share read access with other tools while writing content (#8091) +- Add new `Offset` and `Count` parameters to `Format-Hex` and refactor the cmdlet (#7877) (Thanks @iSazonov!) +- Add `-Name`, `-NoUserOverrides` and `-ListAvailable` parameters to `Get-Culture` cmdlet (#7702) (Thanks @iSazonov!) +- Allow dynamic parameter to be returned even if path does not match any provider (#7957) +- Style fixes in `Format-Hex` (#8083) (Thanks @iSazonov!) +- Fix logic to rely on PowerShell major and minor version instead of build number to determine whether to output `formatdata` (#8063) +- Fix `Rename-Item -Path` with wildcard `char` (#7398) (Thanks @kwkam!) +- When using `Start-Transcript` and file exists, empty file rather than deleting (#8131) (Thanks @paalbra!) +- Error message enhancement for `Clear-Content` cmdlet when targeting a directory (#8134) (Thanks @kvprasoon!) +- Make `Select-String` faster by not doing extra work (#7673) (Thanks @powercode!) +- Remove `ShouldProcess` from `Format-Hex` (#8178) + +### Code Cleanup + +- Remove clone of command-line arguments array (#7910) (Thanks @iSazonov!) +- Use `DefaultPathSeparator` `char` instead of `DefaultPathSeparatorString` (#8082) (Thanks @iSazonov!) +- Replace `StringComparision.CurrentCulture` with `StringComparision.Ordinal` (#8068) (Thanks @iSazonov!) +- Fix typo in `-icontains` description from `incase sensitive` to `case insensitive` (#7840) (Thanks @StingyJack!) +- Refactor module version/`GUID` comparison logic (#7125) + +### Tools + +- Update `installpsh-amazonlinux.sh` for container specific issues (#7907) (Thanks @DarwinJS!) +- Update the `codeowners` file (#8017) + +### Tests + +- Filter the `TestPackage` artifact upload by name to avoid other `ZIP` files being uploaded (#8116) +- Adding `fxdependent` PowerShell package tests (#7830) +- Fix Windows Feature tests running in Azure DevOps (#8220) +- Create `$PROFILE` if it does not exist for `-WorkingDirectory` processing test (#8152) +- Add test coverage for additional `Get-Module` parameters (#8137) (Thanks @KevinMarquette!) +- Fix conflict with `Get-AdlStoreChildItem` from `az` module in tab completion tests (#8167) +- Fix static secret in code (#8186) + +### Build and Packaging Improvements + +- Bump `xunit.runner.visualstudio` from `2.4.0` to `2.4.1` (#8139) +- Bump `xunit` from `2.4.0` to `2.4.1` (#8140) +- Bump `Microsoft.ApplicationInsights` from `2.8.0` to `2.8.1` (#8104) +- Bump `NJsonSchema` from `9.11.1` to `9.12.1` (#8183, #8248) +- Fix `Start-PSBuild -Output` (#7504) (Thanks @kwkam!) +- Adding `YML` for Linux builds (#8168) +- Publish test package at `AGENT_WORKFOLDER` if `TEMP` is not available (#8108) +- Fix `psmodulerestore` path when built in Visual Studio Code (#8075) +- Use approved verb instead of `Generate-CrossGenAssembly` (#8151) (Thanks @kvprasoon!) +- Add path filters to CI `YAML` (#8222) +- Update `SignType` in `signing.xml` (#8223) +- Update metadata for `6.0.5` and `6.1.1` releases (#8259) +- Port changes to allow Azure DevOps NuGet feeds for Mac build (Internal 5818) +- Update version for dependencies (Internal 5822) +- Add code to use private NuGet feeds when running in internal CI system (#8187) +- Add title to `Open Here` window for `MSI` installer (#8164) +- Remove build and documentation references to `git` submodules (#8177) (Thanks @andschwa!) +- Add function to create a new `nuget.config` file (#8170) +- Update macOS release build to create the `nuget.config` (#8185) +- Workaround for accessing Azure Artifacts (#8188) +- Fix script path for `PowerShellPackageVsts.ps1` (#8189) +- `Microsoft.PowerShell.Native` now has `MUSL` binaries for Alpine. + +### Documentation and Help Content + +- Fix grammar in `README.md` (#8059) (Thanks @daviddreher2!) +- Update `powershell-beginners-guide.md` to add alias for `Clear-Host` (#7912) (Thanks @aavdberg!) +- Add Microsoft Docs link to FAQ (#8133) (Thanks @vongrippen!) +- Added updated photo of Visual Studio Code due to new version of Code (#8084) (Thanks @lassehastrup!) +- Update `license.rtf` to only have major version (#8127) +- Updated Pester Syntax in Writing Tests Guide (#8039) (Thanks @markwragg!) +- Remove duplicate parts from license file (#8143) (Thanks @azkarmoulana!) +- Fix spellings in `CHANGELOG.md` (#8062) +- Update license RTF to 6.2 (#8065) +- Combine notes about `ITuple` changes in Change Log (#8077) (Thanks @Jocapear!) +- Correct typos in `powershell-beginners-guide.md` (#8088) (Thanks @nycjan!) +- Added `Learn Windows PowerShell in a Month of Lunches` as recommended reading (#8067) (Thanks @tobvil!) +- Update `README.md` for `v6.1.1` (#8255) +- Fix some typos (#8206) (Thanks @jeis2497052!) +- Promote `HTTPS` (#8160) (Thanks @RDIL!) +- Simple grammatical correction in `README.md` file (#7978) (Thanks @iGotenz!) +- Update URLs to use `HTTPS` instead of `HTTP` in the documentation (#8165) (Thanks @RDIL!) +- Remove #7633 from `v6.2.0-preview.1` `CHANGELOG.md` updates. (#8101) (Thanks @stknohg!) + +## [6.2.0-preview.1] - 2018-10-18 + +### Breaking Changes + +- Do not add `PATHEXT` environment variable on Unix (#7697) (Thanks @iSazonov!) + +### Known Issues + +- Remoting on Windows IOT ARM platforms has an issue loading modules. See [#8053](https://github.com/PowerShell/PowerShell/issues/8053) + +### Engine Updates and Fixes + +- Add C# style type accelerators and suffixes for `ushort`, `uint`, `ulong`, and `short` literals (#7813) (Thanks @vexx32!) +- Create inferred types for `Select-Object`, `Group-Object`, `PSObject` and `Hashtable` (#7231) (Thanks @powercode!) +- Fix .NET adapter to be able to get members from `System.IntPtr` (#7808) +- Fix .NET adapter to not throw when fails to create a `PSMethod` due to `ByRef-like` type (#7788) +- Support calling method with `ByRef-like` type parameters (#7721) +- Fix perf issue in provider by using `Refresh()` to update the status rather than instantiating `ServiceController` which has a significant perf degradation from .NET Framework (#7680) +- Update PowerShell to handle the case where the Windows PowerShell module path is already in the environment's `PSModulePath` (#7727) +- Ensure the `SSHClientSessionTransportManager` stream writer and reader fields are cleared after dispose. (#7746) +- Add unified attribute for completion for `Encoding` parameter. (#7732) (Thanks @ThreeFive-O!) +- Add support for Byte Literals (#7901) (Thanks @vexx32!) +- Fix Property and `ScriptBlock` expressions in `EntrySelectedBy` tags within custom controls (#7913) (Thanks @SeeminglyScience!) +- Fix `BeginInvoke`/`EndInvoke` to return results when `Stop` or `BeginStop`/`EndStop` was called previously (#7917) +- Allow root node of `format.ps1xml` to have attributes that are ignored (#7987) +- Use non-virtual call to invoke 'family or assembly' methods on base class from PowerShell class (#7622) (#7624) (Thanks @yurko7!) +- Make the parameter to `ImportPSModule` use `params` so that it is easier to call (#7933) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Add `EscapeHandling` parameter in `ConvertTo-Json` cmdlet (#7775) (Thanks @iSazonov!) +- Make `Add-Type` open source files with `FileAccess.Read` and `FileShare.Read` explicitly (#7915) (Thanks @IISResetMe!) +- No longer skips a column without name if double quote delimiter is used in `Import-Csv` (#7899) (Thanks @Topping!) +- Add support for `cd +` (#7206) (Thanks @bergmeister!) +- Allow numeric Ids and name of registered code pages in `-Encoding` parameters (#7636) (Thanks @iSazonov!) +- Remove extra space in `LastWriteTime` format (#7810) (Thanks @iSazonov!) +- Fix `Enter-PSSession -ContainerId` for the latest Windows (#7883) +- `Get/Add-Content` throws improved error when targeting a container (#7823) (Thanks @kvprasoon!) +- Ensure `NestedModules` property gets populated by `Test-ModuleManifest` (#7859) +- Add `%F` case to `Get-Date -UFormat` (#7630) (Thanks @britishben!) +- Fix file blocking issue with web cmdlets (#7676) (Thanks @Claustn!) +- Improve error message on non-Windows when importing `clixml` with `securestring` (#7997) +- Add prompt to the use of less in the function 'help' to instruct user how to quit (#7998) +- Fix `Set-Service -Status Stopped` to stop services with dependencies (#5525) (Thanks @zhenggu!) + +### Code Cleanup + +- Use `nameof()` in bound `parameters.contains key()` (#7908) (Thanks @iSazonov!) +- Cleanup all native code from repository (#7892) +- Add `XSDs` for Format and `Types.ps1xml` files (#7832) (Thanks @felixfbecker!) +- Remove unused commented out code (#7935) (Thanks @vpondala!) +- Add `.editorconfig` (#7357) (Thanks @iSazonov!) +- Remove unused stopwatch (#7878) +- Clean up `MshObject.cs` and `MshMemberInfo.cs` (#7446) +- Add `TimeToLive` and `Hops` aliases to `MaxHops` parameter of `Test-Connection` cmdlet. (#7850) (Thanks @sethvs!) +- Fix a typo in `Credential.cs` (#7696) (Thanks @sethvs!) +- Remove workaround on VSTS that is no longer needed (#7666) +- Improve code style of `Send-MailMessage` cmdlet (#7723) (Thanks @ThreeFive-O!) +- Cleanup `FileSystemProvider` from runtime checks (#7655) (Thanks @iSazonov!) +- Remove extra spaces in error messages in `Modules.resx` (#7662) (Thanks @sethvs!) +- Remove empty XML comment lines (missed in #7401) (#7641) (Thanks @kvprasoon!) +- Remove `Suspend-Job` and `Resume-Job` cmdlets from compilation (#7650) + +### Tools + +- Fix syntax error in `installpwsh-amazonlinux.sh` (#7905) (Thanks @DarwinJS!) +- Add tools for PowerShell perf analysis (#7595) (Thanks @lzybkr!) +- Started using [Dependabot](https://dependabot.com) to create PRs to update package and module versions + +### Tests + +- Add test for `$error[0]` tab completion (#7924) (Thanks @iSazonov!) +- Replace test certificates with self-signed certificate generating command (#7875) +- Standardize Pester syntax in `ReplaceOperator.Tests.ps1` (#7963) (Thanks @sethvs!) +- Updating `ModulePath.Tests` for `fxdependent` package (#7772) +- Add tests for `Import-Module -Force` (#7491) +- Updates to Docker package tests (#7667) +- Updating test gallery URL in `PackageManagement` tests (#7879) +- Add version checking tests for `Import-Module` (#7499) +- Update Markdown tests (#7838) +- Change locale of `mdspell` to `en-US` (#7671) +- Test changes needed for running in a container (#7869) +- Add daily build non-windows platforms (#7683) +- Remove workaround on VSTS that is no longer needed (#7666) +- Fix module specification `hashtable` in `ModuleSpecification.Tests.ps1` (#7663) (Thanks @sethvs!) +- Use `dotnet test` since the `dotnet xunit` test runner has been deprecated (#7980) (Thanks @bergmeister!) +- Fix pipeline test where `SmtpServer` key was set wrong in pipeline object (#7745) (Thanks @ThreeFive-O!) +- Change API to get host name to match cmdlet which is more reliable in Azure DevOps Pipelines `Hosted Windows VS2017` (#8003) +- Disable `travis-ci` (#7766) +- Make artifact upload only occur for non-PR builds (#7657) +- Change logic for downloading zip files based on job id (#7653) +- Add missing dependency for hosting xUnit tests + +### Build and Packaging Improvements + +- Change default of `Start-PSBuild` to include `-PSModuleRestore` (#7881) +- Specify verb, `pwsh`, for shell context menu to avoid overriding the default verb (#7932) (Thanks @bergmeister!) +- Converting aliases to cmdlets in `build.psm1` (#7964) (Thanks @kvprasoon!) +- Add dependencies for SUSE (#7938) (Thanks @Jellyfrog!) +- Wait for package manager not to be locked (#7817) +- Make `Start-PSPackage` give better message about how to fix `files.wxs` (#7841) +- Bump to .NET Core `2.1.5` with SDK `2.1.403` and latest packages (#7646, #7834, #7922, #7936) (Thanks @iSazonov!) +- Bump `Markdig.Signed` NuGet package from `0.15.3` to `0.15.4` (#7960) (Thanks @bergmeister!) +- Bump `Microsoft.ApplicationInsights` from `2.7.2` to `2.8.0` (#8002) +- Bump `Microsoft.PowerShell.Native` from `6.1.0-rc.1` to `6.1.0` (#7861) +- Bump `NJsonSchema` from `9.10.71` to `9.11.1` (#7705, #7764, #7990) +- Bump `PackageManagement` from `1.1.7.2` to `1.2.2` in /src/Modules (#8014, #8029) +- Bump `Pester` to use latest version (#8015) +- Bump `PowerShellGet` to `2.0.0` (#7831) +- Bump `PSReadLine` to `2.0.0-beta3` (#7711) +- Bump `Xunit.SkippableFact` from `1.3.6` to `1.3.12` (#7972) +- Make Windows MSI uninstallation shortcut remove work when more than one version is installed (#7701) (Thanks @bergmeister!) +- Update Docker files to use MCR (#7726) +- Update `metadata.json` in preparation for `6.1` release (#7741) +- Build and package framework dependent package (#7729) +- Make sure MSI build works when not preview (#7752) +- Remove `PDBs` from `fxdependent` package (#8006) +- Improve debugging of NuGet package generation and add type to filtering + +### Documentation and Help Content + +- Replace ambiguous term (#7902, #7931) (Thanks @iSazonov!) +- Updating incorrect example of `PowerShell.Create()` (#7926) (Thanks @1RedOne!) +- Update `governance.md` (#7927) (Thanks @tommymaynard!) +- Add `cURL` to the Bash users list in `README.md` (#7948) (Thanks @vmsilvamolina!) +- Optimize image assets used in documentation (#7874) (Thanks @RDIL!) +- Update build badges (#7792) +- Remove packaging, building and installation scripts for Ubuntu 17.10 (#7773) +- Remove badges for master build as it reflects last PR which is not actionable from the `README` file (#7816) +- Improve Markdown formatting of beginners guide (#7684) (Thanks @fbehrens!) +- Fix the `Basic cookbooks` link (#7934) (Thanks @vmsilvamolina!) +- Update version for PowerShell release `6.1.0` (#7751) +- Add VSTS CI build badges for master branch to `README.md` (#7691) (Thanks @bergmeister!) +- Add a paragraph on `files.wxs` updating (#7695) (Thanks @iSazonov!) +- Update `CONTRIBUTION.md` about adding an empty line after the copyright header (#7706) (Thanks @iSazonov!) +- Update docs about .NET Core version `2.0` to be about version `2.x` (#7467) (Thanks @bergmeister!) + +[6.2.7]: https://github.com/PowerShell/PowerShell/compare/v6.2.6...v6.2.7 +[6.2.6]: https://github.com/PowerShell/PowerShell/compare/v6.2.5...v6.2.6 +[6.2.5]: https://github.com/PowerShell/PowerShell/compare/v6.2.4...v6.2.5 +[6.2.4]: https://github.com/PowerShell/PowerShell/compare/v6.2.3...v6.2.4 +[6.2.3]: https://github.com/PowerShell/PowerShell/compare/v6.2.2...v6.2.3 +[6.2.2]: https://github.com/PowerShell/PowerShell/compare/v6.2.1...v6.2.2 +[6.2.1]: https://github.com/PowerShell/PowerShell/compare/v6.2.0...v6.2.1 +[6.2.0]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-rc.1...v6.2.0 +[6.2.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-rc.1...v6.2.0 +[6.2.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-preview.3...v6.2.0-preview.4 +[6.2.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-preview.2...v6.2.0-preview.3 +[6.2.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-preview.1...v6.2.0-preview.2 +[6.2.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v6.1.0...v6.2.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/7.0.md b/PowerShell-master/CHANGELOG/7.0.md new file mode 100644 index 0000000000000000000000000000000000000000..e054b34cfc9daee1ecfb6683fb2b684ef10f547b --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.0.md @@ -0,0 +1,1421 @@ +# 7.0 Changelog + +## [7.0.13] - 2022-10-20 + +### Engine Updates and Fixes + +- Stop sending telemetry about `ApplicationType` (#18265) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 3.1.424 (#18272)

+ +
+ +
    +
  • Update Wix file for new assemblies (Internal 22873)
  • +
  • Update the cgmanifest.json for v7.0.13 (#18318)
  • +
  • Update Newtonsoft.Json version for 7.0.13 release (#18259)
  • +
  • Fix build.psm1 to not specify both version and quality for dotnet-install (#18267)
  • +
  • Update list of PowerShell team members in release tools(#18266)
  • +
  • Move cgmanifest generation to daily (#18268)
  • +
  • Disable static analysis CI on 7.0 (#18269)
  • +
+ +
+ +[7.0.13]: https://github.com/PowerShell/PowerShell/compare/v7.0.12...v7.0.13 + + +## [7.0.12] - 2022-08-11 + +### General Cmdlet Updates and Fixes + +- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) + +### Tests + +- Enable more tests to be run in a container. (#17294) +- Switch to using GitHub action to verify markdown links for PRs (#17281) +- Add `win-x86` test package to the build (#15517) + +### Build and Packaging Improvements + +
+ + +

Bump .NET 3.1 SDK to 3.1.28

+
+ +
    +
  • Update wix file
  • +
  • Add a finalize template which causes jobs with issues to fail (#17314)
  • +
  • Make sure we execute tests on LTS package for older LTS releases (#17326)
  • +
  • Update AzureFileCopy task and fix the syntax for specifying pool (#17013)
  • +
+ +
+ +[7.0.12]: https://github.com/PowerShell/PowerShell/compare/v7.0.11...v7.0.12 + +## [7.0.11] - 2022-05-13 + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 3.1.419

+ +
+ +
    +
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • +
  • Update to use mcr.microsoft.com (#17272)
  • +
  • Update global.json and wix
  • +
  • Put Secure supply chain analysis at correct place (#17273)
  • +
  • Partial back-port of: Update a few tests to make them more stable in CI (#16944) (Internal 20648)
  • +
  • Replace . in notices container name (#17292)
  • +
  • Add an approval for releasing build-info json (#16351)
  • +
  • Release build info json when it is preview (#16335)
  • +
  • Add a major-minor build info JSON file (#16301)
  • +
  • Update release instructions with link to new build (#17256)
  • +
  • Add condition to generate release file in local dev build only (#17255)
  • +
  • Removed old not-used-anymore docker-based tests for PS release packages (#16224)
  • +
  • Publish global tool package for stable releases (#15961)
  • +
  • Update to use windows-latest as the build agent image (#16831)
  • +
  • Don't upload dep or tar.gz for RPM build because there are none. (#17224)
  • +
  • Update to vPack task version 12 (#17225)
  • +
  • Make RPM license recognized (#17223)
  • +
  • Ensure psoptions.json and manifest.spdx.json files always exist in packages (#17226)
  • +
+ +
+ +[7.0.11]: https://github.com/PowerShell/PowerShell/compare/v7.0.10...v7.0.11 + +## [7.0.10] - 2022-04-26 + +### Engine Updates and Fixes + +- Fix for partial PowerShell module search paths, that can be resolved to CWD locations +- Do not include node names when sending telemetry. (#16981) to v7.0.10 (Internal 20186,Internal 20261) + +### Tests + +- Re-enable `PowerShellGet` tests targeting PowerShell gallery (#17062) +- Skip failing scriptblock tests (#17093) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 3.1.418

+ +
+ +
    +
  • Fixed package names verification to support multi-digit versions (Internal 20363)
  • +
  • Fix build failure in `generate checksum file for packages` step - v7.0.10 (Internal 20275)
  • +
  • Updated files.wxs for 7.0.10 (Internal 20208)
  • +
  • Updated to .NET 3.1.24 / SDK 3.1.418 (Internal 20133)
  • +
  • Disable broken macOS CI job, which is unused (Internal 20189)
  • +
  • Update Ubuntu images to use Ubuntu 20.04 (#15906)
  • +
  • Update dotnet-install script download link (Internal 19949)
  • +
  • Create checksum file for global tools (Internal 19934)
  • +
  • Make sure global tool packages are published in stable build (Internal 19623)
  • +
+ +
+ +[7.0.10]: https://github.com/PowerShell/PowerShell/compare/v7.0.9...v7.0.10 + +## [7.0.9] - 2022-03-16 + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 3.1.417

+ +
+ +
    +
  • Fix the NuGet SDK package creation (Internal 19569)
  • +
  • Fix NuGet package compliance issues (#13045)
  • +
  • Fix issues in release build (#16332)
  • +
  • Enable ARM64 packaging for macOS (#15768)
  • +
  • Update feed and analyzer dependency (#16327)
  • +
  • Only upload stable buildinfo for stable releases (#16251)
  • +
  • Opt-in to build security monitoring (#16911)
  • +
  • Update experimental feature json files (#16838) (Thanks @!)
  • +
  • Ensure alpine and arm SKUs have the PowerShell configuration file with experimental features enabled (#16823)
  • +
  • Remove WiX install (#16834)
  • +
  • Add Linux package dependencies for packaging (#16807)
  • +
  • Switch to our custom images for build and release (#16801)
  • +
  • Remove all references to cmake for the builds in this repo (#16578)
  • +
  • Register NuGet source when generating CGManifest (#16570)
  • +
  • Update Images used for release (#16580)
  • +
  • Add Software Bill of Materials to the main packages (#16202, #16641, #16711)
  • +
  • Add GitHub Workflow to keep notices up to date (#16284)
  • +
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • +
  • Update macOS build image and root folder for build (#16609)
  • +
  • Add checkout to build json stage to get ci.psm1 (#16399)
  • +
  • Move mapping file into product repo and add Debian 11 (#16316)
  • +
+ +
+ +[7.0.9]: https://github.com/PowerShell/PowerShell/compare/v7.0.8...v7.0.9 + +## [7.0.8] - 2021-10-14 + +### Engine Updates and Fixes + +- Handle error from unauthorized access when removing `AppLocker` test files (#15881) +- Handle error when the telemetry mutex cannot be created (#15574) (Thanks @gukoff!) +- Configure `ApplicationInsights` to not send cloud role name (Internal 17099) +- Disallow `Add-Type` in NoLanguage mode on a locked down machine (Internal 17521) + +### Tools + +- Add `.stylecop` to `filetypexml` and format it (#16025) + +### Build and Packaging Improvements + +
+ + +

Bump .NET SDK to 3.1.414

+
+ +
    +
  • Update the nuget.config file used for building NuGet packages (Internal 17547)
  • +
  • Sign the .NET createdump executable (#16229)
  • +
  • Upgrade set-value package for markdown test (#16196)
  • +
  • Move vPack build to 1ES Pool (#16169)
  • +
  • Update to .NET SDK 3.1.414 (Internal 17532)
  • +
  • Fix the macOS build by updating the pool image name (#16010)
  • +
  • Move from PkgES hosted agents to 1ES hosted agents (#16023)
  • +
  • Use Alpine 3.12 for building PowerShell for Alpine Linux (#16008)
  • +
+ +
+ +### Documentation and Help Content + +- Fix example nuget.config (#14349) + +[7.0.8]: https://github.com/PowerShell/PowerShell/compare/v7.0.7...v7.0.8 + +## [7.0.7] - 2021-08-12 + +### Build and Packaging Improvements + +
+ + +Bump .NET SDK to 3.1.412 + + +
    +
  • Remove cat file from PSDesiredStateConfiguration module (Internal 16722)
  • +
  • Update .NET SDK to 3.1.412 (Internal 16717)
  • +
+ +
+ +[7.0.7]: https://github.com/PowerShell/PowerShell/compare/v7.0.6...v7.0.7 + +## [7.0.6] - 2021-03-11 + +### General Cmdlet Updates and Fixes + +- Fix web cmdlets to properly construct URI from body when using `-NoProxy` (#14673) +- Fix `PromptForCredential()` to add `targetName` as domain (#14504) +- Clean up the IPC named pipe on PowerShell exit (#12187) + +### Tests + +- Update markdown test packages with security fixes (#13730, #14145, #14454) + +### Build and Packaging Improvements + +
+ + +Bump .NET SDK to version 3.1.407 + + +
    +
  • Bump .NET to version 3.1.407 (Internal 14783)
  • +
  • Fix the miscellaneous analysis CI build (#14971, #14974, #14975)
  • +
  • Declare which variable group is used for checking the blob in the release build (#14970)
  • +
  • Use template that disables component governance for CI (#14938)
  • +
  • Suppress the warning for having multiple nuget feeds (#14893)
  • +
  • Disable codesign validation where the file type is not supported (#14885)
  • +
  • Make universal Deb package based on deb package spec (#14681)
  • +
  • Add manual release automation steps and improve changelog script (#14445)
  • +
  • Fix a typo in the Get-ChangeLog function (#14129)
  • +
  • Add validation and dependencies for Ubuntu 20.04 distribution to packaging script (#13993)
  • +
  • Add comment in release-BuildJson.yml for date formatting
  • +
  • Install wget on centos-7 docker image
  • +
  • Fix install-dotnet download (#14856)
  • +
  • Fix release build to upload global tool packages to artifacts (#14620)
  • +
  • Fixes to release pipeline for GA release (#14034)
  • +
  • Add checkout step to release build templates (#13840)
  • +
  • Add flag to make Linux script publish to production repo (#13714)
  • +
  • Use new release script for Linux packages (#13705)
  • +
  • Change stage dependency for docker release stage in release pipeline (#13512)
  • +
  • Create the folder before copying the global tools (#13476)
  • +
  • A few fixes to the release pipeline (#13473)
  • +
  • Change the variable group name (Internal 12339)
  • +
  • Create release pipeline as a yaml pipeline (#13394)
  • +
+ +
+ +[7.0.6]: https://github.com/PowerShell/PowerShell/compare/v7.0.5...v7.0.6 + +## [7.0.5] - 2021-02-11 + +### Build and Packaging Improvements + +
+ + +Bump .NET SDK to version 3.1.406 + + +
    +
  • Fix third party signing for files in sub-folders (#14751)
  • +
  • Bump .NET SDK to 3.1.12 (Internal 14462)
  • +
+ +
+ +[7.0.5]: https://github.com/PowerShell/PowerShell/compare/v7.0.4...v7.0.5 + +## [7.0.4] - 2021-01-19 + +### Build and Packaging Improvements + +
+ + +Bump .NET SDK to version 3.1.405 + + +
    +
  • Remove MyGet feeds from test nuget.config (Internal 14147)
  • +
  • Update WXS file for 7.0.4 (Internal 14122)
  • +
  • Update .NET dependencies for 7.0.4 (Internal 14104)
  • +
  • Fix 7.0.4 `Get-Module` test failure (Internal 13946)
  • +
  • Fix directory creation failure (Internal 13904)
  • +
  • Disable WMF link invocation test (#13479)
  • +
  • Use PowerShell Core for build and test of package in CI build (#13223)
  • +
  • Disable libmi dependent tests for macOS. (#14446)
  • +
  • Use one feed in each nuget.config in official builds (#14363)
  • +
  • Fix path signed RPMs are uploaded from in release build (#14424)
  • +
  • Fix syntax error in Windows packaging script (#14377)
  • +
  • Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353)
  • +
  • Fix issue with unsigned build (#14367)
  • +
  • Move macOS and NuGet to ESRP signing (#14324)
  • +
  • Move Windows package signing to use ESRP (#14060)
  • +
  • Move Linux to ESRP signing (#14210)
  • +
  • Migrate 3rd party signing to ESRP (#14010)
  • +
  • Don't do a shallow checkout (#13992)
  • +
  • Move to ESRP signing for Windows files (#13988)
  • +
  • Fix breaks in packages daily build due to macOS signing changes (#13421)
  • +
  • Sign individual files in package (#13392)
  • +
  • Use Authenticode certificate for MSIX signing (#13330)
  • +
  • Sign the MSIX files for the store (#12582)
  • +
  • Use temporary personal path at runspace startup when $env:HOME not defined (#13239)
  • +
  • Fix MSIX packaging to determine if a preview release by inspecting the semantic version string (#11991)
  • +
  • Add default help content to the assets folder (#13257)
  • +
+ +
+ +[7.0.4]: https://github.com/PowerShell/PowerShell/compare/v7.0.3...v7.0.4 + +## [7.0.3] - 2020-07-16 + +### Tests + +- Remove dependency on DNS for `Test-Connection` tests on macOS (#12943) + +### Build and Packaging Improvements + +
+ +
    +
  • Fix Azure file copy issues in release build by fixing the path to upload directory content (#13182)
  • +
  • Update .NET Core to 3.1.6 (Internal 12005)
  • +
  • Fix Azure file copy break in AzDevOps by updating task version to latest (#13173)
  • +
+ +
+ +[7.0.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.2...v7.0.3 + +## [7.0.2] - 2020-06-11 + +### Engine Updates and Fixes + +- Ensure null-coalescing LHS is evaluated only once (#12667) +- Restrict loading of `amsi.dll` to `system32` folder (#12730) + +### General Cmdlet Updates and Fixes + +- Change `Get-FileHash` to close file handles before writing output (#12474) (Thanks @iSazonov!) + +### Tools + +- Update the PowerShell team list to correct changelog generation (#12927) + +### Tests + +- Pin major Pester version to 4 to prevent breaking changes caused by upcoming release of `v5` (#12262) (Thanks @bergmeister!) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET Core 3.1.5

+ +
+ +
    +
  • Bump to .NET 3.1.5 and update dependencies (Internal 11699)
  • +
  • Check if Azure Blob exists before overwriting (#12921)
  • +
  • Upgrade APIScan version (#12876)
  • +
  • Fix break in package build by pinning ffi version to 1.12 (#12889)
  • +
  • Update the build to sign any unsigned files as 3rd party Dlls (#12581)
  • +
+ +
+ +## [7.0.1] - 2020-05-14 + +### Engine Updates and Fixes + +- Discover assemblies loaded by `Assembly.Load(byte[])` and `Assembly.LoadFile` (#12203) +- Allow case insensitive paths for determining `PSModulePath` (#12192) + +### General Cmdlet Updates and Fixes + +- Add `null` check for Windows PowerShell install path (#12296) +- Fix Null Reference error in CSV commands (#12281) (Thanks @iSazonov!) +- Fix `WinCompat` module loading to treat Core edition modules higher priority (#12269) +- Fix `` detection regex in web cmdlets (#12099) (Thanks @vexx32!) +- Miscellaneous minor updates to `WinCompat` (#11980) +- Fix `ConciseView` where error message is wider than window width and doesn't have whitespace (#11880, #11746) +- Make `Test-Connection` always use the default synchronization context for sending ping requests (#11517) + +### Tests + +- Fix CIM tab complete test failure (#12636) + +### Build and Packaging Improvements + +
+ + +Move to .NET Core 3.1.202 SDK and update packages. + + +
    +
  • Use dotnet core 3.1.202 (Internal 11551)
  • +
  • Bump PowerShellGet from 2.2.3 to 2.2.4 (#12342)
  • +
  • Move to standard internal pool for building (#12119)
  • +
  • Bump NJsonSchema from 10.1.5 to 10.1.7 (#12050)
  • +
+ +
+ +### Documentation and Help Content + +- Remove the version number of PowerShell from `LICENSE` (#12019) + +## [7.0.0] - 2020-03-04 + +### General Cmdlet Updates and Fixes + +- Enable `Ctrl+C` to work for global tool (#11959) +- Fix `ConciseView` to not show the line information within the error messages (#11952) + +### Build and Packaging Improvements + +- Publish PowerShell into the Windows engineering system package format (#11960) +- Bump .NET core framework to `3.1.2` (#11963) +- Ensure the man page `gzip` has the correct name for LTS release (#11956) +- Bump `Microsoft.ApplicationInsights` from `2.13.0` to `2.13.1` (#11925) + +## [7.0.0-rc.3] - 2020-02-21 + +### Breaking Changes + +- Fix `Invoke-Command` missing error on session termination (#11586) + +### Engine Updates and Fixes + +- Update the map between console color to `VT` sequences (#11891) +- Fix SSH remoting error on Windows platform (#11907) +- Restore the `PowerShellStreamType` `enum` with an `ObsoleteAttribute` (#11836) +- Handle cases where `CustomEvent` was not initially sent (#11807) +- Fix how COM objects are enumerated (#11795) +- Fix `NativeDllHandler` to not throw when file is not found (#11787) +- Restore `SetBreakpoints` API (#11622) +- Do not needlessly pass `-l login_name` or `-p port` to `ssh` (#11518) (Thanks @LucaFilipozzi!) +- Fix for `JEA` user role in virtual account (#11668) +- Do not resolve types from assemblies that are loaded in separate `AssemblyLoadContext` (#11088) + +### General Cmdlet Updates and Fixes + +- Sync current directory in `WinCompat` remote session (#11809) +- Add `WinCompat` deny list support using a setting in `powershell.config.json` (#11726) +- Fix unnecessary trimming of line resulting in incorrect index with `ConciseView` (#11670) + +### Code Cleanup + +- Change name of `ClrVersion` parameter back to revert change in capitalization (#11623) + +### Tools + +- Update changelog generation script (#11736) (Thanks @xtqqczze!) +- Update to `CredScan v2` (#11765) + +### Tests + +- Make sure to test whether we skip a test using consistent logic (#11892) +- Skip directory creation at root test on macOS (#11878) +- Update `Get-PlatformInfo` helper and tests for Debian 10, 11 and CentOS 8 (#11842) +- Ensure correct `pwsh` is used for test runs (#11486) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +- Add `LTSRelease` value from `metadata.json` to `release.json` (#11897) +- Bump `Microsoft.ApplicationInsights` from `2.12.1` to `2.13.0` (#11894) +- Make LTS package always not a preview (#11895) +- Bump `System.Data.SqlClient` from `4.8.0` to `4.8.1` (#11879) +- Change `LTSRelease` value in `metadata.json` to true for `RC.3` release (Internal 10960) +- Update `LTS` logic to depend on `metadata.json` (#11877) +- Set default value of `LTSRelease` to false (#11874) +- Refactor packaging pipeline (#11852) +- Make sure `LTS` packages have symbolic links for `pwsh` and `pwsh-lts` (#11843) +- Bump `Microsoft.PowerShell.Native` from `7.0.0-rc.2` to `7.0.0` (#11839) +- Update the NuGet package generation to include `cimcmdlet.dll` and most of the built-in modules (#11832) +- Bump `Microsoft.PowerShell.Archive` from `1.2.4.0` to `1.2.5` (#11833) +- Bump `PSReadLine` from `2.0.0-rc2` to `2.0.0` (#11831) +- Add trace source and serialization primitives to the allowed assembly list (Internal 10911) +- Update the `NextReleaseTag` to be v7.0.0-preview.7 (#11372) +- Change packaging to produce `LTS` packages (#11772) +- Build tar packages only when building on Ubuntu (#11766) +- Bump `NJsonSchema` from `10.1.4` to `10.1.5` (#11730) +- Fix symbolic link creation in `packaging.psm1` (#11723) +- Bump `Microsoft.ApplicationInsights` from `2.12.0` to `2.12.1` (#11708) +- Bump `NJsonSchema` from `10.1.3` to `10.1.4` (#11620) +- Move to latest Azure DevOps agent images (#11704) +- Bump `Markdig.Signed` from `0.18.0` to `0.18.1` (#11641) + +### Documentation and Help Content + +- Add links to diffs on Github in changelog (#11652) (Thanks @xtqqczze!) +- Fix markdown-link test failure (#11653) (Thanks @xtqqczze!) + +## [7.0.0-rc.2] - 2020-01-16 + +### Breaking Changes +- Use `ISOWeek` for week numbers in `Get-Date` accounting for leap years #11536 (Thanks @paalbra!) + +### Engine Updates and Fixes +- Revert the PRs that made `DBNull.Value` and `NullString.Value` treated as `$null` (#11584) +- Support expanding `~` in `$env:PATH` when doing command discovery (#11552) +- Skip null data in output data received handler to fix a `NullReferenceException` (#11448) (Thanks @iSazonov!) +- Add `ssh` parameter sets for the parameter `-JobName` in `Invoke-Command` (#11444) +- Adding `PowerShell Editor Services` and `PSScriptAnalyzer` to tracked modules (#11514) +- Fix condition when key exchange stops responding with `SecureString` for the `OutOfProc` transports (#11380, #11406) +- Add setting to disable the implicit `WinPS` module loading (#11332) + +### General Cmdlet Updates and Fixes +- Fix `NullReferenceException` in `ConciseView` (#11435) (Thanks @iSazonov!) +- Remove the default value of `$true` for the parameter `-RequireLicenseAcceptance` in `New-ModuleManifest` (#11512) (Thanks @ThomasNieto!) +- Make Web Cmdlets skip processing the content headers with a null or empty value for backward compatibility (#11421) (Thanks @spongemike2!) +- Don't format exceptions that are not `ErrorRecord` objects (#11415) +- Mark `InitialSessionState.ImportPSSnapIn` as Obsolete (#11399) +- Use `PositionMessage` for the line context information for `ConciseView` (#11398) +- Add trailing line number to `filename` for `ConciseView` (#11391) +- Update `HelpInfoUri` for all modules in PowerShell 7.0 (#11389) +- Remove unnecessary newline in `ConciseView` (#11383) +- Move `Set-StrictMode` to the outer script block for `ErrorView` (#11381) +- Remove the declaration of `Get-Error` experimental feature from module manifest (#11369) +- Update error message if `Update-Help` fails for the current `UICulture` (#11356) +- `Test-Connection`: Fallback to hop IP Address on `-Traceroute` without `-ResolveDestination` (#11335) (Thanks @vexx32!) +- Add null host name check in `WSMan` (#11288) (Thanks @iSazonov!) +- Add `Type` member to exceptions containing type of exception for `Get-Error` (#11076) +- Write an error if argument is a directory in `Get-FileHash` cmdlet (#11114) (Thanks @iSazonov!) +- Update `Get-Error` to not modify the original `$Error` object (#11125) + +### Code Cleanup +- Use .NET code to check for processor architecture instead of P/Invoke (#11046) (Thanks @iSazonov!) + +### Tests +- Test fixes for various platforms (#11579, #11541) +- Various test fixes for debugger and remoting (#11528) +- `DSC` test fixes for `Alpine` and `Raspbian` (#11508) +- Normalize line endings before comparing string in tests (#11499) +- Fix `ssh` remoting test to work on all platforms (#11500) +- Build test artifacts for `Alpine` (#11483) +- Make null member access tests as string to avoid parsing errors (#11385) +- Fix test failing when `UnixStat` feature is disabled (#11370) +- Update hosting tests to use the SDK version from the build property (#11368) +- Add retry to `Enter-PSHostProcess` test (#11360) + +### Build and Packaging Improvements +- Bump `Microsoft.PowerShell.Native` from `7.0.0-rc.1` to `7.0.0.rc.2` (#11583) +- Update .NET SDK version to 3.1.101 (#11582) +- Bump `PSReadLine` from `2.0.0-rc1` to `2.0.0-rc2` (#11581) +- Bump `NJsonSchema` from `10.0.28` to `10.1.3` (#11382, #11573) +- Generate the correct reference assembly for `Microsoft.PowerShell.ConsoleHost` NuGet package (#11545) +- Update building of `MSIX` for `RC` to use 100 range revision (#11526) +- Fix symbolic links on Debian 10 packages (#11474) +- Bump `Microsoft.PowerShell.Archive` from `1.2.3.0` to `1.2.4.0` (#11502) +- Add script to rebuild `WIX` component references (#11485) +- Bump `PackageManagement` from `1.4.5` to `1.4.6` (#11427) +- Bump `PowerShellGet` from `2.2.2` to `2.2.3` (#11426) +- Bump `ThreadJob` from `2.0.2` to `2.0.3` (#11416) +- Fix symbolic links to `libs` on Debian 10 (#11390) +- Improve Ubuntu detection for Ubuntu derivatives like `GalliumOS` etc (#11155) + +### Documentation and Help Content +- Fix broken link in debugging `README.md` (#11503) + +## [7.0.0-rc.1] - 2019-12-16 + +### Breaking Changes +- Make update notification support `LTS` and default channels (#11132) + +### Engine Updates and Fixes +- Improvements in breakpoint APIs for remote scenarios (#11312) +- Fix PowerShell class definition leaking into another Runspace (#11273) +- Fix a regression in formatting caused by the `FirstOrDefault` primitive added in `7.0.0-Preview1` (#11258) +- Additional Microsoft Modules to track in `PS7` Telemetry (#10751) +- Make approved features non-experimental (#11303) +- Update `ConciseView` to use `TargetObject` if applicable (#11075) +- Fix `NullReferenceException` in `CompletionCompleters` public methods (#11274) +- Fix apartment thread state check on non-Windows platforms (#11301) +- Update setting `PSModulePath` to concatenate the process and machine environment variables (#11276) +- Bump `.NET Core` to `3.1.0` (#11260) +- Fix detection of `$PSHOME` in front of `$env:PATH` (#11141) + +### General Cmdlet Updates and Fixes +- Fix for issue on Raspbian for setting date of file changes in `UnixStat` Experimental Feature (#11313) +- Add `-AsPlainText` to `ConvertFrom-SecureString` (#11142) +- Added `WindowsPS` version check for `WinCompat` (#11148) +- Fix error-reporting in some `WinCompat` scenarios (#11259) +- Add native binary resolver (#11032) (Thanks @iSazonov!) +- Update calculation of char width to respect `CJK` chars correctly (#11262) +- Add `Unblock-File` for macOS (#11137) +- Fix regression in `Get-PSCallStack` (#11210) (Thanks @iSazonov!) +- Avoid automatically loading the `ScheduledJob` module when using Job cmdlets (#11194) +- Add `OutputType` to `Get-Error` cmdlet and preserve original `TypeNames` (#10856) +- Fix null reference in `SupportsVirtualTerminal` property (#11105) + +### Code Cleanup +- Change comment and element text to meet Microsoft standards (#11304) + +### Tests +- Make unreliable `DSC` test pending (#11131) + +### Build and Packaging Improvements +- Fix Nuget package signing for Coordinated Package build (#11316) +- Update dependencies from PowerShell Gallery and NuGet (#11323) +- Bump `Microsoft.ApplicationInsights` from `2.11.0` to `2.12.0` (#11305) +- Bump `Microsoft.CodeAnalysis.CSharp` from `3.3.1` to `3.4.0` (#11265) +- Updates packages for Debian 10 and 11 (#11236) +- Only enable experimental features prior to `RC` (#11162) +- Update macOS minimum version (#11163) +- Bump `NJsonSchema` from `10.0.27` to `10.0.28` (#11170) + +### Documentation and Help Content +- Refactor change logs into one log per release (#11165) +- Fix `FWLinks` for PowerShell 7 online help documents (#11071) + +## [7.0.0-preview.6] - 2019-11-21 + +### Breaking Changes + +- Update `Test-Connection` to work more like the one in Windows PowerShell (#10697) (Thanks @vexx32!) +- Preserve `$?` for `ParenExpression`, `SubExpression` and `ArrayExpression` (#11040) +- Set working directory to current directory in `Start-Job` (#10920) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Allow `pwsh` to inherit `$env:PSModulePath` and enable `powershell.exe` to start correctly (#11057) + +### Experimental Features + +- Provide Unix stat information in filesystem output (#11042) +- Support null-conditional operators `?.` and `?[]` in PowerShell language (#10960) +- Support using non-compatible Windows PowerShell modules in PowerShell Core (#10973) + +### Performance + +- Avoid using closure in `Parser.SaveError` (#11006) +- Improve the caching when creating new `Regex` instances (#10657) (Thanks @iSazonov!) +- Improve processing of the PowerShell built-in type data from `types.ps1xml`, `typesV3.ps1xml` and `GetEvent.types.ps1xml` (#10898) +- Update `PSConfiguration.ReadValueFromFile` to make it faster and more memory efficient (#10839) + +### General Cmdlet Updates and Fixes + +- Add limit check in `Get-WinEvent` (#10648) (Thanks @iSazonov!) +- Fix command runtime so `StopUpstreamCommandsException` doesn't get populated in `-ErrorVariable` (#10840) +- Set the output encoding to `[Console]::OutputEncoding` for native commands (#10824) +- Support multi-line code blocks in examples (#10776) (Thanks @Greg-Smulko!) +- Add Culture parameter to `Select-String` cmdlet (#10943) (Thanks @iSazonov!) +- Fix `Start-Job` working directory path with trailing backslash (#11041) +- `ConvertFrom-Json`: Unwrap collections by default (#10861) (Thanks @danstur!) +- Use case-sensitive Hashtable for `Group-Object` cmdlet with `-CaseSensitive` and `-AsHashtable` switches (#11030) (Thanks @vexx32!) +- Handle exception if enumerating files fails when rebuilding path to have correct casing (#11014) +- Fix `ConciseView` to show `Activity` instead of `myCommand` (#11007) +- Allow web cmdlets to ignore HTTP error statuses (#10466) (Thanks @vdamewood!) +- Fix piping of more than one `CommandInfo` to `Get-Command` (#10929) +- Add back `Get-Counter` cmdlet for Windows (#10933) +- Make `ConvertTo-Json` treat `[AutomationNull]::Value` and `[NullString]::Value` as `$null` (#10957) +- Remove brackets from `ipv6` address for SSH remoting (#10968) +- Fix crash if command sent to pwsh is just whitespace (#10977) +- Added cross-platform `Get-Clipboard` and `Set-Clipboard` (#10340) +- Fix setting original path of filesystem object to not have extra trailing slash (#10959) +- Support `$null` for `ConvertTo-Json` (#10947) +- Add back `Out-Printer` command on Windows (#10906) +- Fix `Start-Job -WorkingDirectory` with whitespace (#10951) +- Return default value when getting `null` for a setting in `PSConfiguration.cs` (#10963) (Thanks @iSazonov!) +- Handle IO exception as non-terminating (#10950) +- Add `GraphicalHost` assembly to enable `Out-GridView`, `Show-Command`, and `Get-Help -ShowWindow` (#10899) +- Take `ComputerName` via pipeline in `Get-HotFix` (#10852) (Thanks @kvprasoon!) +- Fix tab completion for parameters so that it shows common parameters as available (#10850) +- Fix `GetCorrectCasedPath()` to first check if any system file entries is returned before calling `First()` (#10930) +- Set working directory to current directory in `Start-Job` (#10920) (Thanks @iSazonov!) +- Change `TabExpansion2` to not require `-CursorColumn` and treat as `$InputScript.Length` (#10849) +- Handle case where Host may not return Rows or Columns of screen (#10938) +- Fix use of accent colors for hosts that don't support them (#10937) +- Add back `Update-List` command (#10922) +- Update `FWLink` Id for `Clear-RecycleBin` (#10925) +- During tab completion, skip file if can't read file attributes (#10910) +- Add back `Clear-RecycleBin` for Windows (#10909) +- Add `$env:__SuppressAnsiEscapeSequences` to control whether to have VT escape sequence in output (#10814) + +### Code Cleanup + +- Cleanup style issues in `Compiler.cs` (#10368) (Thanks @iSazonov!) +- Remove the unused type converter for `CommaDelimitedStringCollection` (#11000) (Thanks @iSazonov!) +- Cleanup style in `InitialSessionState.cs` (#10865) (Thanks @iSazonov!) +- Code clean up for `PSSession` class (#11001) +- Remove the not-working 'run `Update-Help` from `Get-Help` when `Get-Help` runs for the first time' feature (#10974) +- Fix style issues (#10998) (Thanks @iSazonov!) +- Cleanup: use the built-in type alias (#10882) (Thanks @iSazonov!) +- Remove the unused setting key `ConsolePrompting` and avoid unnecessary string creation when querying `ExecutionPolicy` setting (#10985) +- Disable update notification check for daily builds (#10903) (Thanks @bergmeister!) +- Reinstate debugging API lost in #10338 (#10808) + +### Tools + +- Add default setting for the `SDKToUse` property so that it builds in VS (#11085) +- `Install-Powershell.ps1`: Add parameter to use MSI installation (#10921) (Thanks @MJECloud!) +- Add basic examples for `install-powershell.ps1` (#10914) (Thanks @kilasuit!) + +### Tests + +- Fix `stringdata` test to correctly validate keys of hashtables (#10810) +- Unload test modules (#11061) (Thanks @iSazonov!) +- Increase time between retries of testing URL (#11015) +- Update tests to accurately describe test actions. (#10928) (Thanks @romero126!) + +### Build and Packaging Improvements + +- Updating links in `README.md` and `metadata.json` for Preview.5 (#10854) +- Select the files for compliance tests which are owned by PowerShell (#10837) +- Allow `win7x86` `msix` package to build. (Internal 10515) +- Allow semantic versions to be passed to `NormalizeVersion` function (#11087) +- Bump .NET core framework to `3.1-preview.3` (#11079) +- Bump `PSReadLine` from `2.0.0-beta5` to `2.0.0-beta6` in /src/Modules (#11078) +- Bump `Newtonsoft.Json` from `12.0.2` to `12.0.3` (#11037) (#11038) +- Add Debian 10, 11 and CentOS 8 packages (#11028) +- Upload `Build-Info` Json file with the `ReleaseDate` field (#10986) +- Bump .NET core framework to `3.1-preview.2` (#10993) +- Enable build of x86 MSIX package (#10934) +- Update the dotnet SDK install script URL in `build.psm1` (#10927) +- Bump `Markdig.Signed` from `0.17.1` to `0.18.0` (#10887) +- Bump `ThreadJob` from `2.0.1` to `2.0.2` (#10886) +- Update `AppX` Manifest and Packaging module to conform to MS Store requirements (#10878) + +### Documentation and Help Content + +- Update `CONTRIBUTING.md` (#11096) (Thanks @mklement0!) +- Fix installation doc links in `README.md` (#11083) +- Adds examples to `install-powershell.ps1` script (#11024) (Thanks @kilasuit!) +- Fix to `Select-String` emphasis and `Import-DscResource` in CHANGELOG.md (#10890) +- Remove the stale link from `powershell-beginners-guide.md` (#10926) + +## [7.0.0-preview.5] - 2019-10-23 + +### Breaking Changes + +- Make `$PSCulture` consistently reflect in-session culture changes (#10138) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Move to `.NET Core 3.1 preview 1` (#10798) +- Refactor reparse tag checks in file system provider (#10431) (Thanks @iSazonov!) +- Replace `CR` and new line with a `0x23CE` character in script logging (#10616) +- Fix a resource leak by unregistering the event handler from `AppDomain.CurrentDomain.ProcessExit` (#10626) + +### Experimental Features + +- Implement `Get-Error` cmdlet as Experimental Feature (#10727,#10800) +- Add `ConciseView` for `$ErrorView` and update it to remove unnecessary text and not color entire line in red (#10641,#10724) +- Support the pipeline chain operators `&&` and `||` in PowerShell language (#9849,#10825,#10836) +- Implement null coalescing (`??`) and null coalescing assignment (`??=`) operators (#10636) +- Support notification on `pwsh` startup when a new release is available and update notification message (#10689,#10777) + +### General Cmdlet Updates and Fixes + +- Add emphasis to `Select-String` output (with `-NoEmphasis` parameter to opt-out) (#8963) (Thanks @derek-xia!) +- Add back `Get-HotFix` cmdlet (#10740) +- Make `Add-Type` usable in applications that host `PowerShell` (#10587) +- Use more effective evaluation order in `LanguagePrimitives.IsNullLike()` (#10781) (Thanks @vexx32!) +- Improve handling of mixed-collection piped input and piped streams of input in `Format-Hex` (#8674) (Thanks @vexx32!) +- Use type conversion in `SSHConnection` hashtables when value doesn't match expected type (#10720) (Thanks @SeeminglyScience!) +- Fix `Get-Content -ReadCount 0` behavior when `-TotalCount` is set (#10749) (Thanks @eugenesmlv!) +- Reword access denied error message in `Get-WinEvent` (#10639) (Thanks @iSazonov!) +- Enable tab completion for variable assignment that is enum or type constrained (#10646) +- Remove unused `SourceLength` remoting property causing formatting issues (#10765) +- Add `-Delimiter` parameter to `ConvertFrom-StringData` (#10665) (Thanks @steviecoaster!) +- Add positional parameter for `ScriptBlock` when using `Invoke-Command` with `SSH` (#10721) (Thanks @machgo!) +- Show line context information if multiple lines but no script name for `ConciseView` (#10746) +- Add support for `\\wsl$\` paths to file system provider (#10674) +- Add the missing token text for `TokenKind.QuestionMark` in parser (#10706) +- Set current working directory of each `ForEach-Object -Parallel` running script to the same location as the calling script. (#10672) +- Replace `api-ms-win-core-file-l1-2-2.dll` with `Kernell32.dll` for `FindFirstStreamW` and `FindNextStreamW` APIs (#10680) (Thanks @iSazonov!) +- Tweak help formatting script to be more `StrictMode` tolerant (#10563) +- Add `-SecurityDescriptorSDDL` parameter to `New-Service` (#10483) (Thanks @kvprasoon!) +- Remove informational output, consolidate ping usage in `Test-Connection` (#10478) (Thanks @vexx32!) +- Read special reparse points without accessing them (#10662) (Thanks @iSazonov!) +- Direct `Clear-Host` output to terminal (#10681) (Thanks @iSazonov!) +- Add back newline for grouping with `Format-Table` and `-Property` (#10653) +- Remove [ValidateNotNullOrEmpty] from `-InputObject` on `Get-Random` to allow empty string (#10644) +- Make suggestion system string distance algorithm case-insensitive (#10549) (Thanks @iSazonov!) +- Fix null reference exception in `ForEach-Object -Parallel` input processing (#10577) + +### Code Cleanup + +- Remove `WorkflowJobSourceAdapter` reference that is no longer used (#10326) (Thanks @KirkMunro!) +- Cleanup `COM` interfaces in jump list code by fixing `PreserveSig` attributes (#9899) (Thanks @weltkante!) +- Add a comment describing why `-ia` is not the alias for `-InformationAction` common parameter (#10703) (Thanks @KirkMunro!) +- Rename `InvokeCommandCmdlet.cs` to `InvokeExpressionCommand.cs` (#10659) (Thanks @kilasuit!) +- Add minor code cleanups related to update notifications (#10698) +- Remove deprecated workflow logic from the remoting setup scripts (#10320) (Thanks @KirkMunro!) +- Update help format to use proper case (#10678) (Thanks @tnieto88!) +- Clean up `CodeFactor` style issues coming in commits for the last month (#10591) (Thanks @iSazonov!) +- Fix typo in description of `PSTernaryOperator` experimental feature (#10586) (Thanks @bergmeister!) + +### Performance + +- Add minor performance improvements for runspace initialization (#10569) (Thanks @iSazonov!) + +### Tools + +- Make `Install-PowerShellRemoting.ps1` handle empty string in `PowerShellHome` parameter (#10526) (Thanks @Orca88!) +- Switch from `/etc/lsb-release` to `/etc/os-release` in `install-powershell.sh` (#10773) (Thanks @Himura2la!) +- Check `pwsh.exe` and `pwsh` in daily version on Windows (#10738) (Thanks @centreboard!) +- Remove unneeded tap in `installpsh-osx.sh` (#10752) + +### Tests + +- Temporary skip the flaky test `TestAppDomainProcessExitEvenHandlerNotLeaking` (#10827) +- Make the event handler leaking test stable (#10790) +- Sync capitalization in `CI` `YAML` (#10767) (Thanks @RDIL!) +- Add test for the event handler leaking fix (#10768) +- Add `Get-ChildItem` test (#10507) (Thanks @iSazonov!) +- Replace ambiguous language for tests from `switch` to `parameter` for accuracy (#10666) (Thanks @romero126!) + +### Build and Packaging Improvements + +- Update package reference for `PowerShell SDK` to `preview.5` (Internal 10295) +- Update `ThirdPartyNotices.txt` (#10834) +- Bump `Microsoft.PowerShell.Native` to `7.0.0-preview.3` (#10826) +- Bump `Microsoft.ApplicationInsights` from `2.10.0` to `2.11.0` (#10608) +- Bump `NJsonSchema` from `10.0.24` to `10.0.27` (#10756) +- Add `MacPorts` support to the build system (#10736) (Thanks @Lucius-Q-User!) +- Bump `PackageManagement` from `1.4.4` to `1.4.5` (#10728) +- Bump `NJsonSchema` from `10.0.23` to `10.0.24` (#10635) +- Add environment variable to differentiate client/server telemetry in `MSI` (#10612) +- Bump `PSDesiredStateConfiguration` from `2.0.3` to `2.0.4` (#10603) +- Bump `Microsoft.CodeAnalysis.CSharp` from `3.2.1` to `3.3.1` (#10607) +- Update to `.Net Core 3.0 RTM` (#10604) (Thanks @bergmeister!) +- Update `MSIX` packaging so the version to `Windows Store` requirements (#10588) + +### Documentation and Help Content + +- Merge stable and servicing change logs (#10527) +- Update used `.NET` version in build docs (#10775) (Thanks @Greg-Smulko!) +- Replace links from `MSDN` to `docs.microsoft.com` in `powershell-beginners-guide.md` (#10778) (Thanks @iSazonov!) +- Fix broken `DSC` overview link (#10702) +- Update `Support_Question.md` to link to `Stack Overflow` as another community resource (#10638) (Thanks @mklement0!) +- Add processor architecture to distribution request template (#10661) +- Add new PowerShell MoL book to learning PowerShell docs (#10602) + +## [7.0.0-preview.4] - 2019-09-19 + +### Engine Updates and Fixes + +- Add support to `ActionPreference.Break` to break into debugger when `Debug`, `Error`, `Information`, `Progress`, `Verbose` or `Warning` messages are generated (#8205) (Thanks @KirkMunro!) +- Enable starting control panel add-ins within PowerShell Core without specifying `.CPL` extension. (#9828) + +### Performance + +- Make `ForEach-Object` faster for its commonly used scenarios (#10454) and fix `ForEach-Object -Parallel` performance problem with many runspaces (#10455) + +### Experimental Features + +- Update `PSDesiredStateConfiguration` module version to `2.0.3` and bring new tests; enable compilation to MOF on non-Windows and use of Invoke-DSCResource without LCM (#10516) +- Add APIs for breakpoint management in runspaces and enable attach to process without `BreakAll` for PowerShell Editor Services (#10338) (Thanks @KirkMunro!) +- Support [ternary operator](https://github.com/PowerShell/PowerShell-RFC/pull/218) in PowerShell language (#10367) + +### General Cmdlet Updates and Fixes + +- Add PowerShell Core group policy definitions (#10468) +- Update console host to support `XTPUSHSGR`/`XTPOPSGR` VT control sequences that are used in [composability scenarios](https://github.com/microsoft/terminal/issues/1796). (#10208) +- Add `WorkingDirectory` parameter to `Start-Job` (#10324) (Thanks @davinci26!) +- Remove the event handler that was causing breakpoint changes to be erroneously replicated to the host runspace debugger (#10503) (Thanks @KirkMunro!) +- Replace `api-ms-win-core-job-12-1-0.dll` with `Kernell32.dll` in `Microsoft.PowerShell.Commands.NativeMethods` P/Invoke API(#10417) (Thanks @iSazonov!) +- Fix wrong output for `New-Service` in variable assignment and `-OutVariable` (#10444) (Thanks @kvprasoon!) +- Fix global tool issues around exit code, command line parameters and path with spaces (#10461) +- Fix recursion into OneDrive - change `FindFirstFileEx()` to use `SafeFindHandle` type (#10405) +- Skip auto-loading `PSReadLine` on Windows if the [NVDA screen reader](https://www.nvaccess.org/about-nvda/) is active (#10385) +- Increase built-with-PowerShell module versions to `7.0.0.0` (#10356) +- Add throwing an error in `Add-Type` if a type with the same name already exists (#9609) (Thanks @iSazonov!) + +### Code Cleanup + +- Convert `ActionPreference.Suspend` enumeration value into a non-supported, reserved state, and remove restriction on using `ActionPreference.Ignore` in preference variables (#10317) (Thanks @KirkMunro!) +- Replace `ArrayList` with `List` to get more readable and reliable code without changing functionality (#10333) (Thanks @iSazonov!) +- Make code style fixes to `TestConnectionCommand` (#10439) (Thanks @vexx32!) +- Cleanup `AutomationEngine` and remove extra `SetSessionStateDrive` method call (#10416) (Thanks @iSazonov!) +- Rename default `ParameterSetName` back to `Delimiter` for `ConvertTo-Csv` and `ConvertFrom-Csv` (#10425) + +### Tools + +- Update `install-powershell.ps1` to check for already installed daily build (#10489) + +### Tests + +- Add experimental check to `ForEach-Object -Parallel` tests (#10354) (Thanks @KirkMunro!) +- Update tests for Alpine validation (#10428) + +### Build and Packaging Improvements + +- Bump `PowerShellGet` version from `2.2` to `2.2.1` (#10382) +- Bump `PackageManagement` version from `1.4.3` to `1.4.4` (#10383) +- Update `README.md` and `metadata.json` for `7.0.0-preview.4` (Internal 10011) +- Upgrade `.Net Core 3.0` version from `Preview 9` to `RC1` (#10552) (Thanks @bergmeister!) +- Fix `ExperimentalFeature` list generation (Internal 9996) +- Bump `PSReadLine` version from `2.0.0-beta4` to `2.0.0-beta5` (#10536) +- Fix release build script to set release tag +- Update version of `Microsoft.PowerShell.Native` to `7.0.0-preview.2` (#10519) +- Upgrade to `Netcoreapp3.0 preview9` (#10484) (Thanks @bergmeister!) +- Make sure the daily coordinated build, knows it is a daily build (#10464) +- Update the combined package build to release the daily builds (#10449) +- Remove appveyor reference (#10445) (Thanks @RDIL!) +- Bump `NJsonSchema` version from `10.0.22` to `10.0.23` (#10421) +- Remove the deletion of `linux-x64` build folder because some dependencies for Alpine need it (#10407) + +### Documentation and Help Content + +- Update `README.md` and metadata for `v6.1.6` and `v6.2.3` releases (#10523) +- Fix a typo in `README.md` (#10465) (Thanks @vedhasp!) +- Add a reference to `PSKoans` module to Learning Resources documentation (#10369) (Thanks @vexx32!) +- Update `README.md` and `metadata.json` for `7.0.0-preview.3` (#10393) + +## [7.0.0-preview.3] - 2019-08-20 + +### Breaking Changes + +- Remove `kill` alias for `Stop-Process` cmdlet on Unix (#10098) (Thanks @iSazonov!) +- Support for starting PowerShell as a login shell (`pwsh -Login` / `pwsh -l`) support (#10050) + +### Engine Updates and Fixes + +- Additional Telemetry - implementation of [`RFC0036`](https://github.com/PowerShell/PowerShell-RFC/pull/158) (#10336) +- Implement `ForEach-Object -Parallel` as an experimental feature (#10229) +- Skip `JumpList` on `NanoServer` and `IoT` (#10164) +- Make `Get-DscResource` work with class based resources (#10350) +- Fix `#requires -version` for `pwsh` 7 to include `6.1` and `6.2` in `PSCompatibleVersions` (#9943) (Thanks @bgelens!) +- Add dispose of `_runspaceDebugCompleteEvent` event object. (#10323) +- Fix performance regression from disabling debugger in system lockdown mode (#10269) +- Special case the `posix` locale in `WildcardPattern` (#10186) +- Use `Platform.IsWindowsDesktop` instead of checking both NanoServer and IoT (#10205) + +### General Cmdlet Updates and Fixes + +- Enable Experimental Features by default on Preview builds (#10228) +- Enable `-sta` and `-mta` switches for `pwsh` (`-sta` is required for `GUIs`) (#10061) +- Make breakpoints display better over PowerShell remoting (#10339) (Thanks @KirkMunro!) +- Add support for `AppX` reparse points (#10331) +- Make module name matching for `get-module -FullyQualifiedName` case insensitive (#10329) +- Expose `PreRelease` label in `PSModuleInfo` formatter (#10316) +- Add `-Raw` switch to `Select-String` which allows returning only the string that was matched (#9901) (Thanks @Jawz84!) + +- ### Performance + +- Reduce allocations in `MakePath()` method (#10027) (Thanks @iSazonov!) +- Remove extra check that the system dll exists (#10244) (Thanks @iSazonov!) +- Avoid boxing when passing value type arguments to `PSTraceSource.WriteLine` (#10052) (Thanks @iSazonov!) +- Reduce allocations in `Escape()` and `Unescape()` (#10041) (Thanks @iSazonov!) + +### Code Cleanup + +- Add the license header to `nanoserver.tests.ps1` (#10171) +- Mark `-parallel` and `-throttlelimit` reserved for `foreach` and `switch` statements (#10328) (Thanks @KirkMunro!) +- Deprecate workflow debugging code (#10321) (Thanks @KirkMunro!) +- Fix style issues in `InternalCommands.cs` (#10352) (Thanks @iSazonov!) +- Deprecate internal `HelpCategory.Workflow` enumeration (#10319) (Thanks @KirkMunro!) +- Update `Microsoft.PowerShell.CoreCLR.Eventing` to resolve conflict with `System.Diagnostics.EventLog` (#10305) +- Don't collect process start time as it's not being used on `consolehost` startup (#10294) +- .NET Core 3.0 now aborts the thread for us. Remove the `ThreadAbortException` code (#10230) (Thanks @iSazonov!) +- Use `nameof()` in `LocationGlobber` and `PathInfo` (#10200) (Thanks @iSazonov!) + +### Tools + +- Fix Hungarian prefix `my` (#9976) (Thanks @RDIL!) +- Fix spelling error in issue template (#10256) +- Quote arguments in `.vscode/tasks.json` in case of spaces (#10204) (Thanks @msftrncs!) + +### Tests + +- Remove `markdownlint` tests due to security issues (#10163) +- Add tests for `WildcardPattern.Escape()` and `Unescape()` (#10090) (Thanks @iSazonov!) +- Cleanup Docker release testing (#10310) (Thanks @RDIL!) + +### Build and Packaging Improvements + +- Update `Microsoft.Management.Infrastructure` version to `2.0.0-preview.2` (#10366) +- Move to `.NET Core 3.0 preview.8` (#10351) (#10227) (Thanks @bergmeister!) +- Bump `NJsonSchema` from `10.0.21` to `10.0.22` (#10364) +- Add `Microsoft.PowerShell.CoreCLR.Eventing.dll` to exception list for build fix (#10337) +- Bump `Microsoft.CodeAnalysis.CSharp` from `3.1.0` to `3.2.1` (#10273) (#10330) +- Revert the temporary AzDevOps artifact workaround (#10260) +- Fix macOS build break (#10207) + +### Documentation and Help Content + +- Update docs for `7.0.0-preview.2` release (#10160) (#10176) +- `PSSA` also includes formatting (#10172) +- Refactor security policy documentation so that they appear in the Security policy tab of GitHub (#9905) (Thanks @bergmeister!) +- Add tooling section to PR template (#10144) +- Update `README.md` and `metadata.json` for next releases (#10087) +- Update DotNet Support links (#10145) +- Update our language on our policy applying to security issues (#10304) +- Update dead links from `powershell.com` (#10297) +- Create `Distribution_Request` issue template (#10253) +- Fix: Removed dependency file with `Dependabot` (#10212) (Thanks @RDIL!) + +## [7.0.0-preview.2] - 2019-07-17 + +### Breaking Changes + +- Cleanup workflow - remove `PSProxyJob` (#10083) (Thanks @iSazonov!) +- Disable `Enter-PSHostProcess` cmdlet when system in lock down mode (Internal 9168) + +### Engine Updates and Fixes + +- Consider `DBNull.Value` and `NullString.Value` the same as `$null` when comparing with `$null` and casting to bool (#9794) (Thanks @vexx32!) +- Allow methods to be named after keywords (#9812) (Thanks @vexx32!) +- Create `JumpList` in `STA` thread as some `COM` `APIs` are strictly `STA` only to avoid sporadic `CLR` crashes (#9928) (#10057) (Thanks @bergmeister!) +- Skip `JumpList` on `NanoServer` and `IoT` (#10164) +- Display `COM` method signature with argument names (#9858) (Thanks @nbkalex!) +- Use the original precision (prior-dotnet-core-3) for double/float-to-string conversion (#9893) +- `Import-DscResource` can now clobber built-in DSC resource names (#9879) +- Add ability to pass `InitialSessionState` to the `ConsoleShell.Start` (#9802) (Thanks @asrosent!) +- Have console host not enter command prompt mode when using `Read-Host -Prompt` (#9743) +- Fix use of `Start-Process http://bing.com` (#9793) +- Support negative numbers in `-split` operator (#8960) (Thanks @ece-jacob-scott!) + +### General Cmdlet Updates and Fixes + +- Support DSC compilation on Linux. (#9834) +- Add alias for Service `StartType` (#9940) (Thanks @NeoBeum!) +- Add `-SecurityDescriptorSddl` parameter to `Set-Service` (#8626) (Thanks @kvprasoon!) +- Fix auto-download of files when enumerating files from a `OneDrive` folder (#9895) +- Set request headers when request body is empty in Web Cmdlets (#10034) (Thanks @markekraus!) +- Fix wrong comparison in `CertificateProvider` (#9987) (Thanks @iSazonov!) +- Sync docs changes into the embedded help for `pwsh` (#9952) +- Display Duration when displaying `HistoryInfo` (#9751) (Thanks @rkeithhill!) +- Update console startup and help `url` for PowerShell docs (#9775) +- Make `UseAbbreviationExpansion` and `TempDrive` official features (#9872) +- Fix `Get-ChildItem -Path` with wildcard `char` (#9257) (Thanks @kwkam!) + +### Performance + +- Add another fast path to `WildcardPattern.IsMatch` for patterns that only have an asterisk in the end (#10054) (Thanks @iSazonov!) +- Move some of the creations of `WildcardPattern` in outer loop to avoid unnecessary allocation (#10053) (Thanks @iSazonov!) +- Make `Foreach-Object` 2 times faster by reducing unnecessary allocations and boxing (#10047) +- Use a static cache for `PSVersionInfo.PSVersion` to avoid casting `SemanticVersion` to `Version` every time accessing that property (#10028) +- Reduce allocations in `NavigationCmdletProvider.NormalizePath()` (#10038) (Thanks @iSazonov!) +- Add fast path for wildcard patterns that contains no wildcard characters (#10020) +- Avoid `Assembly.GetName()` in `ClrFacade.GetAssemblies(string)` to reduce allocations of `CultureInfo` objects (#10024) (Thanks @iSazonov!) +- Avoid the `int[]` and `int[,]` allocation when tokenizing line comments and matching wildcard pattern (#10009) + +### Tools + +- Update change log generation tool to deal with private commits (#10096) +- Update `Start-PSBuild -Clean` logic of `git clean` to ignore locked files from `VS2019` (#10071) (Thanks @bergmeister!) +- Indent fix in `markdown-link.tests.ps1` (#10049) (Thanks @RDIL!) +- `Start-PSBuild -Clean` does not remove all untracked files (#10022) (Thanks @vexx32!) +- Add module to support Pester tests for automating debugger commands (`stepInto`, `stepOut`, etc.), along with basic tests (#9825) (Thanks @KirkMunro!) +- Remove `markdownlint` tests due to security issues (#10163) + +### Code Cleanup + +- Cleanup `CompiledScriptBlock.cs` (#9735) (Thanks @vexx32!) +- Cleanup workflow code (#9638) (Thanks @iSazonov!) +- Use `AddOrUpdate()` instead of `Remove` then `Add` to register runspace (#10007) (Thanks @iSazonov!) +- Suppress `PossibleIncorrectUsageOfAssignmentOperator` rule violation by adding extra parenthesis (#9460) (Thanks @xtqqczze!) +- Use `AddRange` in `GetModules()` (#9975) (Thanks @iSazonov!) +- Code cleanup: use `IndexOf(char)` overload (#9722) (Thanks @iSazonov!) +- Move `consts` and methods to single `CharExtensions` class (#9992) (Thanks @iSazonov!) +- Cleanup: Use `EndsWith(char)` and `StartsWith(char)` (#9994) (Thanks @iSazonov!) +- Remove `LCIDToLocaleName` `P/Invoke` from `GetComputerInfoCommand` (#9716) (Thanks @iSazonov!) +- Cleanup Parser tests (#9792) (Thanks @vexx32!) +- Remove `EtwActivity` empty constructor and make minor style fixes (#9958) (Thanks @RDIL!) +- Fix style issues from last commits (#9937) (Thanks @iSazonov!) +- Remove dead code about `IsTransparentProxy` (#9966) +- Fix minor typos in code comments (#9917) (Thanks @RDIL!) +- Style fixes for `CimAsyncOperations` (#9945) (Thanks @RDIL!) +- Fix minor `CodeFactor` style issues in `ModuleCmdletBase` (#9915) (Thanks @RDIL!) +- Clean up the use of `SetProfileRoot` and `StartProfile` in ConsoleHost (#9931) +- Fix minor style issues come from last commits (#9640) (Thanks @iSazonov!) +- Improve whitespace for Parser tests (#9806) (Thanks @vexx32!) +- Use new `string.ConCat()` in `Process.cs` (#9720) (Thanks @iSazonov!) +- Code Cleanup: Tidy up `scriptblock.cs` (#9732) (Thanks @vexx32!) + +### Tests + +- Mark `Set-Service` tests with password as `Pending` (#10146) +- Fix test password generation rule to meet Windows complexity requirements (#10143) +- Add test for `New-Item -Force` (#9971) (Thanks @robdy!) +- Fix gulp versions (#9916) (Thanks @RDIL!) +- Indentation fixes in `ci.psm1` (#9947) (Thanks @RDIL!) +- Remove some `Travis-CI` references (#9919) (Thanks @RDIL!) +- Improve release testing Docker images (#9942) (Thanks @RDIL!) +- Use `yarn` to install global tools (#9904) (Thanks @RDIL!) +- Attempt to work around the zip download issue in Azure DevOps Windows CI (#9911) +- Update PowerShell SDK version for hosting tests (Internal 9185) + +### Build and Packaging Improvements + +- Update the target framework for reference assemblies to `netcoreapp3.0` (#9747) +- Pin version of `netDumbster` to `2.0.0.4` (#9748) +- Fix daily `CodeCoverageAndTest` build by explicitly calling `Start-PSBootStrap` (#9724) +- Split the `fxdependent` package on Windows into two packages (#10134) +- Bump `System.Data.SqlClient` (#10109) +- Bump `System.Security.AccessControl` (#10100) +- Add performance tag to change log command (Internal) +- Upgrade .Net Core 3 SDK from `preview5` to `preview6` and related out of band `Nuget` packages from `2.1` to `3.0-preview6` (#9888) (Thanks @bergmeister!) +- Add to `/etc/shells` on macOS (#10066) +- Bump `Markdig.Signed` from `0.17.0` to `0.17.1` (#10062) +- Update copyright symbol for `NuGet` packages (#9936) +- Download latest version `(6.2.0)` of `PSDesiredStateConfiguration` `nuget` package. (#9932) +- Add automated `RPM` signing to release build (#10013) +- Bump `ThreadJob` from `1.1.2` to `2.0.1` in `/src/Modules` (#10003) +- Bump `PowerShellGet` from `2.1.4` to `2.2` in /src/Modules (#9933) (#10085) +- Bump `PackageManagement` from `1.4` to `1.4.3` in `/src/Modules` (#9820) (#9918) (#10084) +- Update to use `TSAv2` (#9914) +- Bump `NJsonSchema` from `9.14.1` to `10.0.21` (#9805) (#9843) (#9854) (#9862) (#9875) (#9885) (#9954) (#10017) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.3` to `4.5.4` (#9786) +- Bump `Microsoft.ApplicationInsights` from `2.9.1` to `2.10.0` (#9757) +- Increase timeout of NuGet job to workaround build timeout (#9772) + +### Documentation and Help Content + +- Change log `6.1.4` (#9759) +- Change log for release `6.2.1` (#9760) +- Add quick steps for adding docs to cmdlets (#9978) +- Update readme `gitter` badge (#9920) (Thanks @RDIL!) +- Update `README` and `metadata.json` for `7.0.0-preview.1` release (#9767) + +## [7.0.0-preview.1] - 2019-05-30 + +### Breaking Changes + +- Disable the debugger when in system lock-down mode (#9645) +- Fix `Get-Module -FullyQualifiedName` option to work with paths (#9101) (Thanks @pougetat!) +- Fix `-NoEnumerate` behavior in `Write-Output` (#9069) (Thanks @vexx32!) +- Make command searcher treat wildcard as literal if target exists for execution (#9202) + +### Engine Updates and Fixes + +- Port PowerShell to .NET Core 3.0 (#9597) +- Make sure we always return an object in command searcher (#9623) +- Support line continuance with pipe at the start of a line (#8938) (Thanks @KirkMunro!) +- Add support for `ValidateRangeKind` to `ParameterMetadata.GetProxyAttributeData` (#9059) (Thanks @indented-automation!) +- Allow passing just a dash as an argument to a file via pwsh (#9479) +- Fix tab completion for functions (#9383) +- Reduce string allocation in console output code (#6882) (Thanks @iSazonov!) +- Fixing test run crash by not passing script block to the callback (#9298) +- Add Binary Parsing Support & Refactor `TryGetNumberValue` & `ScanNumberHelper` (#7993) (Thanks @vexx32!) +- Add PowerShell remoting enable/disable cmdlet warning messages (#9203) +- Add `xsd` for `cdxml` (#9177) +- Improve formatting performance by having better primitives on `PSObject` (#8785) (Thanks @powercode!) +- Improve type inference of array literals and foreach statement variables (#8100) (Thanks @SeeminglyScience!) +- Fix for `FormatTable` remote deserialization regression (#9116) +- Get `MethodInfo` from .NET public type with explicit parameter types (#9029) (Thanks @iSazonov!) +- Add retry logic to the operation that updates `powershell.config.json` (#8779) (Thanks @iSazonov!) +- Update the task-based `async` APIs added to PowerShell to return a Task object directly (#9079) +- Add 5 `InvokeAsync` overloads and `StopAsync` to the `PowerShell` type (#8056) (Thanks @KirkMunro!) +- Remove unused cached types (#9015) + +### General Cmdlet Updates and Fixes + +- Fix use of unicode ellipsis in `XML` for truncating error messages (#9589) +- Improve error message in FileSystemProvider when removing a folder containing hidden or read only files (#9551) (Thanks @iSazonov!) +- Enable recursion into `OneDrive` by not treating placeholders as symlinks (#9509) +- Change `MatchType` for `EnumerationOptions` to be `Win32` making this consistent with Windows PowerShell (#9529) +- Add Support for null Usernames in Web Cmdlet Basic Auth (#9536) (Thanks @markekraus!) +- Fix null reference when `Microsoft.PowerShell.Utility` is loaded as a `snapin` in hosting scenarios (#9404) +- Update width of `DateTime` to accommodate change in Japan `DateTime` format with new era starting 5/1/19 (#9503) +- Fix `Get-Runspace` runspace object format Type column (#9438) +- Return correct casing of filesystem path during normalization (#9250) +- Move warning message to `EndProcessing` so it only shows up once (#9385) +- Fix the platform check in `CimDSCParser.cs` (#9338) +- New `New-PSBreakpoint` cmdlet & new `-Breakpoint` parameter for `Debug-Runspace` (#8923) +- Fix help paging issues on macOS/Linux and with custom pager that takes arguments (#9033) (Thanks @rkeithhill!) +- Add `QuoteFields` parameter to `ConvertTo-Csv` and `Export-Csv` (#9132) (Thanks @iSazonov!) +- Fix progress for Get-ComputerInfo (#9236) (Thanks @powercode!) +- Add `ItemSeparator` and `AltItemSeparator` properties in `ProviderInfo` (#8587) (Thanks @renehernandez!) +- Add timestamp to `pshost` trace listener (#9230) +- Implement `Get-Random -Count` without specifying an `InputObject` list (#9111) (Thanks @pougetat!) +- Enable `SecureString` cmdlets for non-Windows (#9199) +- Add Obsolete message to `Send-MailMessage` (#9178) +- Fix `Restart-Computer` to work on `localhost` when WinRM is not present (#9160) +- Make `Start-Job` throw terminating exception when `-RunAs32` is specified in 64-bit pwsh (#9143) +- Make `Start-Job` throw terminating error when PowerShell is being hosted (#9128) +- Made `-Subject` parameter of `Send-MailMessage` command no longer mandatory. (#8961) (Thanks @ece-jacob-scott!) +- Make `New-ModuleManifest` consistent with `Update-ModuleManifest` (#9104) (Thanks @pougetat!) +- Add support for empty `NoteProperty` in `Group-Object` (#9109) (Thanks @iSazonov!) +- Remove `Hardlink` from `Mode` property in default file system format (#8789) (Thanks @powercode!) +- Fixing issue with help progress with `Get-Help` not calling `Completed` (#8788) (Thanks @powercode!) +- Allow `Test-ModuleManifest` to work when `RootModule` has no file extension (#8687) (Thanks @pougetat!) +- Add `UseQuotes` parameter to `Export-Csv` and `ConvertTo-Csv` cmdlets (#8951) (Thanks @iSazonov!) +- Update version for `PowerShell.Native` and hosting tests (#8983) +- Refactor shuffle in `Get-Random` to save a full iteration of the objects. (#8969) (Thanks @st0le!) +- Suggest `-Id pid` for `Get-Process pid` (#8959) (Thanks @MohiTheFish!) + +### Code Cleanup + +- `Attributes.cs` - Style / Formatting Fixes (#9625) (Thanks @vexx32!) +- Remove Workflow from `PSSessionType` (#9618) (Thanks @iSazonov!) +- Update use of "PowerShell Core" to just "PowerShell" (#9513) +- Use `IPGlobalProperties` on all platforms for getting host name (#9530) (Thanks @iSazonov!) +- Remove `IsSymLink()` P/Invoke on Unix (#9534) (Thanks @iSazonov!) +- Cleanup unused P/Invokes on Unix (#9531) (Thanks @iSazonov!) +- Update use of `Windows PowerShell` to just `PowerShell` (#9508) +- Cleanup: sort `usings` (#9490) (Thanks @iSazonov!) +- Cleanup `Export-Command` from `AssemblyInfo` (#9455) (Thanks @iSazonov!) +- Run CodeFormatter for `System.Management.Automation` (#9402) (Thanks @iSazonov!) +- Run CodeFormatter with `BraceNewLine`,`UsingLocation`,`FormatDocument`,`NewLineAbove` rules (#9393) (Thanks @iSazonov!) +- Run CodeFormatter for `WSMan.Management` (#9400) (Thanks @iSazonov!) +- Run CodeFormatter for `WSMan.Runtime` (#9401) (Thanks @iSazonov!) +- Run CodeFormatter for `Security` module (#9399) (Thanks @iSazonov!) +- Run CodeFormatter for `MarkdownRender` (#9398) (Thanks @iSazonov!) +- Run CodeFormatter for `Eventing` (#9394) (Thanks @iSazonov!) +- Use `Environment.NewLine` for new lines in `ConsoleHost` code (#9392) (Thanks @iSazonov!) +- Run CodeFormatter for Diagnostics module (#9378) (Thanks @iSazonov!) +- Run CodeFormatter for `Microsoft.PowerShell.Commands.Management` (#9377) (Thanks @iSazonov!) +- Run CodeFormatter for Utility module (#9376) (Thanks @iSazonov!) +- Style: Match file name casings of C# source files for Utility commands (#9329) (Thanks @ThreeFive-O!) +- Update repo for Ubuntu 14.04 EOL (#9324) +- Cleanup: sort `usings` (#9283) (Thanks @iSazonov!) +- Fix StyleCop Hungarian Notation (#9281) (Thanks @iSazonov!) +- Style: Update StyleCop rules (#8500) +- Enhance the P/Invoke code for `LookupAccountSid` in `Process.cs` (#9197) (Thanks @iSazonov!) +- Fix coding style for `NewModuleManifestCommand` (#9134) (Thanks @pougetat!) +- Remove unused method `CredUIPromptForCredential` from `HostUtilities.cs` (#9220) (Thanks @iSazonov!) +- Remove non-existent paths from `.csproj` files (#9214) (Thanks @ThreeFive-O!) +- Typo in new parameter set (#9205) +- Minor `FileSystemProvider` cleanup (#9182) (Thanks @RDIL!) +- Cleanup style issues in `CoreAdapter` and `MshObject` (#9190) (Thanks @iSazonov!) +- Minor cleanups in `Process.cs` (#9195) (Thanks @iSazonov!) +- Refactor `ReadConsole` P/Invoke in `ConsoleHost` (#9165) (Thanks @iSazonov!) +- Clean up `Get-Random` cmdlet (#9133) (Thanks @pougetat!) +- Fix to not pass `StringBuilder` by reference (`out` or `ref`) in P/Invoke (#9066) (Thanks @iSazonov!) +- Update AppVeyor comments in `Implicit.Remoting.Tests.ps1` (#9020) (Thanks @RDIL!) +- Remove AppImage from tools (#9100) (Thanks @Geweldig!) +- Using supported syntax for restoring warnings - Visual Studio 2019 complains about enable. (#9107) (Thanks @powercode!) +- Use `Type.EmptyTypes` and `Array.Empty()` to replace our custom code of the same functionality (#9042) (Thanks @iSazonov!) +- Rename private methods in `MshCommandRuntime.cs` (#9074) (Thanks @vexx32!) +- Cleanup & update `ErrorRecord` class code style (#9021) (Thanks @vexx32!) +- Remove unused cached types from `CachedReflectionInfo` (#9019) (Thanks @iSazonov!) +- Fix CodeFactor brace style issues in `FileSystemProvider` (#8992) (Thanks @RDIL!) +- Use `List.AddRange` to optimize `-Split` (#9001) (Thanks @iSazonov!) +- Remove Arch Linux Dockerfile (#8990) (Thanks @RDIL!) +- Cleanup `dllimport` (#8847) (Thanks @iSazonov!) + +### Tools + +- Convert custom attribute `ValidatePathNotInSettings` to function (#9406) +- Create `DependaBot` `config.yml` (#9368) +- Add more users to failures detection and fix alias for static analysis (#9292) +- Make `install-powershell.ps1` work on Windows Server 2012 R2 (#9271) +- Enable `PoshChan` for getting and automatic retrieval of test failures for a PR (#9232) +- Fix capitalization cases for `PoshChan` (#9188) (Thanks @RDIL!) +- Update to new format for `PoshChan` settings and allow all users access to reminders (#9198) +- Fix settings to use dashes instead of underscore (#9167) +- Fix `AzDevOps` context names and add all PowerShell team members (#9164) +- Add settings for `PoshChan` (#9162) +- Adding `CmdletsToExport` and `AliasesToExport` to test module manifests. (#9108) (Thanks @powercode!) +- Delete Docker manifest creation script (#9076) (Thanks @RDIL!) +- Make install scripts more consistent over different operating systems (#9071) (Thanks @Geweldig!) +- Comment cleanup in `releaseTools.psm1` (#9064) (Thanks @RDIL!) +- Fix duplicate recommendation of Azure DevOps extension for Visual Studio Code (#9032) (Thanks @ThreeFive-O!) +- Code coverage artifacts (#8993) + +### Tests + +- Update version tests to use `NextReleaseVersion` from `metadata.json` (#9646) +- Convert Windows CI to stages (#9607) +- Multiple test fixes and improved logging for fragile tests (#9569) +- Add unit and feature tests for `Send-MailMessage` (#9213) (Thanks @ThreeFive-O!) +- Update to Pester `4.8.0` (#9510) +- Ensure `Wait-UntilTrue` returns `$true` in Pester tests (#9458) (Thanks @xtqqczze!) +- Adding tests for `Remove-Module` (#9276) (Thanks @pougetat!) +- Allow CI to run on branches with this name pattern: `feature*` (#9415) +- Mark tests in macOS CI which use `AppleScript` as pending/inconclusive (#9352) +- Reduce time for stack overflow test (#9302) +- Added more tests for `Import-Alias` by file regarding parsing difficult aliases strings (#9247) (Thanks @SytzeAndr!) +- Move from `npm` to `Yarn` for markdown tests (#9312) (Thanks @RDIL!) +- Only search for functions in Constrained Language help tests (#9301) +- Fix skipping of tests in `RemoteSession.Basic.Tests.ps1` (#9304) +- Make sure non-Windows CI fails when a test fails (#9303) +- Update tests to account for when `$PSHOME` is read only (#9279) +- Add tests for command globbing (#9180) +- Fix tab completion test to handle multiple matches (#8891) +- Refactor macOS CI so that tests run in parallel (#9056) +- Fix `Enter-PSHostProcess` tests flakiness (#9007) +- Add source for `Install-Package` to install `netDumbster` (#9081) +- Style fixes for `Select-Xml` tests (#9037) (Thanks @ThreeFive-O!) +- Enable cross-platform `Send-MailMessage` tests for CI (#8859) (Thanks @ThreeFive-O!) +- Added `RequireSudoOnUnix` tags to `PowerShellGet` tests and remove pending parameter (#8954) (Thanks @RDIL!) +- Style fixes for `ConvertTo-Xml` tests (#9036) (Thanks @ThreeFive-O!) +- Align name schemes for test files (#9034) (Thanks @ThreeFive-O!) +- Pending `NamedPipeConnectionInfo` test (#9003) (Thanks @iSazonov!) +- Add test for `-WhatIf` for `New-FileCatalog` (#8966) (Thanks @mjanko5!) + +### Build and Packaging Improvements + +- Fix the PowerShell version number in MSI packages (Internal 8547) +- Add cleanup before building test package (Internal 8529) +- Update version for SDK tests and `Microsoft.PowerShell.Native` package (Internal 8512) +- Update the target framework for reference assemblies to `netcoreapp3.0` (Internal 8510) +- Fix syncing modules from PowerShell gallery by normalizing version numbers (Internal 8504) +- Add `tsaVersion` property as `TsaV1` for compliance build phase (#9176) +- Add ability to cross compile (#9374) +- Add `AcessToken` variable to jobs that perform signing (#9351) +- Add CI for `install-powershell.sh` and Amazon Linux (#9314) +- Add component detection to all jobs (#8964) +- Add Preview assets for `MSIX` (#9375) +- Add secret scanning to CI (#9249) +- Build test packages for `windows`, `linux-x64`, `linux-arm`, `linux-arm64` and `macOS` (#9476) +- Bump `gulp` from `4.0.0` to `4.0.2` (#9441, #9544) +- Bump `Markdig.Signed` from `0.15.7` to `0.17.0` (#8981, #9579) +- Bump `Microsoft.CodeAnalysis.CSharp` from `2.10.0` to `3.1.0` (#9277, 9653) +- Bump `Microsoft.PowerShell.Native` from `6.2.0-rc.1` to `6.2.0` (#9200) +- Bump `Microsoft.Windows.Compatibility` from `2.0.1` to `2.1.1` (#9605) +- Bump `Newtonsoft.Json` from `12.0.1` to `12.0.2` (#9431, #9434) +- Bump `NJsonSchema` from `9.13.19` to `9.14.1` (#9044, #9136, #9166, #9172, #9184, #9196, #9265, #9349, #9388, #9421, #9429, #9478, #9523, #9616) +- Bump `PackageManagement` from `1.3.1` to `1.4` (#9567, #9650) +- Bump `PowerShellGet` from `2.0.4` to `2.1.4` in /src/Modules (#9110, #9145, #9600, #9691) +- Bump `PSReadLine` from `2.0.0-beta3` to `2.0.0-beta4` (#9554) +- Bump `SelfSignedCertificate` (#9055) +- Bump `System.Data.SqlClient` from `4.6.0` to `4.6.1` (#9601) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.2` to `4.5.3` (#9333) +- Bump `Microsoft.PowerShell.Archive` from `1.2.2.0` to `1.2.3.0` (#9593) +- Check to be sure that the test result file has actual results before uploading (#9253) +- Clean up static analysis config (#9113) (Thanks @RDIL!) +- Create `codecoverage` and test packages for non-Windows (#9373) +- Create test package for macOS on release builds (#9344) +- Disable Homebrew analytics in macOS Azure DevOps builds (#9130) (Thanks @RDIL!) +- Enable building of `MSIX` package (#9289) +- Enable building on Kali Linux (#9471) +- Fix artifact Download issue in release build (#9095) +- Fix build order in `windows-daily` build (#9275) +- Fix dependencies of NuGet build to wait on `DEB` uploads to finish (#9118) +- Fix `MSI` Upgrade failure for preview builds (#9013) +- Fix publishing daily `nupkg` to MyGet (#9269) +- Fix the failed test and update `Publish-TestResults` to make Azure DevOps fail the task when any tests failed (#9457) +- Fix variable name in `windows-daily.yml` (#9274) +- Fixed Dockerfile syntax highlighting (#8991) (Thanks @RDIL!) +- Make `CodeCoverage` configuration build portable symbol files (#9346) +- Make Linux CI parallel (#9209) +- Move artifacts to artifact staging directory before uploading (#9273) +- Performance improvements for release build (#9179) +- Preserve user shortcuts pinned to TaskBar during MSI upgrade (#9305) (Thanks @bergmeister!) +- Publish global tool packages to `pwshtool` blob and bug fixes (#9163) +- Publish test package on release builds (#9063) +- Publish windows daily build to MyGet (#9288) +- Remove appveyor references from packaging tools (#9117) (Thanks @RDIL!) +- Remove code from `CI.psm1` to optionally run Feature tests (#9212) (Thanks @RDIL!) +- Remove duplicate `PoliCheck` task and pin to specific version (#9297) +- Run `Start-PSBootStrap` in Code Coverage build to install .NET SDK (#9690) +- Switch from `BMP` to `PNG` for graphical `MSI` installer assets (#9606) +- Translate Skipped the test results into something Azure DevOps does NOT understand (#9124) +- Update Markdown test dependencies (#9075) (Thanks @RDIL!) +- Update UML to represent SDK and Global tool builds (#8997) +- Use IL assemblies for NuGet packages to reduce size (#9171) + +### Documentation and Help Content + +- Add checkbox to PR checklist for experimental feature use (#9619) (Thanks @KirkMunro!) +- Updating committee membership (#9577) (Thanks @HemantMahawar!) +- Update `CODEOWNERS` file to reduce noise (#9547) +- add download link to `raspbian64` to readme (#9520) +- Update `Support_Question.md` (#9218) (Thanks @vexx32!) +- Fix version of `PowerShellGet` in changelog (#9335) +- Update release process template to clarify that most tasks are coordinated by the release pipeline (#9238) +- Fix several problems in `WritingPesterTests` guideline (#9078) (Thanks @ThreeFive-O!) +- Update `ChangeLog` for `6.2.0` (#9245) +- Update docs for `v6.2.0` (#9229) +- Update `feature-request` issue template to move instructions into comments. (#9187) (Thanks @mklement0!) +- Update link to Contributing guide to new `PowerShell-Doc` repo (#9090) (Thanks @iSazonov!) +- Correct punctuation in `README.md` (#9045) (Thanks @yashrajbharti!) +- Update Docker `README.md` (#9010) (Thanks @RDIL!) +- Update release process issue template (#9051) (Thanks @RDIL!) +- Documentation Cleanup (#8851) (Thanks @RDIL!) +- Update docs for `6.2.0-rc.1` release (#9022) +- Update release template (#8996) + +[7.0.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.2...v7.0.3 +[7.0.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.1...v7.0.2 +[7.0.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0...v7.0.1 +[7.0.0]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.3...v7.0.0 +[7.0.0-rc.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.2...v7.0.0-rc.3 +[7.0.0-rc.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.1...v7.0.0-rc.2 +[7.0.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.6...v7.0.0-rc.1 +[7.0.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.5...v7.0.0-preview.6 +[7.0.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.4...v7.0.0-preview.5 +[7.0.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.3...v7.0.0-preview.4 +[7.0.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.2...v7.0.0-preview.3 +[7.0.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.1...v7.0.0-preview.2 +[7.0.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-rc.1...v7.0.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/7.1.md b/PowerShell-master/CHANGELOG/7.1.md new file mode 100644 index 0000000000000000000000000000000000000000..eba1998e29ccac0d9dc0ef16c483517392415e20 --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.1.md @@ -0,0 +1,1158 @@ +# 7.1 Changelog + +## [7.1.7] - 2022-04-26 + +### Engine Updates and Fixes + +- Fix for partial PowerShell module search paths, that can be resolved to CWD locations +- Do not include node names when sending telemetry. (#16981) to v7.1.7 (Internal 20187,Internal 20260) + +### Tests + +- Re-enable `PowerShellGet` tests targeting PowerShell gallery (#17062) +- Skip failing scriptblock tests (#17093) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 5.0.407

+ +
+ +
    +
  • Fix build failure in `generate checksum file for packages` step - v7.1.7 (Internal 20274)
  • +
  • Updated files.wxs for 7.1.7 (Internal 20210)
  • +
  • Updated to .NET 5.0.16 / SDK 5.0.407 (Internal 20131)
  • +
  • Update Ubuntu images to use Ubuntu 20.04 (#15906)
  • +
  • Update dotnet-install script download link (Internal 19950)
  • +
  • Create checksum file for global tools (#17056) (Internal 19928)
  • +
  • Make sure global tool packages are published in stable build (Internal 19624)
  • +
+ +
+ +[7.1.7]: https://github.com/PowerShell/PowerShell/compare/v7.1.6...v7.1.7 + +## [7.1.6] - 2022-03-16 + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 5.0.406

+ +
+ +
    +
  • Update the mapping file (#16316, Internal 19528)
  • +
  • Remove code that handles dotnet5 feed (Internal 19525)
  • +
  • Fix issues in release build (#16332)
  • +
  • Enable ARM64 packaging for macOS (#15768)
  • +
  • Update feed and analyzer dependency (#16327)
  • +
  • Only upload stable buildinfo for stable releases (#16251)
  • +
  • Opt-in to build security monitoring (#16911)
  • +
  • Update experimental feature json files (#16838)
  • +
  • Ensure alpine and arm SKUs have the PowerShell configuration file with experimental features enabled (#16823)
  • +
  • Remove WiX install (#16834)
  • +
  • Add Linux package dependencies for packaging (#16807)
  • +
  • Switch to our custom images for build and release (#16801)
  • +
  • Remove all references to cmake for the builds in this repo (#16578)
  • +
  • Register NuGet source when generating CGManifest (#16570)
  • +
  • Update images used for release (#16580)
  • +
  • Add GitHub Workflow to keep notices up to date (#16284)
  • +
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • +
  • Add Software Bill of Materials to the main packages (#16202, #16641, #16711)
  • +
  • Update macOS build image and root folder for build (#16609)
  • +
  • Add diagnostics used to take corrective action when releasing buildInfo JSON file (#16404)
  • +
  • Add checkout to build json stage to get ci.psm1 (#16399)
  • +
+ +
+ +[7.1.6]: https://github.com/PowerShell/PowerShell/compare/v7.1.5...v7.1.6 + +## [7.1.5] - 2021-10-14 + +### Engine Updates and Fixes + +- Handle error from unauthorized access when removing `AppLocker` test files (#15881) +- Test more thoroughly whether a command is `Out-Default` for transcription scenarios (#15653) +- Handle error when the telemetry mutex cannot be created (#15574) (Thanks @gukoff!) +- Configure `ApplicationInsights` to not send cloud role name (Internal 17100) +- Disallow `Add-Type` in NoLanguage mode on a locked down machine (Internal 17522) + +### Tools + +- Add `.stylecop` to `filetypexml` and format it (#16025) + +### Build and Packaging Improvements + +
+ + +

Bump .NET SDK to 5.0.402

+
+ +
    +
  • Upgrade set-value package for markdown test (#16196)
  • +
  • Sign the .NET createdump executable (#16229)
  • +
  • Move vPack build to 1ES Pool (#16169)
  • +
  • Update to .NET SDK 5.0.402 (Internal 17537)
  • +
  • Move from PkgES hosted agents to 1ES hosted agents (#16023)
  • +
  • Fix the macOS build by updating the pool image name (#16010)
  • +
  • Use Alpine 3.12 for building PowerShell for Alpine Linux (#16008)
  • +
+ +
+ +### Documentation and Help Content + +- Fix example nuget.config (#14349) + +[7.1.5]: https://github.com/PowerShell/PowerShell/compare/v7.1.4...v7.1.5 + +## [7.1.4] - 2021-08-12 + +### Build and Packaging Improvements + +
+ + +Bump .NET SDK to version 5.0.400 + + +
    +
  • Remove the cat file from PSDesiredStateConfiguration module (Internal 16723)
  • +
  • Update .NET SDK version and other packages (Internal 16715)
  • +
+ +
+ +[7.1.4]: https://github.com/PowerShell/PowerShell/compare/v7.1.3...v7.1.4 + +## [7.1.3] - 2021-03-11 + +### Engine Updates and Fixes + +- Remove the 32K character limit on the environment block for `Start-Process` (#14111) +- Fix webcmdlets to properly construct URI from body when using `-NoProxy` (#14673) + +### General Cmdlet Updates and Fixes + +- Fix `PromptForCredential()` to add `targetName` as domain (#14504) + +### Build and Packaging Improvements + +
+ + + +Bump .NET SDK to 5.0.4 + + + +
    +
  • Bump .NET SDK to 5.0.4 (Internal 14775)
  • +
  • Disable running markdown link verification in release build CI (#14971, #14974, #14975)
  • +
  • Use template that disables component governance for CI (#14938)
  • +
  • Declare which variable group is used for checking the blob in the release build (#14970)
  • +
  • Add suppress for nuget multi-feed warning (#14893)
  • +
  • Disable code signing validation where the file type is not supported (#14885)
  • +
  • Install wget on CentOS 7 docker image (#14857)
  • +
  • Fix install-dotnet download (#14856)
  • +
  • Make universal Deb package based on deb package spec (#14681)
  • +
  • Fix release build to upload global tool packages to artifacts (#14620)
  • +
  • Update ini component version in test package.json (#14454)
  • +
  • Add manual release automation steps and improve changelog script (#14445)
  • +
  • Update markdown test packages with security fixes (#14145)
  • +
  • Fix a typo in the Get-ChangeLog function (#14129)
  • +
  • Disable global tool copy to unblock release
  • +
+ +
+ +[7.1.3]: https://github.com/PowerShell/PowerShell/compare/v7.1.2...v7.1.3 + +## [7.1.2] - 2021-02-11 + +### Build and Packaging Improvements + +
+ + +Bump .NET SDK to version 5.0.103 + + +
    +
  • Fix third party signing for files in sub-folders (#14751)
  • +
  • Bump .NET SDK to version 5.0.103 (Internal 14459)
  • +
  • Publish the global tool package for stable release
  • +
+ +
+ +[7.1.2]: https://github.com/PowerShell/PowerShell/compare/v7.1.1...v7.1.2 + +## [7.1.1] - 2021-01-14 + +### General Cmdlet Updates and Fixes + +- Avoid an exception if file system does not support reparse points (#13634) (Thanks @iSazonov!) +- Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353) + +### Code Cleanup + +- Fix syntax error in Windows packaging script (#14377) + +### Build and Packaging Improvements + +
+ +
    +
  • Use one feed in each nuget.config in official builds (#14363)
  • +
  • Fix path signed RPMs are uploaded from in release build (#14424)
  • +
  • Fix issue with unsigned build (#14367)
  • +
  • Move macOS and NuGet packages to ESRP signing (#14324)
  • +
  • Move Windows packages signing to use ESRP (#14060)
  • +
  • Move Linux packages to ESRP signing (#14210)
  • +
  • Migrate 3rd party signing to ESRP (#14010)
  • +
  • Don't do a shallow checkout (#13992)
  • +
  • Move to ESRP signing for Windows files (#13988)
  • +
  • Add checkout step to release build templates (#13840)
  • +
+ +
+ +[7.1.1]: https://github.com/PowerShell/PowerShell/compare/v7.1.0...v7.1.1 + +## [7.1.0] - 2020-11-11 + +### Engine Updates and Fixes + +- Fix a logic bug in `MapSecurityZone` (#13921) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Update `pwsh -?` output to match docs (#13748) + +### Tests + +- `markdownlint` security updates (#13730) + +### Build and Packaging Improvements + +
+ +
    +
  • Fixes to release pipeline for GA release (Internal 13410)
  • +
  • Add validation and dependencies for Ubuntu 20.04 distribution to packaging script (#13993)
  • +
  • Change PkgES Lab to unblock build (Internal 13376)
  • +
  • Add .NET install workaround for RTM (#13991)
  • +
  • Bump Microsoft.PowerShell.Native version from 7.1.0-rc.2 to 7.1.0 (#13976)
  • +
  • Bump PSReadLine version to 2.1.0 (#13975)
  • +
  • Bump .NET to version 5.0.100-rtm.20526.5 (#13920)
  • +
  • Update script to use .NET RTM feeds (#13927)
  • +
+ +
+ +[7.1.0]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-rc.2...v7.1.0 + +## [7.1.0-rc.2] - 2020-10-20 + +### Engine Updates and Fixes + +- Rename `Get-Subsystem` to `Get-PSSubsystem` and fix two related minor issues (#13765) +- Add missing `PSToken` token table entries to fix the `PSParser` API (#13779) +- Add additional PowerShell modules to the tracked modules list (#12183) +- Fix blocking wait when starting file associated with a Windows application (#13750) +- Revert `PSNativePSPathResolution` to being an experimental feature (#13734) + +### General Cmdlet Updates and Fixes + +- Emit warning if `ConvertTo-Json` exceeds `-Depth` value (#13692) + +### Build and Packaging Improvements + +- Change Linux package script call to publish to the production repository in release builds (#13714) +- Update `PSReadLine` version to `2.1.0-rc1` (#13777) +- Move PowerShell build to dotnet `5.0-RC.2` (#13780) +- Bump `Microsoft.PowerShell.Native` to `7.1.0-rc.2` (#13794) + +[7.1.0-rc.2]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-rc.1...v7.1.0-rc.2 + +## [7.1.0-rc.1] - 2020-09-29 + +### Engine Updates and Fixes + +- Make fixes to `ComInterop` code as suggested by .NET team (#13533) + +### General Cmdlet Updates and Fixes + +- Fix case where exception message contains just ``"`n"`` on Windows (#13684) +- Recognize `CONOUT$` and `CONIN$` as reserved device names (#13508) (Thanks @davidreis97!) +- Fix `ConciseView` for interactive advanced function when writing error (#13623) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @soccypowa

+ +
+ +
    +
  • Simplify logical negation (#13555) (Thanks @xtqqczze!)
  • +
  • Fixed the indentation of the help content for -nologo (#13557) (Thanks @soccypowa!)
  • +
+ +
+ +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@heaths

+ +
+ +
    +
  • Bump NJsonSchema from 10.1.24 to 10.1.26 (#13586)
  • +
  • Bump PowerShellGet from 2.2.4 to 2.2.5 (#13683)
  • +
  • Bump Microsoft.ApplicationInsights from 2.14.0 to 2.15.0 (#13639)
  • +
  • Update PowerShell to build against dotnet 5.0-RC.1 (#13643)
  • +
  • Write the InstallLocation to fixed registry key (#13576) (Thanks @heaths!)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README` and `metadata.json` for `7.1.0-preview.7` release (#13565) + +[7.1.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.7...v7.1.0-rc.1 + +## [7.1.0-preview.7] - 2020-09-08 + +### Breaking Changes + +- Fix `$?` to not be `$false` when native command writes to `stderr` (#13395) + +### Engine Updates and Fixes + +- Initial work of the subsystem plugin model (for minimal powershell) (#13186) +- Optimize `GetSystemLockdownPolicy` for non-lockdown scenarios (#13438) + +### General Cmdlet Updates and Fixes + +- Revert "Add the parameter `-Paged` to `Get-Help` to support paging (#13374)" (#13519) +- Add support for `TLS` 1.3 in Web cmdlets (#13409) (Thanks @iSazonov!) +- Add null check for `args` in `CommandLineParser` (#13451) (Thanks @iSazonov!) +- Process reparse points for Microsoft Store applications (#13481) (Thanks @iSazonov!) +- Move `PSNullConditionalOperators` feature out of experimental (#13529) +- Move `PSNativePSPathResolution` feature out of Experimental (#13522) +- Use field if property does not exist for `ObRoot` when using PowerShell Direct to container (#13375) (Thanks @hemisphera!) +- Suppress `UTF-7` obsolete warnings (#13484) +- Avoid multiple enumerations of an `IEnumerable` instance in `Compiler.cs` (#13491) +- Change `Add-Type -OutputType` to not support `ConsoleApplication` and `WindowsApplication` (#13440) +- Create warnings when `UTF-7` is specified as an encoding (#13430) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @tamasvajk

+ +
+ +
    +
  • Add single blank line after copyright header (#13486) (Thanks @xtqqczze!)
  • +
  • Use read-only auto-implemented properties (#13507) (Thanks @xtqqczze!)
  • +
  • Use boolean instead of bitwise operators on bool values (#13506) (Thanks @xtqqczze!)
  • +
  • Fix erroneous assert (#13495) (Thanks @tamasvajk!)
  • +
  • Cleanup: remove duplicate words in comments (#13539) (Thanks @xtqqczze!)
  • +
  • Reformat StringUtil (#13509) (Thanks @xtqqczze!)
  • +
  • Use uint instead of long for PDH constants (#13502) (Thanks @xtqqczze!)
  • +
  • Cleanup: Remove redundant empty lines (#13404) (Thanks @xtqqczze!)
  • +
  • Add StringUtil.Format overload to avoid unnecessary allocations (#13408) (Thanks @xtqqczze!)
  • +
  • Fix test hooks for CommandLineParameterParser (#13459)
  • +
  • Remove redundant delegate creation (#13441) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- vscode: Add `editorconfig` to recommended extensions (#13537) (Thanks @xtqqczze!) +- Remove the out-dated `ZapDisable` related code from `build.psm1` (#13350) (Thanks @jackerr3!) + +### Tests + +- Disable `WMF` download link validation test (#13479) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@yecril71pl

+ +
+ +
    +
  • Add Microsoft.NET.Test.Sdk dependency (Internal 12589)
  • +
  • Update .NET NuGet package version to 5.0.0-preview.8.20407.11 (Internal 12555)
  • +
  • Update to .NET 5 preview 8 (#13530)
  • +
  • Change stage dependency for docker release stage in release pipeline (#13512)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.7.0 to 16.7.1 (#13492)
  • +
  • Create the folder before copying the global tools (#13476)
  • +
  • A few fixes to the release pipeline (#13473)
  • +
  • Bump Markdig.Signed from 0.20.0 to 0.21.1 (#13463)
  • +
  • Add a pre-check for git to build.psm1 (#13227) (Thanks @yecril71pl!)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README` links and `metadata.json` for `7.1.0-preview.6` (#13437) + +[7.1.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.6...v7.1.0-preview.7 + +## [7.1.0-preview.6] - 2020-08-17 + +### Breaking Changes + +- Rename `-FromUnixTime` to `-UnixTimeSeconds` on `Get-Date` to allow Unix time input (#13084) (Thanks @aetos382!) +- Make `$ErrorActionPreference` not affect `stderr` output of native commands (#13361) +- Allow explicitly specified named parameter to supersede the same one from hashtable splatting (#13162) + +### Engine Updates and Fixes + +- Refactor command line parser to do early parsing (#11482) (Thanks @iSazonov!) +- Add support for some .NET intrinsic type converters (#12580) (Thanks @iSazonov!) +- Refresh and enable the `ComInterop` code in PowerShell (#13304) + +### Experimental Features + +- Add `-Runspace` parameter to all `*-PSBreakpoint` cmdlets (#10492) (Thanks @KirkMunro!) + +### General Cmdlet Updates and Fixes + +- Fix error message from new symbolic link missing target (#13085) (Thanks @yecril71pl!) +- Make the parameter `args` non-nullable in the public `ConsoleHost` APIs (#13429) +- Add missing dispose for `CancellationTokenSource` (#13420) (Thanks @Youssef1313!) +- Add the parameter `-Paged` to `Get-Help` to support paging (#13374) +- Fix `Get-Help` not properly displaying if parameter supports wildcards (#13353) (Thanks @ThomasNieto!) +- Update `pwsh` help for `-InputFormat` parameter (#13355) (Thanks @sethvs!) +- Declare MIT license for files copied from Roslyn (#13305) (Thanks @xtqqczze!) +- Improve `BigInteger` casting behaviors (#12629) (Thanks @vexx32!) +- Fix `Get-Acl -LiteralPath "HKLM:Software\Classes\*"` behavior (#13107) (Thanks @Shriram0908!) +- Add `DefaultVisit` method to the visitor interface and class (#13258) +- Fix conflicting shorthand switch `-s` (STA) for `pwsh` (#13262) (Thanks @iSazonov!) +- Change `Read-Host -MaskInput` to use existing `SecureString` path, but return as plain text (#13256) +- Remove `ComEnumerator` as COM objects using `IEnumerator` is now supported in .NET 5.0 (#13259) +- Use temporary personal path at Runspace startup when the 'HOME' environment variable is not defined (#13239) +- Fix `Invoke-Command` to detect recursive call of the same history entry (#13197) +- Change `pwsh` executable `-inputformat` switch prefix `-in` to `-inp` to fix conflict with `-interactive` (#13205) (Thanks @iSazonov!) +- Handle WSL filesystem path when analyze security zone of a file (#13120) +- Make other switches mandatory in `Split-Path` (#13150) (Thanks @kvprasoon!) +- New Fluent Design icon for PowerShell 7 (#13100) (Thanks @sarthakmalik!) +- Fix `Move-Item` to support cross-mount moves on Unix (#13044) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @yecril71pl, @ThomasNieto, @dgoldman-msft

+ +
+ +
    +
  • Use null check with pattern-matching instead of object.ReferenceEquals (#13065) (Thanks @xtqqczze!)
  • +
  • Fix comparison of value type object to null (#13285) (Thanks @xtqqczze!)
  • +
  • Use is operator instead of as operator (#13287) (Thanks @xtqqczze!)
  • +
  • Change SwitchParameter fields to properties (#13291) (Thanks @xtqqczze!)
  • +
  • Change "operable" to "executable" (#13281) (Thanks @yecril71pl!)
  • +
  • Remove AssemblyInfo property from list views (#13331) (Thanks @ThomasNieto!)
  • +
  • Use is not syntax where appropriate and remove unnecessary parentheses (#13323) (Thanks @xtqqczze!)
  • +
  • Remove unreachable code in CustomShellCommands.cs (#13316) (Thanks @xtqqczze!)
  • +
  • Add copyright header to .editorconfig and update files (#13306) (Thanks @xtqqczze!)
  • +
  • Fix typo in Out-File.cs and Out-Printer.cs (#13298) (Thanks @dgoldman-msft!)
  • +
  • Fix SA1026CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation (#13249) (Thanks @xtqqczze!)
  • +
  • Remove usage of do statement to create an infinite loop (#13137) (Thanks @xtqqczze!)
  • +
  • Use int instead of uint in places where it's more appropriate (#13141) (Thanks @xtqqczze!)
  • +
  • Use int instead of long to avoid Interlocked.Read (#13069) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Fix `dotnet` install errors (#13387) +- Increase the timeout of Windows daily build to 90 minutes (#13354) +- Update the `dependabot` configuration to version 2 (#13230) (Thanks @RDIL!) +- Fix `Test-XUnitTestResults` function (#13270) (Thanks @iSazonov!) +- Update `.devcontainer` to use nightly docker SDK images (#13128) + +### Tests + +- Mark `Test-Connection -TraceRoute` tests as pending (#13310) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @iSazonov, @77, @WorrenB

+ +
+ +
    +
  • Update README.md and metadata.json for next release (#13059)
  • +
  • Create release pipeline as a yaml pipeline (#13394)
  • +
  • Update infrastructure to consume private builds from .NET (#13427)
  • +
  • Fix breaks in packages daily build due to macOS signing changes (#13421)
  • +
  • Sign individual files for macOS PKG (#13392)
  • +
  • Disable code sign validation on jobs that do not sign (#13389)
  • +
  • Bump PSReadLine from 2.0.2 to 2.0.4 (#13240)
  • +
  • Update build documentation for Visual Studio 2019 dependency (#13336) (Thanks @xtqqczze!)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 3.6.0 to 3.7.0 (#13360)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.6.1 to 16.7.0 (#13364)
  • +
  • Bump xunit.runner.visualstudio from 2.4.2 to 2.4.3 (#13343)
  • +
  • Use Authenticode certificate for MSIX signing (#13330)
  • +
  • Add default help content to the assets folder (#13257)
  • +
  • Update .NET SDK version from 5.0.100-preview.7.20366.2 to 5.0.100-preview.7.20366.15 (#13200)
  • +
  • Set C# language version to preview/9.0 (#13090) (Thanks @iSazonov!)
  • +
  • Use pwsh for build and test of package in CI build (#13223)
  • +
  • Remove rcedit dependency, move daily ico dependency to props file (#13123)
  • +
  • Bump NJsonSchema from 10.1.23 to 10.1.24 (#13214)
  • +
  • Update .NET SDK version from 5.0.100-preview.7.20364.3 to 5.0.100-preview.7.20366.2 (#13192)
  • +
  • Add support for installing arm64 MSIX package. (#13043) (Thanks @77!)
  • +
  • Fix Azure file copy issues in release build (#13182)
  • +
  • Update .NET SDK version from 5.0.100-preview.7.20358.6 to 5.0.100-preview.7.20364.3 (#13155)
  • +
  • Fix Azure file copy break in Azure DevOps (#13173)
  • +
  • Bump Xunit.SkippableFact from 1.4.8 to 1.4.13 (#13143)
  • +
  • Add new chibi svg version of the avatar (#13160) (Thanks @WorrenB!)
  • +
  • Refactor MSI code to make it easier to add a WiX exe installer (#13139)
  • +
  • Disable ReadyToRun for debug build (#13144) (Thanks @iSazonov!)
  • +
  • Add new chibi version of the avatar (#13140)
  • +
  • Update .NET SDK version from 5.0.100-preview.7.20356.2 to 5.0.100-preview.7.20358.6 (#13134) (Thanks @github-actions[bot]!)
  • +
  • Update .NET SDK version from 5.0.100-preview.6.20318.15 to 5.0.100-preview.7.20356.2 (#13125) (Thanks @github-actions[bot]!)
  • +
+ +
+ +### Documentation and Help Content + +- Fix/clarify instructions for running Start-PSPester tests (#13373) +- Improve inline documentation for `VerbInfo` (#13265) (Thanks @yecril71pl!) +- Improve the wording of inline comments in the help system (#13274) (Thanks @yecril71pl!) +- Correct grammar in `README.md` and other docs (#13269) (Thanks @tasnimzotder!) +- Add "GitHub Actions Python builds" to `ADOPTERS.md` (#13228) (Thanks @brcrista!) +- Update change logs for `6.2.x` and `7.0.x` (#13194) +- Update `README.md` and `metadata.json` for the v7.0.3 release (#13187) + +[7.1.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.5...v7.1.0-preview.6 + +## [7.1.0-preview.5] - 2020-07-06 + +### Engine Updates and Fixes + +- Ensure assemblies listed in the module manifest `FileList` field are not loaded (#12968) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze

+ +
+ +
    +
  • Code performance fixes (#12956) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Add missing `.editorconfig` settings present in `dotnet/runtime` (#12871) (Thanks @xtqqczze!) + +### Tests + +- Add new test for `Format-Custom` to avoid data loss (#11393) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +
+ + +

Fixed upgrade code in MSI package.

+ +
+
    +
  • Change log for v7.1.0-preview.5 (Internal 11880)
  • +
  • Fix Path for the Preview MSI (#13070)
  • +
  • Correct stable and preview upgrade codes for MSI (#13036)
  • +
  • Changelog for `v7.1.0-preview.4` (Internal 11841)
  • +
  • Fix NuGet package compliance issues (#13045)
  • +
  • Bump xunit.runner.visualstudio from 2.4.1 to 2.4.2 (#12874)
  • +
  • Bump NJsonSchema from `10.1.21` to `10.1.23` (#13032) (#13022)
  • +
+ +
+ +### Documentation and Help Content + +- Fix links for MSI packages to point to `7.1.0-preview.3` (#13056) +- Add update `packages.microsoft.com` step to distribution request template. (#13008) +- Update `windows-core.md` (#13053) (Thanks @xtqqczze!) +- Add `@rjmholt` to maintainers list (#13033) +- Update docs for `v7.1.0-preview.4` release (#13028) + +## [7.1.0-preview.4] - 2020-06-25 + +### Breaking Changes + +- Make the switch parameter `-Qualifier` not positional for `Split-Path` (#12960) (Thanks @yecril71pl!) +- Resolve the working directory as literal path for `Start-Process` when it's not specified (#11946) (Thanks @NoMoreFood!) +- Make `-OutFile` parameter in web cmdlets to work like `-LiteralPath` (#11701) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Ensure null-coalescing LHS is evaluated only once (#12667) +- Fix path handling bug in `PSTask` (#12554) (Thanks @IISResetMe!) +- Remove extra line before formatting group (#12163) (Thanks @iSazonov!) +- Make module formatting not generate error with strict mode (#11943) +- Adding more ETW logs to WSMan plugin (#12798) (Thanks @krishnayalavarthi!) +- Restrict loading of `amsi.dll` to `system32` folder (#12730) + +### General Cmdlet Updates and Fixes + +- Fix `NullReferenceException` in `CommandSearcher.GetNextCmdlet` (#12659) (Thanks @powercode!) +- Prevent `NullReferenceException` in Unix computer cmdlets with test hooks active (#12651) (Thanks @vexx32!) +- Fix issue in `Select-Object` where `Hashtable` members (e.g. `Keys`) cannot be used with `-Property` or `-ExpandProperty` (#11097) (Thanks @vexx32!) +- Fix conflicting shorthand switch `-w` for pwsh (#12945) +- Rename the `CimCmdlet` resource file (#12955) (Thanks @iSazonov!) +- Remove use of `Test-Path` in `ConciseView` (#12778) +- Flag `default` switch statement condition clause as keyword (#10487) (Thanks @msftrncs!) +- Add parameter `SchemaFile` to `Test-Json` cmdlet (#11934) (Thanks @beatcracker!) +- Bring back Certificate provider parameters (#10622) (Thanks @iSazonov!) +- Fix `New-Item` to create symbolic link to relative path target (#12797) (Thanks @iSazonov!) +- Add `CommandLine` property to Process (#12288) (Thanks @iSazonov!) +- Adds `-MaskInput` parameter to `Read-Host` (#10908) (Thanks @davinci26!) +- Change `CimCmdlets` to use `AliasAttribute` (#12617) (Thanks @thlac!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @sethvs, @romero126, @kvprasoon, @powercode

+ +
+ +
    +
  • Use nameof operator (#12716) (Thanks @xtqqczze!)
  • +
  • Fix comments in Mshexpression.cs (#12711) (Thanks @sethvs!)
  • +
  • Formatting: remove duplicate semicolons (#12666) (Thanks @xtqqczze!)
  • +
  • Replace SortedList with Generic.SortedList<TKey,TValue> (#12954) (Thanks @xtqqczze!)
  • +
  • Use HashSet instead of Hashtable with null values (#12958) (Thanks @xtqqczze!)
  • +
  • Rename CopyItem.Tests.ps1 to Copy-Item.Tests.ps1 to match other tests (#10701) (Thanks @romero126!)
  • +
  • Fix RCS1114: Remove redundant delegate creation (#12917) (Thanks @xtqqczze!)
  • +
  • Code redundancy fixes (#12916) (Thanks @xtqqczze!)
  • +
  • Update the PowerShell modules to use the new Help URI (#12686)
  • +
  • Reorder modifiers according to preferred order (#12864) (Thanks @xtqqczze!)
  • +
  • Expand numberOfPowershellRefAssemblies list capacity (#12840) (Thanks @xtqqczze!)
  • +
  • Add readonly modifier to internal static members (#11777) (Thanks @xtqqczze!)
  • +
  • cleanup: Use coalesce expression (#12829) (Thanks @xtqqczze!)
  • +
  • Add missing assessibility modifiers (#12820) (Thanks @xtqqczze!)
  • +
  • Use t_ naming convention for ThreadStatic members (#12826) (Thanks @xtqqczze!)
  • +
  • Formatting: Add empty line between declarations (#12824) (Thanks @xtqqczze!)
  • +
  • Clarify defaultRefAssemblies list capacity in AddType.cs (#12520) (Thanks @xtqqczze!)
  • +
  • Fixing "Double "period" (..) in message for System.InvalidOperationException" (#12758) (Thanks @kvprasoon!)
  • +
  • Rethrow to preserve stack details for better maintainability (#12723) (Thanks @xtqqczze!)
  • +
  • Delete license.rtf (#12738) (Thanks @xtqqczze!)
  • +
  • Nullable annotations for CommandSearcher (#12733) (Thanks @powercode!)
  • +
  • Redundancy: Remove 'partial' modifier from type with a single part (#12725) (Thanks @xtqqczze!)
  • +
  • Remove phrase 'All rights reserved' from Microsoft copyright statements (#12722) (Thanks @xtqqczze!)
  • +
  • IDictionary -> IDictionary<string, FunctionInfo> for FunctionTable (#12658) (Thanks @powercode!)
  • +
+ +
+ +### Tools + +- Use correct isError parameter with Write-Log (#12989) +- Disable `NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter` rule in `StyleCop` (#12855) (Thanks @xtqqczze!) +- Add @TylerLeonhardt to PowerShell team list to correct changelog generation (#12927) +- Enable the upload of `ETW` traces to `CLR CAP` in Windows daily build (#12890) +- Prevent GitHub workflow for daily dotnet build updates from running in forks (#12763) (Thanks @bergmeister!) +- Add GitHub action for PR creation and `Wix` file generation logic (#12748) + +### Tests + +- Remove duplicate tests from `Measure-Object.Tests.ps1` (#12683) (Thanks @sethvs!) +- Fix tests to not write errors to console (#13010) +- Make sure tabcompletion tests run (#12981) +- Remove dependency on DNS for `Test-Connection` tests on macOS (#12943) +- Restore `markdownlint` tests (#12549) (Thanks @xtqqczze!) +- Wrap tests in pester blocks (#12700) (Thanks @xtqqczze!) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@iSazonov, @kvprasoon, @Saancreed, @heaths, @xtqqczze

+ +
+ +
    +
  • Update Distribution_Request.md
  • +
  • Bump NJsonSchema from 10.1.15 to 10.1.16 (#12685)
  • +
  • Disable uploading Symbols package (#12687)
  • +
  • Update .NET SDK version from 5.0.100-preview.5.20279.10 to 5.0.100-preview.6.20318.15 (#13018)
  • +
  • Remove component ref when re-generating the wix file (#13019)
  • +
  • Make sure icons are added to MSI staging folder (#12983)
  • +
  • Update DotnetRutimeMetadata.json to point to preview 6 (#12972)
  • +
  • Bump PSReadLine from 2.0.1 to 2.0.2 (#12909)
  • +
  • Bump NJsonSchema from 10.1.18 to 10.1.21 (#12944)
  • +
  • Check if Azure Blob exists before overwriting (#12921)
  • +
  • Enable skipped tests (#12894) (Thanks @iSazonov!)
  • +
  • Fix break in package build by pinning ffi version to 1.12 (#12889)
  • +
  • Upgrade APIScan version (#12876)
  • +
  • Make contributors unique in Release notes (#12878) (Thanks @kvprasoon!)
  • +
  • Update Linux daily CI to run in a single agent & collect traces (#12866)
  • +
  • Update .NET SDK version from 5.0.100-preview.5.20278.13 to 5.0.100-preview.5.20279.10 (#12844) (Thanks @github-actions[bot]!)
  • +
  • Sign the MSIX files for the store (#12582)
  • +
  • Update the CI builds (#12830)
  • +
  • Update .NET SDK version from 5.0.100-preview.5.20272.6 to 5.0.100-preview.5.20278.13 (#12772) (Thanks @github-actions[bot]!)
  • +
  • Allow use of build module on unknown Linux distros (#11146) (Thanks @Saancreed!)
  • +
  • Fix MSI upgrade and shortcut issues (#12792) (Thanks @heaths!)
  • +
  • Bump NJsonSchema from 10.1.17 to 10.1.18 (#12812)
  • +
  • Update .NET SDK version from 5.0.100-preview.5.20269.29 to 5.0.100-preview.5.20272.6 (#12759) (Thanks @github-actions[bot]!)
  • +
  • Bump NJsonSchema from 10.1.16 to 10.1.17 (#12761)
  • +
  • Update to dotnet SDK 5.0.0-preview.5.20268.9 (#12740)
  • +
  • Remove assets\license.rtf (#12721) (Thanks @xtqqczze!)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 3.5.0 to 3.6.0 (#12731)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README` and `metadata` files for next release (#12717) +- Update `README.md` removing experimental status of `Arm` builds, but `Win-Arm64` is still preview for Stable release. (#12707) +- Add link to Github compare in changelog (#12713) (Thanks @xtqqczze!) +- Added missing changelog for v7.1.0-preview.2 (#12665) +- Update required Visual Studio version in build docs (#12628) (Thanks @xtqqczze!) +- minor update to Distribution_Request.md (#12705) (Thanks @kilasuit!) +- Update docs.microsoft.com links (#12653) (Thanks @xtqqczze!) +- Update change log for `6.2.5` release (#12670) +- Update `README.md` and `metadata.json` for next release (#12668) +- Merge 7.0.1 change log (#12669) +- Remove markdown unused definitions (#12656) (Thanks @xtqqczze!) +- Add HoloLens to list of PowerShell adopters (#12940) (Thanks @reynoldsbd!) +- Update `README.md` and `metadata.json` for next releases (#12939) +- Fix broken link in `README.md` (#12887) (Thanks @xtqqczze!) +- Minor typo corrections in Distribution Request Issue Templates (#12744) (Thanks @corbob!) +- Correct 'review-for-comments' in `Governance.md` (#11035) (Thanks @MarvTheRobot!) +- Fix markdown ordered lists (#12657) (Thanks @xtqqczze!) +- Fix broken `docs.microsoft.com` link (#12776) (Thanks @xtqqczze!) +- Replace link to Slack with link to PowerShell Virtual User Group (#12786) (Thanks @xtqqczze!) +- Update `LICENSE.txt` so that it's recognized as MIT (#12729) + +## [7.1.0-preview.3] - 2020-05-14 + +### Breaking Changes + +- Fix string parameter binding for `BigInteger` numeric literals (#11634) (Thanks @vexx32!) + +### Engine Updates and Fixes + +- Set correct `PSProvider` full name at module load time (#11813) (Thanks @iSazonov!) + +### Experimental Features + +- Support passing `PSPath` to native commands (#12386) + +### General Cmdlet Updates and Fixes + +- Fix incorrect index in format string in ParameterBinderBase (#12630) (Thanks @powercode!) +- Copy the `CommandInfo` property in `Command.Clone()` (#12301) (Thanks @TylerLeonhardt!) +- Apply `-IncludeEqual` in `Compa-Object` when `-ExcludeDifferent` is specified (#12317) (Thanks @davidseibel!) +- Change `Get-FileHash` to close file handles before writing output (#12474) (Thanks @HumanEquivalentUnit!) +- Fix inconsistent exception message in `-replace` operator (#12388) (Thanks @jackdcasey!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @RDIL, @powercode, @xtqqczze, @xtqqczze

+ +
+ +
    +
  • Replace Unicode non-breaking space character with space (#12576) (Thanks @xtqqczze!)
  • +
  • Remove unused New-DockerTestBuild.ps1 (#12610) (Thanks @RDIL!)
  • +
  • Annotate Assert methods for better code analysis (#12618) (Thanks @powercode!)
  • +
  • Use correct casing for cmdlet names and parameters in *.ps1 files throughout the codebase (#12584) (Thanks @xtqqczze!)
  • +
  • Document why PackageVersion is used in PowerShell.Common.props (#12523) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Update `@PoshChan` config to include `SSH` (#12526) (Thanks @vexx32!) +- Update log message in `Start-PSBootstrap` (#12573) (Thanks @xtqqczze!) +- Add the `.NET SDK` installation path to the current process path in `tools/UpdateDotnetRuntime.ps1` (#12525) + +### Tests + +- Make CIM tab completion test case insensitive (#12636) +- Mark ping tests as Pending due to stability issues in macOS (#12504) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@jcotton42, @iSazonov, @iSazonov, @iSazonov

+ +
+ +
    +
  • Update build to use the new .NET SDK 5.0.100-preview.4.20258.7 (#12637)
  • +
  • Bump NJsonSchema from 10.1.14 to 10.1.15 (#12608)
  • +
  • Bump NJsonSchema from 10.1.13 to 10.1.14 (#12598)
  • +
  • Bump NJsonSchema from 10.1.12 to 10.1.13 (#12583)
  • +
  • Update the build to sign any unsigned files as 3rd party Dlls (#12581)
  • +
  • Update .NET SDK to 5.0.100-preview.4.20229.10 (#12538)
  • +
  • Add ability to Install-Dotnet to specify directory (#12469)
  • +
  • Allow / in relative paths for using module (#7424) (#12492) (Thanks @jcotton42!)
  • +
  • Update dotnet metadata for next channel for automated updates (#12502)
  • +
  • Bump .NET to 5.0.0-preview.4 (#12507)
  • +
  • Bump Microsoft.ApplicationInsights from 2.13.1 to 2.14.0 (#12479)
  • +
  • Bump PackageManagement from 1.4.6 to 1.4.7 in /src/Modules (#12506)
  • +
  • Bump Xunit.SkippableFact from 1.3.12 to 1.4.8 (#12480)
  • +
  • Fix quotes to allow variable expansion (#12512)
  • +
  • Use new TargetFramework as net5.0 in packaging scripts (#12503) (Thanks @iSazonov!)
  • +
  • Use new value for TargetFramework as net5.0 instead of netcoreapp5.0 (#12486) (Thanks @iSazonov!)
  • +
  • Disable PublishReadyToRun for framework dependent packages (#12450)
  • +
  • Add dependabot rules to ignore updates from .NET (#12466)
  • +
  • Update README.md and metadata.json for upcoming release (#12441)
  • +
  • Turn on ReadyToRun (#12361) (Thanks @iSazonov!)
  • +
  • Add summary to compressed sections of change log (#12429)
  • +
+ +
+ +### Documentation and Help Content + +- Add link to life cycle doc to distribution request template (#12638) +- Update TFM reference in build docs (#12514) (Thanks @xtqqczze!) +- Fix broken link for blogs in documents (#12471) + +## [7.1.0-preview.2] - 2020-04-23 + +### Breaking Changes + +- On Windows, `Start-Process` creates a process environment with + all the environment variables from current session, + using `-UseNewEnvironment` creates a new default process environment (#10830) (Thanks @iSazonov!) +- Do not wrap return result to `PSObject` when converting ScriptBlock to delegate (#10619) + +### Engine Updates and Fixes + +- Allow case insensitive paths for determining `PSModulePath` (#12192) +- Add PowerShell version 7.0 to compatible version list (#12184) +- Discover assemblies loaded by `Assembly.Load(byte[])` and `Assembly.LoadFile` (#12203) + +### General Cmdlet Updates and Fixes + +- Fix `WinCompat` module loading to treat PowerShell 7 modules with higher priority (#12269) +- Implement `ForEach-Object -Parallel` runspace reuse (#12122) +- Fix `Get-Service` to not modify collection while enumerating it (#11851) (Thanks @NextTurn!) +- Clean up the IPC named pipe on PowerShell exit (#12187) +- Fix `` detection regex in web cmdlets (#12099) (Thanks @vexx32!) +- Allow shorter signed hex literals with appropriate type suffixes (#11844) (Thanks @vexx32!) +- Update `UseNewEnvironment` parameter behavior of `Start-Process` cmdlet on Windows (#10830) (Thanks @iSazonov!) +- Add `-Shuffle` switch to `Get-Random` command (#11093) (Thanks @eugenesmlv!) +- Make `GetWindowsPowerShellModulePath` compatible with multiple PS installations (#12280) +- Fix `Start-Job` to work on systems that don't have Windows PowerShell registered as default shell (#12296) +- Specifying an alias and `-Syntax` to `Get-Command` returns the aliased commands syntax (#10784) (Thanks @ChrisLGardner!) +- Make CSV cmdlets work when using `-AsNeeded` and there is an incomplete row (#12281) (Thanks @iSazonov!) +- In local invocations, do not require `-PowerShellVersion 5.1` for `Get-FormatData` in order to see all format data. (#11270) (Thanks @mklement0!) +- Added Support For Big Endian `UTF-32` (#11947) (Thanks @NoMoreFood!) +- Fix possible race that leaks PowerShell object dispose in `ForEach-Object -Parallel` (#12227) +- Add `-FromUnixTime` to `Get-Date` to allow Unix time input (#12179) (Thanks @jackdcasey!) +- Change default progress foreground and background colors to provide improved contrast (#11455) (Thanks @rkeithhill!) +- Fix `foreach -parallel` when current drive is not available (#12197) +- Do not wrap return result to `PSObject` when converting `ScriptBlock` to `delegate` (#10619) +- Don't write DNS resolution errors on `Test-Connection -Quiet` (#12204) (Thanks @vexx32!) +- Use dedicated threads to read the redirected output and error streams from the child process for out-of-proc jobs (#11713) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@ShaydeNofziger, @RDIL

+ +
+ +
    +
  • Fix erroneous comment in tokenizer.cs (#12206) (Thanks @ShaydeNofziger!)
  • +
  • Fix terms checker issues (#12189)
  • +
  • Update copyright notice to latest guidance (#12190)
  • +
  • CodeFactor cleanup (#12251) (Thanks @RDIL!)
  • +
+ +
+ +### Tools + +- Update .NET dependency update script to include test `csproj` files (#12372) +- Scripts to update to .NET prerelease version (#12284) + +### Tests + +- Pin major Pester version to 4 to prevent breaking changes caused by upcoming release of v5 (#12262) (Thanks @bergmeister!) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@rkitover, @bergmeister

+ +
+ +
    +
  • Add the nuget.config from root to the temporary build folder (#12394)
  • +
  • Bump System.IO.Packaging (#12365)
  • +
  • Bump Markdig.Signed from 0.18.3 to 0.20.0 (#12379)
  • +
  • Bump to .NET 5 Preview 3 pre-release (#12353)
  • +
  • Bump PowerShellGet from 2.2.3 to 2.2.4 (#12342)
  • +
  • Linux: Initial support for Gentoo installations. (#11429) (Thanks @rkitover!)
  • +
  • Upgrade to .NET 5 Preview 2 (#12250) (Thanks @bergmeister!)
  • +
  • Fix the Sync PSGalleryModules to Artifacts build (#12277)
  • +
  • Bump PSReadLine from 2.0.0 to 2.0.1 (#12243)
  • +
  • Bump NJsonSchema from 10.1.11 to 10.1.12 (#12230)
  • +
  • Update change log generation script to support collapsible sections (#12214)
  • +
+ +
+ +### Documentation and Help Content + +- Add documentation for `WebResponseObject` and `BasicHtmlWebResponseObject` properties (#11876) (Thanks @kevinoid!) +- Add Windows 10 IoT Core reference in `Adopters.md` (#12266) (Thanks @parameshbabu!) +- Update `README.md` and `metadata.json` for `7.1.0-preview.1` (#12211) + +## [7.1.0-preview.1] - 2020-03-26 + +### Breaking Changes + +- Use invariant culture string conversion for `-replace` operator (#10954) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Revert the PRs that made `DBNull.Value` and `NullString.Value` treated as `$null` (#11648) + +### Experimental Features + +- Use invariant culture string conversion for `-replace` operator (#10954) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Fix an operator preference order issue in binder code (#12075) (Thanks @DamirAinullin!) +- Fix `NullReferenceException` when binding common parameters of type `ActionPreference` (#12124) +- Fix default formatting for deserialized `MatchInfo` (#11728) (Thanks @iSazonov!) +- Use asynchronous streams in `Invoke-RestMethod` (#11095) (Thanks @iSazonov!) +- Address UTF-8 Detection In `Get-Content -Tail` (#11899) (Thanks @NoMoreFood!) +- Handle the `IOException` in `Get-FileHash` (#11944) (Thanks @iSazonov!) +- Change `PowerShell Core` to `PowerShell` in a resource string (#11928) (Thanks @alexandair!) +- Bring back `MainWindowTitle` in `PSHostProcessInfo` (#11885) (Thanks @iSazonov!) +- Miscellaneous minor updates to Windows Compatibility (#11980) +- Fix `ConciseView` to split `PositionMessage` using `[Environment]::NewLine` (#12010) +- Remove network hop restriction for interactive sessions (#11920) +- Fix `NullReferenceException` in `SuspendStoppingPipeline()` and `RestoreStoppingPipeline()` (#11870) (Thanks @iSazonov!) +- Generate GUID for `FormatViewDefinition` `InstanceId` if not provided (#11896) +- Fix `ConciseView` where error message is wider than window width and doesn't have whitespace (#11880) +- Allow cross-platform `CAPI-compatible` remote key exchange (#11185) (Thanks @silijon!) +- Fix error message (#11862) (Thanks @NextTurn!) +- Fix `ConciseView` to handle case where there isn't a console to obtain the width (#11784) +- Update `CmsCommands` to use Store vs certificate provider (#11643) (Thanks @mikeTWC1984!) +- Enable `pwsh` to work on Windows systems where `mpr.dll` and STA is not available (#11748) +- Refactor and implement `Restart-Computer` for `Un*x` and macOS (#11319) +- Add an implementation of `Stop-Computer` for Linux and macOS (#11151) +- Fix `help` function to check if `less` is available before using (#11737) +- Update `PSPath` in `certificate_format_ps1.xml` (#11603) (Thanks @xtqqczze!) +- Change regular expression to match relation-types without quotes in Link header (#11711) (Thanks @Marusyk!) +- Fix error message during symbolic link deletion (#11331) +- Add custom `Selected.*` type to `PSCustomObject` in `Select-Object` only once (#11548) (Thanks @iSazonov!) +- Add `-AsUTC` to the `Get-Date` cmdlet (#11611) +- Fix grouping behavior with Boolean values in `Format-Hex` (#11587) (Thanks @vexx32!) +- Make `Test-Connection` always use the default synchronization context for sending ping requests (#11517) +- Correct startup error messages (#11473) (Thanks @iSazonov!) +- Ignore headers with null values in web cmdlets (#11424) (Thanks @iSazonov!) +- Re-add check for `Invoke-Command` job dispose. (#11388) +- Revert "Update formatter to not write newlines if content is empty (#11193)" (#11342) (Thanks @iSazonov!) +- Allow `CompleteInput` to return results from `ArgumentCompleter` when `AST` or Script has matching function definition (#10574) (Thanks @M1kep!) +- Update formatter to not write new lines if content is empty (#11193) + +### Code Cleanup + +
+ +
    +
  • Use span-based overloads (#11884) (Thanks @iSazonov!)
  • +
  • Use new string.Split() overloads (#11867) (Thanks @iSazonov!)
  • +
  • Remove unreachable DSC code (#12076) (Thanks @DamirAinullin!)
  • +
  • Remove old dead code from FullCLR (#11886) (Thanks @iSazonov!)
  • +
  • Use Dictionary.TryAdd() where possible (#11767) (Thanks @iSazonov!)
  • +
  • Use Environment.NewLine instead of hard-coded linefeed in ParseError.ToString (#11746)
  • +
  • Fix FileSystem provider error message (#11741) (Thanks @iSazonov!)
  • +
  • Reformat code according to EditorConfig rules (#11681) (Thanks @xtqqczze!)
  • +
  • Replace use of throw GetExceptionForHR with ThrowExceptionForHR (#11640) (Thanks @xtqqczze!)
  • +
  • Refactor delegate types to lambda expressions (#11690) (Thanks @xtqqczze!)
  • +
  • Remove Unicode BOM from text files (#11546) (Thanks @xtqqczze!)
  • +
  • Fix Typo in Get-ComputerInfo cmdlet description (#11321) (Thanks @doctordns!)
  • +
  • Fix typo in description for Get-ExperimentalFeature PSWindowsPowerShellCompatibility (#11282) (Thanks @alvarodelvalle!)
  • +
  • Cleanups in command discovery (#10815) (Thanks @iSazonov!)
  • +
  • Review CurrentCulture (#11044) (Thanks @iSazonov!)
  • +
+ +
+ +### Tools + +- Change recommended VS Code extension name from `ms-vscode.csharp` to `ms-dotnettools.csharp` (#12083) (Thanks @devlead!) +- Specify `csharp_preferred_modifier_order` in `EditorConfig` (#11775) (Thanks @xtqqczze!) +- Update `.editorconfig` (#11675) (Thanks @xtqqczze!) +- Enable `EditorConfig` support in `OmniSharp` (#11627) (Thanks @xtqqczze!) +- Specify charset in `.editorconfig` as `utf-8` (no BOM) (#11654) (Thanks @xtqqczze!) +- Configure the issue label bot (#11527) +- Avoid variable names that conflict with automatic variables (#11392) (Thanks @xtqqczze!) + +### Tests + +- Add empty `preview.md` file to fix broken link (#12041) +- Add helper functions for SSH remoting tests (#11955) +- Add new tests for `Get-ChildItem` for `FileSystemProvider` (#11602) (Thanks @iSazonov!) +- Ensure that types referenced by `PowerShellStandard` are present (#10634) +- Check state and report reason if it's not "opened" (#11574) +- Fixes for running tests on Raspbian (#11661) +- Unify pester test syntax for the arguments of `-BeOfType` (#11558) (Thanks @xtqqczze!) +- Correct casing for automatic variables (#11568) (Thanks @iSazonov!) +- Avoid variable names that conflict with automatic variables part 2 (#11559) (Thanks @xtqqczze!) +- Update pester syntax to v4 (#11544) (Thanks @xtqqczze!) +- Allow error 504 (Gateway Timeout) in `markdown-link` tests (#11439) (Thanks @xtqqczze!) +- Re-balance CI tests (#11420) (Thanks @iSazonov!) +- Include URL in the markdown-links test error message (#11438) (Thanks @xtqqczze!) +- Use CIM cmdlets instead of WMI cmdlets in tests (#11423) (Thanks @xtqqczze!) + +### Build and Packaging Improvements + +
+ +
    +
  • Put symbols in separate package (#12169)
  • +
  • Disable x86 PDB generation (#12167)
  • +
  • Bump NJsonSchema from 10.1.5 to 10.1.11 (#12050) (#12088) (#12166)
  • +
  • Create crossgen symbols for Windows x64 and x86 (#12157)
  • +
  • Move to .NET 5 preview.1 (#12140)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 3.4.0 to 3.5.0 (#12136)
  • +
  • Move to standard internal pool for building (#12119)
  • +
  • Fix package syncing to private Module Feed (#11841)
  • +
  • Add Ubuntu SSH remoting tests CI (#12033)
  • +
  • Bump Markdig.Signed from 0.18.1 to 0.18.3 (#12078)
  • +
  • Fix MSIX packaging to determine if a Preview release by inspecting the semantic version string (#11991)
  • +
  • Ignore last exit code in the build step as dotnet may return error when SDK is not installed (#11972)
  • +
  • Fix daily package build (#11882)
  • +
  • Fix package sorting for syncing to private Module Feed (#11838)
  • +
  • Set StrictMode version 3.0 (#11563) (Thanks @xtqqczze!)
  • +
  • Bump .devcontainer version to dotnet 3.1.101 (#11707) (Thanks @Jawz84!)
  • +
  • Move to version 3 of AzFileCopy (#11697)
  • +
  • Update README.md and metadata.json for next release (#11664)
  • +
  • Code Cleanup for environment data gathering in build.psm1 (#11572) (Thanks @xtqqczze!)
  • +
  • Update Debian Install Script To Support Debian 10 (#11540) (Thanks @RandomNoun7!)
  • +
  • Update ADOPTERS.md (#11261) (Thanks @edyoung!)
  • +
  • Change back to use powershell.exe in 'SetVersionVariables.yml' to unblock daily build (#11207)
  • +
  • Change to use pwsh to have consistent JSON conversion for DateTime (#11126)
  • +
+ +
+ +### Documentation and Help Content + +- Replace `VSCode` link in `CONTRIBUTING.md` (#11475) (Thanks @stevend811!) +- Remove the version number of PowerShell from LICENSE (#12019) +- Add the 7.0 change log link to `CHANGELOG/README.md` (#12062) (Thanks @LabhanshAgrawal!) +- Improvements to the contribution guide (#12086) (Thanks @ShaydeNofziger!) +- Update the doc about debugging dotnet core in VSCode (#11969) +- Update `README.md` and `metadata.json` for the next release (#11918) (#11992) +- Update `Adopters.md` to include info on Azure Pipelines and GitHub Actions (#11888) (Thanks @alepauly!) +- Add information about how Amazon AWS uses PowerShell. (#11365) (Thanks @bpayette!) +- Add link to .NET CLI version in build documentation (#11725) (Thanks @joeltankam!) +- Added info about `DeploymentScripts` in `ADOPTERS.md` (#11703) +- Update `CHANGELOG.md` for `6.2.4` release (#11699) +- Update `README.md` and `metadata.json` for next release (#11597) +- Update the breaking change definition (#11516) +- Adding System Frontier to the PowerShell Core adopters list `ADOPTERS.md` (#11480) (Thanks @OneScripter!) +- Update `ChangeLog`, `README.md` and `metadata.json` for `7.0.0-rc.1` release (#11363) +- Add `AzFunctions` to `ADOPTERS.md` (#11311) (Thanks @Francisco-Gamino!) +- Add `Universal Dashboard` to `ADOPTERS.md` (#11283) (Thanks @adamdriscoll!) +- Add `config.yml` for `ISSUE_TEMPLATE` so that Doc, Security, Support, and Windows PowerShell issues go to URLs (#11153) +- Add `Adopters.md` file (#11256) +- Update `Readme.md` for `preview.6` release (#11108) +- Update `SUPPORT.md` (#11101) (Thanks @mklement0!) +- Update `README.md` (#11100) (Thanks @mklement0!) + +[7.1.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.4...v7.1.0-preview.5 +[7.1.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.3...v7.1.0-preview.4 +[7.1.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.2...v7.1.0-preview.3 +[7.1.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.1...v7.1.0-preview.2 +[7.1.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.6...v7.1.0-preview.1 + diff --git a/PowerShell-master/CHANGELOG/7.2.md b/PowerShell-master/CHANGELOG/7.2.md new file mode 100644 index 0000000000000000000000000000000000000000..c9bde27a84111ddfec3e34364de6859605e46953 --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.2.md @@ -0,0 +1,1863 @@ +# 7.2 Changelog + +## [7.2.23] - 2024-08-20 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to 6.0.425

+ +
+ +
    +
  • Add feature flags for removing network isolation
  • +
  • Bump PackageManagement to 1.4.8.1 (#24162)
  • +
  • Bump .NET to 6.0.425 (#24161)
  • +
  • Skip build steps that do not have exe packages (#23945) (#24156)
  • +
  • Use correct signing certificates for RPM and DEBs (#21522) (#24154)
  • +
  • Fix exe signing with third party signing for WiX engine (#23878) (#24155)
  • +
  • Fix error in the vPack release, debug script that blocked release (#23904)
  • +
  • Add vPack release (#23898)
  • +
  • Fix nuget publish download path
  • +
  • Use correct signing certificates for RPM and DEBs (#21522)
  • +
+ +
+ +### Documentation and Help Content + +- Update docs sample nuget.config (#24109) (#24157) + +[7.2.23]: https://github.com/PowerShell/PowerShell/compare/v7.2.22...v7.2.23 + +## [7.2.22] - 2024-07-18 + +### Engine Updates and Fixes + +- Resolve paths correctly when importing files or files referenced in the module manifest (Internal 31777 31788) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to 6.0.424

+ +
+ +
    +
  • Enumerate over all signed zip packages
  • +
  • Update TPN for release v7.2.22 (Internal 31807)
  • +
  • Update CG Manifest for 7.2.22 (Internal 31804)
  • +
  • Add macos signing for package files (#24015) (#24058)
  • +
  • Update .NET version to 6.0.424 (#24033)
  • +
+ +
+ +[7.2.22]: https://github.com/PowerShell/PowerShell/compare/v7.2.21...v7.2.22 + +## [7.2.21] - 2024-06-18 + +### Build and Packaging Improvements + +
+ + + +

Release 7.2.20 broadly (was previously just released to the .NET SDK containers.)

Release 7.2.20 broadly

+ +
+ +
    +
  • Fixes for change to new Engineering System.
  • +
  • Create powershell.config.json for PowerShell.Windows.x64 global tool (#23941) (#23942)
  • +
+ +
+ +[7.2.21]: https://github.com/PowerShell/PowerShell/compare/v7.2.19...v7.2.21 + +## [7.2.20] - 2024-06-06 + +Limited release for dotnet SDK container images. + + + +

Update .NET 6 to 6.0.31 and how global tool is generated

+ +
+ +
    +
  • Fixes for change to new Engineering System.
  • +
  • Create powershell.config.json for PowerShell.Windows.x64 global tool (#23941) (#23942)
  • +
  • Update change log for v7.2.20
  • +
  • Update installation on Wix module (#23808)
  • +
  • Updates to package and release pipelines (#23800)
  • +
  • Use feed with Microsoft Wix toolset (#21651)
  • +
  • update wix package install (#21537)
  • +
  • Use PSScriptRoot to find path to Wix module (#21611)
  • +
  • Create the Windows.x64 global tool with shim for signing (#21559)
  • +
  • Add branch counter variables for daily package builds (#21523)
  • +
  • Official PowerShell Package pipeline (#21504)
  • +
  • Add a PAT for fetching PMC cli (#21503)
  • +
  • [StepSecurity] Apply security best practices (#21480)
  • +
  • Fix build failure due to missing reference in GlobalToolShim.cs (#21388)
  • +
  • Fix argument passing in GlobalToolShim (#21333)
  • +
  • Update .NET 6 to 6.0.31 (Internal 31302)
  • +
  • Re-apply the OneBranch changes to packaging.psm1"
  • +
+ + + +[7.2.20]: https://github.com/PowerShell/PowerShell/compare/v7.2.19...v7.2.20 + +## [7.2.19] - 2024-04-11 + +### Build and Packaging Improvements + +
+ + + +

Bump to .NET 6.0.29

+ +
+ +
    +
  • Allow artifacts produced by partially successful builds to be consumed by release pipeline
  • +
  • Update SDK, dependencies and cgmanifest for 7.2.19
  • +
  • Revert changes to packaging.psm1
  • +
  • Verify environment variable for OneBranch before we try to copy (#21441)
  • +
  • Multiple fixes in official build pipeline (#21408)
  • +
  • Add dotenv install as latest version does not work with current Ruby version (#21239)
  • +
  • PowerShell co-ordinated build OneBranch pipeline (#21364)
  • +
  • Remove surrogateFile setting of APIScan (#21238)
  • +
+ +
+ +[7.2.19]: https://github.com/PowerShell/PowerShell/compare/v7.2.18...v7.2.19 + +## [7.2.18] - 2024-01-11 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to 6.0.418

+ +
+ +
    +
  • Update ThirdPartyNotices.txt for v7.2.18 (Internal 29173)
  • +
  • Update cgmanifest.json for v7.2.18 release (Internal 29161)
  • +
  • Update .NET SDK to 6.0.418 (Internal 29141)
  • +
  • Back port 3 build changes to apiscan.yml (#21036)
  • +
  • Set the ollForwardOnNoCandidateFx in runtimeconfig.json to roll forward only on minor and patch versions (#20689)
  • +
  • Remove the ref folder before running compliance (#20373)
  • +
  • Fix the tab completion tests (#20867)
  • +
+ +
+ +[7.2.18]: https://github.com/PowerShell/PowerShell/compare/v7.2.17...v7.2.18 + +## [7.2.17] - 2023-11-16 + +### General Cmdlet Updates and Fixes + +- Redact Auth header content from ErrorRecord (Internal 28411) + +### Build and Packaging Improvements + +
+ + + +

Bump to .NET to version 6.0.417

+ +
+ +
    +
  • Bump to .NET 6.0.417 (Internal 28486)
  • +
  • Copy azure blob with PowerShell global tool to private blob and move to CDN during release (Internal 28450)
  • +
+ +
+ +[7.2.17]: https://github.com/PowerShell/PowerShell/compare/v7.2.16...v7.2.17 + +## [7.2.16] - 2023-10-26 + +### Build and Packaging Improvements + +
+ + + +

Update .NET 6 to version 6.0.416

+ +
+ +
    +
  • Fix release pipeline yaml
  • +
  • Fix issues with merging backports in packaging (Internal 28158)
  • +
  • Update .NET 6 and TPN (Internal 28149)
  • +
  • Add runtime and packaging type info for mariner2 arm64 (#19450) (#20564)
  • +
  • Add mariner arm64 to PMC release (#20176) (#20567)
  • +
  • Remove HostArchitecture dynamic parameter for osxpkg (#19917) (#20565)
  • +
  • Use fxdependent-win-desktop runtime for compliance runs (#20326) (#20568)
  • +
  • Add SBOM for release pipeline (#20519) (#20570)
  • +
  • Increase timeout when publishing packages to pacakages.microsoft.com (#20470) (#20569)
  • +
  • Add mariner arm64 package build to release build (#19946) (#20566)
  • +
+ +
+ +[7.2.16]: https://github.com/PowerShell/PowerShell/compare/v7.2.15...v7.2.16 + +## [7.2.15] - 2023-10-10 + +### Security Fixes + +- Block getting help from network locations in restricted remoting sessions (Internal 27699) + +### Build and Packaging Improvements + +
+ + + +

Build infrastructure maintenance

+ +
+ +
    +
  • Release build: Change the names of the PATs (#20315)
  • +
  • Switch to GitHub Action for linting markdown (#20309)
  • +
  • Put the calls to Set-AzDoProjectInfo and Set-AzDoAuthToken` in the right order (#20312)
  • +
+ +
+ +[7.2.15]: https://github.com/PowerShell/PowerShell/compare/v7.2.14...v7.2.15 + +## [7.2.14] - 2023-09-18 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK version to 6.0.414

+ +
+ +
    +
  • Update to use .NET SDK 6.0.414 (Internal 27575)
  • +
  • Enable vPack provenance data (#20242)
  • +
  • Start using new packages.microsoft.com CLI (#20241)
  • +
  • Remove spelling CI in favor of GitHub Action (#20239)
  • +
  • Make PR creation tool use --web because it is more reliable (#20238)
  • +
  • Update variable used to bypass the blocking check for multiple NuGet feeds (#20237)
  • +
  • Don't publish notice on failure because it prevents retry (#20236)
  • +
  • Publish rpm package for rhel9 (#20234)
  • +
  • Add ProductCode in registry for MSI install (#20233)
  • +
+ +
+ +### Documentation and Help Content + +- Update man page to match current help for pwsh (#20240) +- Update the link for getting started in `README.md` (#20235) + +[7.2.14]: https://github.com/PowerShell/PowerShell/compare/v7.2.13...v7.2.14 + +## [7.2.13] - 2023-07-13 + +### Tests + +- Increase the timeout to make subsystem tests more reliable (#19937) +- Increase the timeout when waiting for the event log (#19936) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK version to 6.0.412

+ +
+ +
    +
  • Update Notice file (#19956)
  • +
  • Update cgmanifest (#19938)
  • +
  • Bump to 6.0.412 SDK (#19933)
  • +
  • Update variable used to bypass the blocking check for multiple NuGet feeds (#19935)
  • +
+ +
+ +[7.2.13]: https://github.com/PowerShell/PowerShell/compare/v7.2.12...v7.2.13 + +## [7.2.12] - 2023-06-27 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET version to 6.0.411

+ +
+ +
    +
  • Disable SBOM signing for CI and add extra files for packaging tests (#19729)
  • +
  • Update ThirdPartyNotices (Internal 26349)
  • +
  • Update the cgmanifest
  • +
  • Add PoolNames variable group to compliance pipeline (#19408)
  • +
  • Add tool to trigger license information gathering for NuGet modules (#18827)
  • +
  • Update to .NET 6.0.410 (#19798)
  • +
  • Always regenerate files wxs fragment (#19803)
  • +
  • Add prompt to fix conflict during backport (#19583)
  • +
  • Add backport function to release tools (#19568)
  • +
  • Do not remove penimc_cor3.dll from build (#18438)
  • +
  • Remove unnecessary native dependencies from the package (#18213)
  • +
  • Delete symbols on Linux as well (#19735)
  • +
  • Bump Microsoft.PowerShell.MarkdownRender (#19751)
  • +
  • Backport compliance changes (#19719)
  • +
  • Delete charset regular expression test (#19585)
  • +
  • Fix issue with merge of 19068 (#19586)
  • +
  • Update the team member list in releaseTools.psm1 (#19574)
  • +
  • Verify that packages have license data (#19543) (#19575)
  • +
  • Update experimental-feature.json (#19581)
  • +
  • Fix the regular expression used for package name check in vPack build (#19573)
  • +
  • Make the vPack PAT library more obvious (#19572)
  • +
  • Add an explicit manual stage for changelog update (#19551) (#19567)
  • +
+ +
+ +[7.2.12]: https://github.com/PowerShell/PowerShell/compare/v7.2.11...v7.2.12 + +## [7.2.11] - 2023-04-12 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET version to 6.0.16

+ +
+ +
    +
  • Update ThirdPartyNotices.txt
  • +
  • Update cgmanifest.json
  • +
  • Fix the template that creates nuget package
  • +
  • Update the wix file
  • +
  • Update .NET SDK to 6.0.408
  • +
  • Fix the build script and signing template
  • +
  • Fix stage dependencies and typo in release build (#19353)
  • +
  • Fix issues in release build and release pipeline (#19338)
  • +
  • Restructure the package build to simplify signing and packaging stages (#19321)
  • +
  • Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413)
  • +
  • Improve package management acceptance tests by not going to the gallery (#19412)
  • +
  • Test fixes for stabilizing tests (#19068)
  • +
  • Add stage for symbols job in Release build (#18937)
  • +
  • Use reference assemblies generated by dotnet (#19302)
  • +
  • Add URL for all distributions (#19159)
  • +
  • Update release pipeline to use Approvals and automate some manual tasks (#17837)
  • +
+ +
+ +[7.2.11]: https://github.com/PowerShell/PowerShell/compare/v7.2.10...v7.2.11 + +## [7.2.10] - 2023-02-23 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET version to 6.0.14

+ +
+ +
    +
  • Fixed package names verification to support multi-digit versions (#17220)
  • +
  • Add pipeline secrets (from #17837) (Internal 24413)
  • +
  • Update to azCopy 10 (#18509)
  • +
  • Update third party notices for v7.2.10 (Internal 24346)
  • +
  • Update cgmanifest for v7.2.10 (Internal 24333)
  • +
  • Pull latest patches for 7.2.10 dependencies (Internal 24325)
  • +
  • Update SDK to 6.0.406 for v7.2.10 (Internal 24324)
  • +
  • Add test for framework dependent package in release pipeline (#18506) (#19114)
  • +
  • Mark 7.2.x releases as latest LTS but not latest stable (#19069)
  • +
+ +
+ +[7.2.10]: https://github.com/PowerShell/PowerShell/compare/v7.2.9...v7.2.10 + +## [7.2.9] - 2023-01-24 + +### Engine Updates and Fixes + +- Fix for JEA session leaking functions (Internal 23821 & 23819) + +### General Cmdlet Updates and Fixes + +- Correct incorrect cmdlet name in script (#18919) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET version to 6.0.13

+ +
+ +
    +
  • Create test artifacts for windows arm64 (#18932)
  • +
  • Update dependencies for .NET release (Internal 23816)
  • +
  • Don't install based on build-id for RPM (#18921)
  • +
  • Apply expected file permissions to linux files after authenticode signing (#18922)
  • +
  • Add authenticode signing for assemblies on linux builds (#18920)
  • +
+ +
+ +[7.2.9]: https://github.com/PowerShell/PowerShell/compare/v7.2.8...v7.2.9 + +## [7.2.8] - 2022-12-13 + +### Engine Updates and Fixes + +- Remove TabExpansion for PSv2 from remote session configuration (Internal 23294) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 6.0.403

+ +
+ +
    +
  • Update CGManifest and ThirdPartyNotices
  • +
  • Update Microsoft.CSharp from 4.3.0 to 4.7.0
  • +
  • Update to latest SDK (#18610)
  • +
  • Allow two-digit revisions in vPack package validation pattern (#18569)
  • +
  • Update outdated dependencies (#18576)
  • +
  • Work around args parsing issue (#18606)
  • +
  • Bump System.Data.SqlClient from 4.8.4 to 4.8.5 (#18515)
  • +
+ +
+ +[7.2.8]: https://github.com/PowerShell/PowerShell/compare/v7.2.7...v7.2.8 + +## [7.2.7] - 2022-10-20 + +### Engine Updates and Fixes + +- On Unix, explicitly terminate the native process during cleanup only if it's not running in background (#18280) +- Stop sending telemetry about `ApplicationType` (#18168) + +### General Cmdlet Updates and Fixes + +- Remove the 1-second minimum delay in `Invoke-WebRequest` for downloading small files, and prevent file-download-error suppression (#18170) +- Enable searching for assemblies in GAC_Arm64 on Windows (#18169) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#18287) + +### Tests + +- Use Ubuntu 20.04 for SSH remoting test (#18289) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to version 6.0.402 (#18188)(#18290)

+ +
+ +
    +
  • Update cgmanifest (#18319)
  • +
  • Fix build.psm1 to find the required .NET SDK version when a higher version is installed (#17299) (#18282)
  • +
  • Update MSI exit message (#18173)
  • +
  • Remove XML files for min-size package (#18274)
  • +
  • Update list of PS team members in release tools (#18171)
  • +
  • Make the link to minimal package blob public during release (#18174)
  • +
  • Add XML reference documents to NuPkg files for SDK (#18172)
  • +
  • Update to use version 2.21.0 of Application Insights (#18271)
  • +
+ +
+ +[7.2.7]: https://github.com/PowerShell/PowerShell/compare/v7.2.6...v7.2.7 + +## [7.2.6] - 2022-08-11 + +### Engine Updates and Fixes + +- Fix `ForEach-Object -Parallel` when passing in script block variable (#16564) + +### General Cmdlet Updates and Fixes + +- Make `Out-String` and `Out-File` keep string input unchanged (#17455) +- Update regular expression used to remove ANSI escape sequences to be more specific to decoration and hyperlinks (#16811) +- Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) +- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) + +### Tests + +- Disable RPM SBOM test. (#17532) + +### Build and Packaging Improvements + +
+ + +

Bump .NET SDK to 6.0.8 (Internal 22065)

+

We thank the following contributors!

+

@tamasvajk

+
+ +
    +
  • Update Wix manifest
  • +
  • Add AppX capabilities in MSIX manifest so that PS7 can call the AppX APIs (#17416)
  • +
  • Use Quality only with Channel in dotnet-install (#17847)
  • +
  • Fix build.psm1 to not specify both version and quality for dotnet-install (#17589) (Thanks @tamasvajk!)
  • +
  • Install .NET 3.1 as it is required by the vPack task
  • +
+ +
+ +[7.2.6]: https://github.com/PowerShell/PowerShell/compare/v7.2.5...v7.2.6 + +## [7.2.5] - 2022-06-21 + +### Engine Updates and Fixes + +- Fix native library loading for osx-arm64 (#17495) (Thanks @awakecoding!) + +### Tests + +- Make Assembly Load Native test work on a FX Dependent Linux Install (#17496) +- Enable more tests to be run in a container. (#17294) +- Switch to using GitHub Action to verify Markdown links for PRs (#17281) +- Try to stabilize a few tests that fail intermittently (#17426) +- TLS test fix back-port (#17424) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 6.0.301 (Internal 21218)

+ +
+ +
    +
  • Update Wix file (Internal 21242)
  • +
  • Conditionally add output argument
  • +
  • Rename mariner package to cm (#17506)
  • +
  • Backport test fixes for 7.2 (#17494)
  • +
  • Update dotnet-runtime version (#17472)
  • +
  • Update to use windows-latest as the build agent image (#17418)
  • +
  • Publish preview versions of mariner to preview repository (#17464)
  • +
  • Move cgmanifest generation to daily (#17258)
  • +
  • Fix mariner mappings (#17413)
  • +
  • Make sure we execute tests on LTS package for older LTS releases (#17430)
  • +
  • Add a finalize template which causes jobs with issues to fail (#17428)
  • +
  • Make mariner packages Framework dependent (#17425)
  • +
  • Base work for adding mariner amd64 package (#17417)
  • +
+ +
+ +[7.2.5]: https://github.com/PowerShell/PowerShell/compare/v7.2.4...v7.2.5 + +## [7.2.4] - 2022-05-17 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 6.0.203

+ +
+ +
    +
  • Add mapping for Ubuntu22.04 Jammy (#17317)
  • +
  • Update to use mcr.microsoft.com (#17272)
  • +
  • Update third party notices
  • +
  • Update global.json and wix
  • +
  • Put Secure supply chain analysis at correct place (#17273)
  • +
  • Fix web cmdlets so that an empty Get does not include a content-length header (#16587)
  • +
  • Update package fallback list for Ubuntu (from those updated for Ubuntu 22.04) (deb) (#17217)
  • +
  • Add sha256 digests to RPM packages (#17215)
  • +
  • Allow multiple installations of dotnet. (#17216)
  • +
+ +
+ +[7.2.4]: https://github.com/PowerShell/PowerShell/compare/v7.2.3...v7.2.4 + +## [7.2.3] - 2022-04-26 + +### Engine Updates and Fixes + +- Fix for partial PowerShell module search paths, that can be resolved to CWD locations (Internal 20126) +- Do not include node names when sending telemetry. (#16981) to v7.2.3 (Internal 20188) + +### Tests + +- Re-enable `PowerShellGet` tests targeting PowerShell gallery (#17062) +- Skip failing scriptblock tests (#17093) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 6.0.202

+ +
+ +
    +
  • Making NameObscurerTelemetryInitializer internal - v7.2.3 (Internal 20239)
  • +
  • Updated files.wxs for 7.2.3 (Internal 20211)
  • +
  • Updated ThirdPartyNotices for 7.2.3 (Internal 20199)
  • +
  • Work around issue with notice generation
  • +
  • Replace . in notices container name
  • +
  • Updated cgmanifest.json by findMissingNotices.ps1 in v7.2.3 (Internal 20190)
  • +
  • v7.2.3 - Updated packages using dotnet-outdated global tool (Internal 20170)
  • +
  • Updated to .NET 6.0.4 / SDK 6.0.202 (Internal 20128)
  • +
  • Update dotnet-install script download link (Internal 19951)
  • +
  • Create checksum file for global tools (#17056) (Internal 19935)
  • +
  • Make sure global tool packages are published in stable build (Internal 19625)
  • +
  • Fix release pipeline (Internal 19617)
  • +
+ +
+ +[7.2.3]: https://github.com/PowerShell/PowerShell/compare/v7.2.2...v7.2.3 + +## [7.2.2] - 2022-03-16 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 6.0.201

+ +
+ +
    +
  • Update WiX file (Internal 19460)
  • +
  • Update .NET SDK version to 6.0.201 (Internal 19457)
  • +
  • Update experimental feature JSON files (#16838)
  • +
  • Ensure Alpine and ARM SKUs have powershell.config.json file with experimental features enabled (#16823)
  • +
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • +
  • Update macOS build image and root folder for build (#16609)
  • +
  • Remove WiX install (#16834)
  • +
  • Opt-in to build security monitoring (#16911)
  • +
  • Add SBOM manifest for release packages (#16641, #16711)
  • +
  • Add Linux package dependencies for packaging (#16807)
  • +
  • Switch to our custom images for build and release (#16801, #16580)
  • +
  • Remove all references to cmake for the builds in this repository (#16578)
  • +
  • Register NuGet source when generating CGManifest (#16570)
  • +
+ +
+ +[7.2.2]: https://github.com/PowerShell/PowerShell/compare/v7.2.1...v7.2.2 + +## [7.2.1] - 2021-12-14 + +### General Cmdlet Updates and Fixes + +- Remove declaration of experimental features in Utility module manifest as they are stable (#16460) +- Bring back pwsh.exe for framework dependent packages to support Start-Job (#16535) +- Change default for `$PSStyle.OutputRendering` to `Ansi` (Internal 18394) +- Update `HelpInfoUri` for 7.2 release (#16456) +- Fix typo for "privacy" in MSI installer (#16407) + +### Tests + +- Set clean state before testing `UseMU` in the MSI (#16543) + +### Build and Packaging Improvements + +
+ +
    +
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • +
  • Fixing the build by removing duplicate TSAUpload entries (Internal 18399)
  • +
  • Port CGManifest fixes (Internal 18402)
  • +
  • Update CGManifest (Internal 18403)
  • +
  • Updated package dependencies for 7.2.1 (Internal 18388)
  • +
  • Use different containers for different branches (#16434)
  • +
  • Use notice task to generate license assuming CGManifest contains all components (#16340)
  • +
  • Create compliance build (#16286)
  • +
  • Update release instructions with link to new build (#16419)
  • +
  • Add diagnostics used to take corrective action when releasing buildInfoJson (#16404)
  • +
  • vPack release should use buildInfoJson new to 7.2 (#16402)
  • +
  • Add checkout to build json stage to get ci.psm1 (#16399)
  • +
  • Update the usage of metadata.json for getting LTS information (#16381)
  • +
  • Move mapping file into product repository and add Debian 11 (#16316)
  • +
+ +
+ +[7.2.1]: https://github.com/PowerShell/PowerShell/compare/v7.2.0...v7.2.1 + +## [7.2.0] - 2021-11-08 + +### General Cmdlet Updates and Fixes + +- Handle exception when trying to resolve a possible link path (#16310) + +### Tests + +- Fix global tool and SDK tests in release pipeline (#16342) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@kondratyev-nv

+ +
+ +
    +
  • Add an approval for releasing build-info json (#16351)
  • +
  • Release build info json when it is preview (#16335)
  • +
  • Update metadata.json for v7.2.0 release
  • +
  • Update to the latest notices file and update cgmanifest.json (#16339)(#16325)
  • +
  • Fix issues in release build by updating usage of powershell.exe with pwsh.exe (#16332)
  • +
  • Update feed and analyzer dependency (#16327)
  • +
  • Update to .NET 6 GA build 6.0.100-rtm.21527.11 (#16309)
  • +
  • Add a major-minor build info JSON file (#16301)
  • +
  • Fix Windows build ZIP packaging (#16299) (Thanks @kondratyev-nv!)
  • +
  • Clean up crossgen related build scripts also generate native symbols for R2R images (#16297)
  • +
  • Fix issues reported by code signing verification tool (#16291)
  • +
+ +
+ +[7.2.0]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-rc.1...v7.2.0 + +## [7.2.0-rc.1] - 2021-10-21 + +### General Cmdlet Updates and Fixes + +- Disallow COM calls for AppLocker system lockdown (#16268) +- Configure `Microsoft.ApplicationInsights` to not send cloud role name (#16246) +- Disallow `Add-Type` in NoLanguage mode on a locked down machine (#16245) +- Make property names for color VT100 sequences consistent with documentation (#16212) +- Make moving a directory into itself with `Move-Item` an error (#16198) +- Change `FileSystemInfo.Target` from a `CodeProperty` to an `AliasProperty` that points to `FileSystemInfo.LinkTarget` (#16165) + +### Tests + +- Removed deprecated docker-based tests for PowerShell release packages (#16224) + +### Build and Packaging Improvements + +
+ + +

Bump .NET SDK to 6.0.100-rc.2

+
+ +
    +
  • Update .NET 6 to version 6.0.100-rc.2.21505.57 (#16249)
  • +
  • Fix RPM packaging (Internal 17704)
  • +
  • Update ThirdPartyNotices.txt (#16283)
  • +
  • Update pipeline yaml file to use ubuntu-latest image (#16279)
  • +
  • Add script to generate cgmanifest.json (#16278)
  • +
  • Update version of Microsoft.PowerShell.Native and Microsoft.PowerShell.MarkdownRender packages (#16277)
  • +
  • Add cgmanifest.json for generating correct third party notice file (#16266)
  • +
  • Only upload stable buildinfo for stable releases (#16251)
  • +
  • Don't upload .dep or .tar.gz for RPM because there are none (#16230)
  • +
  • Ensure RPM license is recognized (#16189)
  • +
  • Add condition to only generate release files in local dev build only (#16259)
  • +
  • Ensure psoptions.json and manifest.spdx.json files always exist in packages (#16258)
  • +
  • Fix CI script and split out ARM runs (#16252)
  • +
  • Update vPack task version to 12 (#16250)
  • +
  • Sign third party executables (#16229)
  • +
  • Add Software Bill of Materials to the main packages (#16202)
  • +
  • Upgrade set-value package for Markdown test (#16196)
  • +
  • Fix Microsoft update spelling issue (#16178)
  • +
  • Move vPack build to 1ES Pool (#16169)
  • +
+ +
+ +[7.2.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.10...v7.2.0-rc.1 + +## [7.2.0-preview.10] - 2021-09-28 + +### Engine Updates and Fixes + +- Remove duplicate remote server mediator code (#16027) + +### General Cmdlet Updates and Fixes + +- Use `PlainText` when writing to a host that doesn't support VT (#16092) +- Remove support for `AppExecLinks` to retrieve target (#16044) +- Move `GetOuputString()` and `GetFormatStyleString()` to `PSHostUserInterface` as public API (#16075) +- Add `isOutputRedirected` parameter to `GetFormatStyleString()` method (#14397) +- Fix `ConvertTo-SecureString` with key regression due to .NET breaking change (#16068) +- Fix regression in `Move-Item` to only fallback to `CopyAndDelete` in specific cases (#16029) +- Set `$?` correctly for command expression with redirection (#16046) +- Use `CurrentCulture` when handling conversions to `DateTime` in `Add-History` (#16005) (Thanks @vexx32!) +- Fix `NullReferenceException` in `Format-Wide` (#15990) (Thanks @DarylGraves!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze!

+ +
+ +
    +
  • Improve CommandInvocationIntrinsics API documentation and style (#14369)
  • +
  • Use bool?.GetValueOrDefault() in FormatWideCommand (#15988) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Fix typo in build.psm1 (#16038) (Thanks @eltociear!) +- Add `.stylecop` to `filetypexml` and format it (#16025) +- Enable sending Teams notification when workflow fails (#15982) + +### Tests + +- Enable two previously disabled `Get-Process` tests (#15845) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +
+ + +Details + + +
    +
  • Add SHA256 hashes to release (#16147)
  • +
  • Update Microsoft.CodeAnalysis.CSharp version (#16138)
  • +
  • Change path for Component Governance for build to the path we actually use to build (#16137)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16070) (#16045) (#16036) (#16021) (#15985)
  • +
  • Update .NET to 6.0.100-rc.1.21458.32 (#16066)
  • +
  • Update minimum required OS version for macOS (#16088)
  • +
  • Ensure locale is set correctly on Ubuntu 20.04 in CI (#16067) (#16073)
  • +
  • Update .NET SDK version from 6.0.100-preview.6.21355.2 to 6.0.100-rc.1.21455.2 (#16041) (#16028) (#15648)
  • +
  • Fix the GitHub Action for updating .NET daily builds (#16042)
  • +
  • Move from PkgES hosted agents to 1ES hosted agents (#16023)
  • +
  • Update Ubuntu images to use Ubuntu 20.04 (#15906)
  • +
  • Fix the macOS build by updating the pool image name (#16010)
  • +
  • Use Alpine 3.12 for building PowerShell for Alpine Linux (#16008)
  • +
  • Ignore error from Find-Package (#15999)
  • +
  • Find packages separately for each source in UpdateDotnetRuntime.ps1 script (#15998)
  • +
  • Update metadata to start using .NET 6 RC1 builds (#15981)
  • +
+ +
+ +[7.2.0-preview.10]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.9...v7.2.0-preview.10 + +## [7.2.0-preview.9] - 2021-08-23 + +### Breaking Changes + +- Change the default value of `$PSStyle.OutputRendering` to `OutputRendering.Host` and remove `OutputRendering.Automatic` (#15882) +- Fix `CA1052` for public API to make classes static when they only have static methods (#15775) (Thanks @xtqqczze!) +- Update `pwsh.exe -File` to only accept `.ps1` script files on Windows (#15859) + +### Engine Updates and Fixes + +- Update .NET adapter to handle interface static members properly (#15908) +- Catch and handle unauthorized access exception when removing AppLocker test files (#15881) + +### General Cmdlet Updates and Fixes + +- Add `-PassThru` parameter to `Set-Clipboard` (#13713) (Thanks @ThomasNieto!) +- Add `-Encoding` parameter for `Tee-Object` (#12135) (Thanks @Peter-Schneider!) +- Update `ConvertTo-Csv` and `Export-Csv` to handle `IDictionary` objects (#11029) (Thanks @vexx32!) +- Update the parameters `-Exception` and `-ErrorRecord` for `Write-Error` to be position 0 (#13813) (Thanks @ThomasNieto!) +- Don't use `ArgumentList` when creating COM object with `New-Object` as it's not applicable to the COM parameter set (#15915) +- Fix `$PSStyle` list output to correctly show `TableHeader` (#15928) +- Remove the `PSImplicitRemotingBatching` experimental feature (#15863) +- Fix issue with `Get-Process -Module` failing to stop when it's piped to `Select-Object` (#15682) (Thanks @ArmaanMcleod!) +- Make the experimental features `PSUnixFileStat`, `PSCultureInvariantReplaceOperator`, `PSNotApplyErrorActionToStderr`, `PSAnsiRendering`, `PSAnsiProgressFeatureName` stable (#15864) +- Enhance `Remove-Item` to work with OneDrive (#15571) (Thanks @iSazonov!) +- Make global tool entrypoint class static (#15880) +- Update `ServerRemoteHost` version to be same as `PSVersion` (#15809) +- Make the initialization of `HttpKnownHeaderNames` thread safe (#15519) (Thanks @iSazonov!) +- `ConvertTo-Csv`: Quote fields with quotes and newlines when using `-UseQuotes AsNeeded` (#15765) (Thanks @lselden!) +- Forwarding progress stream changes from `Foreach-Object -Parallel` runspaces (#14271) (Thanks @powercode!) +- Add validation to `$PSStyle` to reject printable text when setting a property that only expects ANSI escape sequence (#15825) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze

+ +
+ +
    +
  • Avoid unneeded array allocation in module code (#14329) (Thanks @xtqqczze!)
  • +
  • Enable and fix analysis rules CA1052, CA1067, and IDE0049 (#15840) (Thanks @xtqqczze!)
  • +
  • Avoid unnecessary allocation in formatting code (#15832) (Thanks @xtqqczze!)
  • +
  • Specify the analyzed API surface for all code quality rules (#15778) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Enable `/rebase` to automatically rebase a PR (#15808) +- Update `.editorconfig` to not replace tabs with spaces in `.tsv` files (#15815) (Thanks @SethFalco!) +- Update PowerShell team members in the changelog generation script (#15817) + +### Tests + +- Add more tests to validate the current command error handling behaviors (#15919) +- Make `Measure-Object` property test independent of the file system (#15879) +- Add more information when a `syslog` parsing error occurs (#15857) +- Harden logic when looking for `syslog` entries to be sure that we select based on the process ID (#15841) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@xtqqczze

+ +
+ +
    +
  • Disable implicit namespace imports for test projects (#15895)
  • +
  • Update language version to 10 and fix related issues (#15886)
  • +
  • Update CodeQL workflow to use Ubuntu 18.04 (#15868)
  • +
  • Bump the version of various packages (#15944, #15934, #15935, #15891, #15812, #15822) (Thanks @xtqqczze!)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README` and `metadata files` for release `v7.2.0-preview.8` (#15819) +- Update changelogs for 7.0.7 and 7.1.4 (#15921) +- Fix spelling in XML docs (#15939) (Thanks @slowy07!) +- Update PowerShell Committee members (#15837) + +[7.2.0-preview.9]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.8...v7.2.0-preview.9 + +## [7.2.0-preview.8] - 2021-07-22 + +### Engine Updates and Fixes + +- Add a Windows mode to `$PSNativeCommandArgumentPassing` that allows some commands to use legacy argument passing (#15408) +- Use `nameof` to get parameter names when creating `ArgumentNullException` (#15604) (Thanks @gukoff!) +- Test if a command is 'Out-Default' more thoroughly for transcribing scenarios (#15653) +- Add `Microsoft.PowerShell.Crescendo` to telemetry allow list (#15372) + +### General Cmdlet Updates and Fixes + +- Use `$PSStyle.Formatting.FormatAccent` for `Format-List` and `$PSStyle.Formatting.TableHeader` for `Format-Table` output (#14406) +- Highlight using error color the exception `Message` and underline in `PositionMessage` for `Get-Error` (#15786) +- Implement a completion for View parameter of format cmdlets (#14513) (Thanks @iSazonov!) +- Add support to colorize `FileInfo` filenames (#14403) +- Don't serialize to JSON ETS properties for `DateTime` and `string` types (#15665) +- Fix `HyperVSocketEndPoint.ServiceId` setter (#15704) (Thanks @xtqqczze!) +- Add `DetailedView` to `$ErrorView` (#15609) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@iSazonov, @xtqqczze

+ +
+ +
    +
  • Remove consolehost.proto file (#15741) (Thanks @iSazonov!)
  • +
  • Implement IDisposable for ConvertToJsonCommand (#15787) (Thanks @xtqqczze!)
  • +
  • Fix IDisposable implementation for CommandPathSearch (#15793) (Thanks @xtqqczze!)
  • +
  • Delete IDE dispose analyzer rules (#15798) (Thanks @xtqqczze!)
  • +
  • Seal private classes (#15725) (Thanks @xtqqczze!)
  • +
  • Enable IDE0029: UseCoalesceExpression (#15770) (Thanks @xtqqczze!)
  • +
  • Enable IDE0070: UseSystemHashCode (#15715) (Thanks @xtqqczze!)
  • +
  • Enable IDE0030: UseCoalesceExpressionForNullable (#14289) (Thanks @xtqqczze!)
  • +
  • Fix CA1846 and CA1845 for using AsSpan instead of Substring (#15738)
  • +
  • Use List<T>.RemoveAll to avoid creating temporary list (#15686) (Thanks @xtqqczze!)
  • +
  • Enable IDE0044: MakeFieldReadonly (#13880) (Thanks @xtqqczze!)
  • +
  • Disable IDE0130 (#15728) (Thanks @xtqqczze!)
  • +
  • Make classes sealed (#15675) (Thanks @xtqqczze!)
  • +
  • Enable CA1043: Use integral or string argument for indexers (#14467) (Thanks @xtqqczze!)
  • +
  • Enable CA1812 (#15674) (Thanks @xtqqczze!)
  • +
  • Replace Single with First when we know the element count is 1 (#15676) (Thanks @xtqqczze!)
  • +
  • Skip analyzers for Microsoft.Management.UI.Internal (#15677) (Thanks @xtqqczze!)
  • +
  • Fix CA2243: Attribute string literals should parse correctly (#15622) (Thanks @xtqqczze!)
  • +
  • Enable CA1401 (#15621) (Thanks @xtqqczze!)
  • +
  • Fix CA1309: Use ordinal StringComparison in Certificate Provider (#14352) (Thanks @xtqqczze!)
  • +
  • Fix CA1839: Use Environment.ProcessPath (#15650) (Thanks @xtqqczze!)
  • +
  • Add new analyzer rules (#15620) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Add `SkipRoslynAnalyzers` parameter to `Start-PSBuild` (#15640) (Thanks @xtqqczze!) +- Create issue template for issues updating PowerShell through Windows update. (#15700) +- Add `DocumentationAnalyzers` to build (#14336) (Thanks @xtqqczze!) +- Convert GitHub issue templates to modern forms (#15645) + +### Tests + +- Add more tests for `ConvertFrom-Json` (#15706) (Thanks @strawgate!) +- Update `glob-parent` and `hosted-git-info` test dependencies (#15643) + +### Build and Packaging Improvements + +
+ + +Update .NET to version v6.0.0-preview.6 + + +
    +
  • Add new package name for osx-arm64 (#15813)
  • +
  • Prefer version when available for dotnet-install (#15810)
  • +
  • Make warning about MU being required dynamic (#15776)
  • +
  • Add Start-PSBootstrap before running tests (#15804)
  • +
  • Update to .NET 6 Preview 6 and use crossgen2 (#15763)
  • +
  • Enable ARM64 packaging for macOS (#15768)
  • +
  • Make Microsoft Update opt-out/in check boxes work (#15784)
  • +
  • Add Microsoft Update opt out to MSI install (#15727)
  • +
  • Bump NJsonSchema from 10.4.4 to 10.4.5 (#15769)
  • +
  • Fix computation of SHA512 checksum (#15736)
  • +
  • Update the script to use quality parameter for dotnet-install (#15731)
  • +
  • Generate SHA512 checksum file for all packages (#15678)
  • +
  • Enable signing daily release build with lifetime certificate (#15642)
  • +
  • Update metadata and README for 7.2.0-preview.7 (#15593)
  • +
+ +
+ +### Documentation and Help Content + +- Fix broken RFC links (#15807) +- Add to bug report template getting details from `Get-Error` (#15737) +- Update issue templates to link to new docs (#15711) +- Add @jborean93 to Remoting Working Group (#15683) + +[7.2.0-preview.8]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.7...v7.2.0-preview.8 + +## [7.2.0-preview.7] - 2021-06-17 + +### Breaking Changes + +- Remove PSDesiredStateConfiguration v2.0.5 module and published it to the PowerShell Gallery (#15536) + +### Engine Updates and Fixes + +- Fix splatting being treated as positional parameter in completions (#14623) (Thanks @MartinGC94!) +- Prevent PowerShell from crashing when a telemetry mutex can't be created (#15574) (Thanks @gukoff!) +- Ignore all exceptions when disposing an instance of a subsystem implementation (#15511) +- Wait for SSH exit when closing remote connection (#14635) (Thanks @dinhngtu!) + +### Performance + +- Retrieve `ProductVersion` using informational version attribute in `AmsiUtils.Init()` (#15527) (Thanks @Fs00!) + +### General Cmdlet Updates and Fixes + +- Fix retrieving dynamic parameters from provider even if globbed path returns no results (#15525) +- Revert "Enhance Remove-Item to work with OneDrive (#15260)" due to long path issue (#15546) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@octos4murai, @iSazonov, @Fs00

+ +
+ +
    +
  • Correct parameter name passed to exception in PSCommand constructor (#15580) (Thanks @octos4murai!)
  • +
  • Enable nullable: System.Management.Automation.ICommandRuntime (#15566) (Thanks @iSazonov!)
  • +
  • Clean up code regarding AppDomain.CreateDomain and AppDomain.Unload (#15554)
  • +
  • Replace ProcessModule.FileName with Environment.ProcessPath and remove PSUtils.GetMainModule (#15012) (Thanks @Fs00!)
  • +
+ +
+ +### Tests + +- Fix `Start-Benchmarking` to put `TargetPSVersion` and `TargetFramework` in separate parameter sets (#15508) +- Add `win-x86` test package to the build (#15517) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@schuelermine

+ +
+ +
    +
  • Update README.md and metadata.json for version 7.2.0-preview.6 (#15464)
  • +
  • Make sure GA revision increases from RC and Preview releases (#15558)
  • +
  • Remove SupportsShouldProcess from Start-PSBootstrap in build.psm1 (#15491) (Thanks @schuelermine!)
  • +
  • Update DotnetMetadataRuntime.json next channel to take daily build from .NET preview 5 (#15518)
  • +
  • Fix deps.json update in the release pipeline (#15486)
  • +
+ +
+ +### Documentation and Help Content + +- Add new members to Engine and Cmdlet Working Groups document (#15560) +- Update the `mdspell` command to exclude the folder that should be ignored (#15576) +- Replace 'User Voice' with 'Feedback Hub' in `README.md` (#15557) +- Update Virtual User Group chat links (#15505) (Thanks @Jaykul!) +- Fix typo in `FileSystemProvider.cs` (#15445) (Thanks @eltociear!) +- Add `PipelineStoppedException` notes to PowerShell API (#15324) +- Updated governance on Working Groups (WGs) (#14603) +- Correct and improve XML documentation comments on `PSCommand` (#15568) (Thanks @octos4murai!) + +[7.2.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.6...v7.2.0-preview.7 + +## [7.2.0-preview.6] - 2021-05-27 + +### Experimental Features + +- [Breaking Change] Update prediction interface to provide additional feedback to a predictor plugin (#15421) + +### Performance + +- Avoid collecting logs in buffer if a pipeline execution event is not going to be logged (#15350) +- Avoid allocation in `LanguagePrimitives.UpdateTypeConvertFromTypeTable` (#15168) (Thanks @xtqqczze!) +- Replace `Directory.GetDirectories` with `Directory.EnumerateDirectories` to avoid array allocations (#15167) (Thanks @xtqqczze!) +- Use `List.ConvertAll` instead of `LINQ` (#15140) (Thanks @xtqqczze!) + +### General Cmdlet Updates and Fixes + +- Use `AllocConsole` before initializing CLR to ensure codepage is correct for WinRM remoting (PowerShell/PowerShell-Native#70) (Thanks @jborean93!) +- Add completions for `#requires` statements (#14596) (Thanks @MartinGC94!) +- Add completions for comment-based help keywords (#15337) (Thanks @MartinGC94!) +- Move cross platform DSC code to a PowerShell engine subsystem (#15127) +- Fix `Minimal` progress view to handle activity that is longer than console width (#15264) +- Handle exception if ConsoleHost tries to set cursor out of bounds because screen buffer changed (#15380) +- Fix `NullReferenceException` in DSC `ClearCache()` (#15373) +- Update `ControlSequenceLength` to handle colon as a virtual terminal parameter separator (#14942) +- Update the summary comment for `StopTranscriptCmdlet.cs` (#15349) (Thanks @dbaileyut!) +- Remove the unusable alias `d` for the `-Directory` parameter from `Get-ChildItem` (#15171) (Thanks @kvprasoon!) +- Fix tab completion for un-localized `about` topics (#15265) (Thanks @MartinGC94!) +- Remove the unneeded SSH stdio handle workaround (#15308) +- Add `LoadAssemblyFromNativeMemory` API to load assemblies from memory in a native PowerShell host (#14652) (Thanks @awakecoding!) +- Re-implement `Remove-Item` OneDrive support (#15260) (Thanks @iSazonov!) +- Kill native processes in pipeline when pipeline is disposed on Unix (#15287) +- Default to MTA on Windows platforms where STA is not supported (#15106) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @powercode, @bcwood

+ +
+ +
    +
  • Enable nullable in some classes (#14185, #14177, #14159, #14191, #14162, #14150, #14156, #14161, #14155, #14163, #14181, #14157, #14151) (Thanks @powercode!)
  • +
  • Annotate ThrowTerminatingError with DoesNotReturn attribute (#15352) (Thanks @powercode!)
  • +
  • Use GetValueOrDefault() for nullable PSLanguageMode (#13849) (Thanks @bcwood!)
  • +
  • Enable SA1008: Opening parenthesis should be spaced correctly (#14242) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Add `winget` release script (#15050) + +### Tests + +- Enable cross-runtime benchmarking to compare different .NET runtimes (#15387) (Thanks @adamsitnik!) +- Add the performance benchmark project for PowerShell performance testing (#15242) + +### Build and Packaging Improvements + +
+ + +Update .NET to version v6.0.0-preview.4 + + +
    +
  • Suppress prompting when uploading the msixbundle package to blob (#15227)
  • +
  • Update to .NET preview 4 SDK (#15452)
  • +
  • Update AppxManifest.xml with newer OS version to allow PowerShell installed from Windows Store to make system-level changes (#15375)
  • +
  • Ensure the build works when PSDesiredStateConfiguration module is pulled in from PSGallery (#15355)
  • +
  • Make sure daily release tag does not change when retrying failures (#15286)
  • +
  • Improve messages and behavior when there's a problem in finding zip files (#15284)
  • +
+ +
+ +### Documentation and Help Content + +- Add documentation comments section to coding guidelines (#14316) (Thanks @xtqqczze!) + +[7.2.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.5...v7.2.0-preview.6 + +## [7.2.0-preview.5] - 2021-04-14 + +### Breaking Changes + +- Make PowerShell Linux deb and RPM packages universal (#15109) +- Enforce AppLocker Deny configuration before Execution Policy Bypass configuration (#15035) +- Disallow mixed dash and slash in command-line parameter prefix (#15142) (Thanks @davidBar-On!) + +### Experimental Features + +- `PSNativeCommandArgumentPassing`: Use `ArgumentList` for native executable invocation (breaking change) (#14692) + +### Engine Updates and Fixes + +- Add `IArgumentCompleterFactory` for parameterized `ArgumentCompleters` (#12605) (Thanks @powercode!) + +### General Cmdlet Updates and Fixes + +- Fix SSH remoting connection never finishing with misconfigured endpoint (#15175) +- Respect `TERM` and `NO_COLOR` environment variables for `$PSStyle` rendering (#14969) +- Use `ProgressView.Classic` when Virtual Terminal is not supported (#15048) +- Fix `Get-Counter` issue with `-Computer` parameter (#15166) (Thanks @krishnayalavarthi!) +- Fix redundant iteration while splitting lines (#14851) (Thanks @hez2010!) +- Enhance `Remove-Item -Recurse` to work with OneDrive (#14902) (Thanks @iSazonov!) +- Change minimum depth to 0 for `ConvertTo-Json` (#14830) (Thanks @kvprasoon!) +- Allow `Set-Clipboard` to accept empty string (#14579) +- Turn on and off `DECCKM` to modify keyboard mode for Unix native commands to work correctly (#14943) +- Fall back to `CopyAndDelete()` when `MoveTo()` fails due to an `IOException` (#15077) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @iSazonov, @ZhiZe-ZG

+ +
+ +
    +
  • Update .NET to 6.0.0-preview.3 (#15221)
  • +
  • Add space before comma to hosting test to fix error reported by SA1001 (#15224)
  • +
  • Add SecureStringHelper.FromPlainTextString helper method for efficient secure string creation (#14124) (Thanks @xtqqczze!)
  • +
  • Use static lambda keyword (#15154) (Thanks @iSazonov!)
  • +
  • Remove unnecessary Array -> List -> Array conversion in ProcessBaseCommand.AllProcesses (#15052) (Thanks @xtqqczze!)
  • +
  • Standardize grammar comments in Parser.cs (#15114) (Thanks @ZhiZe-ZG!)
  • +
  • Enable SA1001: Commas should be spaced correctly (#14171) (Thanks @xtqqczze!)
  • +
  • Refactor MultipleServiceCommandBase.AllServices (#15053) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Use Unix line endings for shell scripts (#15180) (Thanks @xtqqczze!) + +### Tests + +- Add the missing tag in Host Utilities tests (#14983) +- Update `copy-props` version in `package.json` (#15124) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@JustinGrote

+ +
+ +
    +
  • Fix yarn-lock for copy-props (#15225)
  • +
  • Make package validation regular expression accept universal Linux packages (#15226)
  • +
  • Bump NJsonSchema from 10.4.0 to 10.4.1 (#15190)
  • +
  • Make MSI and EXE signing always copy to fix daily build (#15191)
  • +
  • Sign internals of EXE package so that it works correctly when signed (#15132)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.9.1 to 16.9.4 (#15141)
  • +
  • Update daily release tag format to work with new Microsoft Update work (#15164)
  • +
  • Feature: Add Ubuntu 20.04 Support to install-powershell.sh (#15095) (Thanks @JustinGrote!)
  • +
  • Treat rebuild branches like release branches (#15099)
  • +
  • Update WiX to 3.11.2 (#15097)
  • +
  • Bump NJsonSchema from 10.3.11 to 10.4.0 (#15092)
  • +
  • Allow patching of preview releases (#15074)
  • +
  • Bump Newtonsoft.Json from 12.0.3 to 13.0.1 (#15084, #15085)
  • +
  • Update the minSize build package filter to be explicit (#15055)
  • +
  • Bump NJsonSchema from 10.3.10 to 10.3.11 (#14965)
  • +
+ +
+ +### Documentation and Help Content + +- Merge `7.2.0-preview.4` changes to master (#15056) +- Update `README` and `metadata.json` (#15046) +- Fix broken links for `dotnet` CLI (#14937) + +[7.2.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.4...v7.2.0-preview.5 + +## [7.2.0-preview.4] - 2021-03-16 + +### Breaking Changes + +- Fix `Get-Date -UFormat` `%G` and `%g` behavior (#14555) (Thanks @brianary!) + +### Engine Updates and Fixes + +- Update engine script signature validation to match `Get-AuthenticodeSignature` logic (#14849) +- Avoid array allocations from `GetDirectories` and `GetFiles` (#14327) (Thanks @xtqqczze!) + +### General Cmdlet Updates and Fixes + +- Add `UseOSCIndicator` setting to enable progress indicator in terminal (#14927) +- Re-enable VT mode on Windows after running command in `ConsoleHost` (#14413) +- Fix `Move-Item` for `FileSystemProvider` to use copy-delete instead of move for DFS paths (#14913) +- Fix `PromptForCredential()` to add `targetName` as domain (#14504) +- Update `Concise` `ErrorView` to not show line information for errors from script module functions (#14912) +- Remove the 32,767 character limit on the environment block for `Start-Process` (#14111) (Thanks @hbuckle!) +- Don't write possible secrets to verbose stream for web cmdlets (#14788) + +### Tools + +- Update `dependabot` configuration to V2 format (#14882) +- Add tooling issue slots in PR template (#14697) + +### Tests + +- Move misplaced test file to tests directory (#14908) (Thanks @MarianoAlipi!) +- Refactor MSI CI (#14753) + +### Build and Packaging Improvements + +
+ + +Update .NET to version 6.0.100-preview.2.21155.3 + + +
    +
  • Update .NET to version 6.0.100-preview.2.21155.3 (#15007)
  • +
  • Bump Microsoft.PowerShell.Native to 7.2.0-preview.1 (#15030)
  • +
  • Create MSIX Bundle package in release pipeline (#14982)
  • +
  • Build self-contained minimal size package for Guest Config team (#14976)
  • +
  • Bump XunitXml.TestLogger from 3.0.62 to 3.0.66 (#14993) (Thanks @dependabot[bot]!)
  • +
  • Enable building PowerShell for Apple M1 runtime (#14923)
  • +
  • Fix the variable name in the condition for miscellaneous analysis CI (#14975)
  • +
  • Fix the variable usage in CI yaml (#14974)
  • +
  • Disable running Markdown link verification in release build CI (#14971)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 3.9.0-3.final to 3.9.0 (#14934) (Thanks @dependabot[bot]!)
  • +
  • Declare which variable group is used for checking the blob in the release build (#14970)
  • +
  • Update metadata and script to enable consuming .NET daily builds (#14940)
  • +
  • Bump NJsonSchema from 10.3.9 to 10.3.10 (#14933) (Thanks @dependabot[bot]!)
  • +
  • Use template that disables component governance for CI (#14938)
  • +
  • Add suppress for nuget multi-feed warning (#14893)
  • +
  • Bump NJsonSchema from 10.3.8 to 10.3.9 (#14926) (Thanks @dependabot[bot]!)
  • +
  • Add exe wrapper to release (#14881)
  • +
  • Bump Microsoft.ApplicationInsights from 2.16.0 to 2.17.0 (#14847)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.8.3 to 16.9.1 (#14895) (Thanks @dependabot[bot]!)
  • +
  • Bump NJsonSchema from 10.3.7 to 10.3.8 (#14896) (Thanks @dependabot[bot]!)
  • +
  • Disable codesign validation where the file type is not supported (#14885)
  • +
  • Fixing broken Experimental Feature list in powershell.config.json (#14858)
  • +
  • Bump NJsonSchema from 10.3.6 to 10.3.7 (#14855)
  • +
  • Add exe wrapper for Microsoft Update scenarios (#14737)
  • +
  • Install wget on CentOS 7 docker image (#14857)
  • +
  • Fix install-dotnet download (#14856)
  • +
  • Fix Bootstrap step in Windows daily test runs (#14820)
  • +
  • Bump NJsonSchema from 10.3.5 to 10.3.6 (#14818)
  • +
  • Bump NJsonSchema from 10.3.4 to 10.3.5 (#14807)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README.md` and `metadata.json` for upcoming releases (#14755) +- Merge 7.1.3 and 7.0.6 changelog to master (#15009) +- Update `README` and `metadata.json` for releases (#14997) +- Update ChangeLog for `v7.1.2` release (#14783) +- Update ChangeLog for `v7.0.5` release (#14782) (Internal 14479) + +[7.2.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.3...v7.2.0-preview.4 + +## [7.2.0-preview.3] - 2021-02-11 + +### Breaking Changes + +- Fix `Get-Date -UFormat %u` behavior to comply with ISO 8601 (#14549) (Thanks @brianary!) + +### Engine Updates and Fixes + +- Together with `PSDesiredStateConfiguration` `v3` module allows `Get-DscResource`, `Invoke-DscResource` and DSC configuration compilation on all platforms, supported by PowerShell (using class-based DSC resources). + +### Performance + +- Avoid array allocations from `Directory.GetDirectories` and `Directory.GetFiles`. (#14326) (Thanks @xtqqczze!) +- Avoid `string.ToLowerInvariant()` from `GetEnvironmentVariableAsBool()` to avoid loading libicu at startup (#14323) (Thanks @iSazonov!) +- Get PowerShell version in `PSVersionInfo` using assembly attribute instead of `FileVersionInfo` (#14332) (Thanks @Fs00!) + +### General Cmdlet Updates and Fixes + +- Suppress `Write-Progress` in `ConsoleHost` if output is redirected and fix tests (#14716) +- Experimental feature `PSAnsiProgress`: Add minimal progress bar using ANSI rendering (#14414) +- Fix web cmdlets to properly construct URI from body when using `-NoProxy` (#14673) +- Update the `ICommandPredictor` to provide more feedback and also make feedback easier to be correlated (#14649) +- Reset color after writing `Verbose`, `Debug`, and `Warning` messages (#14698) +- Fix using variable for nested `ForEach-Object -Parallel` calls (#14548) +- When formatting, if collection is modified, don't fail the entire pipeline (#14438) +- Improve completion of parameters for attributes (#14525) (Thanks @MartinGC94!) +- Write proper error messages for `Get-Command ' '` (#13564) (Thanks @jakekerr!) +- Fix typo in the resource string `ProxyURINotSupplied` (#14526) (Thanks @romero126!) +- Add support to `$PSStyle` for strikethrough and hyperlinks (#14461) +- Fix `$PSStyle` blink codes (#14447) (Thanks @iSazonov!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @powercode

+ +
+ +
    +
  • Fix coding style issues: RCS1215, IDE0090, SA1504, SA1119, RCS1139, IDE0032 (#14356, #14341, #14241, #14204, #14442, #14443) (Thanks @xtqqczze!)
  • +
  • Enable coding style checks: CA2249, CA1052, IDE0076, IDE0077, SA1205, SA1003, SA1314, SA1216, SA1217, SA1213 (#14395, #14483, #14494, #14495, #14441, #14476, #14470, #14471, #14472) (Thanks @xtqqczze!)
  • +
  • Enable nullable in PowerShell codebase (#14160, #14172, #14088, #14154, #14166, #14184, #14178) (Thanks @powercode!)
  • +
  • Use string.Split(char) instead of string.Split(string) (#14465) (Thanks @xtqqczze!)
  • +
  • Use string.Contains(char) overload (#14368) (Thanks @xtqqczze!)
  • +
  • Refactor complex if statements (#14398) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Update script to use .NET 6 build resources (#14705) +- Fix the daily GitHub Action (#14711) (Thanks @imba-tjd!) +- GitHub Actions: fix deprecated `::set-env` (#14629) (Thanks @imba-tjd!) +- Update Markdown test tools (#14325) (Thanks @RDIL!) +- Upgrade `StyleCopAnalyzers` to `v1.2.0-beta.312` (#14354) (Thanks @xtqqczze!) + +### Tests + +- Remove packaging from daily Windows build (#14749) +- Update link to the Manning book (#14750) +- A separate Windows packaging CI (#14670) +- Update `ini` component version in test `package.json` (#14454) +- Disable `libmi` dependent tests for macOS. (#14446) + +### Build and Packaging Improvements + +
+ +
    +
  • Fix the NuGet feed name and URL for .NET 6
  • +
  • Fix third party signing for files in sub-folders (#14751)
  • +
  • Make build script variable an ArrayList to enable Add() method (#14748)
  • +
  • Remove old .NET SDKs to make dotnet restore work with the latest SDK in CI pipeline (#14746)
  • +
  • Remove outdated Linux dependencies (#14688)
  • +
  • Bump .NET SDK version to 6.0.0-preview.1 (#14719)
  • +
  • Bump NJsonSchema to 10.3.4 (#14714)
  • +
  • Update daily GitHub action to allow manual trigger (#14718)
  • +
  • Bump XunitXml.TestLogger to 3.0.62 (#14702)
  • +
  • Make universal deb package based on the deb package specification (#14681)
  • +
  • Add manual release automation steps and improve changelog script (#14445)
  • +
  • Fix release build to upload global tool packages to artifacts (#14620)
  • +
  • Port changes from the PowerShell v7.0.4 release (#14637)
  • +
  • Port changes from the PowerShell v7.1.1 release (#14621)
  • +
  • Updated README and metadata.json (#14401, #14606, #14612)
  • +
  • Do not push nupkg artifacts to MyGet (#14613)
  • +
  • Use one feed in each nuget.config in official builds (#14363)
  • +
  • Fix path signed RPMs are uploaded from in release build (#14424)
  • +
+ +
+ +### Documentation and Help Content + +- Update distribution support request template to point to .NET 5.0 support document (#14578) +- Remove security GitHub issue template (#14453) +- Add intent for using the Discussions feature in repository (#14399) +- Fix Universal Dashboard to refer to PowerShell Universal (#14437) +- Update document link because of HTTP 301 redirect (#14431) (Thanks @xtqqczze!) + +[7.2.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.2...v7.2.0-preview.3 + +## [7.2.0-preview.2] - 2020-12-15 + +### Breaking Changes + +- Improve detection of mutable value types (#12495) (Thanks @vexx32!) +- Ensure `-PipelineVariable` is set for all output from script cmdlets (#12766) (Thanks @vexx32!) + +### Experimental Features + +- `PSAnsiRendering`: Enable ANSI formatting via `$PSStyle` and support suppressing ANSI output (#13758) + +### Performance + +- Optimize `IEnumerable` variant of replace operator (#14221) (Thanks @iSazonov!) +- Refactor multiply operation for better performance in two `Microsoft.PowerShell.Commands.Utility` methods (#14148) (Thanks @xtqqczze!) +- Use `Environment.TickCount64` instead of `Datetime.Now` as the random seed for AppLocker test file content (#14283) (Thanks @iSazonov!) +- Avoid unnecessary array allocations when searching in GAC (#14291) (Thanks @xtqqczze!) +- Use `OrdinalIgnoreCase` in `CommandLineParser` (#14303) (Thanks @iSazonov!) +- Use `StringComparison.Ordinal` instead of `StringComparison.CurrentCulture` (#14298) (Thanks @iSazonov!) +- Avoid creating instances of the generated delegate helper class in `-replace` implementation (#14128) + +### General Cmdlet Updates and Fixes + +- Write better error message if config file is broken (#13496) (Thanks @iSazonov!) +- Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353) +- Add `-SkipLimitCheck` switch to `Import-PowerShellDataFile` (#13672) +- Restrict `New-Object` in NoLanguage mode under lock down (#14140) (Thanks @krishnayalavarthi!) +- The `-Stream` parameter now works with directories (#13941) (Thanks @kyanha!) +- Avoid an exception if file system does not support reparse points (#13634) (Thanks @iSazonov!) +- Enable `CA1012`: Abstract types should not have public constructors (#13940) (Thanks @xtqqczze!) +- Enable `SA1212`: Property accessors should follow order (#14051) (Thanks @xtqqczze!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @matthewjdegarmo, @powercode, @Gimly

+ +
+ +
    +
  • Enable SA1007: Operator keyword should be followed by space (#14130) (Thanks @xtqqczze!)
  • +
  • Expand where alias to Where-Object in Reset-PWSHSystemPath.ps1 (#14113) (Thanks @matthewjdegarmo!)
  • +
  • Fix whitespace issues (#14092) (Thanks @xtqqczze!)
  • +
  • Add StyleCop.Analyzers package (#13963) (Thanks @xtqqczze!)
  • +
  • Enable IDE0041: UseIsNullCheck (#14041) (Thanks @xtqqczze!)
  • +
  • Enable IDE0082: ConvertTypeOfToNameOf (#14042) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary usings part 4 (#14023) (Thanks @xtqqczze!)
  • +
  • Fix PriorityAttribute name (#14094) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Interpreter.IBoxableInstruction (#14165) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Provider.IDynamicPropertyProvider (#14167) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Language.IScriptExtent (#14179) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Language.ICustomAstVisitor2 (#14192) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.LanguagePrimitives.IConversionData (#14187) (Thanks @powercode!)
  • +
  • Enable nullable: System.Automation.Remoting.Client.IWSManNativeApiFacade (#14186) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Language.ISupportsAssignment (#14180) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.ICommandRuntime2 (#14183) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IOutputProcessingState (#14175) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IJobDebugger (#14174) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Interpreter.IInstructionProvider (#14173) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IHasSessionStateEntryVisibility (#14169) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Tracing.IEtwEventCorrelator (#14168) (Thanks @powercode!)
  • +
  • Fix syntax error in Windows packaging script (#14377)
  • +
  • Remove redundant local assignment in AclCommands (#14358) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Language.IAstPostVisitHandler (#14164) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IModuleAssemblyInitializer (#14158) (Thanks @powercode!)
  • +
  • Use Microsoft.PowerShell.MarkdownRender package from nuget.org (#14090)
  • +
  • Replace GetFiles in TestModuleManifestCommand (#14317) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Provider.IContentWriter (#14152) (Thanks @powercode!)
  • +
  • Simplify getting Encoding in TranscriptionOption.FlushContentToDisk (#13910) (Thanks @Gimly!)
  • +
  • Mark applicable structs as readonly and use in-modifier (#13919) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.IArgumentCompleter (#14182) (Thanks @powercode!)
  • +
  • Enable CA1822: Mark private members as static (#13897) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 6 (#14338) (Thanks @xtqqczze!)
  • +
  • Avoid array allocations from GetDirectories/GetFiles. (#14328) (Thanks @xtqqczze!)
  • +
  • Avoid array allocations from GetDirectories/GetFiles. (#14330) (Thanks @xtqqczze!)
  • +
  • Fix RCS1188: Remove redundant auto-property initialization part 2 (#14262) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Host.IHostSupportsInteractiveSession (#14170) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Provider.IPropertyCmdletProvider (#14176) (Thanks @powercode!)
  • +
  • Fix IDE0090: Simplify new expression part 5 (#14301) (Thanks @xtqqczze!)
  • +
  • Enable IDE0075: SimplifyConditionalExpression (#14078) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary usings part 9 (#14288) (Thanks @xtqqczze!)
  • +
  • Fix StyleCop and MarkdownLint CI failures (#14297) (Thanks @xtqqczze!)
  • +
  • Enable SA1000: Keywords should be spaced correctly (#13973) (Thanks @xtqqczze!)
  • +
  • Fix RCS1188: Remove redundant auto-property initialization part 1 (#14261) (Thanks @xtqqczze!)
  • +
  • Mark private members as static part 10 (#14235) (Thanks @xtqqczze!)
  • +
  • Mark private members as static part 9 (#14234) (Thanks @xtqqczze!)
  • +
  • Fix SA1642 for Microsoft.Management.Infrastructure.CimCmdlets (#14239) (Thanks @xtqqczze!)
  • +
  • Use AsSpan/AsMemory slice constructor (#14265) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.6 (#14260) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.5 (#14259) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.3 (#14257) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.2 (#14256) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 2 (#14200) (Thanks @xtqqczze!)
  • +
  • Enable SA1643: Destructor summary documentation should begin with standard text (#14236) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.4 (#14258) (Thanks @xtqqczze!)
  • +
  • Use xml documentation child blocks correctly (#14249) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.1 (#14255) (Thanks @xtqqczze!)
  • +
  • Use consistent spacing in xml documentation tags (#14231) (Thanks @xtqqczze!)
  • +
  • Enable IDE0074: Use coalesce compound assignment (#13396) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary finalizers (#14248) (Thanks @xtqqczze!)
  • +
  • Mark local variable as const (#13217) (Thanks @xtqqczze!)
  • +
  • Fix IDE0032: UseAutoProperty part 2 (#14244) (Thanks @xtqqczze!)
  • +
  • Fix IDE0032: UseAutoProperty part 1 (#14243) (Thanks @xtqqczze!)
  • +
  • Mark private members as static part 8 (#14233) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 6 (#14229) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 5 (#14228) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 4 (#14227) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 3 (#14226) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 2 (#14225) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 1 (#14224) (Thanks @xtqqczze!)
  • +
  • Use see keyword in documentation (#14220) (Thanks @xtqqczze!)
  • +
  • Enable CA2211: Non-constant fields should not be visible (#14073) (Thanks @xtqqczze!)
  • +
  • Enable CA1816: Dispose methods should call SuppressFinalize (#14074) (Thanks @xtqqczze!)
  • +
  • Remove incorrectly implemented finalizer (#14246) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 7 (#14230) (Thanks @xtqqczze!)
  • +
  • Fix SA1122: Use string.Empty for empty strings (#14218) (Thanks @xtqqczze!)
  • +
  • Fix various xml documentation issues (#14223) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary usings part 8 (#14072) (Thanks @xtqqczze!)
  • +
  • Enable SA1006: Preprocessor keywords should not be preceded by space (#14052) (Thanks @xtqqczze!)
  • +
  • Fix SA1642 for Microsoft.PowerShell.Commands.Utility (#14142) (Thanks @xtqqczze!)
  • +
  • Enable CA2216: Disposable types should declare finalizer (#14089) (Thanks @xtqqczze!)
  • +
  • Wrap and name LoadBinaryModule arguments (#14193) (Thanks @xtqqczze!)
  • +
  • Wrap and name GetListOfFilesFromData arguments (#14194) (Thanks @xtqqczze!)
  • +
  • Enable SA1002: Semicolons should be spaced correctly (#14197) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 3 (#14201) (Thanks @xtqqczze!)
  • +
  • Enable SA1106: Code should not contain empty statements (#13964) (Thanks @xtqqczze!)
  • +
  • Code performance fixes follow-up (#14207) (Thanks @xtqqczze!)
  • +
  • Remove uninformative comments (#14199) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 1 (#14027) (Thanks @xtqqczze!)
  • +
  • Enable SA1517: Code should not contain blank lines at start of file (#14131) (Thanks @xtqqczze!)
  • +
  • Enable SA1131: Use readable conditions (#14132) (Thanks @xtqqczze!)
  • +
  • Enable SA1507: Code should not contain multiple blank lines in a row (#14136) (Thanks @xtqqczze!)
  • +
  • Enable SA1516 Elements should be separated by blank line (#14137) (Thanks @xtqqczze!)
  • +
  • Enable IDE0031: Null check can be simplified (#13548) (Thanks @xtqqczze!)
  • +
  • Enable CA1065: Do not raise exceptions in unexpected locations (#14117) (Thanks @xtqqczze!)
  • +
  • Enable CA1000: Do not declare static members on generic types (#14097) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Fixing formatting in `Reset-PWSHSystemPath.ps1` (#13689) (Thanks @dgoldman-msft!) + +### Tests + +- Reinstate `Test-Connection` tests (#13324) +- Update Markdown test packages with security fixes (#14145) + +### Build and Packaging Improvements + +
+ +
    +
  • Fix a typo in the Get-ChangeLog function (#14129)
  • +
  • Update README and metadata.json for 7.2.0-preview.1 release (#14104)
  • +
  • Bump NJsonSchema from 10.2.2 to 10.3.1 (#14040)
  • +
  • Move windows package signing to use ESRP (#14060)
  • +
  • Use one feed in each nuget.config in official builds (#14363)
  • +
  • Fix path signed RPMs are uploaded from in release build (#14424)
  • +
  • Add Microsoft.PowerShell.MarkdownRender to the package reference list (#14386)
  • +
  • Fix issue with unsigned build (#14367)
  • +
  • Move macOS and nuget to ESRP signing (#14324)
  • +
  • Fix nuget packaging to scrub NullableAttribute (#14344)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.8.0 to 16.8.3 (#14310)
  • +
  • Bump Markdig.Signed from 0.22.0 to 0.22.1 (#14305)
  • +
  • Bump Microsoft.ApplicationInsights from 2.15.0 to 2.16.0 (#14031)
  • +
  • Move Linux to ESRP signing (#14210)
  • +
+ +
+ +### Documentation and Help Content + +- Fix example `nuget.config` (#14349) +- Fix a broken link in Code Guidelines doc (#14314) (Thanks @iSazonov!) + +[7.2.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.1...v7.2.0-preview.2 + +## [7.2.0-preview.1] - 2020-11-17 + +### Engine Updates and Fixes + +- Change the default fallback encoding for `GetEncoding` in `Start-Transcript` to be `UTF8` without a BOM (#13732) (Thanks @Gimly!) + +### General Cmdlet Updates and Fixes + +- Update `pwsh -?` output to match docs (#13748) +- Fix `NullReferenceException` in `Test-Json` (#12942) (Thanks @iSazonov!) +- Make `Dispose` in `TranscriptionOption` idempotent (#13839) (Thanks @krishnayalavarthi!) +- Add additional Microsoft PowerShell modules to the tracked modules list (#12183) +- Relax further `SSL` verification checks for `WSMan` on non-Windows hosts with verification available (#13786) (Thanks @jborean93!) +- Add the `OutputTypeAttribute` to `Get-ExperimentalFeature` (#13738) (Thanks @ThomasNieto!) +- Fix blocking wait when starting file associated with a Windows application (#13750) +- Emit warning if `ConvertTo-Json` exceeds `-Depth` value (#13692) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @mkswd, @ThomasNieto, @PatLeong, @paul-cheung, @georgettica

+ +
+ +
    +
  • Fix RCS1049: Simplify boolean comparison (#13994) (Thanks @xtqqczze!)
  • +
  • Enable IDE0062: Make local function static (#14044) (Thanks @xtqqczze!)
  • +
  • Enable CA2207: Initialize value type static fields inline (#14068) (Thanks @xtqqczze!)
  • +
  • Enable CA1837: Use ProcessId and CurrentManagedThreadId from System.Environment (#14063) (Thanks @xtqqczze and @PatLeong!)
  • +
  • Remove unnecessary using directives (#14014, #14017, #14021, #14050, #14065, #14066, #13863, #13860, #13861, #13814) (Thanks @xtqqczze and @ThomasNieto!)
  • +
  • Remove unnecessary usage of LINQ Count method (#13545) (Thanks @xtqqczze!)
  • +
  • Fix SA1518: The code must not contain extra blank lines at the end of the file (#13574) (Thanks @xtqqczze!)
  • +
  • Enable CA1829: Use the Length or Count property instead of Count() (#13925) (Thanks @xtqqczze!)
  • +
  • Enable CA1827: Do not use Count() or LongCount() when Any() can be used (#13923) (Thanks @xtqqczze!)
  • +
  • Enable or fix nullable usage in a few files (#13793, #13805, #13808, #14018, #13804) (Thanks @mkswd and @georgettica!)
  • +
  • Enable IDE0040: Add accessibility modifiers (#13962, #13874) (Thanks @xtqqczze!)
  • +
  • Make applicable private Guid fields readonly (#14000) (Thanks @xtqqczze!)
  • +
  • Fix CA1003: Use generic event handler instances (#13937) (Thanks @xtqqczze!)
  • +
  • Simplify delegate creation (#13578) (Thanks @xtqqczze!)
  • +
  • Fix RCS1033: Remove redundant boolean literal (#13454) (Thanks @xtqqczze!)
  • +
  • Fix RCS1221: Use pattern matching instead of combination of as operator and null check (#13333) (Thanks @xtqqczze!)
  • +
  • Use is not syntax (#13338) (Thanks @xtqqczze!)
  • +
  • Replace magic number with constant in PDH (#13536) (Thanks @xtqqczze!)
  • +
  • Fix accessor order (#13538) (Thanks @xtqqczze!)
  • +
  • Enable IDE0054: Use compound assignment (#13546) (Thanks @xtqqczze!)
  • +
  • Fix RCS1098: Constant values should be on right side of comparisons (#13833) (Thanks @xtqqczze!)
  • +
  • Enable CA1068: CancellationToken parameters must come last (#13867) (Thanks @xtqqczze!)
  • +
  • Enable CA10XX rules with suggestion severity (#13870, #13928, #13924) (Thanks @xtqqczze!)
  • +
  • Enable IDE0064: Make Struct fields writable (#13945) (Thanks @xtqqczze!)
  • +
  • Run dotnet-format to improve formatting of source code (#13503) (Thanks @xtqqczze!)
  • +
  • Enable CA1825: Avoid zero-length array allocations (#13961) (Thanks @xtqqczze!)
  • +
  • Add IDE analyzer rule IDs to comments (#13960) (Thanks @xtqqczze!)
  • +
  • Enable CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder (#13926) (Thanks @xtqqczze!)
  • +
  • Enforce code style in build (#13957) (Thanks @xtqqczze!)
  • +
  • Enable CA1836: Prefer IsEmpty over Count when available (#13877) (Thanks @xtqqczze!)
  • +
  • Enable CA1834: Consider using StringBuilder.Append(char) when applicable (#13878) (Thanks @xtqqczze!)
  • +
  • Fix IDE0044: Make field readonly (#13884, #13885, #13888, #13892, #13889, #13886, #13890, #13891, #13887, #13893, #13969, #13967, #13968, #13970, #13971, #13966, #14012) (Thanks @xtqqczze!)
  • +
  • Enable IDE0048: Add required parentheses (#13896) (Thanks @xtqqczze!)
  • +
  • Enable IDE1005: Invoke delegate with conditional access (#13911) (Thanks @xtqqczze!)
  • +
  • Enable IDE0036: Enable the check on the order of modifiers (#13958, #13881) (Thanks @xtqqczze!)
  • +
  • Use span-based String.Concat instead of String.Substring (#13500) (Thanks @xtqqczze!)
  • +
  • Enable CA1050: Declare types in namespace (#13872) (Thanks @xtqqczze!)
  • +
  • Fix minor keyword typo in C# code comment (#13811) (Thanks @paul-cheung!)
  • +
+ +
+ +### Tools + +- Enable `CodeQL` Security scanning (#13894) +- Add global `AnalyzerConfig` with default configuration (#13835) (Thanks @xtqqczze!) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@mkswd, @xtqqczze

+ +
+ +
    +
  • Bump Microsoft.NET.Test.Sdk to 16.8.0 (#14020)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp to 3.8.0 (#14075)
  • +
  • Remove workarounds for .NET 5 RTM builds (#14038)
  • +
  • Migrate 3rd party signing to ESRP (#14010)
  • +
  • Fixes to release pipeline for GA release (#14034)
  • +
  • Don't do a shallow checkout (#13992)
  • +
  • Add validation and dependencies for Ubuntu 20.04 distribution to packaging script (#13993)
  • +
  • Add .NET install workaround for RTM (#13991)
  • +
  • Move to ESRP signing for Windows files (#13988)
  • +
  • Update PSReadLine version to 2.1.0 (#13975)
  • +
  • Bump .NET to version 5.0.100-rtm.20526.5 (#13920)
  • +
  • Update script to use .NET RTM feeds (#13927)
  • +
  • Add checkout step to release build templates (#13840)
  • +
  • Turn on /features:strict for all projects (#13383) (Thanks @xtqqczze!)
  • +
  • Bump NJsonSchema to 10.2.2 (#13722, #13751)
  • +
  • Add flag to make Linux script publish to production repository (#13714)
  • +
  • Bump Markdig.Signed to 0.22.0 (#13741)
  • +
  • Use new release script for Linux packages (#13705)
  • +
+ +
+ +### Documentation and Help Content + +- Fix links to LTS versions for Windows (#14070) +- Fix `crontab` formatting in example doc (#13712) (Thanks @dgoldman-msft!) + +[7.2.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.1.0...v7.2.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/7.3.md b/PowerShell-master/CHANGELOG/7.3.md new file mode 100644 index 0000000000000000000000000000000000000000..25da137b1c2d8b88c8ff71223ef55eae377ec414 --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.3.md @@ -0,0 +1,1307 @@ +# 7.3 Changelog + +## [7.3.12] - 2024-04-11 + +### Build and Packaging Improvements + +
+ + + +

Bump to .NET 7.0.18

+ +
+ +
    +
  • Update SDK, dependencies and cgmanifest for 7.3.12
  • +
  • Revert changes to packaging.psm1
  • +
  • Verify environment variable for OneBranch before we try to copy (#21441)
  • +
  • Multiple fixes in official build pipeline (#21408)
  • +
  • PowerShell co-ordinated build OneBranch pipeline (#21364)
  • +
  • Add dotenv install as latest version does not work with current Ruby version (#21239)
  • +
  • Remove surrogateFile setting of APIScan (#21238)
  • +
+ +
+ +[7.3.12]: https://github.com/PowerShell/PowerShell/compare/v7.3.11...v7.3.12 + +## [7.3.11] - 2024-01-11 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to 7.0.405

+ +
+ +
    +
  • Update cgmanifest.json for v7.3.11 release (Internal 29160)
  • +
  • Update .NET SDK to 7.0.405 (Internal 29140)
  • +
  • Back port 3 build changes to apiscan.yml (#21035)
  • +
  • Set the ollForwardOnNoCandidateFx in runtimeconfig.json to roll forward only on minor and patch versions (#20689)
  • +
  • Remove the ref folder before running compliance (#20373)
  • +
  • Fix the tab completion tests (#20867)
  • +
+ +
+ +[7.3.11]: https://github.com/PowerShell/PowerShell/compare/v7.3.10...v7.3.11 + +## [7.3.10] - 2023-11-16 + +### General Cmdlet Updates and Fixes + +- Redact Auth header content from ErrorRecord (Internal 28410) + +### Build and Packaging Improvements + +
+ + + +

Update .NET to 7.0.404

+ +
+ +
    +
  • Add internal .NET SDK URL parameter to release pipeline (Internal 28505)
  • +
  • Fix release build by making the internal SDK parameter optional (#20658) (Internal 28440)
  • +
  • Make internal .NET SDK URL as a parameter for release builld (#20655) (Internal 28428)
  • +
  • Update the Notices file and cgmanifest (Internal 28500)
  • +
  • Update .NET to 7.0.404 (Internal 28485)
  • +
  • Copy azure blob with PowerShell global tool to private blob and move to CDN during release (Internal 28448)
  • +
+ +
+ +[7.3.10]: https://github.com/PowerShell/PowerShell/compare/v7.3.9...v7.3.10 + +## [7.3.9] - 2023-10-26 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET 7 to version 7.0.403

+ +
+ +
    +
  • Use correct agent pool for downloading from Azure blob
  • +
  • Remove a timeout value from ADO pipeline stage to resolve a syntax issue
  • +
  • Update .NET 7 and manifests (Internal 28148)
  • +
  • Add SBOM for release pipeline (#20519) (#20573)
  • +
  • Increase timeout when publishing packages to pacakages.microsoft.com (#20470) (#20572)
  • +
  • Use fxdependent-win-desktop runtime for compliance runs (#20326) (#20571)
  • +
+ +
+ +[7.3.9]: https://github.com/PowerShell/PowerShell/compare/v7.3.8...v7.3.9 + +## [7.3.8] - 2023-10-10 + +### Security Fixes + +- Block getting help from network locations in restricted remoting sessions (Internal 27698) + +### Build and Packaging Improvements + +
+ + + +

Build infrastructure maintenance

+ +
+ +
    +
  • Release build: Change the names of the PATs (#20316)
  • +
  • Add mapping for mariner arm64 stable (#20310)
  • +
  • Switch to GitHub Action for linting markdown (#20308)
  • +
  • Put the calls to Set-AzDoProjectInfo and Set-AzDoAuthToken` in the right order (#20311)
  • +
+ +
+ +[7.3.8]: https://github.com/PowerShell/PowerShell/compare/v7.3.7...v7.3.8 + +## [7.3.7] - 2023-09-18 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK version to 7.0.401

+ +
+ +
    +
  • Update 'ThirdPartyNotices.txt' (Internal 27602)
  • +
  • Update to use .NET SDK 7.0.401 (Internal 27591)
  • +
  • Remove HostArchitecture dynamic parameter for osxpkg (#19917)
  • +
  • Remove spelling CI in favor of GitHub Action (#20248)
  • +
  • Enable vPack provenance data (#20253)
  • +
  • Start using new packages.microsoft.com cli (#20252)
  • +
  • Add mariner arm64 to PMC release (#20251)
  • +
  • Add mariner arm64 package build to release build (#20250)
  • +
  • Make PR creation tool use --web because it is more reliable (#20247)
  • +
  • Update variable used to bypass the blocking check for multiple NuGet feeds (#20246)
  • +
  • Publish rpm package for rhel9 (#20245)
  • +
  • Add runtime and packaging type info for mariner2 arm64 (#20244)
  • +
+ +
+ +### Documentation and Help Content + +- Update man page to match current help for pwsh (#20249) + +[7.3.7]: https://github.com/PowerShell/PowerShell/compare/v7.3.6...v7.3.7 + +## [7.3.6] - 2023-07-13 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to 7.0.306

+ +
+ +
    +
  • Update Notices file
  • +
  • Don't publish notice on failure because it prevents retry
  • +
  • Bump .NET to 7.0.306 (#19945)
  • +
  • Remove the property disabling optimization (#19952)
  • +
  • Add ProductCode in registry for MSI install (#19951)
  • +
  • Update variable used to bypass the blocking check for multiple NuGet feeds (#19953)
  • +
  • Change System.Security.AccessControl preview version to stable version (#19931)
  • +
+ +
+ +### Documentation and Help Content + +- Update the link for getting started in `README.md` (#19947) + +[7.3.6]: https://github.com/PowerShell/PowerShell/compare/v7.3.5...v7.3.6 + +## [7.3.5] - 2023-06-27 + +### Build and Packaging Improvements + +
+ + + +

Bump to use .NET 7.0.305

+ +
+ +
    +
  • Update the ThirdPartyNotice (Internal 26372)
  • +
  • Add PoolNames variable group to compliance pipeline (#19408)
  • +
  • Update cgmanifest.json
  • +
  • Update to .NET 7.0.304 (#19807)
  • +
  • Disable SBOM signing for CI and add extra files for packaging tests (#19729)
  • +
  • Increase timeout to make subsystem tests more reliable (#18380)
  • +
  • Increase the timeout when waiting for the event log (#19264)
  • +
  • Implement IDisposable in NamedPipeClient (#18341) (Thanks @xtqqczze!)
  • +
  • Always regenerate files wxs fragment (#19196)
  • +
  • Bump Microsoft.PowerShell.MarkdownRender (#19751)
  • +
  • Delete symbols on Linux as well (#19735)
  • +
  • Add prompt to fix conflict during backport (#19583)
  • +
  • Add backport function to release tools (#19568)
  • +
  • Add an explicit manual stage for changelog update (#19551)
  • +
  • Update the team member list in releaseTools.psm1 (#19544)
  • +
  • Verify that packages have license data (#19543)
  • +
  • Fix the regex used for package name check in vPack build (#19511)
  • +
  • Make the vPack PAT library more obvious (#19505)
  • +
  • Update the metadata.json to mark 7.3 releases as latest for stable channel (#19565)
  • +
+ +
+ +[7.3.5]: https://github.com/PowerShell/PowerShell/compare/v7.3.4...v7.3.5 + +## [7.3.4] - 2023-04-12 + +### Engine Updates and Fixes + +- Add instrumentation to `AmsiUtil` and make the `init` variable readonly (#18727) +- Fix support for `NanoServer` due to the lack of AMSI (#18882) +- Adding missing guard for telemetry optout to avoid `NullReferenceException` when importing modules (#18949) (Thanks @powercode!) +- Fix `VtSubstring` helper method to correctly check chars copied (#19240) +- Fix `ConciseView` to handle custom `ParserError` error records (#19239) + +### Build and Packaging Improvements + +
+ + + +

Bump to use .NET 7.0.5

+ +
+ +
    +
  • Update ThirdPartyNotices.txt
  • +
  • Update cgmanifest.json
  • +
  • Fix the template that creates nuget package
  • +
  • Update the wix file
  • +
  • Update to .NET SDK 7.0.203
  • +
  • Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413)
  • +
  • Improve package management acceptance tests by not going to the gallery (#19412)
  • +
  • Fix stage dependencies and typo in release build (#19353)
  • +
  • Fix issues in release build and release pipeline (#19338)
  • +
  • Restructure the package build to simplify signing and packaging stages (#19321)
  • +
  • Test fixes for stabilizing tests (#19068)
  • +
  • Add stage for symbols job in Release build (#18937)
  • +
  • Use reference assemblies generated by dotnet (#19302)
  • +
  • Add URL for all distributions (#19159)
  • +
+ +
+ +[7.3.4]: https://github.com/PowerShell/PowerShell/compare/v7.3.3...v7.3.4 + +## [7.3.3] - 2023-02-23 + +### Build and Packaging Improvements + +
+ + + +

Bump to use .NET 7.0.3

+ +
+ +
    +
  • Update third party notices for v7.3.3 (Internal 24353)
  • +
  • Add tool to trigger license information gathering for NuGet modules (#18827)
  • +
  • Update global.json to 7.0.200 for v7.3.3 (Internal 24334)
  • +
  • Update cgmanifest for v7.3.3 (Internal 24338)
  • +
+ +
+ +[7.3.3]: https://github.com/PowerShell/PowerShell/compare/v7.3.2...v7.3.3 + +## [7.3.2] - 2023-01-24 + +### Engine Updates and Fixes + +- Fix `SuspiciousContentChecker.Match` to detect a predefined string when the text starts with it (#18916) +- Fix for JEA session leaking functions (Internal 23820) + +### General Cmdlet Updates and Fixes + +- Fix `Start-Job` to check the existence of working directory using the PowerShell way (#18917) +- Fix `Switch-Process` error to include the command that is not found (#18650) + +### Tests + +- Allow system lock down test debug hook to work with new `WLDP` API (fixes system lock down tests) (#18962) + +### Build and Packaging Improvements + +
+ + + +

Bump to use .NET 7.0.2

+ +
+ +
    +
  • Update dependencies for .NET release (Internal 23818)
  • +
  • Remove unnecessary reference to System.Runtime.CompilerServices.Unsafe (#18918)
  • +
  • Add bootstrap after SBOM task to re-install .NET (#18891)
  • +
+ +
+ +[7.3.2]: https://github.com/PowerShell/PowerShell/compare/v7.3.1...v7.3.2 + +## [7.3.1] - 2022-12-13 + +### Engine Updates and Fixes + +- Remove TabExpansion for PSv2 from remote session configuration (Internal 23331) +- Add `sqlcmd` to list to use legacy argument passing (#18645 #18646) +- Change `exec` from alias to function to handle arbitrary args (#18644) +- Fix `Switch-Process` to copy the current env to the new process (#18632) +- Fix issue when completing the first command in a script with an empty array expression (#18355) +- Fix `Switch-Process` to set `termios` appropriate for child process (#18572) +- Fix native access violation (#18571) + +### Tests + +- Backport CI fixed from #18508 (#18626) +- Mark charset test as pending (#18609) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+ +
+ +
    +
  • Update packages (Internal 23330)
  • +
  • Apply expected file permissions to linux files after authenticode signing (#18647)
  • +
  • Bump System.Data.SqlClient (#18573)
  • +
  • Don't install based on build-id for RPM (#18570)
  • +
  • Work around args parsing issue (#18607)
  • +
  • Fix package download in vPack job
  • +
+ +
+ +[7.3.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0...v7.3.1 + +## [7.3.0] - 2022-11-08 + +### General Cmdlet Updates and Fixes + +- Correct calling cmdlet `New-PSSessionOption` in script for `Restart-Computer` (#18374) + +### Tests + +- Add test for framework dependent package in release pipeline (Internal 23139) + +### Build and Packaging Improvements + +
+ + + +

Bump to use internal .NET 7 GA build (Internal 23096)

+ +
+ +
    +
  • Fix issues with building test artifacts (Internal 23116)
  • +
  • Use AzFileCopy task instead of AzCopy.exe
  • +
  • Remove AzCopy installation from msixbundle step
  • +
  • Add TSAUpload for APIScan (#18446)
  • +
  • Add authenticode signing for assemblies on Linux builds (#18440)
  • +
  • Do not remove penimc_cor3.dll from build (#18438)
  • +
  • Allow two-digit revisions in vPack package validation pattern (#18392)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-rc.1 to 7.3.0 (#18413)
  • +
+ +
+ +[7.3.0]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-rc.1...v7.3.0 + +## [7.3.0-rc.1] - 2022-10-26 + +### Breaking Change + +- Update to use `ComputeCore.dll` for PowerShell Direct (#18194) + +### Engine Updates and Fixes + +- On Unix, explicitly terminate the native process during cleanup only if it's not running in background (#18215) + +### General Cmdlet Updates and Fixes + +- Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) + +### Tests + +- Add missing `-Tag 'CI'` to describe blocks. (#18317) + +### Build and Packaging Improvements + +
+ + +

Bump to .NET 7 to 7.0.100-rc.2.22477.20 (#18328)(#18286)

+
+ +
    +
  • Update ThirdPartyNotices (Internal 22987)
  • +
  • Remove API sets (#18304) (#18376)
  • +
  • Do not cleanup pwsh.deps.json for framework dependent packages (#18300)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-preview.1 to 7.3.0-rc.1 (#18217)
  • +
  • Remove unnecessary native dependencies from the package (#18213)
  • +
  • Make the link to minimal package blob public during release (#18158)
  • +
  • Create tasks to collect and publish hashes for build files. (#18276)(#18277)
  • +
  • Add branch counter to compliance build (#18214)
  • +
  • Move APIScan to compliance build (#18191)
  • +
  • Update MSI exit message (#18137)
  • +
  • Remove XML files for min-size package (#18189)
  • +
+ +
+ +[7.3.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.8...v7.3.0-rc.1 + +## [7.3.0-preview.8] - 2022-09-20 + +### General Cmdlet Updates and Fixes + +- Filter out compiler generated types for `Add-Type -PassThru` (#18095) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) +- Handle `PSObject` argument specially in method invocation logging (#18060) +- Revert the experimental feature `PSStrictModeAssignment` (#18040) +- Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) +- Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) +- Make experimental feature `PSCleanBlock` stable (#18043) +- Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) +- Make experimental feature `PSExec` stable (#18045) +- Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) +- Add the `ConfigurationFile` option to the PowerShell help content (#18093) + +### Build and Packaging Improvements + + +

Bump .NET SDK to version `7.0.100-rc.1`

+
+ +
+
    +
  • Update ThirdPartyNotices.txt for 7.3.0-preview.8 (Internal 22553)
  • +
  • Update cgmanifest.json for 7.3.0-preview.8 (Internal 22551)
  • +
  • Re-enable building with Ready-to-Run (#18107)
  • +
  • Make sure Security.types.ps1xml gets signed in release build (#17930)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 RC1 build (#18106)
  • +
  • Add XML reference documents to NuPkg files for SDK (#18017)
  • +
  • Make Register MU timeout (#17995)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17924)
  • +
  • Update list of PS team members in release tools (#17928)
  • +
  • Update to use version 2.21.0 of Application Insights (#17927)
  • +
  • Complete ongoing Write-Progress in test (#17922)
  • +
+
+ +[7.3.0-preview.8]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.7...v7.3.0-preview.8 + +## [7.3.0-preview.7] - 2022-08-09 + +### Breaking Changes + +- Move the type data definition of `System.Security.AccessControl.ObjectSecurity` to the `Microsoft.PowerShell.Security` module (#16355) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Enable searching for assemblies in `GAC_Arm64` on Windows (#17816) +- Fix parser exception in using statements with empty aliases (#16745) (Thanks @MartinGC94!) +- Do not always collapse space between parameter and value for native arguments. (#17708) +- Remove `PSNativePSPathResolution` experimental feature (#17670) + +### General Cmdlet Updates and Fixes + +- Fix for deserializing imported ordered dictionary (#15545) (Thanks @davidBar-On!) +- Make generated implicit remoting modules backward compatible with PowerShell 5.1 (#17227) (Thanks @Tadas!) +- Re-enable IDE0031: Use Null propagation (#17811) (Thanks @fflaten!) +- Allow commands to still be executed even if the current working directory no longer exists (#17579) +- Stop referencing `Microsoft.PowerShell.Security` when the core snapin is used (#17771) +- Add support for HTTPS with `Set-AuthenticodeSignature -TimeStampServer` (#16134) (Thanks @Ryan-Hutchison-USAF!) +- Add type accelerator `ordered` for `OrderedDictionary` (#17804) (Thanks @fflaten!) +- Fix the definition of the `PDH_COUNTER_INFO` struct (#17779) +- Adding Virtualization Based Security feature names to Get-ComputerInfo (#16415) (Thanks @mattifestation!) +- Fix `FileSystemProvider` to work with volume and pipe paths (#15873) +- Remove pre-parse for array-based JSON (#15684) (Thanks @strawgate!) +- Improve type inference for `$_` (#17716) (Thanks @MartinGC94!) +- Prevent braces from being removed when completing variables (#17751) (Thanks @MartinGC94!) +- Fix type inference for `ICollection` (#17752) (Thanks @MartinGC94!) +- Fix `Test-Json` not handling non-object types at root (#17741) (Thanks @dkaszews!) +- Change `Get-ChildItem` to treat trailing slash in path as indicating a directory when used with `-Recurse` (#17704) +- Add `find.exe` to legacy argument binding behavior for Windows (#17715) +- Add completion for index expressions for dictionaries (#17619) (Thanks @MartinGC94!) +- Fix enum-ranges for `ValidateRange` in proxy commands (#17572) (Thanks @fflaten!) +- Fix type completion for attribute tokens (#17484) (Thanks @MartinGC94!) +- Add `-noprofileloadtime` switch to `pwsh` (#17535) (Thanks @rkeithhill!) +- Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) +- Improve dynamic parameter tab completion (#17661) (Thanks @MartinGC94!) +- Avoid binding positional parameters when completing parameter in front of value (#17693) (Thanks @MartinGC94!) +- Render decimal numbers in a table using current culture (#17650) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@fflaten, @Molkree, @eltociear

+ +
+ +
    +
  • Fix other path constructions using Path.Join (#17825)
  • +
  • Use null propagation (#17787)(#17789)(#17790)(#17791)(#17792)(#17795) (Thanks @fflaten!)
  • +
  • Re-enable compound assignment preference (#17784) (Thanks @Molkree!)
  • +
  • Use null-coalescing assignment (#17719)(#17720)(#17721)(#17722)(#17723)(#17724)(#17725)(#17726)(#17727)(#17728)(#17729) (Thanks @Molkree!)
  • +
  • Disable the warning IDE0031 to take .NET 7 Preview 7 (#17770)
  • +
  • Fix typo in ModuleCmdletBase.cs (#17714) (Thanks @eltociear!)
  • +
+ +
+ +### Tests + +- Re-enable tests because the corresponding dotnet issues were fixed (#17839) +- Add test for `LanguageMode` using remoting (#17803) (Thanks @fflaten!) +- Fix test perf by stopping ongoing `write-progress` (#17749) (Thanks @fflaten!) +- Re-enable the test `TestLoadNativeInMemoryAssembly` (#17738) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@varunsh-coder, @dkaszews, @Molkree, @ChuckieChen945

+ +
+ +
    +
  • Update release pipeline to use Approvals and automate some manual tasks (#17837)
  • +
  • Add GitHub token permissions for workflows (#17781) (Thanks @varunsh-coder!)
  • +
  • Bump actions/github-script from 3 to 6 (#17842)
  • +
  • Bump cirrus-actions/rebase from 1.6 to 1.7 (#17843)
  • +
  • Remove unneeded verbose message in build (#17840)
  • +
  • Detect default runtime using dotnet --info in build.psm1 (#17818) (Thanks @dkaszews!)
  • +
  • Bump actions/checkout from 2 to 3 (#17828)
  • +
  • Bump actions/download-artifact from 2 to 3 (#17829)
  • +
  • Bump github/codeql-action from 1 to 2 (#17830)
  • +
  • Bump peter-evans/create-pull-request from 3 to 4 (#17831)
  • +
  • Bump actions/upload-artifact from 2 to 3 (#17832)
  • +
  • Enable Dependabot for GitHub Actions (#17775) (Thanks @Molkree!)
  • +
  • Update .NET SDK version from 7.0.100-preview.6.22352.1 to 7.0.100-preview.7.22377.5 (#17776)
  • +
  • Fix a bug in install-powershell.ps1 (#17794) (Thanks @ChuckieChen945!)
  • +
  • Bump xunit from 2.4.1 to 2.4.2 (#17817)
  • +
  • Update how to update homebrew (#17798)
  • +
  • Don't run link check on forks (#17797)
  • +
  • Update dotnetmetadata.json to start consuming .NET 7 preview 7 builds (#17736)
  • +
  • Bump PackageManagement from 1.4.7 to 1.4.8.1 (#17709)
  • +
  • Exclude ARM images from running in CI (#17713)
  • +
+ +
+ +### Documentation and Help Content + +- Update the comment about why R2R is disabled (#17850) +- Update changelog and `.spelling` for `7.3.0-preview.6` release (#17835) +- Updated `ADOPTERS.md` for Power BI (#17766) +- Update README.md with the current Fedora version (#15717) (Thanks @ananya26-vishnoi!) +- Update `README` and `metadata.json` for next release (#17676) (Thanks @SeeminglyScience!) + +[7.3.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.6...v7.3.0-preview.7 + +## [7.3.0-preview.6] - 2022-07-18 + +### General Cmdlet Updates and Fixes + +- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) +- Change `ConvertFrom-Json -AsHashtable` to use ordered hashtable (#17405) +- Remove potential ANSI escape sequences in strings before using in `Out-GridView` (#17664) +- Add the `-Milliseconds` parameter to `New-TimeSpan` (#17621) (Thanks @NoMoreFood!) +- Update `Set-AuthenticodeSignature` to use `SHA256` as the default (#17560) (Thanks @jborean93!) +- Fix tab completion regression when completing `ValidateSet` values (#17628) (Thanks @MartinGC94!) +- Show optional parameters as such when displaying method definition and overloads (#13799) (Thanks @eugenesmlv!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@sethvs, @MartinGC94, @eltociear

+ +
+ +
    +
  • Fix comment in InternalCommands.cs (#17669) (Thanks @sethvs!)
  • +
  • Use discards for unused variables (#17620) (Thanks @MartinGC94!)
  • +
  • Fix typo in CommonCommandParameters.cs (#17524) (Thanks @eltociear!)
  • +
+ +
+ +### Tests + +- Fix SDK tests for release build (#17678) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@tamasvajk

+ +
+ +
    +
  • Create test artifacts for Windows ARM64 (#17675)
  • +
  • Update to the latest NOTICES file (#17607)
  • +
  • Update .NET SDK version from 7.0.100-preview.5.22307.18 to 7.0.100-preview.6.22352.1 (#17634)
  • +
  • Set the compound assignment preference to false (#17632)
  • +
  • Update DotnetMetadata.json to start consuming .NET 7 Preview 6 builds (#17630)
  • +
  • Install .NET 3.1 as it is required by the vPack task (#17600)
  • +
  • Update to use PSReadLine v2.2.6 (#17595)
  • +
  • Fix build.psm1 to not specify both version and quality for dotnet-install (#17589) (Thanks @tamasvajk!)
  • +
  • Bump Newtonsoft.Json in /test/perf/dotnet-tools/Reporting (#17592)
  • +
  • Bump Newtonsoft.Json in /test/perf/dotnet-tools/ResultsComparer (#17566)
  • +
  • Disable RPM SBOM test. (#17532)
  • +
+ +
+ +### Documentation and Help Content + +- Remove `katacoda.com` from doc as it now returns 404 (#17625) +- Update changelog for `v7.2.5` and `v7.3.0-preview.5` (#17565) +- Update `README.md` and `metadata.json` for upcoming releases (#17526) + +[7.3.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.5...v7.3.0-preview.6 + +## [7.3.0-preview.5] - 2022-06-21 + +### Engine Updates and Fixes + +- Improve type inference and completions (#16963) (Thanks @MartinGC94!) +- Make `Out-String` and `Out-File` keep string input unchanged (#17455) +- Make `AnsiRegex` able to capture Hyperlink ANSI sequences (#17442) +- Add the `-ConfigurationFile` command-line parameter to `pwsh` to support local session configuration (#17447) +- Fix native library loading for `osx-arm64` (#17365) (Thanks @awakecoding!) +- Fix formatting to act appropriately when the style of table header or list label is empty string (#17463) + +### General Cmdlet Updates and Fixes + +- Fix various completion issues inside the `param` block (#17489) (Thanks @MartinGC94!) +- Add Amended switch to `Get-CimClass` cmdlet (#17477) (Thanks @iSazonov!) +- Improve completion on operators (#17486) (Thanks @MartinGC94!) +- Improve array element completion for command arguments (#17078) (Thanks @matt9ucci!) +- Use AST extent for `PSScriptRoot` path completion (#17376) +- Add type inference support for generic methods with type parameters (#16951) (Thanks @MartinGC94!) +- Write out OSC indicator only if the `stdout` is not redirected (#17419) +- Remove the assert and use a relatively larger capacity to cover possible increase of .NET reference assemblies (#17423) +- Increase reference assembly count to 161 (#17420) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@Yulv-git, @eltociear

+ +
+ +
    +
  • Fix some typos in source code (#17481) (Thanks @Yulv-git!)
  • +
  • Fix typo in `AsyncResult.cs` (#17396) (Thanks @eltociear!)
  • +
+ +
+ +### Tools + +- Update script to pin to .NET 7 preview 5 version (#17448) +- Start-PSPester: argument completer for `-Path` (#17334) (Thanks @powercode!) +- Add reminder workflows (#17387) +- Move to configuring the fabric bot via JSON (#17411) +- Update Documentation Issue Template URL (#17410) (Thanks @michaeltlombardi!) +- Update script to automatically take new preview prerelease builds (#17375) + +### Tests + +- Make Assembly Load Native test work on a FX Dependent Linux Install (#17380) +- Update `Get-Error` test to not depend on DNS APIs (#17471) + +### Build and Packaging Improvements + +
+ +
    +
  • Update .NET SDK version from 7.0.100-preview.4.22252.9 to 7.0.100-preview.5.22307.18 (#17402)
  • +
  • Downgrade the Microsoft.CodeAnalysis.NetAnalyzers package to 7.0.0-preview1.22217.1 (#17515)
  • +
  • Rename mariner package to cm (#17505)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17476)
  • +
  • Bump NJsonSchema from 10.7.1 to 10.7.2 (#17475)
  • +
  • Publish preview versions of mariner to preview repo (#17451)
  • +
  • Update to the latest NOTICES file (#17421)
  • +
  • Do not publish package for Mariner 1.0 (#17415)
  • +
  • Add AppX capabilities in MSIX manifest so that PS7 can call the AppX APIs (#17416)
  • +
  • Update to the latest NOTICES file (#17401)
  • +
  • Fix mariner mappings (#17413)
  • +
  • Update the cgmanifest (#17393)
  • +
  • Bump `NJsonSchema` from `10.7.0` to `10.7.1` (#17381)
  • +
+ +
+ +### Documentation and Help Content + +- Update to the latest NOTICES file (#17493) (Thanks @github-actions[bot]!) +- Update the cgmanifest (#17478) (Thanks @github-actions[bot]!) +- Correct spelling in Comments and tests (#17480) (Thanks @Yulv-git!) +- Fix spelling errors introduced in changelog (#17414) +- Update changelog for v7.3.0-preview.4 release (#17412) +- Update readme and metadata for 7.3.0-preview.4 release (#17378) + +[7.3.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.4...v7.3.0-preview.5 + +## [7.3.0-preview.4] - 2022-05-23 + +### Engine Updates and Fixes + +
    +
  • Remove the use of BinaryFormatter in PSRP serialization (#17133) (Thanks @jborean93!)
  • +
  • Update telemetry collection removing unused data and adding some new data (#17304)
  • +
  • Fix the word wrapping in formatting to handle escape sequences properly (#17316)
  • +
  • Fix the error message in Hashtable-to-object conversion (#17329)
  • +
  • Add support for new WDAC API (#17247)
  • +
  • On Windows, reset cursor visibility back to previous state when rendering progress (#16782)
  • +
  • Fix the list view to not leak VT decorations (#17262)
  • +
  • Fix formatting truncation to handle strings with VT sequences (#17251)
  • +
  • Fix line breakpoints for return statements without a value (#17179)
  • +
  • Fix for partial PowerShell module search paths, that can be resolved to CWD locations (#17231) (Internal 20126)
  • +
  • Change logic in the testing helper module for determining whether PSHOME is writable (#17218)
  • +
  • Make a variable assignment in a ParenExpression to return the variable value (#17174)
  • +
  • Use new Windows signature APIs from Microsoft.Security.Extensions package (#17159)
  • +
  • Do not include node names when sending telemetry. (#16981)
  • +
  • Support forward slashes in network share (UNC path) completion (#17111) (#17117) (Thanks @sba923!)
  • +
  • Do not generate clean block in proxy function when the feature is disabled (#17112)
  • +
  • Ignore failure attempting to set console window title (#16948)
  • +
  • Update regex used to remove ANSI escape sequences to be more specific to decoration and CSI sequences (#16811)
  • +
  • Improve member auto completion (#16504) (Thanks @MartinGC94!)
  • +
  • Prioritize ValidateSet completions over Enums for parameters (#15257) (Thanks @MartinGC94!)
  • +
  • Add Custom Remote Connections Feature (#17011)
  • +
+ +### General Cmdlet Updates and Fixes + +
    +
  • Add check for ScriptBlock wrapped in PSObject to $using used in ForEach-Object -Parallel (#17234) (Thanks @ryneandal!)
  • +
  • Fix ForEach method to set property on a scalar object (#17213)
  • +
  • Fix Sort-Object -Stable -Unique to actually do stable sorting (#17189) (Thanks @m1k0net!)
  • +
  • Add OutputType attribute to various commands (#16962) (Thanks @MartinGC94!)
  • +
  • Make Stop-Service only request needed privileges when not setting SDDL. (#16663) (Thanks @kvprasoon!)
  • +
+ +### Code Cleanup + +
    +
  • Remove EventLogLogProvider and its related legacy code (#17027)
  • +
  • Fix typos in names of method (#17003) (Thanks @al-cheb!)
  • +
  • SemanticChecks: Avoid repeated type resolution of [ordered] (#17328) (Thanks IISResetMe!)
  • +
  • Redo the change that was reverted by #15853 (#17357)
  • +
  • Correct spelling of pseudo in Compiler.cs (#17285) (Thanks @eltociear!)
  • +
  • MakeNameObscurerTelemetryInitializer internal (#17214)
  • +
  • Make NameObscurerTelemetryInitializer internal (#17167)
  • +
  • Correct Typo in the resource string PathResolvedToMultiple (#17098) (Thanks @charltonstanley!)
  • +
  • Fix typo in ComRuntimeHelpers.cs (#17104) (Thanks @eltociear!)
  • +
+ +### Documentation and Help Content + +
    +
  • Update link to PowerShell remoting in depth video (#17166)
  • +
+ +### Tests + +
    +
  • Add -because to the failing test to aid in debugging (#17030)
  • +
  • Simplify Enum generator for the -bnot operator test (#17014)
  • +
  • Improve unique naming for tests (#17043)
  • +
  • Use a random string for the missing help topic to improve the chances that the help topic really won't be found. (#17042)
  • +
+ +### Build and Packaging Improvements + +
    +
  • Update README.md and metadata.json for v7.3.0-preview.3 release (#17029)
  • +
  • Do not pull dotnet updates from internal feed (#17007)
  • +
  • Simplify Get-WSManSupport based on current .NET Distro Support (#17356)
  • +
  • Update to the latest NOTICES file (#17372, #17332, #17311, #17275)
  • +
  • Run on every PR and let the action skip (#17366)
  • +
  • Make sure verbose message is not null (#17363)
  • +
  • Release changelogs (#17364)
  • +
  • Update build versions (#17318)
  • +
  • Add Daily Link Check GitHub Workflow (#17351)
  • +
  • Update the cgmanifest (#17361, #17344, #17324, #17302, #17268)
  • +
  • Bump NJsonSchema from 10.6.10 to 10.7.0 (#17350)
  • +
  • Disable broken macOS CI job, which is unused (#17221)
  • +
  • Have rebase workflow Post a message when it starts (#17341)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 Preview 4 (#17336)
  • +
  • Update Ubuntu 22 to be detected as not supported WSMan (#17338)
  • +
  • Bump xunit.runner.visualstudio from 2.4.3 to 2.4.5 (#17274)
  • +
  • Make sure we execute tests on LTS package for older LTS releases (#17326)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.1.0 to 17.2.0 (#17320)
  • +
  • Add fedora to the OS's that can't run WSMan (#17325)
  • +
  • Add sles15 support to install-powershell.sh (#16984)
  • +
  • Start rotating through all images (#17315)
  • +
  • Update .NET SDK version from 7.0.100-preview.2.22153.17 to 7.0.100-preview.4.22252.9 (#17061)
  • +
  • Disable release security analysis for SSH CI (#17303)
  • +
  • Add a finalize template which causes jobs with issues to fail (#17314)
  • +
  • Add mapping for ubuntu22.04 jammy (#17317)
  • +
  • Enable more tests to be run in a container. (#17294)
  • +
  • Fix build.psm1 to find the required .NET SDK version when a higher version is installed (#17299)
  • +
  • Improve how Linux container CI builds are identified (#17295)
  • +
  • Only inject NuGet security analysis if we are using secure nuget.config (#17293)
  • +
  • Reduce unneeded verbose message from build.psm1 (#17291)
  • +
  • Switch to using GitHub action to verify Markdown links for PRs (#17281)
  • +
  • Put Secure supply chain analysis at correct place (#17273)
  • +
  • Fix build id variable name when selecting CI container (#17279)
  • +
  • Add rotation between the two mariner images (#17277)
  • +
  • Update to use mcr.microsoft.com (#17272)
  • +
  • Update engine working group members (#17271)
  • +
  • Bump PSReadLine from 2.2.2 to 2.2.5 in /src/Modules (#17252)
  • +
  • Update timeout for daily (#17263)
  • +
  • Bump NJsonSchema from 10.6.9 to 10.6.10 (#16902)
  • +
  • Update the cgmanifest (#17260)
  • +
  • Fix Generate checksum file for packages build failure - v7.1.7 (#17219) (Internal 20274)
  • +
  • Move cgmanifest generation to daily (#17258)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17245)
  • +
  • Update to the latest notice file (#17238)
  • +
  • Add container to Linux CI (#17233)
  • +
  • Mark Microsoft.Management.Infrastructure.Runtime.Win as a developer dependency to hide in notice file (#17230)
  • +
  • Fixing dotnet SDK version parsing in build.psm1 (#17198) (Thanks @powercode!)
  • +
  • Fixed package names verification to support multi-digit versions (#17220)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.2.0-1.final to 4.2.0-4.final (#17210)
  • +
  • Add backport action (#17212)
  • +
  • Updated changelogs for v7.0.9 / v7.0.10 / v7.1.6 / v7.1.7 / v7.2.2 / v7.2.3 (#17207)
  • +
  • Updated metadata.json and README.md for v7.2.3 and v7.0.10 (#17158)
  • +
  • Update package fallback list for ubuntu (from those updated for ubuntu 22.04) (deb) (#17180)
  • +
  • Update wix to include security extensions package (#17171)
  • +
  • Update rebase.yml (#17170)
  • +
  • Adds sha256 digests to RPM packages (#16896) (Thanks @ngharo!)
  • +
  • Make mariner packages Framework dependent (#17151)
  • +
  • Update to the latest notice file (#17169)
  • +
  • Update to the latest notice file (#17146)
  • +
  • Replace . in notices container name (#17154)
  • +
  • Allow multiple installations of dotnet. (#17141)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17105)
  • +
  • Update to the latest notice file (#16437)
  • +
  • Skip failing scriptblock tests (#17093)
  • +
  • Update dotnet-install script download link (#17086)
  • +
  • Fix the version of the Microsoft.CodeAnalysis.NetAnalyzers package (#17075)
  • +
  • Update dotnetmetadata.json to accept .NET 7 preview 3 builds (#17063)
  • +
  • Re-enable PowerShellGet tests targeting PowerShell gallery (#17062)
  • +
  • Add mariner 1.0 amd64 package (#17057)
  • +
  • Create checksum file for global tools (#17056)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17065)
  • +
  • Use new cask format (#17064)
  • +
+ +[7.3.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.3...v7.3.0-preview.4 + +## [7.3.0-preview.3] - 2022-03-21 + +### Engine Updates and Fixes + +- Fix the parsing code for .NET method generic arguments (#16937) +- Allow the `PSGetMemberBinder` to get value of `ByRef` property (#16956) +- Allow a collection that contains `Automation.Null` elements to be piped to pipeline (#16957) + +### General Cmdlet Updates and Fixes + +- Add the module `CompatPowerShellGet` to the allow-list of telemetry modules (#16935) +- Fix `Enter-PSHostProcess` and `Get-PSHostProcessInfo` cmdlets by handling processes that have exited (#16946) +- Improve Hashtable completion in multiple scenarios (#16498) (Thanks @MartinGC94!) + +### Code Cleanup + +- Fix a typo in `CommandHelpProvider.cs` (#16949) (Thanks @eltociear!) + +### Tests + +- Update a few tests to make them more stable in CI (#16944) +- Roll back Windows images used in testing to Windows Server 2019 (#16958) + +### Build and Packaging Improvements + +
+ + +

Update .NET SDK to 7.0.0-preview.2

+
+ +
    +
  • Update .NET to 7.0.0-preview.2 build (#16930)
  • +
  • Update AzureFileCopy task and fix the syntax for specifying pool (#17013)
  • +
+ +
+ +[7.3.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.2...v7.3.0-preview.3 + +## [7.3.0-preview.2] - 2022-02-24 + +### Engine Updates and Fixes + +- Fix the `clean` block for generated proxy function (#16827) +- Add support to allow invoking method with generic type arguments (#12412 and #16822) (Thanks @vexx32!) +- Report error when PowerShell built-in modules are missing (#16628) + +### General Cmdlet Updates and Fixes + +- Prevent command completion if the word to complete is a single dash (#16781) (Thanks @ayousuf23!) +- Use `FindFirstFileW` instead of `FindFirstFileExW` to correctly handle Unicode filenames on FAT32 (#16840) (Thanks @iSazonov!) +- Add completion for loop labels after Break/Continue (#16438) (Thanks @MartinGC94!) +- Support OpenSSH options for `PSRP` over SSH commands (#12802) (Thanks @BrannenGH!) +- Adds a `.ResolvedTarget` Property to `File-System` Items to Reflect a Symlink's Target as `FileSystemInfo` (#16490) (Thanks @hammy3502!) +- Use `NotifyEndApplication` to re-enable VT mode (#16612) +- Add new parameter to `Start-Sleep`: `[-Duration] ` (#16185) (Thanks @IISResetMe!) +- Add lock and null check to remoting internals (#16542) (#16683) (Thanks @SergeyZalyadeev!) +- Make `Measure-Object` ignore missing properties unless running in strict mode (#16589) (Thanks @KiwiThePoodle!) +- Add `-StrictMode` to `Invoke-Command` to allow specifying strict mode when invoking command locally (#16545) (Thanks @Thomas-Yu!) +- Fix `$PSNativeCommandArgPassing` = `Windows` to handle empty args correctly (#16639) +- Reduce the amount of startup banner text (#16516) (Thanks @rkeithhill!) +- Add `exec` cmdlet for bash compatibility (#16462) +- Add AMSI method invocation logging as experimental feature (#16496) +- Fix web cmdlets so that an empty `Get` does not include a `content-length` header (#16587) +- Update `HelpInfoUri` for 7.3 release (#16646) +- Fix parsing `SemanticVersion` build label from version string (#16608) +- Fix `ForEach-Object -Parallel` when passing in script block variable (#16564) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @iSazonov, @xtqqczze

+ +
+ +
    +
  • Fix typo in PowerShellExecutionHelper.cs (#16776) (Thanks @eltociear!)
  • +
  • Use more efficient platform detection API (#16760) (Thanks @iSazonov!)
  • +
  • Seal ClientRemotePowerShell (#15802) (Thanks @xtqqczze!)
  • +
  • Fix the DSC overview URL in a Markdown file and some small cleanup changes (#16629)
  • +
+ +
+ +### Tools + +- Fix automation to update experimental JSON files in GitHub action (#16837) + +### Tests + +- Update `markdownlint` to the latest version (#16825) +- Bump the package `path-parse` from `1.0.6` to `1.0.7` (#16820) +- Remove assert that is incorrect and affecting our tests (#16588) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@dahlia

+ +
+ +
    +
  • Update NuGet Testing to not re-install dotnet, +when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269, 19272, 19273, and 19274)
  • +
  • Remove SkipExperimentalFeatureGeneration when building alpine (Internal 19248)
  • +
  • Revert .NET 7 changes, Update to the latest .NET 6 and Update WXS file due to blocking issue in .NET 7 Preview 1
  • +
  • Install and Find AzCopy
  • +
  • Use Start-PSBootStrap for installing .NET during nuget packaging
  • +
  • Fix pool syntax for deployments (Internal 19189)
  • +
  • Bump NJsonSchema from 10.5.2 to 10.6.9 (#16888)
  • +
  • Update projects and scripts to use .NET 7 preview 1 prerelease builds (#16856)
  • +
  • Add warning messages when package precheck fails (#16867)
  • +
  • Refactor Global Tool packaging to include SBOM generation (#16860)
  • +
  • Update to use windows-latest as the build agent image (#16831)
  • +
  • Ensure alpine and arm SKUs have powershell.config.json file with experimental features enabled (#16823)
  • +
  • Update experimental feature json files (#16838) (Thanks @github-actions[bot]!)
  • +
  • Remove WiX install (#16834)
  • +
  • Add experimental json update automation (#16833)
  • +
  • Update .NET SDK to 6.0.101 and fix Microsoft.PowerShell.GlobalTool.Shim.csproj (#16821)
  • +
  • Add SBOM manifest to nuget packages (#16711)
  • +
  • Improve logic for updating .NET in CI (#16808)
  • +
  • Add Linux package dependencies for packaging (#16807)
  • +
  • Switch to our custom images for build and release (#16801)
  • +
  • Remove all references to cmake for the builds in this repo (#16578)
  • +
  • Fix build for new InvokeCommand attributes (#16800)
  • +
  • Let macOS installer run without Rosetta on Apple Silicon (#16742) (Thanks @dahlia!)
  • +
  • Update the expect .NET SDK quality to GA for installing dotnet (#16784)
  • +
  • Change nuget release yaml to use UseDotNet task (#16701)
  • +
  • Bump Microsoft.ApplicationInsights from 2.19.0 to 2.20.0 (#16642)
  • +
  • Register NuGet source when generating CGManifest (#16570)
  • +
  • Update Images used for release (#16580)
  • +
  • Update SBOM generation (#16641)
  • +
  • Bring changes from 7.3.0-preview.1 (#16640)
  • +
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • +
  • Update macOS build image and root folder for build (#16609)
  • +
  • Disabled Yarn cache in markdown.yml (#16599)
  • +
  • Update cgmanifest (#16600)
  • +
  • Fix broken links in Markdown (#16598)
  • +
+ +
+ +### Documentation and Help Content + +- Add newly joined members to their respective Working Groups (#16849) +- Update Engine Working Group members (#16780) +- Replace the broken link about pull request (#16771) +- Update changelog to remove a broken URL (#16735) +- Updated `README.md` and `metadata.json` for `v7.3.0-preview.1` release (#16627) +- Updating changelog for `7.2.1` (#16616) +- Updated `README.md` and `metadata.json` for `7.2.1` release (#16586) + +[7.3.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.1...v7.3.0-preview.2 + +## [7.3.0-preview.1] - 2021-12-16 + +### Breaking Changes + +- Add `clean` block to script block as a peer to `begin`, `process`, and `end` to allow easy resource cleanup (#15177) +- Change default for `$PSStyle.OutputRendering` to `Ansi` (Internal 18449) + +### Engine Updates and Fixes + +- Remove duplicate remote server mediator code (#16027) +- Fix `PSVersion` parameter version checks and error messages for PowerShell 7 remoting (#16228) +- Use the same temporary home directory when `HOME` env variable is not set (#16263) +- Fix parser to generate error when array has more than 32 dimensions (#16276) + +### Performance + +- Avoid validation for built-in file extension and color VT sequences (#16320) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Update `README.md` and `metadata.json` for next preview release (#16107) +- Use `PlainText` when writing to a host that doesn't support VT (#16092) +- Remove support for `AppExeCLinks` to retrieve target (#16044) +- Move `GetOuputString()` and `GetFormatStyleString()` to `PSHostUserInterface` as public API (#16075) +- Fix `ConvertTo-SecureString` with key regression due to .NET breaking change (#16068) +- Fix regression in `Move-Item` to only fallback to `copy and delete` in specific cases (#16029) +- Set `$?` correctly for command expression with redirections (#16046) +- Use `CurrentCulture` when handling conversions to `DateTime` in `Add-History` (#16005) (Thanks @vexx32!) +- Fix link header parsing to handle unquoted `rel` types (#15973) (Thanks @StevenLiekens!) +- Fix a casting error when using `$PSNativeCommandUsesErrorActionPreference` (#15993) +- Format-Wide: Fix `NullReferenceException` (#15990) (Thanks @DarylGraves!) +- Make the native command error handling optionally honor `ErrorActionPreference` (#15897) +- Remove declaration of experimental features in Utility module manifest as they are stable (#16460) +- Fix race condition between `DisconnectAsync` and `Dispose` (#16536) (Thanks @i3arnon!) +- Fix the `Max_PATH` condition check to handle long path correctly (#16487) (Thanks @Shriram0908!) +- Update `HelpInfoUri` for 7.2 release (#16456) +- Fix tab completion within the script block specified for the `ValidateScriptAttribute`. (#14550) (Thanks @MartinGC94!) +- Update `README.md` to specify gathered telemetry (#16379) +- Fix typo for "privacy" in MSI installer (#16407) +- Remove unneeded call to `File.ResolveLinkTarget` from `IsWindowsApplication` (#16371) (Thanks @iSazonov!) +- Add `-HttpVersion` parameter to web cmdlets (#15853) (Thanks @hayhay27!) +- Add support to web cmdlets for open-ended input tags (#16193) (Thanks @farmerau!) +- Add more tests to `Tee-Object -Encoding` (#14539) (Thanks @rpolley!) +- Don't throw exception when trying to resolve a possible link path (#16310) +- Fix `ConvertTo-Json -Depth` to allow 100 at maximum (#16197) (Thanks @KevRitchie!) +- Fix for SSH remoting when banner is enabled on SSHD endpoint (#16205) +- Disallow all COM for AppLocker system lock down (#16268) +- Configure `ApplicationInsights` to not send cloud role name (#16246) +- Disallow `Add-Type` in NoLanguage mode on a locked down machine (#16245) +- Specify the executable path as `TargetObect` for non-zero exit code `ErrorRecord` (#16108) (Thanks @rkeithhill!) +- Don't allow `Move-Item` with FileSystemProvider to move a directory into itself (#16198) +- Make property names for the color VT sequences consistent with documentations (#16212) +- Fix `PipelineVariable` to set variable in the right scope (#16199) +- Invoke-Command: improve handling of variables with $using: expression (#16113) (Thanks @dwtaber!) +- Change `Target` from a `CodeProperty` to be an `AliasProperty` that points to `FileSystemInfo.LinkTarget` (#16165) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @eltociear, @iSazonov

+ +
+ +
    +
  • Improve CommandInvocationIntrinsics API documentation and style (#14369)
  • +
  • Use bool?.GetValueOrDefault() in FormatWideCommand (#15988) (Thanks @xtqqczze!)
  • +
  • Remove 4 assertions which cause debug build test runs to fail (#15963)
  • +
  • Fix typo in `Job.cs` (#16454) (Thanks @eltociear!)
  • +
  • Remove unnecessary call to `ToArray` (#16307) (Thanks @iSazonov!)
  • +
  • Remove the unused `FollowSymLink` function (#16231)
  • +
  • Fix typo in `TypeTable.cs` (#16220) (Thanks @eltociear!)
  • +
  • Fixes #16176 - replace snippet tag with code tag in comments (#16177)
  • +
+ +
+ +### Tools + +- Fix typo in build.psm1 (#16038) (Thanks @eltociear!) +- Add `.stylecop` to `filetypexml` and format it (#16025) +- Enable sending Teams notification when workflow fails (#15982) +- Use `Convert-Path` for unknown drive in `Build.psm1` (#16416) (Thanks @matt9ucci!) + +### Tests + +- Add benchmark to test compiler performance (#16083) +- Enable two previously disabled `Get-Process` tests (#15845) (Thanks @iSazonov!) +- Set clean state before testing `UseMU` in the MSI (#16543) +- Fix global tool and SDK tests in release pipeline (#16342) +- Remove the outdated test (#16269) +- Removed old not-used-anymore docker-based tests for PS release packages (#16224) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@github-actions[bot], @kondratyev-nv

+ +
+ +
    +
  • fix issue with hash file getting created before we have finished get-childitem (#16170)
  • +
  • Add sha256 hashes to release (#16147)
  • +
  • Change path for Component Governance for build to the path we actually use to build (#16137)
  • +
  • Update Microsoft.CodeAnalysis.CSharp version (#16138)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16070)
  • +
  • Update .NET to 6.0.100-rc.1.21458.32 (#16066)
  • +
  • Update minimum required OS version for macOS (#16088)
  • +
  • Set locale correctly on Linux CI (#16073)
  • +
  • Ensure locale is set correctly on Ubuntu 20.04 in CI (#16067)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16045)
  • +
  • Update .NET SDK version from `6.0.100-rc.1.21430.44` to `6.0.100-rc.1.21455.2` (#16041) (Thanks @github-actions[bot]!)
  • +
  • Fix the GitHub Action for updating .NET daily builds (#16042)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.0.0-3.final to 4.0.0-4.21430.4 (#16036)
  • +
  • Bump .NET to `6.0.100-rc.1.21430.44` (#16028)
  • +
  • Move from PkgES hosted agents to 1ES hosted agents (#16023)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16021)
  • +
  • Update Ubuntu images to use Ubuntu 20.04 (#15906)
  • +
  • Fix the mac build by updating the pool image name (#16010)
  • +
  • Use Alpine 3.12 for building PowerShell for alpine (#16008)
  • +
  • Update .NET SDK version from `6.0.100-preview.6.21355.2` to `6.0.100-rc.1.21426.1` (#15648) (Thanks @github-actions[bot]!)
  • +
  • Ignore error from Find-Package (#15999)
  • +
  • Find packages separately for each source in UpdateDotnetRuntime.ps1 script (#15998)
  • +
  • Update metadata to start using .NET 6 RC1 builds (#15981)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#15985)
  • +
  • Merge the v7.2.0-preview.9 release branch back to GitHub master (#15983)
  • +
  • Publish global tool package for stable releases (#15961)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers to newer version (#15962)
  • +
  • Disabled Yarn cache in markdown.yml (#16599)
  • +
  • Update cgmanifest (#16600)
  • +
  • Fix broken links in Markdown (#16598)
  • +
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • +
  • Bring back pwsh.exe for framework dependent packages to support Start-Job (#16535)
  • +
  • Fix NuGet package generation in release build (#16509)
  • +
  • Add `Microsoft.PowerShell.Commands.SetStrictModeCommand.ArgumentToPSVersionTransformationAttribute` to list of patterns to remove for generated ref assembly (#16489)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from `4.0.0-6.final` to `4.0.1` (#16423)
  • +
  • use different containers for different branches (#16434)
  • +
  • Add import so we can use common GitHub workflow function. (#16433)
  • +
  • Remove prerelease .NET 6 build sources (#16418)
  • +
  • Update release instructions with link to new build (#16419)
  • +
  • Bump Microsoft.ApplicationInsights from 2.18.0 to 2.19.0 (#16413)
  • +
  • Update metadata.json to make 7.2.0 the latest LTS (#16417)
  • +
  • Make static CI a matrix (#16397)
  • +
  • Update metadata.json in preparation on 7.3.0-preview.1 release (#16406)
  • +
  • Update cgmanifest (#16405)
  • +
  • Add diagnostics used to take corrective action when releasing `buildInfoJson` (#16404)
  • +
  • `vPack` release should use `buildInfoJson` new to 7.2 (#16402)
  • +
  • Update the usage of metadata.json for getting LTS information (#16381)
  • +
  • Add checkout to build json stage to get `ci.psm1` (#16399)
  • +
  • Update CgManifest.json for 6.0.0 .NET packages (#16398)
  • +
  • Add current folder to the beginning of the module import (#16353)
  • +
  • Increment RC MSI build number by 100 (#16354)
  • +
  • Bump XunitXml.TestLogger from 3.0.66 to 3.0.70 (#16356)
  • +
  • Move PR Quantifier config to subfolder (#16352)
  • +
  • Release build info json when it is preview (#16335)
  • +
  • Add an approval for releasing build-info json (#16351)
  • +
  • Generate manifest with latest public version of the packages (#16337)
  • +
  • Update to the latest notices file (#16339) (Thanks @github-actions[bot]!)
  • +
  • Use notice task to generate license assuming cgmanifest contains all components (#16340)
  • +
  • Refactor cgmanifest generator to include all components (#16326)
  • +
  • Fix issues in release build (#16332)
  • +
  • Update feed and analyzer dependency (#16327)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.11.0 to 17.0.0 (#16312)
  • +
  • Update license and cgmanifest (#16325) (Thanks @github-actions[bot]!)
  • +
  • Fix condition in cgmanifest logic (#16324)
  • +
  • Add GitHub Workflow to keep notices up to date (#16284)
  • +
  • Update to latest .NET 6 GA build 6.0.100-rtm.21527.11 (#16309)
  • +
  • Create compliance build (#16286)
  • +
  • Move mapping file into product repo and add Debian 11 (#16316)
  • +
  • Add a major-minor build info JSON file (#16301)
  • +
  • Clean up crossgen related build scripts also generate native symbols for R2R images (#16297)
  • +
  • Fix Windows build ZIP packaging (#16299) (Thanks @kondratyev-nv!)
  • +
  • Revert "Update to use .NET 6 GA build (#16296)" (#16308)
  • +
  • Add wget as a dependency for Bootstrap script (#16303) (Thanks @kondratyev-nv!)
  • +
  • Fix issues reported by code signing verification tool (#16291)
  • +
  • Update to use .NET 6 GA build (#16296)
  • +
  • Revert "add GH workflow to keep the cgmanifest up to date." (#16294)
  • +
  • Update ChangeLog for 7.2.0-rc.1 and also fix RPM packaging (#16290)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16271)
  • +
  • add GH workflow to keep the cgmanifest up to date.
  • +
  • Update ThirdPartyNotices.txt (#16283)
  • +
  • Update `testartifacts.yml` to use ubuntu-latest image (#16279)
  • +
  • Update version of Microsoft.PowerShell.Native and Microsoft.PowerShell.MarkdownRender packages (#16277)
  • +
  • Add script to generate cgmanifest.json (#16278)
  • +
  • Add cgmanifest.json for generating correct third party notice file (#16266)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers from `6.0.0-rtm.21504.2` to `6.0.0-rtm.21516.1` (#16264)
  • +
  • Only upload stable buildinfo for stable releases (#16251)
  • +
  • Make RPM license recognized (#16189)
  • +
  • Don't upload dep or tar.gz for RPM because there are none. (#16230)
  • +
  • Add condition to generate release files in local dev build only (#16259)
  • +
  • Update .NET 6 to version 6.0.100-rc.2.21505.57 (#16249)
  • +
  • change order of try-catch-finally and split out arm runs (#16252)
  • +
  • Ensure psoptions.json and manifest.spdx.json files always exist in packages (#16258)
  • +
  • Update to vPack task version to 12 (#16250)
  • +
  • Remove unneeded `NuGetConfigFile` resource string (#16232)
  • +
  • Add Software Bill of Materials to the main packages (#16202)
  • +
  • Sign third party exes (#16229)
  • +
  • Upgrade set-value package for Markdown test (#16196)
  • +
  • Use Ubuntu 20.04 for SSH remoting test (#16225)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16194)
  • +
  • Bump `Microsoft.CodeAnalysis.NetAnalyzers` from `6.0.0-rc2.21458.5` to `6.0.0-rtm.21480.8` (#16183)
  • +
  • Move vPack build to 1ES Pool (#16169)
  • +
  • Fix Microsoft update spelling issue. (#16178)
  • +
+ +
+ +### Documentation and Help Content + +- Update Windows PowerShell issues link (#16105) (Thanks @andschwa!) +- Remove Joey from Committee and WG membership (#16119) +- Update more docs for `net6.0` TFM (#16102) (Thanks @xtqqczze!) +- Change `snippet` tag to `code` tag in XML comments (#16106) +- Update build documentation to reflect .NET 6 (#15751) (Thanks @Kellen-Stuart!) +- Update `README.md` about the changelogs (#16471) (Thanks @powershellpr0mpt!) +- Update changelog for 7.2.0 (#16401) +- Update `metadata.json` and `README.md` for 7.2.0 release (#16395) +- Update `README.md` and `metadata.json` files for `v7.2.0-rc.1` release (#16285) +- Update the changelogs for `v7.0.8` and `v7.1.5` releases (#16248) + +[7.3.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.10...v7.3.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/7.4.md b/PowerShell-master/CHANGELOG/7.4.md new file mode 100644 index 0000000000000000000000000000000000000000..f999c20315f62d469600c9a1d9467af64264a2fa --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.4.md @@ -0,0 +1,1614 @@ +# 7.4 Changelog + +## [7.4.14] + +### General Cmdlet Updates and Fixes + +- Fix `PSMethodInvocationConstraints.GetHashCode` method (#26959) + +### Tools + +- Add merge conflict marker detection to `linux-ci` workflow and refactor existing actions to use reusable `get-changed-files` action (#26362) +- Add reusable `get-changed-files` action and refactor existing actions (#26361) +- Refactor analyze job to reusable workflow and enable on Windows CI (#26342) + +### Tests + +- Skip the flaky `Update-Help` test for the `PackageManagement` module (#26871) +- Fix `$PSDefaultParameterValues` leak causing tests to skip unexpectedly (#26869) +- Add GitHub Actions annotations for Pester test failures (#26800) +- Mark flaky `Update-Help` web tests as pending to unblock CI (#26805) +- Update the `Update-Help` tests to use `-Force` to remove read-only files (#26786) +- Fix merge conflict checker for empty file lists and filter `*.cs` files (#26387) +- Add markdown link verification for PRs (#26340) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.419

+ +
+ +
    +
  • Update MaxVisitCount and MaxHashtableKeyCount if visitor safe value context indicates SkipLimitCheck is true (Internal 38882)
  • +
  • Hardcode Official templates (#26962)
  • +
  • Split TPN manifest and Component Governance manifest (#26961)
  • +
  • Correct the package name for .deb and .rpm packages (#26960)
  • +
  • Bring over all changes for MSIX packaging template (#26933)
  • +
  • .NET Resolution and Store Publishing Updates (#26930)
  • +
  • Update Application Insights package version to 2.23.0 (#26883)
  • +
  • Update metadata.json to update the Latest attribute with a better name (#26872)
  • +
  • Update Get-ChangeLog to handle backport PRs correctly (#26870)
  • +
  • Remove unused runCodesignValidationInjection variable from pipeline templates (#26868)
  • +
  • Refactor: Centralize xUnit tests into reusable workflow and remove legacy verification (#26864)
  • +
  • Fix buildinfo.json uploading for preview, LTS, and stable releases (#26863)
  • +
  • Fix macOS preview package identifier detection to use version string (#26774)
  • +
  • Update the macOS package name for preview releases to match the previous pattern (#26435)
  • +
  • Fix condition syntax for StoreBroker package tasks in MSIX pipeline (#26434)
  • +
  • Fix template path for rebuild branch check in package.yml (#26433)
  • +
  • Add rebuild branch support with conditional MSIX signing (#26418)
  • +
  • Move package validation to package pipeline (#26417)
  • +
  • Backport Store publishing improvements (#26401)
  • +
  • Fix path to metadata.json in channel selection script (#26399)
  • +
  • Optimize/split Windows package signing (#26413)
  • +
  • Improve ADO package build and validation across platforms (#26405)
  • +
  • Separate Store Automation Service Endpoints, Resolve AppID (#26396)
  • +
  • Fix the task name to not use the pre-release task (#26395)
  • +
  • Remove usage of fpm for DEB package generation (#26382)
  • +
  • Replace fpm with native macOS packaging tools (pkgbuild/productbuild) (#26344)
  • +
  • Replace fpm with native rpmbuild for RPM package generation (#26337)
  • +
  • Add log grouping to build.psm1 for collapsible GitHub Actions logs (#26363)
  • +
  • Convert Azure DevOps Linux Packaging pipeline to GitHub Actions workflow (#26336)
  • +
  • Integrate Windows packaging into windows-ci workflow using reusable workflow (#26335)
  • +
  • Add network isolation policy parameter to vPack pipeline (#26339)
  • +
  • GitHub Workflow cleanup (#26334)
  • +
  • Add build to vPack Pipeline (#25980)
  • +
  • Update vPack name (#26222)
  • +
+ +
+ +### Documentation and Help Content + +- Update Third Party Notices (#26892) + +[7.4.14]: https://github.com/PowerShell/PowerShell/compare/v7.4.13...v7.4.14 + +## [7.4.13] + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.415

+ +
+ +
    +
  • [release/v7.4] Update StableRelease to not be the latest (#26042)
  • +
  • [release/v7.4] Update Ev2 Shell Extension Image to AzureLinux 3 for PMC Release (#26033)
  • +
  • [release/v7.4] Add 7.4.12 Changelog (#26018)
  • +
  • [release/v7.4] Fix variable reference for release environment in pipeline (#26014)
  • +
  • Backport Release Pipeline Changes (Internal 37169)
  • +
  • [release/v7.4] Update branch for release (#26194)
  • +
  • [release/v7.4] Mark the 3 consistently failing tests as pending to unblock PRs (#26197)
  • +
  • [release/v7.4] Remove UseDotnet task and use the dotnet-install script (#26170)
  • +
  • [release/v7.4] Automate Store Publishing (#26163)
  • +
  • [release/v7.4] add CodeQL suppresion for NativeCommandProcessor (#26174)
  • +
  • [release/v7.4] add CodeQL suppressions for UpdatableHelp and NativeCommandProcessor methods (#26172)
  • +
  • [release/v7.4] Suppress false positive PSScriptAnalyzer warnings in tests and build scripts (#26058)
  • +
  • [release/v7.4] Ensure that socket timeouts are set only during the token validation (#26080)
  • +
+ +
+ +[7.4.13]: https://github.com/PowerShell/PowerShell/compare/v7.4.12...v7.4.13 + +## [7.4.12] + +### Tools + +- Add CodeQL suppressions (#25973) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.413

+ +
+ +
    +
  • Add LinuxHost Network configuration to PowerShell Packages pipeline (#26003)
  • +
  • Update container images to use mcr.microsoft.com for Linux and Azure Linux (#25987)
  • +
  • Update SDK to 8.0.413 (#25993)
  • +
  • Make logical template name consistent between pipelines (#25992)
  • +
  • Remove AsyncSDL from Pipelines Toggle Official/NonOfficial Runs (#25965)
  • +
+ +
+ +### Documentation and Help Content + +- Update third-party library versions to `8.0.19` for `ObjectPool`, Windows Compatibility, and `System.Drawing.Common` (#26001) + +[7.4.12]: https://github.com/PowerShell/PowerShell/compare/v7.4.11...v7.4.12 + +## [7.4.11] - 2025-06-17 + +### Engine Updates and Fixes + +- Move .NET method invocation logging to after the needed type conversion is done for method arguments (#25568) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.411

+ +
+ +
    +
  • Correct Capitalization Referencing Templates (#25672)
  • +
  • Manually update SqlClient in TestService
  • +
  • Update cgmanifest
  • +
  • Update package references
  • +
  • Update .NET SDK to latest version
  • +
  • Change linux packaging tests to ubuntu latest (#25640)
  • +
+ +
+ +### Documentation and Help Content + +- Update Third Party Notices (#25524, #25659) + +[7.4.11]: https://github.com/PowerShell/PowerShell/compare/v7.4.10...v7.4.11 + + +## [7.4.10] + +### Engine Updates and Fixes + +- Fallback to AppLocker after `WldpCanExecuteFile` (#25229) + +### Code Cleanup + +
+ +
    +
  • Remove obsolete template from Windows Packaging CI (#25405)
  • +
  • Cleanup old release pipelines (#25404)
  • +
+ +
+ +### Tools + +- Do not run labels workflow in the internal repository (#25411) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.408

+ +
+ +
    +
  • Update branch for release (#25518)
  • +
  • Move MSIXBundle to Packages and Release to GitHub (#25516)
  • +
  • Add CodeQL suppressions for PowerShell intended behavior (#25376)
  • +
  • Enhance path filters action to set outputs for all changes when not a PR (#25378)
  • +
  • Fix Merge Errors from #25401 and Internal 33077 (#25478)
  • +
  • Fix MSIX artifact upload, vPack template, changelog hashes, git tag command (#25476)
  • +
  • Fix Conditional Parameter to Skip NuGet Publish (#25475)
  • +
  • Use new variables template for vPack (#25474)
  • +
  • Add Windows Store Signing to MSIX bundle (#25472)
  • +
  • Update test result processing to use NUnitXml format and enhance logging for better clarity (#25471)
  • +
  • Fix the expected path of .NET after using UseDotnet 2 task to install (#25470)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.1.0 (#25469)
  • +
  • Combine GitHub and Nuget Release Stage (#25473)
  • +
  • Make GitHub Workflows work in the internal mirror (#25409)
  • +
  • Add default .NET install path for SDK validation (#25339)
  • +
  • Update APIScan to use new symbols server (#25400)
  • +
  • Use GitHubReleaseTask (#25401)
  • +
  • Migrate MacOS Signing to OneBranch (#25412)
  • +
  • Remove call to NuGet (#25410)
  • +
  • Restore a script needed for build from the old release pipeline cleanup (#25201) (#25408)
  • +
  • Switch to ubuntu-latest for CI (#25406)
  • +
  • Update GitHub Actions to work in private GitHub repository (#25403)
  • +
  • Simplify PR Template (#25407)
  • +
  • Disable SBOM generation on set variables job in release build (#25341)
  • +
  • Update package pipeline windows image version (#25192)
  • +
+ +
+ +[7.4.10]: https://github.com/PowerShell/PowerShell/compare/v7.4.9...v7.4.10 + +## [7.4.9] + +### Notes + +_This release is internal only. It is not available for download._ + +### Tools + +- Check GH token availability for `Get-Changelog` (#25156) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.407

+ +
+ +
    +
  • Update branch for release (#25101)
  • +
  • Only build Linux for packaging changes (#25161)
  • +
  • Skip additional packages when generating component manifest (#25160)
  • +
  • Remove Az module installs and AzureRM uninstalls in pipeline (#25157)
  • +
  • Add GitHub Actions workflow to verify PR labels (#25158)
  • +
  • Update security extensions (#25099)
  • +
  • Make Component Manifest Updater use neutral target in addition to RID target (#25100)
  • +
+ +
+ +[7.4.9]: https://github.com/PowerShell/PowerShell/compare/v7.4.8...v7.4.9 + +## [7.4.8] + +### Notes + +_This release is internal only. It is not available for download._ + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.406

+ +
+ +
    +
  • Update branch for release (#25085) (#24884)
  • +
  • Add UseDotnet task for installing dotnet (#25080)
  • +
  • Add Justin Chung as PowerShell team member in releaseTools.psm1 (#25074)
  • +
  • Fix V-Pack download package name (#25078)
  • +
  • Fix MSIX stage in release pipeline (#25079)
  • +
  • Give the pipeline runs meaningful names (#25081)
  • +
  • Make sure the vPack pipeline does not produce an empty package (#25082)
  • +
  • Update CODEOWNERS (#25083)
  • +
  • Add setup dotnet action to the build composite action (#25084)
  • +
  • Remove AzDO credscan as it is now in GitHub (#25077)
  • +
  • Use workload identity service connection to download makeappx tool from storage account (#25075)
  • +
  • Update .NET SDK (#24993)
  • +
  • Fix GitHub Action filter overmatching (#24957)
  • +
  • Fix release branch filters (#24960)
  • +
  • Convert powershell/PowerShell-CI-macos to GitHub Actions (#24955)
  • +
  • Convert powershell/PowerShell-CI-linux to GitHub Actions (#24945)
  • +
  • Convert powershell/PowerShell-Windows-CI to GitHub Actions (#24932)
  • +
  • PMC parse state correctly from update command's response (#24860)
  • +
  • Add EV2 support for publishing PowerShell packages to PMC (#24857)
  • +
+ +
+ +[7.4.8]: https://github.com/PowerShell/PowerShell/compare/v7.4.7...v7.4.8 + +## [7.4.7] + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.405

+ +
+ +
    +
  • Update branch for release - Transitive - true - minor (#24546)
  • +
  • Fix backport mistake in #24429 (#24545)
  • +
  • Fix seed max value for Container Linux CI (#24510) (#24543)
  • +
  • Add a way to use only NuGet feed sources (#24528) (#24542)
  • +
  • Bump Microsoft.PowerShell.PSResourceGet to 1.0.6 (#24419)
  • +
  • Update path due to pool change (Internal 33083)
  • +
  • Update pool for "Publish BuildInfo" job (Internal 33082)
  • +
  • Add missing backports and new fixes (Internal 33077)
  • +
  • Port copy blob changes (Internal 33055)
  • +
  • Update firewall to monitor (Internal 33048)
  • +
  • Fix typo in release-MakeBlobPublic.yml (Internal 33046)
  • +
  • Update change log for 7.4.6 (Internal 33040)
  • +
  • Update changelog for v7.4.6 release (Internal 32983)
  • +
  • Fix backport issues with release pipeline (#24835)
  • +
  • Remove duplicated parameter (#24832)
  • +
  • Make the AssemblyVersion not change for servicing releases 7.4.7 and onward (#24821)
  • +
  • Add *.props and sort path filters for windows CI (#24822) (#24823)
  • +
  • Take the newest windows signature nuget packages (#24818)
  • +
  • Use work load identity service connection to download makeappx tool from storage account (#24817) (#24820)
  • +
  • Update path filters for Windows CI (#24809) (#24819)
  • +
  • Fixed release pipeline errors and switched to KS3 (#24751) (#24816)
  • +
  • Update branch for release - Transitive - true - minor (#24806)
  • +
  • Add ability to capture MSBuild Binary logs when restore fails (#24128) (#24799)
  • +
  • Download package from package build for generating vpack (#24481) (#24801)
  • +
  • Add a parameter that skips verify packages step (#24763) (#24803)
  • +
  • Fix Changelog content grab during GitHub Release (#24788) (#24804)
  • +
  • Add tool package download in publish nuget stage (#24790) (#24805)
  • +
  • Add CodeQL scanning to APIScan build (#24303) (#24800)
  • +
  • Deploy Box Update (#24632) (#24802)
  • +
+ +
+ +### Documentation and Help Content + +- Update notices file (#24810) + +[7.4.7]: https://github.com/PowerShell/PowerShell/compare/v7.4.6...v7.4.7 + +## [7.4.6] - 2024-10-22 + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 8.0.403

+ +
+ +
    +
  • Copy to static site instead of making blob public (#24269) (#24473)
  • +
  • Add ability to capture MSBuild Binary logs when restore fails (#24128)
  • +
  • Keep the roff file when gzipping it. (#24450)
  • +
  • Update PowerShell-Coordinated_Packages-Official.yml (#24449)
  • +
  • Update and add new NuGet package sources for different environments. (#24440)
  • +
  • Add PMC mapping for Debian 12 (bookworm) (#24413)
  • +
  • Fixes to Azure Public feed usage (#24429)
  • +
  • Delete assets/AppImageThirdPartyNotices.txt (#24256)
  • +
  • Delete demos directory (#24258)
  • +
  • Add specific path for issues in tsaconfig (#24244)
  • +
  • Checkin generated manpage (#24423)
  • +
  • Add updated libicu dependency for Debian packages (#24301)
  • +
  • Add mapping to azurelinux repo (#24290)
  • +
  • Update vpack pipeline (#24281)
  • +
  • Add BaseUrl to buildinfo JSON file (#24376)
  • +
  • Delete the msix blob if it's already there (#24353)
  • +
  • Make some release tests run in a hosted pools (#24270)
  • +
  • Create new pipeline for compliance (#24252)
  • +
  • Use Managed Identity for APIScan authentication (#24243)
  • +
  • Check Create and Submit in vPack build by default (#24181)
  • +
  • Capture environment better (#24148)
  • +
  • Refactor Nuget package source creation to use New-NugetPackageSource function (#24104)
  • +
  • Make Microsoft feeds the default (#24426)
  • +
  • Bump to .NET 8.0.403 and update dependencies (#24405)
  • +
+ +
+ +[7.4.6]: https://github.com/PowerShell/PowerShell/compare/v7.4.5...v7.4.6 + +## [7.4.5] - 2024-08-20 + +### General Cmdlet Updates and Fixes + +- Fix WebCmdlets when `-Body` is specified but `ContentType` is not (#24145) + +### Tests + +- Rewrite the mac syslog tests to make them less flaky (#24152) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 8.0.400

+ +
+ +
    +
  • Add feature flags for removing network isolation (Internal 32126)
  • +
  • Update ThirdPartyNotices.txt for v7.4.5 (#24160)
  • +
  • Update cgmanifest.json for v7.4.5 (#24159)
  • +
  • Update .NET SDK to 8.0.400 (#24151)
  • +
  • Cleanup unused csproj (#24146)
  • +
  • Remember installation options and used them to initialize options for the next installation (#24143)
  • +
  • Fix failures in GitHub action markdown-link-check (#24142)
  • +
  • Use correct signing certificates for RPM and DEBs (#21522)
  • +
+ +
+ +### Documentation and Help Content + +- Update docs sample nuget.config (#24147) +- Fix up broken links in Markdown files (#24144) + +[7.4.5]: https://github.com/PowerShell/PowerShell/compare/v7.4.4...v7.4.5 + +## [7.4.4] - 2024-07-18 + +### Engine Updates and Fixes + +- Resolve paths correctly when importing files or files referenced in the module manifest (Internal 31780) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to 8.0.303

+ +
+ +
    +
  • Enumerate over all signed zip packages in macos signing
  • +
  • Update TPN for the v7.4.4 release (Internal 31793)
  • +
  • Add update cgmanifest (Internal 31789)
  • +
  • Add macos signing for package files (#24015) (#24059)
  • +
  • Update .NET SDK to 8.0.303 (#24038)
  • +
+ +
+ +[7.4.4]: https://github.com/PowerShell/PowerShell/compare/v7.4.3...v7.4.4 + +## [7.4.3] - 2024-06-18 + +### General Cmdlet Updates and Fixes + +- Fix the error when using `Start-Process -Credential` without the admin privilege (#21393) (Thanks @jborean93!) +- Fix `Test-Path -IsValid` to check for invalid path and filename characters (#21358) + +### Engine Updates and Fixes + +- Fix generating `OutputType` when running in Constrained Language Mode (#21605) +- Expand `~` to `$home` on Windows with tab completion (#21529) +- Make sure both stdout and stderr can be redirected from a native executable (#20997) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET 8.0.6

+

We thank the following contributors!

+

@ForNeVeR!

+ +
+ +
    +
  • Fixes for change to new Engineering System.
  • +
  • Fix argument passing in GlobalToolShim (#21333) (Thanks @ForNeVeR!)
  • +
  • Create powershell.config.json for PowerShell.Windows.x64 global tool (#23941)
  • +
  • Remove markdown link check on release branches (#23937)
  • +
  • Update to .NET 8.0.6 (#23936)
  • +
  • Fix error in the vPack release, debug script that blocked release (#23904)
  • +
  • Add branch counter variables for daily package builds (#21523)
  • +
  • Updates to package and release pipelines (#23800)
  • +
  • Fix exe signing with third party signing for WiX engine (#23878)
  • +
  • Use PSScriptRoot to find path to Wix module (#21611)
  • +
  • [StepSecurity] Apply security best practices (#21480)
  • +
  • Fix build failure due to missing reference in GlobalToolShim.cs (#21388)
  • +
  • Update installation on Wix module (#23808)
  • +
  • Use feed with Microsoft Wix toolset (#21651)
  • +
  • Create the Windows.x64 global tool with shim for signing (#21559)
  • +
  • Generate MSI for win-arm64 installer (#20516)
  • +
  • update wix package install (#21537)
  • +
  • Add a PAT for fetching PMC cli (#21503)
  • +
  • Official PowerShell Package pipeline (#21504)
  • +
+ +
+ +[7.4.3]: https://github.com/PowerShell/PowerShell/compare/v7.4.2...v7.4.3 + +## [7.4.2] - 2024-04-11 + +### General Cmdlet Updates and Fixes + +- Revert "Adjust PUT method behavior to POST one for default content type in WebCmdlets" (#21049) +- Fix regression with `Get-Content` when `-Tail 0` and `-Wait` are both used (#20734) (Thanks @CarloToso!) +- Fix `Get-Error` serialization of array values (#21085) (Thanks @jborean93!) +- Fix a regression in `Format-Table` when header label is empty (#21156) + +### Engine Updates and Fixes + +- Revert the PR #17856 (Do not preserve temporary results when no need to do so) (#21368) +- Make sure the assembly/library resolvers are registered at early stage (#21361) +- Handle the case that `Runspace.DefaultRunspace` is `null` when logging for WDAC Audit (#21344) +- Fix PowerShell class to support deriving from an abstract class with abstract properties (#21331) +- Fix the regression when doing type inference for `$_` (#21223) (Thanks @MartinGC94!) + +### Build and Packaging Improvements + +
+ + + +

Bump to .NET 8.0.4

+ +
+ +
    +
  • Revert analyzer package back to stable
  • +
  • Update SDK, deps and cgmanifest for 7.4.2
  • +
  • Revert changes to packaging.psm1
  • +
  • Update PSResourceGet version from 1.0.2 to 1.0.4.1 (#21439)
  • +
  • Verify environment variable for OneBranch before we try to copy (#21441)
  • +
  • Remove surrogateFile setting of APIScan (#21238)
  • +
  • Add dotenv install as latest version does not work with current Ruby version (#21239)
  • +
  • Multiple fixes in official build pipeline (#21408)
  • +
  • Add back 2 transitive dependency packages (#21415)
  • +
  • Update PSReadLine to v2.3.5 for the next v7.4.x servicing release (#21414)
  • +
  • PowerShell co-ordinated build OneBranch pipeline (#21364)
  • +
+ +
+ +[7.4.2]: https://github.com/PowerShell/PowerShell/compare/v7.4.1...v7.4.2 + +## [7.4.1] - 2024-01-11 + +### General Cmdlet Updates and Fixes + +- Fix `Group-Object` output using interpolated strings (#20745) (Thanks @mawosoft!) +- Fix `Start-Process -PassThru` to make sure the `ExitCode` property is accessible for the returned `Process` object (#20749) (#20866) (Thanks @CodeCyclone!) +- Fix rendering of DisplayRoot for network PSDrive (#20793) (#20863) + +### Engine Updates and Fixes + +- Ensure filename is not null when logging WDAC ETW events (#20910) (Thanks @jborean93!) +- Fix four regressions introduced by WDAC audit logging feature (#20913) + +### Build and Packaging Improvements + +
+ + + +Bump .NET 8 to version 8.0.101 + + + +
    +
  • Update .NET SDK and dependencies for v7.4.1 (Internal 29142)
  • +
  • Update cgmanifest for v7.4.1 (#20874)
  • +
  • Update package dependencies for v7.4.1 (#20871)
  • +
  • Set the rollForwardOnNoCandidateFx in runtimeconfig.json to roll forward only on minor and patch versions (#20689) (#20865)
  • +
  • Remove RHEL7 publishing to packages.microsoft.com as it's no longer supported (#20849) (#20864)
  • +
  • Fix the tab completion tests (#20867)
  • +
+ +
+ +[7.4.1]: https://github.com/PowerShell/PowerShell/compare/v7.4.0...v7.4.1 + +## [7.4.0] - 2023-11-16 + +### General Cmdlet Updates and Fixes + +- Added a missing `ConfigureAwait(false)` call to webcmdlets so they don't block (#20622) +- Fix `Group-Object` so output uses current culture (#20623) +- Block getting help from network locations in restricted remoting sessions (#20615) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET 8 to 8.0.0 RTM build

+ +
+ +
    +
  • Add internal .NET SDK URL parameter to release pipeline (Internal 28474)
  • +
  • Update the CGManifest file for v7.4.0 release (Internal 28457)
  • +
  • Fix repository root for the nuget.config (Internal 28456)
  • +
  • Add internal nuget feed to compliance build (Internal 28449)
  • +
  • Copy azure blob with PowerShell global tool to private blob and move to CDN during release (Internal 28438)
  • +
  • Fix release build by making the internal SDK parameter optional (#20658) (Internal 28440)
  • +
  • Make internal .NET SDK URL as a parameter for release builld (#20655) (Internal 28428)
  • +
  • Update PSResourceGet version for 1.0.1 release (#20652) (Internal 28427)
  • +
  • Bump .NET 8 to 8.0.0 RTM build (Internal 28360)
  • +
  • Remove Auth header content from ErrorRecord (Internal 28409)
  • +
  • Fix setting of variable to consume internal SDK source (Internal 28354)
  • +
  • Bump Microsoft.Management.Infrastructure to v3.0.0 (Internal 28352)
  • +
  • Bump Microsoft.PowerShell.Native to v7.4.0 (#20617) (#20624)
  • +
+ +
+ +[7.4.0]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-rc.1...v7.4.0 + +## [7.4.0-rc.1] - 2023-10-24 + +### General Cmdlet Updates and Fixes + +- Fix `Test-Connection` due to .NET 8 changes (#20369) (#20531) +- Add telemetry to check for specific tags when importing a module (#20371) (#20540) +- Fix `Copy-Item` progress to only show completed when all files are copied (#20517) (#20544) +- Fix `unixmode` to handle `setuid` and `sticky` when file is not an executable (#20366) (#20537) +- Fix UNC path completion regression (#20419) (#20541) +- Fix implicit remoting proxy cmdlets to act on common parameters (#20367) (#20530) +- Fix `Get-Service` non-terminating error message to include category (#20276) (#20529) +- Fixing regression in DSC (#20268) (#20528) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+ +
+ +
    +
  • Update ThirdPartyNotices.txt file (Internal 28110)
  • +
  • Update CGManifest for release
  • +
  • Fix package version for .NET nuget packages (#20551) (#20552)
  • +
  • Only registry App Path for release package (#20478) (#20549)
  • +
  • Bump PSReadLine from 2.2.6 to 2.3.4 (#20305) (#20533)
  • +
  • Bump Microsoft.Management.Infrastructure (#20511) (#20512) (#20433) (#20434) (#20534) (#20535) (#20545) (#20547)
  • +
  • Bump to .NET 8 RC2 (#20510) (#20543)
  • + +
  • Add SBOM for release pipeline (#20519) (#20548)
  • +
  • Bump version of Microsoft.PowerShell.PSResourceGet to v1.0.0 (#20485) (#20538)
  • +
  • Bump xunit.runner.visualstudio from 2.5.1 to 2.5.3 (#20486) (#20542)
  • +
  • Bump JsonSchema.Net from 5.2.5 to 5.2.6 (#20421) (#20532)
  • +
  • Fix alpine tar package name and do not crossgen alpine fxdependent package (#20459) (#20536)
  • +
  • Increase timeout when publishing packages to packages.microsoft.com (#20470) (#20539)
  • +
  • Block any preview vPack release (#20243) (#20526)
  • +
  • Add surrogate file for compliance scanning (#20423)
  • +
+ +
+ +[7.4.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.6...v7.4.0-rc.1 + +## [7.4.0-preview.6] - 2023-09-28 + +### General Cmdlet Updates and Fixes + +- Set approved experimental features to stable for 7.4 release (#20362) +- Revert changes to continue using `BinaryFormatter` for `Out-GridView` (#20360) +- Remove the comment trigger from feedback provider (#20346) + +### Tests + +- Continued improvement to tests for release automation (#20259) +- Skip the test on x86 as `InstallDate` is not visible on `Wow64` (#20255) +- Harden some problematic release tests (#20254) + +### Build and Packaging Improvements + +
+ + + +

Move to .NET 8.0.100-rc.1.23463.5

+ +
+ +
    +
  • Update the regex for package name validation (Internal 27783, 27795)
  • +
  • Update ThirdPartyNotices.txt (Internal 27772)
  • +
  • Remove the ref folder before running compliance (#20375)
  • +
  • Updates RIDs used to generate component Inventory (#20372)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.7.0 to 4.8.0-2.final (#20368)
  • +
  • Fix the release build by moving to the official .NET 8-rc.1 release build version (#20365)
  • +
  • Update the experimental feature JSON files (#20363)
  • +
  • Bump XunitXml.TestLogger from 3.1.11 to 3.1.17 (#20364)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 0.9.0-rc1 (#20361)
  • +
  • Update .NET SDK to version 8.0.100-rc.1.23455.8 (#20358)
  • +
  • Use fxdependent-win-desktop runtime for compliance runs (#20359)
  • +
  • Add mapping for mariner arm64 stable (#20348)
  • +
  • Bump xunit.runner.visualstudio from 2.5.0 to 2.5.1 (#20357)
  • +
  • Bump JsonSchema.Net from 5.2.1 to 5.2.5 (#20356)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.7.1 to 17.7.2 (#20355)
  • +
  • Bump Markdig.Signed from 0.32.0 to 0.33.0 (#20354)
  • +
  • Bump JsonSchema.Net from 5.1.3 to 5.2.1 (#20353)
  • +
  • Bump actions/checkout from 3 to 4 (#20352)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.7.0 to 17.7.1 (#20351)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.7.0-2.final to 4.7.0 (#20350)
  • +
  • Release build: Change the names of the PATs (#20349)
  • +
  • Put the calls to Set-AzDoProjectInfo and Set-AzDoAuthToken` in the right order (#20347)
  • +
  • Bump Microsoft.Management.Infrastructure (continued) (#20262)
  • +
  • Bump Microsoft.Management.Infrastructure to 3.0.0-preview.2 (#20261)
  • +
  • Enable vPack provenance data (#20260)
  • +
  • Start using new packages.microsoft.com cli (#20258)
  • +
  • Add mariner arm64 to PMC release (#20257)
  • +
  • Fix typo donet to dotnet in build scripts and pipelines (#20256)
  • +
+ +
+ +[7.4.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.5...v7.4.0-preview.6 + +## [7.4.0-preview.5] - 2023-08-21 + +### Breaking Changes + +- Change how relative paths in `Resolve-Path` are handled when using the `RelativeBasePath` parameter (#19755) (Thanks @MartinGC94!) + +### Engine Updates and Fixes + +- Fix dynamic parameter completion (#19510) (Thanks @MartinGC94!) +- Use `OrdinalIgnoreCase` to lookup script breakpoints (#20046) (Thanks @fflaten!) +- Guard against `null` or blank path components when adding to module path (#19922) (Thanks @stevenebutler!) +- Fix deadlock when piping to shell associated file extension (#19940) +- Fix completion regression for filesystem paths with custom `PSDrive` names (#19921) (Thanks @MartinGC94!) +- Add completion for variables assigned by the `Data` statement (#19831) (Thanks @MartinGC94!) +- Fix a null reference crash in completion code (#19916) (Thanks @MartinGC94!) + +### General Cmdlet Updates and Fixes + +- Fix `Out-GridView` by implementing `Clone()` method to replace old use of binary format serialization (#20050) +- Support Unix domain socket in WebCmdlets (#19343) (Thanks @CarloToso!) +- Wait-Process: add `-Any` and `-PassThru` parameters (#19423) (Thanks @dwtaber!) +- Added the switch parameter `-CaseInsensitive` to `Select-Object` and `Get-Unique` cmdlets (#19683) (Thanks @ArmaanMcleod!) +- `Restore-Computer` and `Stop-Computer` should fail with error when not running via `sudo` on Unix (#19824) +- Add Help proxy function for non-Windows platforms (#19972) +- Remove input text from the error message resulted by `SecureString` and `PSCredential` conversion failure (#19977) (Thanks @ArmaanMcleod!) +- Add `Microsoft.PowerShell.PSResourceGet` to the telemetry module list (#19926) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @Molkree, @MartinGC94

+ +
+ +
    +
  • Fix use of ThrowIf where the arguments were reversed (#20052)
  • +
  • Fix typo in Logging.Tests.ps1 (#20048) (Thanks @eltociear!)
  • +
  • Apply the InlineAsTypeCheck in the engine code - 2nd pass (#19694) (Thanks @Molkree!)
  • +
  • Apply the InlineAsTypeCheck rule in the engine code - 1st pass (#19692) (Thanks @Molkree!)
  • +
  • Remove unused string completion code (#19879) (Thanks @MartinGC94!)
  • +
+ +
+ +### Tools + +- Give the `assignPRs` workflow write permissions (#20021) + +### Tests + +- Additional test hardening for tests which fail in release pass. (#20093) +- Don't use a completion which has a space in it (#20064) +- Fixes for release tests (#20028) +- Remove spelling CI in favor of GitHub Action (#19973) +- Hide expected error for negative test on windows for script extension (#19929) +- Add more debugging to try to determine why these test fail in release build. (#19829) + +### Build and Packaging Improvements + +
    +
  • Update ThirdPartyNotices for 7.4.0-preview.5
  • +
  • Update PSResourceGet to 0.5.24-beta24 (#20118)
  • +
  • Fix build after the change to remove win-arm32 (#20102)
  • +
  • Add comment about pinned packages (#20096)
  • +
  • Bump to .NET 8 Preview 7 (#20092)
  • +
  • Remove Win-Arm32 from release build. (#20095)
  • +
  • Add alpine framework dependent package (#19995)
  • +
  • Bump JsonSchema.Net from 4.1.8 to 5.1.3 (#20089)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.6.3 to 17.7.0 (#20088)
  • +
  • Move build to .NET 8 preview 6 (#19991)
  • +
  • Bump Microsoft.Management.Infrastructure from 2.0.0 to 3.0.0-preview.1 (#20081)
  • +
  • Bump Markdig.Signed from 0.31.0 to 0.32.0 (#20076)
  • +
  • Auto assign PR Maintainer (#20020)
  • +
  • Delete rule that was supposed to round-robin assign a maintainer (#20019)
  • +
  • Update the cgmanifest (#20012)
  • +
  • Update the cgmanifest (#20008)
  • +
  • Bump JsonSchema.Net from 4.1.7 to 4.1.8 (#20006)
  • +
  • Bump JsonSchema.Net from 4.1.6 to 4.1.7 (#20000)
  • +
  • Add mariner arm64 package build to release build (#19946)
  • +
  • Check for pre-release packages when it's a stable release (#19939)
  • +
  • Make PR creation tool use --web because it is more reliable (#19944)
  • +
  • Update to the latest NOTICES file (#19971)
  • +
  • Update variable used to bypass the blocking check for multiple NuGet feeds for release pipeline (#19963)
  • +
  • Update variable used to bypass the blocking check for multiple NuGet feeds (#19967)
  • +
  • Update README.md and metadata.json for release v7.2.13 and v7.3.6 (#19964)
  • +
  • Don't publish notice on failure because it prevent retry (#19955)
  • +
  • Change variable used to bypass nuget security scanning (#19954)
  • +
  • Update the cgmanifest (#19924)
  • +
  • Publish rpm package for rhel9 (#19750)
  • +
  • Bump XunitXml.TestLogger from 3.0.78 to 3.1.11 (#19900)
  • +
  • Bump JsonSchema.Net from 4.1.5 to 4.1.6 (#19885)
  • +
  • Bump xunit from 2.4.2 to 2.5.0 (#19902)
  • +
  • Remove HostArchitecture dynamic parameter for osxpkg (#19917)
  • +
  • FabricBot: Onboarding to GitOps.ResourceManagement because of FabricBot decommissioning (#19905)
  • +
  • Change variable used to bypass nuget security scanning (#19907)
  • +
  • Checkout history for markdown lint check (#19908)
  • +
  • Switch to GitHub Action for linting markdown (#19899)
  • +
  • Bump xunit.runner.visualstudio from 2.4.5 to 2.5.0 (#19901)
  • +
  • Add runtime and packaging type info for mariner2 arm64 (#19450)
  • +
  • Update to the latest NOTICES file (#19856)
  • +
+ + + +### Documentation and Help Content + +- Update `README.md` and `metadata.json` for `7.4.0-preview.4` release (#19872) +- Fix grammatical issue in `ADOPTERS.md` (#20037) (Thanks @nikohoffren!) +- Replace docs.microsoft.com URLs in code with FWLinks (#19996) +- Change `docs.microsoft.com` to `learn.microsoft.com` (#19994) +- Update man page to match current help for pwsh (#19993) +- Merge `7.3.5`, `7.3.6`, `7.2.12` and `7.2.13` changelogs (#19968) +- Fix ///-comments that violate the docs schema (#19957) +- Update the link for getting started in `README.md` (#19932) +- Migrate user docs to the PowerShell-Docs repository (#19871) + +[7.4.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.4...v7.4.0-preview.5 + +## [7.4.0-preview.4] - 2023-06-29 + +### Breaking Changes + +- `Test-Json`: Use `JsonSchema.Net` (`System.Text.Json`) instead of `NJsonSchema` (`Newtonsoft.Json`) (#18141) (Thanks @gregsdennis!) +- `Test-Connection`: Increase output detail when performing a TCP test (#11452) (Thanks @jackdcasey!) + +### Engine Updates and Fixes + +- Fix native executables not redirecting to file (#19842) +- Add a new experimental feature to control native argument passing style on Windows (#18706) +- Fix `TabExpansion2` variable leak when completing variables (#18763) (Thanks @MartinGC94!) +- Enable completion of variables across ScriptBlock scopes (#19819) (Thanks @MartinGC94!) +- Fix completion of the `foreach` statement variable (#19814) (Thanks @MartinGC94!) +- Fix variable type inference precedence (#18691) (Thanks @MartinGC94!) +- Fix member completion for PowerShell Enum class (#19740) (Thanks @MartinGC94!) +- Fix parsing for array literals in index expressions in method calls (#19224) (Thanks @MartinGC94!) +- Fix incorrect string to type conversion (#19560) (Thanks @MartinGC94!) +- Fix slow execution when many breakpoints are used (#14953) (Thanks @nohwnd!) +- Add a public API for getting locations of `PSModulePath` elements (#19422) +- Add WDAC Audit logging (#19641) +- Improve path completion (#19489) (Thanks @MartinGC94!) +- Fix an indexing out of bound error in `CompleteInput` for empty script input (#19501) (Thanks @MartinGC94!) +- Improve variable completion performance (#19595) (Thanks @MartinGC94!) +- Allow partial culture matching in `Update-Help` (#18037) (Thanks @dkaszews!) +- Fix the check when reading input in `NativeCommandProcessor` (#19614) +- Add support of respecting `$PSStyle.OutputRendering` on the remote host (#19601) +- Support byte stream piping between native commands and file redirection (#17857) + +### General Cmdlet Updates and Fixes + +- Disallow negative values for `Get-Content` cmdlet parameters `-Head` and `-Tail` (#19715) (Thanks @CarloToso!) +- Make `Update-Help` throw proper error when current culture is not associated with a language (#19765) (Thanks @josea!) +- Do not require activity when creating a completed progress record (#18474) (Thanks @MartinGC94!) +- WebCmdlets: Add alias for `-TimeoutSec` to `-ConnectionTimeoutSeconds` and add `-OperationTimeoutSeconds` (#19558) (Thanks @stevenebutler!) +- Avoid checking screen scraping on non-Windows platforms before launching native app (#19812) +- Add reference to PSResourceGet (#19597) +- Add `FileNameStar` to `MultipartFileContent` in WebCmdlets (#19467) (Thanks @CarloToso!) +- Add `ParameterSetName` for the `-Detailed` parameter of `Test-Connection` (#19727) +- Remove the property disabling optimization (#19701) +- Filter completion for enum parameter against `ValidateRange` attributes (#17750) (Thanks @fflaten!) +- Small cleanup `Invoke-RestMethod` (#19490) (Thanks @CarloToso!) +- Fix wildcard globbing in root of device paths (#19442) (Thanks @MartinGC94!) +- Add specific error message that creating Junctions requires absolute path (#19409) +- Fix array type parsing in generic types (#19205) (Thanks @MartinGC94!) +- Improve the verbose message of WebCmdlets to show correct HTTP version (#19616) (Thanks @CarloToso!) +- Fix HTTP status from 409 to 429 for WebCmdlets to get retry interval from Retry-After header. (#19622) (Thanks @mkht!) +- Remove minor versions from `PSCompatibleVersions` (#18635) (Thanks @xtqqczze!) +- Update `JsonSchema.Net` version to 4.1.0 (#19610) (Thanks @gregsdennis!) +- Allow combining of `-Skip` and `-SkipLast` parameters in `Select-Object` cmdlet. (#18849) (Thanks @ArmaanMcleod!) +- Fix constructing `PSModulePath` if a sub-path has trailing separator (#13147) +- Add `Get-SecureRandom` cmdlet (#19587) +- Fix `New-Item` to re-create `Junction` when `-Force` is specified (#18311) (Thanks @GigaScratch!) +- Improve Hashtable key completion for type constrained variable assignments, nested Hashtables and more (#17660) (Thanks @MartinGC94!) +- `Set-Clipboard -AsOSC52` for remote usage (#18222) (Thanks @dkaszews!) +- Refactor `MUIFileSearcher.AddFiles` in the help related code (#18825) (Thanks @xtqqczze!) +- Set `SetLastError` to `true` for symbolic and hard link native APIs (#19566) +- Fix `Get-AuthenticodeSignature -Content` to not roundtrip the bytes to a Unicode string and then back to bytes (#18774) (Thanks @jborean93!) +- WebCmdlets: Rename `-TimeoutSec` to `-ConnectionTimeoutSeconds` (with alias) and add `-OperationTimeoutSeconds` (#19558) (Thanks @stevenebutler!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @ArmaanMcleod, @turbedi, @CarloToso, @Molkree, @xtqqczze

+ +
+ +
    +
  • Fix typo in NativeCommandProcessor.cs (#19846) (Thanks @eltociear!)
  • +
  • Rename file from PingPathCommand.cs to TestPathCommand.cs (#19782) (Thanks @ArmaanMcleod!)
  • +
  • Make use of the new Random.Shared property (#18417) (Thanks @turbedi!)
  • +
  • six files (#19695) (Thanks @CarloToso!)
  • +
  • Apply IDE0019: InlineAsTypeCheck in Microsoft.PowerShell.Commands (#19688)(#19690)(#19687)(#19689) (Thanks @Molkree!)
  • +
  • Remove PSv2CompletionCompleter as part of the PowerShell v2 code cleanup (#18337) (Thanks @xtqqczze!)
  • +
  • Enable more nullable annotations in WebCmdlets (#19359) (Thanks @CarloToso!)
  • +
+ +
+ +### Tools + +- Add Git mailmap for Andy Jordan (#19469) +- Add backport function to release tools (#19568) + +### Tests + +- Improve reliability of the `Ctrl+c` tests for WebCmdlets (#19532) (Thanks @stevenebutler!) +- Fix logic for `Import-CliXml` test (#19805) +- Add some debugging to the transcript test for `SilentlyContinue` (#19770) +- Re-enable `Get-ComputerInfo` pending tests (#19746) +- Update syslog parser to handle modern formats. (#19737) +- Pass `-UserScope` as required by `RunUpdateHelpTests` (#13400) (Thanks @yecril71pl!) +- Change how `isPreview` is determined for default cmdlets tests (#19650) +- Skip file signature tests on 2012R2 where PKI cmdlet do not work (#19643) +- Change logic for testing missing or extra cmdlets. (#19635) +- Fix incorrect test cases in `ExecutionPolicy.Tests.ps1` (#19485) (Thanks @xtqqczze!) +- Fixing structure typo in test setup (#17458) (Thanks @powercode!) +- Fix test failures on Windows for time zone and remoting (#19466) +- Harden 'All approved Cmdlets present' test (#19530) + +### Build and Packaging Improvements + +
+ + +

Updated to .NET 8 Preview 4 +

We thank the following contributors!

+

@krishnayalavarthi

+ +
+ +
    +
  • Update to the latest NOTICES file (#19537)(#19820)(#19784)(#19720)(#19644)(#19620)(#19605)(#19546)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.5.0 to 17.6.3 (#19867)(#19762)(#19733)(#19668)(#19613)
  • +
  • Update the cgmanifest (#19847)(#19800)(#19792)(#19776)(#19763)(#19697)(#19631)
  • +
  • Bump StyleCop.Analyzers from 1.2.0-beta.406 to 1.2.0-beta.507 (#19837)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.6.0-1.final to 4.7.0-2.final (#19838)(#19667)
  • +
  • Update to .NET 8 Preview 4 (#19696)
  • +
  • Update experimental-feature JSON files (#19828)
  • +
  • Bump JsonSchema.Net from 4.1.1 to 4.1.5 (#19790)(#19768)(#19788)
  • +
  • Update group to assign PRs in fabricbot.json (#19759)
  • +
  • Add retry on failure for all upload tasks in Azure Pipelines (#19761)
  • +
  • Bump Microsoft.PowerShell.MarkdownRender from 7.2.0 to 7.2.1 (#19751)(#19752)
  • +
  • Delete symbols on Linux as well (#19735)
  • +
  • Update windows.json packaging BOM (#19728)
  • +
  • Disable SBOM signing for CI and add extra files for packaging tests (#19729)
  • +
  • Update experimental-feature JSON files (#19698(#19588))
  • +
  • Add ProductCode in registry for MSI install (#19590)
  • +
  • Runas format changed (#15434) (Thanks @krishnayalavarthi!)
  • +
  • For Preview releases, add pwsh-preview.exe alias to MSIX package (#19602)
  • +
  • Add prompt to fix conflict during backport (#19583)
  • +
  • Add comment in wix detailing use of UseMU (#19371)
  • +
  • Verify that packages have license data (#19543)
  • +
  • Add an explicit manual stage for changelog update (#19551)
  • +
  • Update the team member list in releaseTools.psm1 (#19544)
  • +
+ +
+ +### Documentation and Help Content + +- Update `metadata.json` and `README.md` for upcoming releases (#19863)(#19542) +- Update message to use the actual parameter name (#19851) +- Update `CONTRIBUTING.md` to include Code of Conduct enforcement (#19810) +- Update `working-group-definitions.md` (#19809)(#19561) +- Update `working-group.md` to add section about reporting working group members (#19758) +- Correct capitalization in readme (#19666) (Thanks @Aishat452!) +- Updated the public dashboard link (#19634) +- Fix a typo in `serialization.cs` (#19598) (Thanks @eltociear!) + +[7.4.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.3...v7.4.0-preview.4 + +## [7.4.0-preview.3] - 2023-04-20 + +### Breaking Changes + +- Remove code related to `#requires -pssnapin` (#19320) + +### Engine Updates and Fixes + +- Change the arrow used in feedback suggestion to a more common Unicode character (#19534) +- Support trigger registration in feedback provider (#19525) +- Update the `ICommandPredictor` interface to reduce boilerplate code from predictor implementation (#19414) +- Fix a crash in the type inference code (#19400) (Thanks @MartinGC94!) + +### Performance + +- Speed up `Resolve-Path` relative path resolution (#19171) (Thanks @MartinGC94!) + +### General Cmdlet Updates and Fixes + +- Infer external application output as strings (#19193) (Thanks @MartinGC94!) +- Fix a race condition in `Add-Type` (#19471) +- Detect insecure `https-to-http` redirect only if both URIs are absolute (#19468) (Thanks @CarloToso!) +- Support `Ctrl+c` when connection hangs while reading data in WebCmdlets (#19330) (Thanks @stevenebutler!) +- Enable type conversion of `AutomationNull` to `$null` for assignment (#19415) +- Add the parameter `-Environment` to `Start-Process` (#19374) +- Add the parameter `-RelativeBasePath` to `Resolve-Path` (#19358) (Thanks @MartinGC94!) +- Exclude redundant parameter aliases from completion results (#19382) (Thanks @MartinGC94!) +- Allow using a folder path in WebCmdlets' `-OutFile` parameter (#19007) (Thanks @CarloToso!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @CarloToso

+ +
+ +
    +
  • Fix typo in typeDataXmlLoader.cs (#19319) (Thanks @eltociear!)
  • +
  • Fix typo in Compiler.cs (#19491) (Thanks @eltociear!)
  • +
  • Inline the GetResponseObject method (#19380) (Thanks @CarloToso!)
  • +
  • Simplify ContentHelper methods (#19367) (Thanks @CarloToso!)
  • +
  • Initialize regex lazily in BasicHtmlWebResponseObject (#19361) (Thanks @CarloToso!)
  • +
  • Fix codefactor issue in if-statement (part 5) (#19286) (Thanks @CarloToso!)
  • +
  • Add nullable annotations in WebRequestSession.cs (#19291) (Thanks @CarloToso!)
  • +
+ +
+ +### Tests + +- Harden the default command test (#19416) +- Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413) +- Improve package management acceptance tests by not going to the gallery (#19412) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@dkattan

+ +
+ +
    +
  • Fixing MSI checkbox (#19325)
  • +
  • Update the experimental feature JSON files (#19297)
  • +
  • Update the cgmanifest (#19459, #19465)
  • +
  • Update .NET SDK version to 8.0.100-preview.3.23178.7 (#19381)
  • +
  • Force updating the transitive dependency on Microsoft.CSharp (#19514)
  • +
  • Update DotnetRuntimeMetadata.json to consume the .NET 8.0.0-preview.3 release (#19529)
  • +
  • Move PSGallery sync to a pool (#19523)
  • +
  • Fix the regex used for package name check in vPack build (#19511)
  • +
  • Make the vPack PAT library more obvious (#19505)
  • +
  • Change Microsoft.CodeAnalysis.CSharp back to 4.5.0 (#19464) (Thanks @dkattan!)
  • +
  • Update to the latest NOTICES file (#19332)
  • +
  • Add PoolNames variable group to compliance pipeline (#19408)
  • +
  • Fix stage dependencies and typo in release build (#19353)
  • +
  • Fix issues in release build and release pipeline (#19338)
  • +
+ +
+ +[7.4.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.2...v7.4.0-preview.3 + +## [7.4.0-preview.2] - 2023-03-14 + +### Breaking Changes + +- Update some PowerShell APIs to throw `ArgumentException` instead of `ArgumentNullException` when the argument is an empty string (#19215) (Thanks @xtqqczze!) +- Add the parameter `-ProgressAction` to the common parameters (#18887) + +### Engine Updates and Fixes + +- Fix `PlainText` output to correctly remove the `Reset` VT sequence without number (#19283) +- Fix `ConciseView` to handle custom `ParserError` error records (#19239) +- Fix `VtSubstring` helper method to correctly check characters copied (#19240) +- Update the `FeedbackProvider` interface to return structured data (#19133) +- Make the exception error in PowerShell able to associate with the right history entry (#19095) +- Fix for JEA session leaking functions (#19024) +- Add WDAC events and system lockdown notification (#18893) +- Fix support for nanoserver due to lack of AMSI (#18882) + +### Performance + +- Use interpolated strings (#19002)(#19003)(#18977)(#18980)(#18996)(#18979)(#18997)(#18978)(#18983)(#18992)(#18993)(#18985)(#18988) (Thanks @CarloToso!) + +### General Cmdlet Updates and Fixes + +- Fix completion for `PSCustomObject` variable properties (#18682) (Thanks @MartinGC94!) +- Improve type inference for `Get-Random` (#18972) (Thanks @MartinGC94!) +- Make `-Encoding` parameter able to take `ANSI` encoding in PowerShell (#19298) (Thanks @CarloToso!) +- Telemetry improvements for tracking experimental feature opt out (#18762) +- Support HTTP persistent connections in Web Cmdlets (#19249) (Thanks @stevenebutler!) +- Fix using XML `-Body` in webcmdlets without an encoding (#19281) (Thanks @CarloToso!) +- Add the `Statement` property to `$MyInvocation` (#19027) (Thanks @IISResetMe!) +- Fix `Start-Process` `-Wait` with `-Credential` (#19096) (Thanks @jborean93!) +- Adjust `PUT` method behavior to `POST` one for default content type in WebCmdlets (#19152) (Thanks @CarloToso!) +- Improve verbose message in web cmdlets when content length is unknown (#19252) (Thanks @CarloToso!) +- Preserve `WebSession.MaximumRedirection` from changes (#19190) (Thanks @CarloToso!) +- Take into account `ContentType` from Headers in WebCmdlets (#19227) (Thanks @CarloToso!) +- Use C# 11 UTF-8 string literals (#19243) (Thanks @turbedi!) +- Add property assignment completion for enums (#19178) (Thanks @MartinGC94!) +- Fix class member completion for classes with base types (#19179) (Thanks @MartinGC94!) +- Add `-Path` and `-LiteralPath` parameters to `Test-Json` cmdlet (#19042) (Thanks @ArmaanMcleod!) +- Allow to preserve the original HTTP method by adding `-PreserveHttpMethodOnRedirect` to Web cmdlets (#18894) (Thanks @CarloToso!) +- Webcmdlets display an error on HTTPS to http redirect (#18595) (Thanks @CarloToso!) +- Build the relative URI for links from the response in `Invoke-WebRequest` (#19092) (Thanks @CarloToso!) +- Fix redirection for `-CustomMethod` `POST` in WebCmdlets (#19111) (Thanks @CarloToso!) +- Dispose previous response in Webcmdlets (#19117) (Thanks @CarloToso!) +- Improve `Invoke-WebRequest` XML and JSON errors format (#18837) (Thanks @CarloToso!) +- Fix error formatting to remove the unneeded leading newline for concise view (#19080) +- Add `-NoHeader` parameter to `ConvertTo-Csv` and `Export-Csv` cmdlets (#19108) (Thanks @ArmaanMcleod!) +- Fix `Start-Process -Credential -Wait` to work on Windows (#19082) +- Add `ValidateNotNullOrEmpty` to `OutFile` and `InFile` parameters of WebCmdlets (#19044) (Thanks @CarloToso!) +- Correct spelling of "custom" in event (#19059) (Thanks @spaette!) +- Ignore expected error for file systems not supporting alternate streams (#19065) +- Adding missing guard for telemetry opt out to avoid `NullReferenceException` when importing modules (#18949) (Thanks @powercode!) +- Fix progress calculation divide by zero in Copy-Item (#19038) +- Add progress to `Copy-Item` (#18735) +- WebCmdlets parse XML declaration to get encoding value, if present. (#18748) (Thanks @CarloToso!) +- `HttpKnownHeaderNames` update headers list (#18947) (Thanks @CarloToso!) +- Fix bug with managing redirection and `KeepAuthorization` in Web cmdlets (#18902) (Thanks @CarloToso!) +- Fix `Get-Error` to work with strict mode (#18895) +- Add `AllowInsecureRedirect` switch to Web cmdlets (#18546) (Thanks @CarloToso!) +- `Invoke-RestMethod` `-FollowRelLink` fix links containing commas (#18829) (Thanks @CarloToso!) +- Prioritize the default parameter set when completing positional arguments (#18755) (Thanks @MartinGC94!) +- Add `-CommandWithArgs` parameter to pwsh (#18726) +- Enable creating composite subsystem implementation in modules (#18888) +- Fix `Format-Table -RepeatHeader` for property derived tables (#18870) +- Add `StatusCode` to `HttpResponseException` (#18842) (Thanks @CarloToso!) +- Fix type inference for all scope variables (#18758) (Thanks @MartinGC94!) +- Add completion for Using keywords (#16514) (Thanks @MartinGC94!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@CarloToso, @iSazonov, @xtqqczze, @turbedi, @syntax-tm, @eltociear, @ArmaanMcleod

+ +
+ +
    +
  • Small cleanup in the WebCmdlet code (#19299) (Thanks @CarloToso!)
  • +
  • Remove unused GUID detection code from console host (#18871) (Thanks @iSazonov!)
  • +
  • Fix CodeFactor issues in the code base - part 4 (#19270) (Thanks @CarloToso!)
  • +
  • Fix codefactor if part 3 (#19269) (Thanks @CarloToso!)
  • +
  • Fix codefactor if part 2 (#19267) (Thanks @CarloToso!)
  • +
  • Fix codefactor if part 1 (#19266) (Thanks @CarloToso!)
  • +
  • Remove comment and simplify condition in WebCmdlets (#19251) (Thanks @CarloToso!)
  • +
  • Small style changes (#19241) (Thanks @CarloToso!)
  • +
  • Use ArgumentException.ThrowIfNullOrEmpty as appropriate [part 1] (#19215) (Thanks @xtqqczze!)
  • +
  • Use using variable to reduce the nested level (#19229) (Thanks @CarloToso!)
  • +
  • Use ArgumentException.ThrowIfNullOrEmpty() in more places (#19213) (Thanks @CarloToso!)
  • +
  • Replace BitConverter.ToString with Convert.ToHexString where appropriate (#19216) (Thanks @turbedi!)
  • +
  • Replace Requires.NotNullOrEmpty(string) with ArgumentException.ThrowIfNullOrEmpty (#19197) (Thanks @xtqqczze!)
  • +
  • Use ArgumentOutOfRangeException.ThrowIfNegativeOrZero when applicable (#19201) (Thanks @xtqqczze!)
  • +
  • Use CallerArgumentExpression on Requires.NotNull (#19200) (Thanks @xtqqczze!)
  • +
  • Revert a few change to not use 'ArgumentNullException.ThrowIfNull' (#19151)
  • +
  • Corrected some minor spelling mistakes (#19176) (Thanks @syntax-tm!)
  • +
  • Fix a typo in InitialSessionState.cs (#19177) (Thanks @eltociear!)
  • +
  • Fix a typo in pwsh help content (#19153)
  • +
  • Revert comment changes in WebRequestPSCmdlet.Common.cs (#19136) (Thanks @CarloToso!)
  • +
  • Small cleanup webcmdlets (#19128) (Thanks @CarloToso!)
  • +
  • Merge partials in WebRequestPSCmdlet.Common.cs (#19126) (Thanks @CarloToso!)
  • +
  • Cleanup WebCmdlets comments (#19124) (Thanks @CarloToso!)
  • +
  • Added minor readability and refactoring fixes to Process.cs (#19123) (Thanks @ArmaanMcleod!)
  • +
  • Small changes in Webcmdlets (#19109) (Thanks @CarloToso!)
  • +
  • Rework SetRequestContent in WebCmdlets (#18964) (Thanks @CarloToso!)
  • +
  • Small cleanup WebCmdlets (#19030) (Thanks @CarloToso!)
  • +
  • Update additional interpolated string changes (#19029)
  • +
  • Revert some of the interpolated string changes (#19018)
  • +
  • Cleanup StreamHelper.cs, WebRequestPSCmdlet.Common.cs and InvokeRestMethodCommand.Common.cs (#18950) (Thanks @CarloToso!)
  • +
  • Small cleanup common code of webcmdlets (#18946) (Thanks @CarloToso!)
  • +
  • Simplification of GetHttpMethod and HttpMethod in WebCmdlets (#18846) (Thanks @CarloToso!)
  • +
  • Fix typo in ModuleCmdletBase.cs (#18933) (Thanks @eltociear!)
  • +
  • Fix regression in RemoveNulls (#18881) (Thanks @iSazonov!)
  • +
  • Replace all NotNull with ArgumentNullException.ThrowIfNull (#18820) (Thanks @CarloToso!)
  • +
  • Cleanup InvokeRestMethodCommand.Common.cs (#18861) (Thanks @CarloToso!)
  • +
+ +
+ +### Tools + +- Add a Mariner install script (#19294) +- Add tool to trigger license information gathering for NuGet modules (#18827) + +### Tests + +- Update and enable the test for the type of `$input` (#18968) (Thanks @MartinGC94!) +- Increase the timeout for creating the `WebListener` (#19268) +- Increase the timeout when waiting for the event log (#19264) +- Add Windows ARM64 CI (#19040) +- Change test so output does not include newline (#19026) +- Allow system lock down test debug hook to work with new WLDP API (#18962) +- Add tests for `Allowinsecureredirect` parameter in Web cmdlets (#18939) (Thanks @CarloToso!) +- Enable `get-help` pattern tests on Unix (#18855) (Thanks @xtqqczze!) +- Create test to check if WebCmdlets decompress brotli-encoded data (#18905) (Thanks @CarloToso!) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@bergmeister, @xtqqczze

+ +
+ +
    +
  • Restructure the package build to simplify signing and packaging stages (#19321)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.4.0 to 4.6.0-2.23152.6 (#19306)(#19233)
  • +
  • Test fixes for stabilizing tests (#19068)
  • +
  • Bump Newtonsoft.Json from 13.0.2 to 13.0.3 (#19290)(#19289)
  • +
  • Fix mariner sudo detection (#19304)
  • +
  • Add stage for symbols job in Release build (#18937)
  • +
  • Bump .NET to Preview 2 version (#19305)
  • +
  • Move workflows that create PRs to private repo (#19276)
  • +
  • Use reference assemblies generated by dotnet (#19302)
  • +
  • Update the cgmanifest (#18814)(#19165)(#19296)
  • +
  • Always regenerate files WXS fragment (#19196)
  • +
  • MSI installer: Add checkbox and MSI property DISABLE_TELEMETRY to optionally disable telemetry. (#10725) (Thanks @bergmeister!)
  • +
  • Add -Force to Move-Item to fix the GitHub workflow (#19262)
  • +
  • Update and remove outdated docs to fix the URL link checks (#19261)
  • +
  • Bump Markdig.Signed from 0.30.4 to 0.31.0 (#19232)
  • +
  • Add pattern to replace for reference API generation (#19214)
  • +
  • Split test artifact build into windows and non-windows (#19199)
  • +
  • Set LangVersion compiler option to 11.0 (#18877) (Thanks @xtqqczze!)
  • +
  • Update to .NET 8 preview 1 build (#19194)
  • +
  • Simplify Windows Packaging CI Trigger YAML (#19160)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.4.0 to 17.5.0 (#18823)(#19191)
  • +
  • Add URL for all distributions (#19159)
  • +
  • Bump Microsoft.Extensions.ObjectPool from 7.0.1 to 7.0.3 (#18925)(#19155)
  • +
  • Add verification of R2R at packaging (#19129)
  • +
  • Allow cross compiling windows (#19119)
  • +
  • Update CodeQL build agent (#19113)
  • +
  • Bump XunitXml.TestLogger from 3.0.70 to 3.0.78 (#19066)
  • +
  • Bump Microsoft.CodeAnalysis.Analyzers from 3.3.3 to 3.3.4 (#18975)
  • +
  • Bump BenchmarkDotNet to 0.13.3 (#18878) (Thanks @xtqqczze!)
  • +
  • Bump Microsoft.PowerShell.Native from 7.4.0-preview.1 to 7.4.0-preview.2 (#18910)
  • +
  • Add checks for Windows 8.1 and Server 2012 in the MSI installer (#18904)
  • +
  • Update build to include WinForms / WPF in all Windows builds (#18859)
  • +
+ +
+ +### Documentation and Help Content + +- Update to the latest NOTICES file (#19169)(#19309)(#19086)(#19077) +- Update supported distros in readme (#18667) (Thanks @techguy16!) +- Remove the 'Code Coverage Status' badge (#19265) +- Pull in changelogs for `v7.2.10` and `v7.3.3` releases (#19219) +- Update tools `metadata` and `README` (#18831)(#19204)(#19014) +- Update a broken link in the `README.md` (#19187) +- Fix typos in comments (#19064) (Thanks @spaette!) +- Add `7.2` and `7.3` changelogs (#19025) +- typos (#19058) (Thanks @spaette!) +- Fix typo in `dotnet-tools/README.md` (#19021) (Thanks @spaette!) +- Fix up all comments to be in the proper order with proper spacing (#18619) +- Changelog for `v7.4.0-preview.1` release (#18835) + +[7.4.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.1...v7.4.0-preview.2 + +## [7.4.0-preview.1] - 2022-12-20 + +### Engine Updates and Fixes + +- Add Instrumentation to `AmsiUtil` and make the init variable readonly (#18727) +- Fix typo in `OutOfProcTransportManager.cs` (#18766) (Thanks @eltociear!) +- Allow non-default encodings to be used in user's script/code (#18605) +- Add `Dim` and `DimOff` to `$PSStyle` (#18653) +- Change `exec` from alias to function to handle arbitrary arguments (#18567) +- The command prefix should also be in the error color for `NormalView` (#18555) +- Skip cloud files marked as "not on disk" during command discovery (#18152) +- Replace `UTF8Encoding(false)` with `Encoding.Default` (#18356) (Thanks @xtqqczze!) +- Fix `Switch-Process` to set `termios` appropriate for child process (#18467) +- On Unix, only explicitly terminate the native process if not in background (#18215) +- Treat `[NullString]::Value` as the string type when resolving methods (#18080) +- Improve pseudo binding for dynamic parameters (#18030) (Thanks @MartinGC94!) +- Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) +- Update to use version `2.21.0` of Application Insights. (#17903) +- Do not preserve temporary results when no need to do so (#17856) + +### Performance + +- Remove some static constants from `Utils.Separators` (#18154) (Thanks @iSazonov!) +- Avoid using regular expression when unnecessary in `ScriptWriter` (#18348) +- Use source generator for `PSVersionInfo` to improve startup time (#15603) (Thanks @iSazonov!) +- Skip evaluating suggestions at startup (#18232) +- Avoid using `Regex` when not necessary (#18210) + +### General Cmdlet Updates and Fixes + +- Update to use `ComputeCore.dll` for PowerShell Direct (#18194) +- Replace `ArgumentNullException(nameof())` with `ArgumentNullException.ThrowIfNull()` (#18792)(#18784) (Thanks @CarloToso!) +- Remove `TabExpansion` from remote session configuration (#18795) (Internal 23331) +- WebCmdlets get Retry-After from headers if status code is 429 (#18717) (Thanks @CarloToso!) +- Implement `SupportsShouldProcess` in `Stop-Transcript` (#18731) (Thanks @JohnLBevan!) +- Fix `New-Item -ItemType Hardlink` to resolve target to absolute path and not allow link to itself (#18634) +- Add output types to Format commands (#18746) (Thanks @MartinGC94!) +- Fix the process `CommandLine` on Linux (#18710) (Thanks @jborean93!) +- Fix `SuspiciousContentChecker.Match` to detect a predefined string when the text starts with it (#18693) +- Switch `$PSNativeCommandUseErrorActionPreference` to `$true` when feature is enabled (#18695) +- Fix `Start-Job` to check the existence of working directory using the PowerShell way (#18675) +- Webcmdlets add 308 to redirect codes and small cleanup (#18536) (Thanks @CarloToso!) +- Ensure `HelpInfo.Category` is consistently a string (#18254) +- Remove `gcloud` from the legacy list because it's resolved to a .ps1 script (#18575) +- Add `gcloud` and `sqlcmd` to list to use legacy argument passing (#18559) +- Fix native access violation (#18545) (#18547) (Thanks @chrullrich!) +- Fix issue when completing the first command in a script with an empty array expression (#18355) (Thanks @MartinGC94!) +- Improve type inference of hashtable keys (#17907) (Thanks @MartinGC94!) +- Fix `Switch-Process` to copy the current env to the new process (#18452) +- Fix `Switch-Process` error to include the command that is not found (#18443) +- Update `Out-Printer` to remove all decorating ANSI escape sequences from PowerShell formatting (#18425) +- Web cmdlets set default charset encoding to `UTF8` (#18219) (Thanks @CarloToso!) +- Fix incorrect cmdlet name in the script used by `Restart-Computer` (#18374) (Thanks @urizen-source!) +- Add the function `cd~` (#18308) (Thanks @GigaScratch!) +- Fix type inference error for empty return statements (#18351) (Thanks @MartinGC94!) +- Fix the exception reporting in `ConvertFrom-StringData` (#18336) (Thanks @GigaScratch!) +- Implement `IDisposable` in `NamedPipeClient` (#18341) (Thanks @xtqqczze!) +- Replace command-error suggestion with new implementation based on subsystem plugin (#18252) +- Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) +- Make the fuzzy searching flexible by passing in the fuzzy matcher (#18270) +- Add `-FuzzyMinimumDistance` parameter to `Get-Command` (#18261) +- Improve startup time by triggering initialization of additional types on background thread (#18195) +- Fix decompression in web cmdlets (#17955) (Thanks @iSazonov!) +- Add `CustomTableHeaderLabel` formatting to differentiate table header labels that are not property names (#17346) +- Remove the extra new line form List formatting (#18185) +- Minor update to the `FileInfo` table formatting on Unix to make it more concise (#18183) +- Fix Parent property on processes with complex name (#17545) (Thanks @jborean93!) +- Make PowerShell class not affiliate with `Runspace` when declaring the `NoRunspaceAffinity` attribute (#18138) +- Complete the progress bar rendering in `Invoke-WebRequest` when downloading is complete or cancelled (#18130) +- Display download progress in human readable format for `Invoke-WebRequest` (#14611) (Thanks @bergmeister!) +- Update `WriteConsole` to not use `stackalloc` for buffer with too large size (#18084) +- Filter out compiler generated types for `Add-Type -PassThru` (#18095) +- Fixing `CA2014` warnings and removing the warning suppression (#17982) (Thanks @creative-cloud!) +- Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) +- Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) +- Handle `PSObject` argument specially in method invocation logging (#18060) +- Fix typos in `EventResource.resx` (#18063) (Thanks @eltociear!) +- Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) +- Make experimental feature `PSExec` stable (#18045) +- Make experimental feature `PSCleanBlock` stable (#18043) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) +- Remove unneeded use of `chmod 777` (#17974) +- Support mapping foreground/background `ConsoleColor` values to VT escape sequences (#17938) +- Make `pwsh` server modes implicitly not show banner (#17921) +- Add output type attributes for `Get-WinEvent` (#17948) (Thanks @MartinGC94!) +- Remove 1 second minimum delay in `Invoke-WebRequest` for small files, and prevent file-download-error suppression. (#17896) (Thanks @AAATechGuy!) +- Add completion for values in comparisons when comparing Enums (#17654) (Thanks @MartinGC94!) +- Fix positional argument completion (#17796) (Thanks @MartinGC94!) +- Fix member completion in attribute argument (#17902) (Thanks @MartinGC94!) +- Throw when too many parameter sets are defined (#17881) (Thanks @fflaten!) +- Limit searching of `charset` attribute in `meta` tag for HTML to first 1024 characters in webcmdlets (#17813) +- Fix `Update-Help` failing silently with implicit non-US culture. (#17780) (Thanks @dkaszews!) +- Add the `ValidateNotNullOrWhiteSpace` attribute (#17191) (Thanks @wmentha!) +- Improve enumeration of inferred types in pipeline (#17799) (Thanks @MartinGC94!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@MartinGC94, @CarloToso, @iSazonov, @xtqqczze, @turbedi, @trossr32, @eltociear, @AtariDreams, @jborean93

+ +
+ +
    +
  • Add TSAUpload for APIScan (#18446)
  • +
  • Use Pattern matching in ast.cs (#18794) (Thanks @MartinGC94!)
  • +
  • Cleanup webrequestpscmdlet.common.cs (#18596) (Thanks @CarloToso!)
  • +
  • Unify CreateFile pinvoke in SMA (#18751) (Thanks @iSazonov!)
  • +
  • Cleanup webresponseobject.common (#18785) (Thanks @CarloToso!)
  • +
  • InvokeRestMethodCommand.Common cleanup and merge partials (#18736) (Thanks @CarloToso!)
  • +
  • Replace GetDirectories in CimDscParser (#14319) (Thanks @xtqqczze!)
  • +
  • WebResponseObject.Common merge partials atomic commits (#18703) (Thanks @CarloToso!)
  • +
  • Enable pending test for Start-Process (#18724) (Thanks @iSazonov!)
  • +
  • Remove one CreateFileW (#18732) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport for WNetAddConnection2 (#18721) (Thanks @iSazonov!)
  • +
  • Use File.OpenHandle() instead CreateFileW pinvoke (#18722) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport for WNetGetConnection (#18690) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport - 1 (#18603) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 3 (#18564) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA - 7 (#18594) (Thanks @iSazonov!)
  • +
  • Use static DateTime.UnixEpoch and RandomNumberGenerator.Fill() (#18621) (Thanks @turbedi!)
  • +
  • Rewrite Get-FileHash to use static HashData methods (#18471) (Thanks @turbedi!)
  • +
  • Replace DllImport with LibraryImport in SMA 8 (#18599) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 4 (#18579) (Thanks @iSazonov!)
  • +
  • Remove NativeCultureResolver as dead code (#18582) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 6 (#18581) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 2 (#18543) (Thanks @iSazonov!)
  • +
  • Use standard SBCS detection (#18593) (Thanks @iSazonov!)
  • +
  • Remove unused pinvokes in RemoteSessionNamedPipe (#18583) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 5 (#18580) (Thanks @iSazonov!)
  • +
  • Remove SafeRegistryHandle (#18597) (Thanks @iSazonov!)
  • +
  • Remove ArchitectureSensitiveAttribute from the code base (#18598) (Thanks @iSazonov!)
  • +
  • Build COM adapter only on Windows (#18590)
  • +
  • Include timer instantiation for legacy telemetry in conditional compiler statements in Get-Help (#18475) (Thanks @trossr32!)
  • +
  • Convert DllImport to LibraryImport for recycle bin, clipboard, and computerinfo cmdlets (#18526)
  • +
  • Replace DllImport with LibraryImport in SMA 1 (#18520) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in engine (#18496)
  • +
  • Fix typo in InitialSessionState.cs (#18435) (Thanks @eltociear!)
  • +
  • Remove remaining unused strings from resx files (#18448)
  • +
  • Use new LINQ Order() methods instead of OrderBy(static x => x) (#18395) (Thanks @turbedi!)
  • +
  • Make use of StringSplitOptions.TrimEntries when possible (#18412) (Thanks @turbedi!)
  • +
  • Replace some string.Join(string) calls with string.Join(char) (#18411) (Thanks @turbedi!)
  • +
  • Remove unused strings from FileSystem and Registry providers (#18403)
  • +
  • Use generic GetValues<T>, GetNames<T> enum methods (#18391) (Thanks @xtqqczze!)
  • +
  • Remove unused resource strings from SessionStateStrings (#18394)
  • +
  • Remove unused resource strings in System.Management.Automation (#18388)
  • +
  • Use Enum.HasFlags part 1 (#18386) (Thanks @xtqqczze!)
  • +
  • Remove unused strings from parser (#18383)
  • +
  • Remove unused strings from Utility module (#18370)
  • +
  • Remove unused console strings (#18369)
  • +
  • Remove unused strings from ConsoleInfoErrorStrings.resx (#18367)
  • +
  • Code cleanup in ContentHelper.Common.cs (#18288) (Thanks @CarloToso!)
  • +
  • Remove FusionAssemblyIdentity and GlobalAssemblyCache as they are not used (#18334) (Thanks @iSazonov!)
  • +
  • Remove some static initializations in StringManipulationHelper (#18243) (Thanks @xtqqczze!)
  • +
  • Use MemoryExtensions.IndexOfAny in PSv2CompletionCompleter (#18245) (Thanks @xtqqczze!)
  • +
  • Use MemoryExtensions.IndexOfAny in WildcardPattern (#18242) (Thanks @xtqqczze!)
  • +
  • Small cleanup of the stub code (#18301) (Thanks @CarloToso!)
  • +
  • Fix typo in RemoteRunspacePoolInternal.cs (#18263) (Thanks @eltociear!)
  • +
  • Some more code cleanup related to the use of PSVersionInfo (#18231)
  • +
  • Use MemoryExtensions.IndexOfAny in SessionStateInternal (#18244) (Thanks @xtqqczze!)
  • +
  • Use overload APIs that take char instead of string when it's possible (#18179) (Thanks @iSazonov!)
  • +
  • Replace UTF8Encoding(false) with Encoding.Default (#18144) (Thanks @xtqqczze!)
  • +
  • Remove unused variables (#18058) (Thanks @AtariDreams!)
  • +
  • Fix typo in PowerShell.Core.Instrumentation.man (#17963) (Thanks @eltociear!)
  • +
  • Migrate WinTrust functions to a common location (#17598) (Thanks @jborean93!)
  • +
+ +
+ +### Tools + +- Add a function to get the PR Back-port report (#18299) +- Add a workaround in automatic rebase workflow to continue on error (#18176) +- Update list of PowerShell team members in release tools (#17909) +- Don't block if we fail to create the comment (#17869) + +### Tests + +- Add `testexe.exe -echocmdline` to output raw command-line received by the process on Windows (#18591) +- Mark charset test as pending (#18511) +- Skip output rendering tests on Windows Server 2012 R2 (#18382) +- Increase timeout to make subsystem tests more reliable (#18380) +- Add missing -Tag 'CI' to describe blocks. (#18316) +- Use short path instead of multiple quotes in `Get-Item` test relying on node (#18250) +- Replace the CIM class used for `-Amended` parameter test (#17884) (Thanks @sethvs!) +- Stop ongoing progress-bar in `Write-Progress` test (#17880) (Thanks @fflaten!) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+ +
+ +
    +
  • Fix reference assembly generation logic for Microsoft.PowerShell.Commands.Utility (#18818)
  • +
  • Update the cgmanifest (#18676)(#18521)(#18415)(#18408)(#18197)(#18111)(#18051)(#17913)(#17867)(#17934)(#18088)
  • +
  • Bump Microsoft.PowerShell.Native to the latest preview version v7.4.0-preview.1 (#18805)
  • +
  • Remove unnecessary reference to System.Runtime.CompilerServices.Unsafe (#18806)
  • +
  • Update the release tag in metadata.json for next preview (#18799)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18750)
  • +
  • Bump .NET SDK to version 7.0.101 (#18786)
  • +
  • Bump cirrus-actions/rebase from 1.7 to 1.8 (#18788)
  • +
  • Bump decode-uri-component from 0.2.0 to 0.2.2 (#18712)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.4.0-4.final to 4.4.0 (#18562)
  • +
  • Bump Newtonsoft.Json from 13.0.1 to 13.0.2 (#18657)
  • +
  • Apply expected file permissions to Linux files after Authenticode signing (#18643)
  • +
  • Remove extra quotes after agent moves to pwsh 7.3 (#18577)
  • +
  • Don't install based on build-id for RPM (#18560)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.3.2 to 17.4.0 (#18487)
  • +
  • Bump minimatch from 3.0.4 to 3.1.2 (#18514)
  • +
  • Avoid depending on the pre-generated experimental feature list in private and CI builds (#18484)
  • +
  • Update release-MsixBundle.yml to add retries (#18465)
  • +
  • Bump System.Data.SqlClient from 4.8.4 to 4.8.5 in /src/Microsoft.PowerShell.SDK (#18515)
  • +
  • Bump to use internal .NET 7 GA build (#18508)
  • +
  • Insert the pre-release nuget feed before building test artifacts (#18507)
  • +
  • Add test for framework dependent package in release pipeline (#18506) (Internal 23139)
  • +
  • Update to azCopy 10 (#18509)
  • +
  • Fix issues with uploading changelog to GitHub release draft (#18504)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18442)
  • +
  • Add authenticode signing for assemblies on linux builds (#18440)
  • +
  • Do not remove penimc_cor3.dll from build (#18438)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-rc.1 to 7.3.0 (#18405)
  • +
  • Allow two-digit revisions in vPack package validation pattern (#18392)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18363)
  • +
  • Bump to .NET 7 RC2 official version (#18328)
  • +
  • Bump to .NET 7 to version 7.0.100-rc.2.22477.20 (#18286)
  • +
  • Replace win7 runtime with win8 and remove APISets (#18304)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18312)
  • +
  • Recurse the file listing. (#18277)
  • +
  • Create tasks to collect and publish hashes for build files. (#18276)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18262)
  • +
  • Remove ETW trace collection and uploading for CLR CAP (#18253)
  • +
  • Do not cleanup pwsh.deps.json for framework dependent packages (#18226)
  • +
  • Add branch counter to APIScan build (#18214)
  • +
  • Remove unnecessary native dependencies from the package (#18213)
  • +
  • Remove XML files for min-size package (#18189)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18216)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-preview.1 to 7.3.0-rc.1 (#18217)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18201)
  • +
  • Move ApiScan to compliance build (#18191)
  • +
  • Fix the verbose message when using dotnet-install.sh (#18184)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.3.1 to 17.3.2 (#18163)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18164)
  • +
  • Make the link to minimal package blob public during release (#18158)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18147)
  • +
  • Update MSI exit message (#18137)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.4.0-1.final to 4.4.0-2.final (#18132)
  • +
  • Re-enable building with Ready-to-Run (#18105)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 RC1 build (#18091)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18096)
  • +
  • Add schema for cgmanifest.json (#18036)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.3.0-3.final to 4.3.0 (#18012)
  • +
  • Add XML reference documents to NuPkg files for SDK (#17997)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.3.0 to 17.3.1 (#18000)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17988)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17983)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17945)
  • +
  • Make sure Security.types.ps1xml gets signed in release build (#17916)
  • +
  • Make Register Microsoft Update timeout (#17910)
  • +
  • Merge changes from v7.0.12 v7.2.6 and v7.3.0-preview.7
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17871)
  • +
+ +
+ +### Documentation and Help Content + +- Update readme and metadata for releases (#18780)(#18493)(#18393)(#18332)(#18128)(#17870) +- Remove 'please' and 'Core' from README.md per MS style guide (#18578) (Thanks @Rick-Anderson!) +- Change unsupported XML documentation tag (#18608) +- Change public API mention of `monad` to PowerShell (#18491) +- Update security reporting policy to recommend security portal for more streamlined reporting (#18437) +- Changelog for v7.3.0 (#18505) (Internal 23161) +- Replace `msh` in public API comment based documentation with PowerShell equivalent (#18483) +- Add missing XML doc elements for methods in `RunspaceFactory` (#18450) +- Changelog for `v7.3.0-rc.1` (#18400) +- Update changelogs for `v7.2.7` and `v7.0.13` (#18342) +- Update the changelog for v7.3.0-preview.8 (#18136) +- Add the `ConfigurationFile` option to the PowerShell help content (#18093) +- Update help content about the PowerShell flag `-NonInteractive` (#17952) + +[7.4.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.8...v7.4.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/7.5.md b/PowerShell-master/CHANGELOG/7.5.md new file mode 100644 index 0000000000000000000000000000000000000000..d908532ff828e6aa1ba2407b51830f44d2736938 --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.5.md @@ -0,0 +1,902 @@ +# 7.5 Changelog + +## [7.5.5] + +### Engine Updates and Fixes + +- Fix up `SSHConnectionInfo` ssh PATH checks (#26165) (Thanks @jborean93!) + +### General Cmdlet Updates and Fixes + +- Close pipe client handles after creating the child ssh process (#26822) +- Fix the progress preference variable in script cmdlets (#26791) (Thanks @cmkb3!) + +### Tools + +- Add merge conflict marker detection to `linux-ci` workflow and refactor existing actions to use reusable `get-changed-files` action (#26812) +- Add reusable `get-changed-files` action and refactor existing actions (#26811) +- Create GitHub Copilot setup workflow (#26807) +- Refactor analyze job to reusable workflow and enable on Windows CI (#26799) + +### Tests + +- Mark flaky `Update-Help` web tests as pending to unblock CI (#26837) +- Add GitHub Actions annotations for Pester test failures (#26836) +- Fix `$PSDefaultParameterValues` leak causing tests to skip unexpectedly (#26823) +- Fix merge conflict checker for empty file lists and filter `*.cs` files (#26813) +- Update the `Update-Help` tests to use `-Force` to remove read-only files (#26788) +- Add markdown link verification for PRs (#26407) + +### Build and Packaging Improvements + +
+ + +

Update to .NET SDK 9.0.312

+

We thank the following contributors!

+

@kasperk81, @RichardSlater

+ +
+ +
    +
  • Revert change to module name ThreadJob (#26997)
  • +
  • Update branch for release (#26990)
  • +
  • Fix ConvertFrom-ClearlyDefinedCoordinates to handle API object coordinates (#26987)
  • +
  • Update CGManifests (#26981)
  • +
  • Hardcode Official templates (#26968)
  • +
  • Split TPN manifest and Component Governance manifest (#26967)
  • +
  • Fix a preview detection test for the packaging script (#26966)
  • +
  • Correct the package name for .deb and .rpm packages (#26964)
  • +
  • Bring Release Changes from v7.6.0-preview.6 (#26963)
  • +
  • Merge the v7.6.0-preview.5 release branch back to master (#26958)
  • +
  • Fix macOS preview package identifier detection to use version string (#26835)
  • +
  • Update metadata.json to update the Latest attribute with a better name (#26826)
  • +
  • Remove unused runCodesignValidationInjection variable from pipeline templates (#26825)
  • +
  • Update Get-ChangeLog to handle backport PRs correctly (#26824)
  • +
  • Mirror .NET/runtime ICU version range in PowerShell (#26821) (Thanks @kasperk81!)
  • +
  • Update the macos package name for preview releases to match the previous pattern (#26820)
  • +
  • Fix condition syntax for StoreBroker package tasks in MSIX pipeline (#26819)
  • +
  • Fix template path for rebuild branch check in package.yml (#26818)
  • +
  • Add rebuild branch support with conditional MSIX signing (#26817)
  • +
  • Move package validation to package pipeline (#26816)
  • +
  • Optimize/split windows package signing (#26815)
  • +
  • Improve ADO package build and validation across platforms (#26814)
  • +
  • Add log grouping to build.psm1 for collapsible GitHub Actions logs (#26810)
  • +
  • Remove usage of fpm for DEB package generation (#26809)
  • +
  • Replace fpm with native macOS packaging tools (pkgbuild/productbuild) (#26801)
  • +
  • Fix build to only enable ready-to-run for the Release configuration (#26798)
  • +
  • Fix R2R for fxdependent packaging (#26797)
  • +
  • Refactor: Centralize xUnit tests into reusable workflow and remove legacy verification (#26794)
  • +
  • Replace fpm with native rpmbuild for RPM package generation (#26793)
  • +
  • Add libicu76 dependency to support Debian 13 (#26792) (Thanks @RichardSlater!)
  • +
  • Specify .NET search by build type (#26408)
  • +
  • Fix buildinfo.json uploading for preview, LTS, and stable releases (#26773)
  • +
  • Fix path to metadata.json in channel selection script (#26400)
  • +
  • Separate store automation service endpoints and resolve AppID (#26266)
  • +
  • Update a few packages to use the right version corresponding to .NET 9 (#26671)
  • +
  • Add network isolation policy parameter to vPack pipeline (#26393)
  • +
  • Convert Azure DevOps Linux Packaging pipeline to GitHub Actions workflow (#26391)
  • +
  • Integrate Windows packaging into windows-ci workflow using reusable workflow (#26390)
  • +
  • GitHub Workflow cleanup (#26389)
  • +
  • Update vPack name (#26221)
  • +
+ +
+ +[7.5.5]: https://github.com/PowerShell/PowerShell/compare/v7.5.4...v7.5.5 + +## [7.5.4] + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.306

+ +
+ +
    +
  • [release/v7.5] Update Ev2 Shell Extension Image to AzureLinux 3 for PMC Release (#26032)
  • +
  • [release/v7.5] Fix variable reference for release environment in pipeline (#26013)
  • +
  • [release/v7.5] Add v7.5.3 Changelog (#26015)
  • +
  • [release/v7.5] Add LinuxHost Network configuration to PowerShell Packages pipeline (#26002)
  • +
  • Backport Release Pipeline Changes (Internal 37168)
  • +
  • [release/v7.5] Update branch for release (#26195)
  • +
  • [release/v7.5] Mark the 3 consistently failing tests as pending to unblock PRs (#26196)
  • +
  • [release/v7.5] add CodeQL suppresion for NativeCommandProcessor (#26173)
  • +
  • [release/v7.5] add CodeQL suppressions for UpdatableHelp and NativeCommandProcessor methods (#26171)
  • +
  • [release/v7.5] Remove UseDotnet task and use the dotnet-install script (#26169)
  • +
  • [release/v7.5] Automate Store Publishing (#26164)
  • +
  • [release/v7.5] Ensure that socket timeouts are set only during the token validation (#26079)
  • +
  • [release/v7.5] Suppress false positive PSScriptAnalyzer warnings in tests and build scripts (#26059)
  • +
+ +
+ +[7.5.4]: https://github.com/PowerShell/PowerShell/compare/v7.5.3...v7.5.4 + + +## [7.5.3] + +### General Cmdlet Updates and Fixes + +- Fix `Out-GridView` by replacing the use of obsolete `BinaryFormatter` with custom implementation. (#25559) +- Remove `OnDeserialized` and `Serializable` attributes from `Microsoft.Management.UI.Internal` project (#25831) +- Make the interface `IDeepCloneable` internal (#25830) + +### Tools + +- Add CodeQL suppressions (#25972) + +### Tests + +- Fix updatable help test for new content (#25944) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.304

+ +
+ +
    +
  • Make logical template name consistent between pipelines (#25991)
  • +
  • Update container images to use mcr.microsoft.com for Linux and Azure Linux (#25986)
  • +
  • Add build to vPack Pipeline (#25975)
  • +
  • Remove AsyncSDL from Pipelines Toggle Official/NonOfficial Runs (#25964)
  • +
  • Update branch for release (#25942)
  • +
+ +
+ +### Documentation and Help Content + +- Fix typo in CHANGELOG for script filename suggestion (#25963) + +[7.5.3]: https://github.com/PowerShell/PowerShell/compare/v7.5.2...v7.5.3 + +## [7.5.2] - 2025-06-24 + +### Engine Updates and Fixes + +- Move .NET method invocation logging to after the needed type conversion is done for method arguments (#25357) + +### General Cmdlet Updates and Fixes + +- Set standard handles explicitly when starting a process with `-NoNewWindow` (#25324) +- Make inherited protected internal instance members accessible in class scope. (#25547) (Thanks @mawosoft!) +- Remove the old fuzzy suggestion and fix the local script filename suggestion (#25330) +- Fix `PSMethodInvocationConstraints.GetHashCode` method (#25306) (Thanks @crazyjncsu!) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.301

+ +
+ +
    +
  • Correct Capitalization Referencing Templates (#25673)
  • +
  • Publish .msixbundle package as a VPack (#25621)
  • +
  • Update ThirdPartyNotices for v7.5.2 (#25658)
  • +
  • Manually update SqlClient in TestService
  • +
  • Update cgmanifest
  • +
  • Update package references
  • +
  • Update .NET SDK to latest version
  • +
  • Change linux packaging tests to ubuntu latest (#25639)
  • +
  • Fix MSIX artifact upload, vPack template, changelog hashes, git tag command (#25633)
  • +
  • Move MSIXBundle to Packages and Release to GitHub (#25517)
  • +
  • Use new variables template for vPack (#25435)
  • +
+ +
+ +[7.5.2]: https://github.com/PowerShell/PowerShell/compare/v7.5.1...v7.5.2 + +## [7.5.1] + +### Engine Updates and Fixes + +- Fallback to AppLocker after `WldpCanExecuteFile` (#25305) + +### Code Cleanup + +
+ +
    +
  • Cleanup old release pipelines (#25236)
  • +
+ +
+ +### Tools + +- Do not run labels workflow in the internal repository (#25343) +- Update `CODEOWNERS` (#25321) +- Check GitHub token availability for `Get-Changelog` (#25328) +- Update PowerShell team members in `releaseTools.psm1` (#25302) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.203

+ +
+ +
    +
  • Finish 7.5.0 release (#24855)
  • +
  • Add CodeQL suppressions for PowerShell intended behavior (#25375)
  • +
  • Update to .NET SDK 9.0.203 (#25373)
  • +
  • Switch to ubuntu-lastest for CI (#25374)
  • +
  • Add default .NET install path for SDK validation (#25338)
  • +
  • Combine GitHub and Nuget Release Stage (#25371)
  • +
  • Add Windows Store Signing to MSIX bundle (#25370)
  • +
  • Update test result processing to use NUnitXml format and enhance logging for better clarity (#25344)
  • +
  • Fix MSIX stage in release pipeline (#25345)
  • +
  • Make GitHub Workflows work in the internal mirror (#25342)
  • +
  • Update security extensions (#25322)
  • +
  • Disable SBOM generation on set variables job in release build (#25340)
  • +
  • Update GitHub Actions to work in private GitHub repo (#25332)
  • +
  • Revert "Cleanup old release pipelines (#25201)" (#25335)
  • +
  • Remove call to NuGet (#25334)
  • +
  • Simplify PR Template (#25333)
  • +
  • Update package pipeline windows image version (#25331)
  • +
  • Skip additional packages when generating component manifest (#25329)
  • +
  • Only build Linux for packaging changes (#25326)
  • +
  • Make Component Manifest Updater use neutral target in addition to RID target (#25325)
  • +
  • Remove Az module installs and AzureRM uninstalls in pipeline (#25327)
  • +
  • Make sure the vPack pipeline does not produce an empty package (#25320)
  • +
  • Add *.props and sort path filters for windows CI (#25316)
  • +
  • Fix V-Pack download package name (#25314)
  • +
  • Update path filters for Windows CI (#25312)
  • +
  • Give the pipeline runs meaningful names (#25309)
  • +
  • Migrate MacOS Signing to OneBranch (#25304)
  • +
  • Add UseDotnet task for installing dotnet (#25281)
  • +
  • Remove obsolete template from Windows Packaging CI (#25237)
  • +
  • Add setup dotnet action to the build composite action (#25235)
  • +
  • Add GitHub Actions workflow to verify PR labels (#25159)
  • +
  • Update branch for release - Transitive - true - minor (#24994)
  • +
  • Fix GitHub Action filter overmatching (#24958)
  • +
  • Fix release branch filters (#24959)
  • +
  • Convert powershell/PowerShell-CI-macos to GitHub Actions (#24954)
  • +
  • Convert powershell/PowerShell-CI-linux to GitHub Actions (#24946)
  • +
  • Convert powershell/PowerShell-Windows-CI to GitHub Actions (#24931)
  • +
  • PMC parse state correctly from update command's response (#24859)
  • +
  • Add EV2 support for publishing PowerShell packages to PMC (#24856)
  • +
+ +
+ +[7.5.1]: https://github.com/PowerShell/PowerShell/compare/v7.5.0...v7.5.1 + +## [7.5.0] + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 9.0.102

+ +
+ +
    +
  • Add tool package download in publish nuget stage (#24790) (#24792)
  • +
  • Fix Changelog content grab during GitHub Release (#24788) (#24791)
  • +
  • Mark build as latest stable (#24789)
  • +
  • [release/v7.5] Update branch for release - Transitive - true - minor (#24786)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.1.0 (#24767) (#24785)
  • +
  • Make the AssemblyVersion not change for servicing releases (#24667) (#24783)
  • +
  • Deploy Box Update (#24632) (#24779)
  • +
  • Update machine pool for copy blob and upload buildinfo stage (#24587) (#24776)
  • +
  • Update nuget publish to use Deploy Box (#24596) (#24597)
  • +
  • Added Deploy Box Product Pathway to GitHub Release and NuGet Release Pipelines (#24583) (#24595)
  • +
+ +
+ +### Documentation and Help Content + +- Update `HelpInfoUri` for 7.5 (#24610) (#24777) + +[7.5.0]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-rc.1...v7.5.0 + +## [7.5.0-rc.1] - 2024-11-14 + +**NOTE:** Due to technical issues, release of packages to packages.microsoft.com ~and release to NuGet.org~ is delayed. + +### Build and Packaging Improvements + +
+ + + +

Bump to .NET 9.0.100

+ +
+ +
    +
  • Update ThirdPartyNotices file (#24582) (#24536)
  • +
  • Bump to .NET 9.0.100 (#24576) (#24535)
  • +
  • Add a way to use only NuGet feed sources (#24528) (#24530)
  • +
  • Update PSResourceGet to v1.1.0-RC2 (#24512) (#24525)
  • +
  • Add PMC mapping for debian 12 (bookworm) (#24413) (#24518)
  • +
  • Bump .NET to 9.0.100-rc.2.24474.11 (#24509) (#24522)
  • +
  • Keep the roff file when gzipping it. (#24450) (#24520)
  • +
  • Checkin generated manpage (#24423) (#24519)
  • +
  • Update PSReadLine to 2.3.6 (#24380) (#24517)
  • +
  • Download package from package build for generating vpack (#24481) (#24521)
  • +
  • Delete the msix blob if it's already there (#24353) (#24516)
  • +
  • Add CodeQL scanning to APIScan build (#24303) (#24515)
  • +
  • Update vpack pipeline (#24281) (#24514)
  • +
  • Fix seed max value for Container Linux CI (#24510) (#24511)
  • +
  • Bring preview.5 release fixes to release/v7.5 (#24379) (#24368)
  • +
  • Add BaseUrl to buildinfo json file (#24376) (#24377)
  • +
+ +
+ +[7.5.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-preview.5...v7.5.0-rc.1 + +## [7.5.0-preview.5] - 2024-10-01 + +### Breaking Changes + +- Treat large `Enum` values as numbers in `ConvertTo-Json` (#20999) (#24304) + +### Engine Updates and Fixes + +- Fix how processor architecture is validated in `Import-Module` (#24265) (#24317) + +### Experimental Features + +### General Cmdlet Updates and Fixes + +- Add `-Force` parameter to `Resolve-Path` and `Convert-Path` cmdlets to support wildcard hidden files (#20981) (#24344) +- Add telemetry to track the use of features (#24247) (#24331) +- Treat large `Enum` values as numbers in `ConvertTo-Json` (#20999) (#24304) +- Make features `PSCommandNotFoundSuggestion`, `PSCommandWithArgs`, and `PSModuleAutoLoadSkipOfflineFiles` stable (#24246) (#24310) +- Handle global tool when prepending `$PSHome` to `PATH` (#24228) (#24307) + +### Tests + +- Fix cleanup in `PSResourceGet` test (#24339) (#24345) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 9.0.100-rc.1.24452.12

+ +
+ +
    +
  • Fixed Test Scenario for Compress-PSResource (Internal 32696)
  • +
  • Add back local NuGet source for test packages (Internal 32693)
  • +
  • Fix typo in release-MakeBlobPublic.yml (Internal 32689)
  • +
  • Copy to static site instead of making blob public (#24269) (#24343)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.1.0-preview2 (#24300) (#24337)
  • +
  • Remove the MD5 branch in the strong name signing token calculation (#24288) (#24321)
  • +
  • Update experimental-feature json files (#24271) (#24319)
  • +
  • Add updated libicu dependency for Debian packages (#24301) (#24324)
  • +
  • Add mapping to AzureLinux repo (#24290) (#24322)
  • +
  • Update and add new NuGet package sources for different environments. (#24264) (#24316)
  • +
  • Bump .NET 9 to 9.0.100-rc.1.24452.12 (#24273) (#24320)
  • +
  • Make some release tests run in a hosted pools (#24270) (#24318)
  • +
  • Do not build the exe for Global tool shim project (#24263) (#24315)
  • +
  • Delete assets/AppImageThirdPartyNotices.txt (#24256) (#24313)
  • +
  • Create new pipeline for compliance (#24252) (#24312)
  • +
  • Add specific path for issues in tsaconfig (#24244) (#24309)
  • +
  • Use Managed Identity for APIScan authentication (#24243) (#24308)
  • +
  • Add Windows signing for pwsh.exe (#24219) (#24306)
  • +
  • Check Create and Submit in vPack build by default (#24181) (#24305)
  • +
+ +
+ +### Documentation and Help Content + +- Delete demos directory (#24258) (#24314) + +[7.5.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-preview.4...v7.5.0-preview.5 + +## [7.5.0-preview.4] - 2024-08-28 + +### Engine Updates and Fixes + +- RecommendedAction: Explicitly start and stop ANSI Error Color (#24065) (Thanks @JustinGrote!) +- Improve .NET overload definition of generic methods (#21326) (Thanks @jborean93!) +- Optimize the `+=` operation for a collection when it's an object array (#23901) (Thanks @jborean93!) +- Allow redirecting to a variable as experimental feature `PSRedirectToVariable` (#20381) + +### General Cmdlet Updates and Fixes + +- Change type of `LineNumber` to `ulong` in `Select-String` (#24075) (Thanks @Snowman-25!) +- Fix `Invoke-RestMethod` to allow `-PassThru` and `-Outfile` work together (#24086) (Thanks @jshigetomi!) +- Fix Hyper-V Remoting when the module is imported via implicit remoting (#24032) (Thanks @jborean93!) +- Add `ConvertTo-CliXml` and `ConvertFrom-CliXml` cmdlets (#21063) (Thanks @ArmaanMcleod!) +- Add `OutFile` property in `WebResponseObject` (#24047) (Thanks @jshigetomi!) +- Show filename in `Invoke-WebRequest -OutFile -Verbose` (#24041) (Thanks @jshigetomi!) +- `Set-Acl`: Do not fail on untranslatable SID (#21096) (Thanks @jborean93!) +- Fix the extent of the parser error when a number constant is invalid (#24024) +- Fix `Move-Item` to throw error when moving into itself (#24004) +- Fix up .NET method invocation with `Optional` argument (#21387) (Thanks @jborean93!) +- Fix progress calculation on `Remove-Item` (#23869) (Thanks @jborean93!) +- Fix WebCmdlets when `-Body` is specified but `ContentType` is not (#23952) (Thanks @CarloToso!) +- Enable `-NoRestart` to work with `Register-PSSessionConfiguration` (#23891) +- Add `IgnoreComments` and `AllowTrailingCommas` options to `Test-Json` cmdlet (#23817) (Thanks @ArmaanMcleod!) +- Get-Help may report parameters with `ValueFromRemainingArguments` attribute as pipeline-able (#23871) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @eltociear

+ +
+ +
    +
  • Minor cleanup on local variable names within a method (#24105)
  • +
  • Remove explicit IDE1005 suppressions (#21217) (Thanks @xtqqczze!)
  • +
  • Fix a typo in WebRequestSession.cs (#23963) (Thanks @eltociear!)
  • +
+ +
+ +### Tools + +- devcontainers: mount workspace in /PowerShell (#23857) (Thanks @rzippo!) + +### Tests + +- Add debugging to the MTU size test (#21463) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@bosesubham2011

+ +
+ +
    +
  • Update third party notices (Internal 32128)
  • +
  • Update cgmanifest (#24163)
  • +
  • Fixes to Azure Public feed usage (#24149)
  • +
  • Add support for back porting PRs from GitHub or the Private Azure Repos (#20670)
  • +
  • Move to 9.0.0-preview.6.24327.7 (#24133)
  • +
  • update path (#24134)
  • +
  • Update to the latest NOTICES file (#24131)
  • +
  • Fix semver issue with updating cgmanifest (#24132)
  • +
  • Add ability to capture MSBuild Binary logs when restore fails (#24128)
  • +
  • add ability to skip windows stage (#24116)
  • +
  • chore: Refactor Nuget package source creation to use New-NugetPackageSource function (#24104)
  • +
  • Make Microsoft feeds the default (#24098)
  • +
  • Cleanup unused csproj (#23951)
  • +
  • Add script to update SDK version during release (#24034)
  • +
  • Enumerate over all signed zip packages (#24063)
  • +
  • Update metadata.json for PowerShell July releases (#24082)
  • +
  • Add macos signing for package files (#24015)
  • +
  • Update install-powershell.sh to support azure-linux (#23955) (Thanks @bosesubham2011!)
  • +
  • Skip build steps that do not have exe packages (#23945)
  • +
  • Update metadata.json for PowerShell June releases (#23973)
  • +
  • Create powershell.config.json for PowerShell.Windows.x64 global tool (#23941)
  • +
  • Fix error in the vPack release, debug script that blocked release (#23904)
  • +
  • Add vPack release (#23898)
  • +
  • Fix exe signing with third party signing for WiX engine (#23878)
  • +
  • Update wix installation in CI (#23870)
  • +
  • Add checkout to fix TSA config paths (#23865)
  • +
  • Merge the v7.5.0-preview.3 release branch to GitHub master branch
  • +
  • Update metadata.json for the v7.5.0-preview.3 release (#23862)
  • +
  • Bump PSResourceGet to 1.1.0-preview1 (#24129)
  • +
  • Bump github/codeql-action from 3.25.8 to 3.26.0 (#23953) (#23999) (#24053) (#24069) (#24095) (#24118)
  • +
  • Bump actions/upload-artifact from 4.3.3 to 4.3.6 (#24019) (#24113) (#24119)
  • +
  • Bump agrc/create-reminder-action from 1.1.13 to 1.1.15 (#24029) (#24043)
  • +
  • Bump agrc/reminder-action from 1.0.12 to 1.0.14 (#24028) (#24042)
  • +
  • Bump super-linter/super-linter from 5.7.2 to 6.8.0 (#23809) (#23856) (#23894) (#24030) (#24103)
  • +
  • Bump ossf/scorecard-action from 2.3.1 to 2.4.0 (#23802) (#24096)
  • +
  • Bump actions/dependency-review-action from 4.3.2 to 4.3.4 (#23897) (#24046)
  • +
  • Bump actions/checkout from 4.1.5 to 4.1.7 (#23813) (#23947)
  • +
  • Bump github/codeql-action from 3.25.4 to 3.25.8 (#23801) (#23893)
  • +
+ +
+ +### Documentation and Help Content + +- Update docs sample nuget.config (#24109) +- Update Code of Conduct and Security Policy (#23811) +- Update working-group-definitions.md for the Security WG (#23884) +- Fix up broken links in Markdown files (#23863) +- Update Engine Working Group Members (#23803) (Thanks @kilasuit!) +- Remove outdated and contradictory information from `README` (#23812) + +[7.5.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-preview.3...v7.5.0-preview.4 + +## [7.5.0-preview.3] - 2024-05-16 + +### Breaking Changes + +- Remember installation options and used them to initialize options for the next installation (#20420) (Thanks @reduckted!) +- `ConvertTo-Json`: Serialize `BigInteger` as a number (#21000) (Thanks @jborean93!) + +### Engine Updates and Fixes + +- Fix generating `OutputType` when running in Constrained Language Mode (#21605) +- Revert the PR #17856 (Do not preserve temporary results when no need to do so) (#21368) +- Make sure the assembly/library resolvers are registered at early stage (#21361) +- Fix PowerShell class to support deriving from an abstract class with abstract properties (#21331) +- Fix error formatting for pipeline enumeration exceptions (#20211) + +### General Cmdlet Updates and Fixes + +- Added progress bar for `Remove-Item` cmdlet (#20778) (Thanks @ArmaanMcleod!) +- Expand `~` to `$home` on Windows with tab completion (#21529) +- Separate DSC configuration parser check for ARM processor (#21395) (Thanks @dkontyko!) +- Fix `[semver]` type to pass `semver.org` tests (#21401) +- Don't complete when declaring parameter name and class member (#21182) (Thanks @MartinGC94!) +- Add `RecommendedAction` to `ConciseView` of the error reporting (#20826) (Thanks @JustinGrote!) +- Fix the error when using `Start-Process -Credential` without the admin privilege (#21393) (Thanks @jborean93!) +- Fix `Test-Path -IsValid` to check for invalid path and filename characters (#21358) +- Fix build failure due to missing reference in `GlobalToolShim.cs` (#21388) +- Fix argument passing in `GlobalToolShim` (#21333) (Thanks @ForNeVeR!) +- Make sure both stdout and stderr can be redirected from a native executable (#20997) +- Handle the case that `Runspace.DefaultRunspace == null` when logging for WDAC Audit (#21344) +- Fix a typo in `releaseTools.psm1` (#21306) (Thanks @eltociear!) +- `Get-Process`: Remove admin requirement for `-IncludeUserName` (#21302) (Thanks @jborean93!) +- Fall back to type inference when hashtable key-value cannot be retrieved from safe expression (#21184) (Thanks @MartinGC94!) +- Fix the regression when doing type inference for `$_` (#21223) (Thanks @MartinGC94!) +- Revert "Adjust PUT method behavior to POST one for default content type in WebCmdlets" (#21049) +- Fix a regression in `Format-Table` when header label is empty (#21156) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze

+ +
+ +
    +
  • Enable CA1868: Unnecessary call to 'Contains' for sets (#21165) (Thanks @xtqqczze!)
  • +
  • Remove JetBrains.Annotations attributes (#21246) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tests + +- Update `metadata.json` and `README.md` (#21454) +- Skip test on Windows Server 2012 R2 for `no-nl` (#21265) + +### Build and Packaging Improvements + +
+ + + +

Bump to .NET 9.0.0-preview.3

+

We thank the following contributors!

+

@alerickson, @tgauth, @step-security-bot, @xtqqczze

+ +
+ +
    +
  • Fix PMC publish and the file path for msixbundle
  • +
  • Fix release version and stage issues in build and packaging
  • +
  • Add release tag if the environment variable is set
  • +
  • Update installation on Wix module (#23808)
  • +
  • Updates to package and release pipelines (#23800)
  • +
  • Update PSResourceGet to 1.0.5 (#23796)
  • +
  • Bump actions/upload-artifact from 4.3.2 to 4.3.3 (#21520)
  • +
  • Bump actions/dependency-review-action from 4.2.5 to 4.3.2 (#21560)
  • +
  • Bump actions/checkout from 4.1.2 to 4.1.5 (#21613)
  • +
  • Bump github/codeql-action from 3.25.1 to 3.25.4 (#22071)
  • +
  • Use feed with Microsoft Wix toolset (#21651) (Thanks @tgauth!)
  • +
  • Bump to .NET 9 preview 3 (#21782)
  • +
  • Use PSScriptRoot to find path to Wix module (#21611)
  • +
  • Create the Windows.x64 global tool with shim for signing (#21559)
  • +
  • Update Wix package install (#21537) (Thanks @tgauth!)
  • +
  • Add branch counter variables for daily package builds (#21523)
  • +
  • Use correct signing certificates for RPM and DEBs (#21522)
  • +
  • Revert to version available on Nuget for Microsoft.CodeAnalysis.Analyzers (#21515)
  • +
  • Official PowerShell Package pipeline (#21504)
  • +
  • Add a PAT for fetching PMC cli (#21503)
  • +
  • Bump ossf/scorecard-action from 2.0.6 to 2.3.1 (#21485)
  • +
  • Apply security best practices (#21480) (Thanks @step-security-bot!)
  • +
  • Bump Microsoft.CodeAnalysis.Analyzers (#21449)
  • +
  • Fix package build to not check some files for a signature. (#21458)
  • +
  • Update PSResourceGet version from 1.0.2 to 1.0.4.1 (#21439) (Thanks @alerickson!)
  • +
  • Verify environment variable for OneBranch before we try to copy (#21441)
  • +
  • Add back two transitive dependency packages (#21415)
  • +
  • Multiple fixes in official build pipeline (#21408)
  • +
  • Update PSReadLine to v2.3.5 (#21414)
  • +
  • PowerShell co-ordinated build OneBranch pipeline (#21364)
  • +
  • Add file description to pwsh.exe (#21352)
  • +
  • Suppress MacOS package manager output (#21244) (Thanks @xtqqczze!)
  • +
  • Update metadata.json and README.md (#21264)
  • +
+ +
+ +### Documentation and Help Content + +- Update the doc about how to build PowerShell (#21334) (Thanks @ForNeVeR!) +- Update the member lists for the Engine and Interactive-UX working groups (#20991) (Thanks @kilasuit!) +- Update CHANGELOG for `v7.2.19`, `v7.3.12` and `v7.4.2` (#21462) +- Fix grammar in `FAQ.md` (#21468) (Thanks @CodingGod987!) +- Fix typo in `SessionStateCmdletAPIs.cs` (#21413) (Thanks @eltociear!) +- Fix typo in a test (#21337) (Thanks @testwill!) +- Fix typo in `ast.cs` (#21350) (Thanks @eltociear!) +- Adding Working Group membership template (#21153) + +[7.5.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-preview.2...v7.5.0-preview.3 + +## [7.5.0-preview.2] - 2024-02-22 + +### Engine Updates and Fixes + +- Fix `using assembly` to use `Path.Combine` when constructing assembly paths (#21169) +- Validate the value for `using namespace` during semantic checks to prevent declaring invalid namespaces (#21162) + +### General Cmdlet Updates and Fixes + +- Add `WinGetCommandNotFound` and `CompletionPredictor` modules to track usage (#21040) +- `ConvertFrom-Json`: Add `-DateKind` parameter (#20925) (Thanks @jborean93!) +- Add tilde expansion for windows native executables (#20402) (Thanks @domsleee!) +- Add `DirectoryInfo` to the `OutputType` for `New-Item` (#21126) (Thanks @MartinGC94!) +- Fix `Get-Error` serialization of array values (#21085) (Thanks @jborean93!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear

+ +
+ +
    +
  • Fix a typo in CoreAdapter.cs (#21179) (Thanks @eltociear!)
  • +
  • Remove PSScheduledJob module source code (#21189)
  • +
+ +
+ +### Tests + +- Rewrite the mac syslog tests to make them less flaky (#21174) + +### Build and Packaging Improvements + +
+ + +

Bump to .NET 9 Preview 1

+

We thank the following contributors!

+

@gregsdennis

+ +
+ +
    +
  • Bump to .NET 9 Preview 1 (#21229)
  • +
  • Add dotnet-runtime-9.0 as a dependency for the Mariner package
  • +
  • Add dotenv install as latest version does not work with current Ruby version (#21239)
  • +
  • Remove surrogateFile setting of APIScan (#21238)
  • +
  • Update experimental-feature json files (#21213)
  • +
  • Update to the latest NOTICES file (#21236)(#21177)
  • +
  • Update the cgmanifest (#21237)(#21093)
  • +
  • Update the cgmanifest (#21178)
  • +
  • Bump XunitXml.TestLogger from 3.1.17 to 3.1.20 (#21207)
  • +
  • Update versions of PSResourceGet (#21190)
  • +
  • Generate MSI for win-arm64 installer (#20516)
  • +
  • Bump JsonSchema.Net to v5.5.1 (#21120) (Thanks @gregsdennis!)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README.md` and `metadata.json` for v7.5.0-preview.1 release (#21094) +- Fix incorrect examples in XML docs in `PowerShell.cs` (#21173) +- Update WG members (#21091) +- Update changelog for v7.4.1 (#21098) + +[7.5.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-preview.1...v7.5.0-preview.2 + +## [7.5.0-preview.1] - 2024-01-18 + +### Breaking Changes + +- Fix `-OlderThan` and `-NewerThan` parameters for `Test-Path` when using `PathType` and date range (#20942) (Thanks @ArmaanMcleod!) +- Previously `-OlderThan` would be ignored if specified together +- Change `New-FileCatalog -CatalogVersion` default to 2 (#20428) (Thanks @ThomasNieto!) + +### General Cmdlet Updates and Fixes + +- Fix completion crash for the SCCM provider (#20815, #20919, #20915) (Thanks @MartinGC94!) +- Fix regression in `Get-Content` when `-Tail 0` and `-Wait` are used together (#20734) (Thanks @CarloToso!) +- Add `Aliases` to the properties shown up when formatting the help content of the parameter returned by `Get-Help` (#20994) +- Add implicit localization fallback to `Import-LocalizedData` (#19896) (Thanks @chrisdent-de!) +- Change `Test-FileCatalog` to use `File.OpenRead` to better handle the case where the file is being used (#20939) (Thanks @dxk3355!) +- Added `-Module` completion for `Save-Help` and `Update-Help` commands (#20678) (Thanks @ArmaanMcleod!) +- Add argument completer to `-Verb` for `Start-Process` (#20415) (Thanks @ArmaanMcleod!) +- Add argument completer to `-Scope` for `*-Variable`, `*-Alias` & `*-PSDrive` commands (#20451) (Thanks @ArmaanMcleod!) +- Add argument completer to `-Verb` for `Get-Verb` and `Get-Command` (#20286) (Thanks @ArmaanMcleod!) +- Fixing incorrect formatting string in `CommandSearcher` trace logging (#20928) (Thanks @powercode!) +- Ensure the filename is not null when logging WDAC ETW events (#20910) (Thanks @jborean93!) +- Fix four regressions introduced by the WDAC logging feature (#20913) +- Leave the input, output, and error handles unset when they are not redirected (#20853) +- Fix `Start-Process -PassThru` to make sure the `ExitCode` property is accessible for the returned `Process` object (#20749) (Thanks @CodeCyclone!) +- Fix `Group-Object` output using interpolated strings (#20745) (Thanks @mawosoft!) +- Fix rendering of `DisplayRoot` for network `PSDrive` (#20793) +- Fix `Invoke-WebRequest` to report correct size when `-Resume` is specified (#20207) (Thanks @LNKLEO!) +- Add `PSAdapter` and `ConsoleGuiTools` to module load telemetry allow list (#20641) +- Fix Web Cmdlets to allow `WinForm` apps to work correctly (#20606) +- Block getting help from network locations in restricted remoting sessions (#20593) +- Fix `Group-Object` to use current culture for its output (#20608) +- Add argument completer to `-Version` for `Set-StrictMode` (#20554) (Thanks @ArmaanMcleod!) +- Fix `Copy-Item` progress to only show completed when all files are copied (#20517) +- Fix UNC path completion regression (#20419) (Thanks @MartinGC94!) +- Add telemetry to check for specific tags when importing a module (#20371) +- Report error if invalid `-ExecutionPolicy` is passed to `pwsh` (#20460) +- Add `HelpUri` to `Remove-Service` (#20476) +- Fix `unixmode` to handle `setuid` and `sticky` when file is not an executable (#20366) +- Fix `Test-Connection` due to .NET 8 changes (#20369) +- Fix implicit remoting proxy cmdlets to act on common parameters (#20367) +- Set experimental features to stable for 7.4 release (#20285) +- Revert changes to continue using `BinaryFormatter` for `Out-GridView` (#20300) +- Fix `Get-Service` non-terminating error message to include category (#20276) +- Prevent `Export-CSV` from flushing with every input (#20282) (Thanks @Chris--A!) +- Fix a regression in DSC (#20268) +- Include the module version in error messages when module is not found (#20144) (Thanks @ArmaanMcleod!) +- Add `-Empty` and `-InputObject` parameters to `New-Guid` (#20014) (Thanks @CarloToso!) +- Remove the comment trigger from feedback provider (#20136) +- Prevent fallback to file completion when tab completing type names (#20084) (Thanks @MartinGC94!) +- Add the alias `r` to the parameter `-Recurse` for the `Get-ChildItem` command (#20100) (Thanks @kilasuit!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @ImportTaste, @ThomasNieto, @0o001

+ +
+ +
    +
  • Fix typos in the code base (#20147, #20492, #20632, #21015, #20838) (Thanks @eltociear!)
  • +
  • Add the missing alias LP to -LiteralPath for some cmdlets (#20820) (Thanks @ImportTaste!)
  • +
  • Remove parenthesis for empty attribute parameters (#20087) (Thanks @ThomasNieto!)
  • +
  • Add space around keyword according to the CodeFactor rule (#20090) (Thanks @ThomasNieto!)
  • +
  • Remove blank lines as instructed by CodeFactor rules (#20086) (Thanks @ThomasNieto!)
  • +
  • Remove trailing whitespace (#20085) (Thanks @ThomasNieto!)
  • +
  • Fix typo in error message (#20145) (Thanks @0o001!)
  • +
+ +
+ +### Tools + +- Make sure feedback link in the bot's comment is clickable (#20878) (Thanks @floh96!) +- Fix bot so anyone who comments will remove the "Resolution-No Activity" label (#20788) +- Fix bot configuration to prevent multiple comments about "no activity" (#20758) +- Add bot logic for closing GitHub issues after 6 months of "no activity" (#20525) +- Refactor bot for easier use and updating (#20805) +- Configure bot to add survey comment for closed issues (#20397) + +### Tests + +- Suppress error output from `Set-Location` tests (#20499) +- Fix typo in `FileCatalog.Tests.ps1` (#20329) (Thanks @eltociear!) +- Continue to improve tests for release automation (#20182) +- Skip the test on x86 as `InstallDate` is not visible on `Wow64` (#20165) +- Harden some problematic release tests (#20155) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@alerickson, @Zhoneym, @0o001

+ +
+ +
    +
  • Bump .NET SDK to 8.0.101 (#21084)
  • +
  • Update the cgmanifest (#20083, #20436, #20523, #20560, #20627, #20764, #20906, #20933, #20955, #21047)
  • +
  • Update to the latest NOTICES file (#20074, #20161, #20385, #20453, #20576, #20590, #20880, #20905)
  • +
  • Bump StyleCop.Analyzers from 1.2.0-beta.507 to 1.2.0-beta.556 (#20953)
  • +
  • Bump xUnit to 2.6.6 (#21071)
  • +
  • Bump JsonSchema.Net to 5.5.0 (#21027)
  • +
  • Fix failures in GitHub action markdown-link-check (#20996)
  • +
  • Bump xunit.runner.visualstudio to 2.5.6 (#20966)
  • +
  • Bump github/codeql-action from 2 to 3 (#20927)
  • +
  • Bump Markdig.Signed to 0.34.0 (#20926)
  • +
  • Bump Microsoft.ApplicationInsights from 2.21.0 to 2.22.0 (#20888)
  • +
  • Bump Microsoft.NET.Test.Sdk to 17.8.0 (#20660)
  • +
  • Update apiscan.yml to have access to the AzDevOpsArtifacts variable group (#20671)
  • +
  • Set the ollForwardOnNoCandidateFx in runtimeconfig.json to roll forward only on minor and patch versions (#20689)
  • +
  • Sign the global tool shim executable (#20794)
  • +
  • Bump actions/github-script from 6 to 7 (#20682)
  • +
  • Remove RHEL7 publishing to packages.microsoft.com as it's no longer supported (#20849)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp to 4.8.0 (#20751)
  • +
  • Add internal nuget feed to compliance build (#20669)
  • +
  • Copy azure blob with PowerShell global tool to private blob and move to CDN during release (#20659)
  • +
  • Fix release build by making the internal SDK parameter optional (#20658)
  • +
  • Update PSResourceGet version to 1.0.1 (#20652)
  • +
  • Make internal .NET SDK URL as a parameter for release builld (#20655)
  • +
  • Fix setting of variable to consume internal SDK source (#20644)
  • +
  • Bump Microsoft.Management.Infrastructure to v3.0.0 (#20642)
  • +
  • Bump Microsoft.PowerShell.Native to v7.4.0 (#20617)
  • +
  • Bump Microsoft.Security.Extensions from 1.2.0 to 1.3.0 (#20556)
  • +
  • Fix package version for .NET nuget packages (#20551)
  • +
  • Add SBOM for release pipeline (#20519)
  • +
  • Block any preview vPack release (#20243)
  • +
  • Only registry App Path for release package (#20478)
  • +
  • Increase timeout when publishing packages to pacakages.microsoft.com (#20470)
  • +
  • Fix alpine tar package name and do not crossgen alpine fxdependent package (#20459)
  • +
  • Bump PSReadLine from 2.2.6 to 2.3.4 (#20305)
  • +
  • Remove the ref folder before running compliance (#20373)
  • +
  • Updates RIDs used to generate component Inventory (#20370)
  • +
  • Bump XunitXml.TestLogger from 3.1.11 to 3.1.17 (#20293)
  • +
  • Update experimental-feature json files (#20335)
  • +
  • Use fxdependent-win-desktop runtime for compliance runs (#20326)
  • +
  • Release build: Change the names of the PATs (#20307)
  • +
  • Add mapping for mariner arm64 stable (#20213)
  • +
  • Put the calls to Set-AzDoProjectInfo and Set-AzDoAuthToken in the right order (#20306)
  • +
  • Enable vPack provenance data (#20220)
  • +
  • Bump actions/checkout from 3 to 4 (#20205)
  • +
  • Start using new packages.microsoft.com cli (#20140, #20141)
  • +
  • Add mariner arm64 to PMC release (#20176)
  • +
  • Fix typo donet to dotnet in build scripts and pipelines (#20122) (Thanks @0o001!)
  • +
  • Install the pmc cli
  • +
  • Add skip publish parameter
  • +
  • Add verbose to clone
  • +
+ +
+ +### Documentation and Help Content + +- Include information about upgrading in readme (#20993) +- Expand "iff" to "if-and-only-if" in XML doc content (#20852) +- Update LTS links in README.md to point to the v7.4 packages (#20839) (Thanks @kilasuit!) +- Update `README.md` to improve readability (#20553) (Thanks @AnkitaSikdar005!) +- Fix link in `docs/community/governance.md` (#20515) (Thanks @suravshresth!) +- Update `ADOPTERS.md` (#20555) (Thanks @AnkitaSikdar005!) +- Fix a typo in `ADOPTERS.md` (#20504, #20520) (Thanks @shruti-sen2004!) +- Correct grammatical errors in `README.md` (#20509) (Thanks @alienishi!) +- Add 7.3 changelog URL to readme (#20473) (Thanks @Saibamen!) +- Clarify some comments and documentation (#20462) (Thanks @darkstar!) + +[7.5.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.4.1...v7.5.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/7.6.md b/PowerShell-master/CHANGELOG/7.6.md new file mode 100644 index 0000000000000000000000000000000000000000..47a8d33182fe03f12e4a424f6194d423c5e007cb --- /dev/null +++ b/PowerShell-master/CHANGELOG/7.6.md @@ -0,0 +1,807 @@ +# 7.6 Changelog + +## [7.6.0] + +### General Cmdlet Updates and Fixes + +- Update PowerShell Profile DSC resource manifests to allow `null` for content (#26973) + +### Tests + +- Add GitHub Actions annotations for Pester test failures (#26969) +- Fix `Import-Module.Tests.ps1` to handle Arm32 platform (#26888) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 10.0.201

+ +
+ +
    +
  • Update v7.6 release branch to use .NET SDK 10.0.201 (#27041)
  • +
  • Create LTS package and non-LTS package for macOS for LTS releases (#27040)
  • +
  • Fix the container image for package pipelines (#27020)
  • +
  • Update Microsoft.PowerShell.PSResourceGet version to 1.2.0 (#27007)
  • +
  • Update LTS and Stable release settings in metadata (#27006)
  • +
  • Update branch for release (#26989)
  • +
  • Fix ConvertFrom-ClearlyDefinedCoordinates to handle API object coordinates (#26986)
  • +
  • Update NuGet package versions in cgmanifest.json to actually match the branch (#26982)
  • +
  • Bump actions/upload-artifact from 6 to 7 (#26979)
  • +
  • Split TPN manifest and Component Governance manifest (#26978)
  • +
  • Bump github/codeql-action from 4.32.4 to 4.32.6 (#26975)
  • +
  • Bump actions/dependency-review-action from 4.8.3 to 4.9.0 (#26974)
  • +
  • Hardcode Official templates (#26972)
  • +
  • Fix a preview detection test for the packaging script (#26971)
  • +
  • Add PMC packages for debian13 and rhel10 (#26917)
  • +
  • Add version in description and pass store task on failure (#26889)
  • +
  • Exclude .exe packages from publishing to GitHub (#26887)
  • +
  • Correct the package name for .deb and .rpm packages (#26884)
  • +
+ +
+ +[7.6.0]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-rc.1...v7.6.0 + +## [7.6.0-rc.1] - 2026-02-19 + +### Tests + +- Fix `$PSDefaultParameterValues` leak causing tests to skip unexpectedly (#26705) + +### Build and Packaging Improvements + +
+ + + +

Expand to see details.

+ +
+ +
    +
  • Update branch for release (#26779)
  • +
  • Update Microsoft.PowerShell.PSResourceGet version to 1.2.0-rc3 (#26767)
  • +
  • Update Microsoft.PowerShell.Native package version (#26748)
  • +
  • Move PowerShell build to depend on .NET SDK 10.0.102 (#26717)
  • +
  • Fix buildinfo.json uploading for preview, LTS, and stable releases (#26715)
  • +
  • Fix macOS preview package identifier detection to use version string (#26709)
  • +
  • Update metadata.json to update the Latest attribute with a better name (#26708)
  • +
  • Remove unused runCodesignValidationInjection variable from pipeline templates (#26707)
  • +
  • Update Get-ChangeLog to handle backport PRs correctly (#26706)
  • +
  • Bring release changes from the v7.6.0-preview.6 release (#26626)
  • +
  • Fix the DSC test by skipping AfterAll cleanup if the initial setup in BeforeAll failed (#26622)
  • +
+ +
+ +[7.6.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-preview.6...v7.6.0-rc.1 + +## [7.6.0-preview.6] - 2025-12-11 + +### Engine Updates and Fixes + +- Properly Expand Aliases to their actual ResolvedCommand (#26571) (Thanks @kilasuit!) + +### General Cmdlet Updates and Fixes + +- Update `Microsoft.PowerShell.PSResourceGet` to `v1.2.0-preview5` (#26590) +- Make the experimental feature `PSFeedbackProvider` stable (#26502) +- Fix a regression in the API `CompletionCompleters.CompleteFilename()` that causes null reference exception (#26487) +- Add Delimiter parameter to `Get-Clipboard` (#26572) (Thanks @MartinGC94!) +- Close pipe client handles after creating the child ssh process (#26564) +- Make some experimental features stable (#26490) +- DSC v3 resource for PowerShell Profile (#26447) + +### Tools + +- Add merge conflict marker detection to linux-ci workflow and refactor existing actions to use reusable get-changed-files action (#26530) +- Add reusable get-changed-files action and refactor existing actions (#26529) +- Refactor analyze job to reusable workflow and enable on Windows CI (#26494) + +### Tests + +- Fix merge conflict checker for empty file lists and filter *.cs files (#26556) +- Add markdown link verification for PRs (#26445) + +### Build and Packaging Improvements + +
+ + + +

Expand to see details.

+ +
+ +
    +
  • Fix template path for rebuild branch check in package.yml (#26560)
  • +
  • Update the macos package name for preview releases to match the previous pattern (#26576)
  • +
  • Add rebuild branch support with conditional MSIX signing (#26573)
  • +
  • Update the WCF packages to the latest version that is compatible with v4.10.3 (#26503)
  • +
  • Improve ADO package build and validation across platforms (#26532)
  • +
  • Mirror .NET/runtime ICU version range in PowerShell (#26563) (Thanks @kasperk81!)
  • +
  • Update the macos package name for preview releases to match the previous pattern (#26562)
  • +
  • Fix condition syntax for StoreBroker package tasks in MSIX pipeline (#26561)
  • +
  • Move package validation to package pipeline (#26558)
  • +
  • Optimize/split windows package signing (#26557)
  • +
  • Remove usage of fpm for DEB package generation (#26504)
  • +
  • Add log grouping to build.psm1 for collapsible GitHub Actions logs (#26524)
  • +
  • Replace fpm with native macOS packaging tools (pkgbuild/productbuild) (#26501)
  • +
  • Replace fpm with native rpmbuild for RPM package generation (#26441)
  • +
  • Fix GitHub API rate limit errors in test actions (#26492)
  • +
  • Convert Azure DevOps Linux Packaging pipeline to GitHub Actions workflow (#26493)
  • +
  • Refactor: Centralize xUnit tests into reusable workflow and remove legacy verification (#26488)
  • +
  • Fix build to only enable ready-to-run for the Release configuration (#26481)
  • +
  • Integrate Windows packaging into windows-ci workflow using reusable workflow (#26468)
  • +
  • Update outdated package references (#26471)
  • +
  • GitHub Workflow cleanup (#26439)
  • +
  • Update PSResourceGet package version to preview4 (#26438)
  • +
  • Update PSReadLine to v2.4.5 (#26446)
  • +
  • Add network isolation policy parameter to vPack pipeline (#26444)
  • +
  • Fix a couple more lint errors
  • +
  • Fix lint errors in preview.md
  • +
  • Make MSIX publish stage dependent on SetReleaseTagandContainerName stage
  • +
+ +
+ +[7.6.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-preview.5...v7.6.0-preview.6 + +## [7.6.0-preview.5] - 2025-09-30 + +### Engine Updates and Fixes + +- Allow opt-out of the named-pipe listener using the environment variable `POWERSHELL_DIAGNOSTICS_OPTOUT` (#26086) +- Ensure that socket timeouts are set only during the token validation (#26066) +- Fix race condition in `RemoteHyperVSocket` (#26057) +- Fix `stderr` output of console host to respect `NO_COLOR` (#24391) +- Update PSRP protocol to deprecate session key exchange between newer client and server (#25774) +- Fix the `ssh` PATH check in `SSHConnectionInfo` when the default Runspace is not available (#25780) (Thanks @jborean93!) +- Adding hex format for native command exit codes (#21067) (Thanks @sba923!) +- Fix infinite loop crash in variable type inference (#25696) (Thanks @MartinGC94!) +- Add `PSForEach` and `PSWhere` as aliases for the PowerShell intrinsic methods `Where` and `Foreach` (#25511) (Thanks @powercode!) + +### General Cmdlet Updates and Fixes + +- Remove `IsScreenReaderActive()` check from `ConsoleHost` (#26118) +- Fix `ConvertFrom-Json` to ignore comments inside array literals (#14553) (#26050) (Thanks @MatejKafka!) +- Fix `-Debug` to not trigger the `ShouldProcess` prompt (#26081) +- Add the parameter `Register-ArgumentCompleter -NativeFallback` to support registering a cover-all completer for native commands (#25230) +- Change the default feedback provider timeout from 300ms to 1000ms (#25910) +- Update PATH environment variable for package manager executable on Windows (#25847) +- Fix `Write-Host` to respect `OutputRendering = PlainText` (#21188) +- Improve the `$using` expression support in `Invoke-Command` (#24025) (Thanks @jborean93!) +- Use parameter `HelpMessage` for tool tip in parameter completion (#25108) (Thanks @jborean93!) +- Revert "Never load a module targeting the PSReadLine module's `SessionState`" (#25792) +- Fix debug tracing error with magic extents (#25726) (Thanks @jborean93!) +- Add `MethodInvocation` trace for overload tracing (#21320) (Thanks @jborean93!) +- Improve verbose and debug logging level messaging in web cmdlets (#25510) (Thanks @JustinGrote!) +- Fix quoting in completion if the path includes a double quote character (#25631) (Thanks @MartinGC94!) +- Fix the common parameter `-ProgressAction` for advanced functions (#24591) (Thanks @cmkb3!) +- Use absolute path in `FileSystemProvider.CreateDirectory` (#24615) (Thanks @Tadas!) +- Make inherited protected internal instance members accessible in PowerShell class scope (#25245) (Thanks @mawosoft!) +- Treat `-Target` as literal in `New-Item` (#25186) (Thanks @GameMicrowave!) +- Remove duplicate modules from completion results (#25538) (Thanks @MartinGC94!) +- Add completion for variables assigned in `ArrayLiteralAst` and `ParenExpressionAst` (#25303) (Thanks @MartinGC94!) +- Add support for thousands separators in `[bigint]` casting (#25396) (Thanks @AbishekPonmudi!) +- Add internal methods to check Preferences (#25514) (Thanks @iSazonov!) +- Improve debug logging of Web cmdlet request and response (#25479) (Thanks @JustinGrote!) +- Revert "Allow empty prefix string in 'Import-Module -Prefix' to override default prefix in manifest (#20409)" (#25462) (Thanks @MartinGC94!) +- Fix the `NullReferenceException` when writing progress records to console from multiple threads (#25440) (Thanks @kborowinski!) +- Update `Get-Service` to ignore common errors when retrieving non-critical properties for a service (#24245) (Thanks @jborean93!) +- Add single/double quote support for `Join-String` Argument Completer (#25283) (Thanks @ArmaanMcleod!) +- Fix tab completion for env/function variables (#25346) (Thanks @jborean93!) +- Fix `Out-GridView` by replacing use of obsolete `BinaryFormatter` with custom implementation (#25497) (Thanks @mawosoft!) +- Remove the use of Windows PowerShell ETW provider ID from codebase and update the `PSDiagnostics` module to work for PowerShell 7 (#25590) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @mawosoft, @ArmaanMcleod

+ +
+ +
    +
  • Enable CA2021: Do not call Enumerable.Cast or Enumerable.OfType with incompatible types (#25813) (Thanks @xtqqczze!)
  • +
  • Remove some unused ConsoleControl structs (#26063) (Thanks @xtqqczze!)
  • +
  • Remove unused FileStreamBackReader.NativeMethods type (#26062) (Thanks @xtqqczze!)
  • +
  • Ensure data-serialization files end with one newline (#26039) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary CS0618 suppressions from Variant APIs (#26006) (Thanks @xtqqczze!)
  • +
  • Ensure .cs files end with exactly one newline (#25968) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA2105 rule suppression (#25938) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA1703 rule suppression (#25955) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA2240 rule suppression (#25957) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA1701 rule suppression (#25948) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA2233 rule suppression (#25951) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA1026 rule suppression (#25934) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA1059 rule suppression (#25940) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA2118 rule suppression (#25924) (Thanks @xtqqczze!)
  • +
  • Remove redundant System.Runtime.Versioning attributes (#25926) (Thanks @xtqqczze!)
  • +
  • Seal internal types in Microsoft.PowerShell.Commands.Utility (#25892) (Thanks @xtqqczze!)
  • +
  • Seal internal types in Microsoft.PowerShell.Commands.Management (#25849) (Thanks @xtqqczze!)
  • +
  • Make the interface IDeepCloneable internal to minimize confusion (#25552)
  • +
  • Remove OnDeserialized and Serializable attributes from Microsoft.Management.UI.Internal project (#25548)
  • +
  • Refactor Tooltip/ListItemText mapping to use CompletionDisplayInfoMapper delegate (#25395) (Thanks @ArmaanMcleod!)
  • +
+ +
+ +### Tools + +- Add Codeql Suppressions (#25943, #26132) +- Update CODEOWNERS to add Justin as a maintainer (#25386) +- Do not run labels workflow in the internal repository (#25279) + +### Tests + +- Mark the 3 consistently failing tests as pending to unblock PRs (#26091) +- Make some tests less noisy on failure (#26035) (Thanks @xtqqczze!) +- Suppress false positive `PSScriptAnalyzer` warnings in tests and build scripts (#25864) +- Fix updatable help test for new content (#25819) +- Add more tests for `PSForEach` and `PSWhere` methods (#25519) +- Fix the isolated module test that was disabled previously (#25420) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@alerickson, @senerh, @RichardSlater, @xtqqczze

+ +
+ +
    +
  • Update package references for the master branch (#26124)
  • +
  • Remove ThreadJob module and update PSReadLine to 2.4.4-beta4 (#26120)
  • +
  • Automate Store Publishing (#25725)
  • +
  • Add global config change detection to action (#26082)
  • +
  • Update outdated package references (#26069)
  • +
  • Ensure that the workflows are triggered on .globalconfig and other files at the root of the repo (#26034)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.2.0-preview3 (#26056) (Thanks @alerickson!)
  • +
  • Update metadata for Stable to v7.5.3 and LTS to v7.4.12 (#26054) (Thanks @senerh!)
  • +
  • Bump github/codeql-action from 3.30.2 to 3.30.3 (#26036)
  • +
  • Update version for the package Microsoft.PowerShell.Native (#26041)
  • +
  • Fix the APIScan pipeline (#26016)
  • +
  • Move PowerShell build to use .NET SDK 10.0.100-rc.1 (#26027)
  • +
  • fix(apt-package): add libicu76 dependency to support Debian 13 (#25866) (Thanks @RichardSlater!)
  • +
  • Bump github/codeql-action from 3.30.1 to 3.30.2 (#26029)
  • +
  • Update Ev2 Shell Extension Image to AzureLinux 3 for PMC Release (#26025)
  • +
  • Bump github/codeql-action from 3.30.0 to 3.30.1 (#26008)
  • +
  • Bump actions/github-script from 7 to 8 (#25983)
  • +
  • Fix variable reference for release environment in pipeline (#26012)
  • +
  • Add LinuxHost Network configuration to PowerShell Packages pipeline (#26000)
  • +
  • Make logical template name consistent between pipelines (#25990)
  • +
  • Update container images to use mcr.microsoft.com for Linux and Azure GǪ (#25981)
  • +
  • Bump github/codeql-action from 3.29.11 to 3.30.0 (#25966)
  • +
  • Bump actions/setup-dotnet from 4 to 5 (#25978)
  • +
  • Add build to vPack Pipeline (#25915)
  • +
  • Replace DOTNET_SKIP_FIRST_TIME_EXPERIENCE with DOTNET_NOLOGO (#25946) (Thanks @xtqqczze!)
  • +
  • Bump actions/dependency-review-action from 4.7.2 to 4.7.3 (#25930)
  • +
  • Bump github/codeql-action from 3.29.10 to 3.29.11 (#25889)
  • +
  • Remove AsyncSDL from Pipelines Toggle Official/NonOfficial Runs (#25885)
  • +
  • Specify .NET Search by Build Type (#25837)
  • +
  • Update PowerShell to use .NET SDK v10-preview.7 (#25876)
  • +
  • Bump actions/dependency-review-action from 4.7.1 to 4.7.2 (#25882)
  • +
  • Bump github/codeql-action from 3.29.9 to 3.29.10 (#25881)
  • +
  • Change the macos runner image to macos 15 large (#25867)
  • +
  • Bump actions/checkout from 4 to 5 (#25853)
  • +
  • Bump github/codeql-action from 3.29.7 to 3.29.9 (#25857)
  • +
  • Update to .NET 10 Preview 6 (#25828)
  • +
  • Bump agrc/create-reminder-action from 1.1.20 to 1.1.22 (#25808)
  • +
  • Bump agrc/reminder-action from 1.0.17 to 1.0.18 (#25807)
  • +
  • Bump github/codeql-action from 3.28.19 to 3.29.5 (#25797)
  • +
  • Bump super-linter/super-linter from 7.4.0 to 8.0.0 (#25770)
  • +
  • Update metadata for v7.5.2 and v7.4.11 releases (#25687)
  • +
  • Correct Capitalization Referencing Templates (#25669)
  • +
  • Change linux packaging tests to ubuntu latest (#25634)
  • +
  • Bump github/codeql-action from 3.28.18 to 3.28.19 (#25636)
  • +
  • Move to .NET 10 preview 4 and update package references (#25602)
  • +
  • Revert "Add windows signing for pwsh.exe" (#25586)
  • +
  • Bump ossf/scorecard-action from 2.4.1 to 2.4.2 (#25628)
  • +
  • Publish .msixbundle package as a VPack (#25612)
  • +
  • Bump agrc/reminder-action from 1.0.16 to 1.0.17 (#25573)
  • +
  • Bump agrc/create-reminder-action from 1.1.18 to 1.1.20 (#25572)
  • +
  • Bump github/codeql-action from 3.28.17 to 3.28.18 (#25580)
  • +
  • Bump super-linter/super-linter from 7.3.0 to 7.4.0 (#25563)
  • +
  • Bump actions/dependency-review-action from 4.7.0 to 4.7.1 (#25562)
  • +
  • Update metadata.json with 7.4.10 (#25554)
  • +
  • Bump github/codeql-action from 3.28.16 to 3.28.17 (#25508)
  • +
  • Bump actions/dependency-review-action from 4.6.0 to 4.7.0 (#25529)
  • +
  • Move MSIXBundle to Packages and Release to GitHub (#25512)
  • +
  • Update outdated package references (#25506)
  • +
  • Bump github/codeql-action from 3.28.15 to 3.28.16 (#25429)
  • +
  • Fix Conditional Parameter to Skip NuGet Publish (#25468)
  • +
  • Update metadata.json (#25438)
  • +
  • Fix MSIX artifact upload, vPack template, changelog hashes, git tag command (#25437)
  • +
  • Use new variables template for vPack (#25434)
  • +
  • Bump agrc/create-reminder-action from 1.1.17 to 1.1.18 (#25416)
  • +
  • Add PSScriptAnalyzer (#25423)
  • +
  • Update outdated package references (#25392)
  • +
  • Use GitHubReleaseTask instead of custom script (#25398)
  • +
  • Update APIScan to use new symbols server (#25388)
  • +
  • Retry ClearlyDefined operations (#25385)
  • +
  • Update to .NET 10.0.100-preview.3 (#25358)
  • +
  • Enhance path filters action to set outputs for all changes when not a PR (#25367)
  • +
  • Combine GitHub and Nuget Release Stage (#25318)
  • +
  • Add Windows Store Signing to MSIX bundle (#25296)
  • +
  • Bump skitionek/notify-microsoft-teams from 190d4d92146df11f854709774a4dae6eaf5e2aa3 to e7a2493ac87dad8aa7a62f079f295e54ff511d88 (#25366)
  • +
  • Add CodeQL suppressions for PowerShell intended behavior (#25359)
  • +
  • Migrate MacOS Signing to OneBranch (#25295)
  • +
  • Bump github/codeql-action from 3.28.13 to 3.28.15 (#25290)
  • +
  • Update test result processing to use NUnitXml format and enhance logging for better clarity (#25288)
  • +
  • Fix R2R for fxdependent packaging (#26131)
  • +
  • Remove UseDotnet task and use the dotnet-install script (#26093)
  • +
+ +
+ +### Documentation and Help Content + +- Fix a typo in the 7.4 changelog (#26038) (Thanks @VbhvGupta!) +- Add 7.4.12 changelog (#26011) +- Add v7.5.3 changelog (#25994) +- Fix typo in changelog for script filename suggestion (#25962) +- Update changelog for v7.5.2 (#25668) +- Update changelog for v7.4.11 (#25667) +- Update build documentation with instruction of dev terminal (#25587) +- Update links and contribution guide in documentation (#25532) (Thanks @JustinGrote!) +- Add 7.4.10 changelog (#25520) +- Add 7.5.1 changelog (#25382) + +[7.6.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-preview.4...v7.6.0-preview.5 + +## [7.6.0-preview.4] + +### Breaking Changes + +- Fix `WildcardPattern.Escape` to escape lone backticks correctly (#25211) (Thanks @ArmaanMcleod!) +- Convert `-ChildPath` parameter to `string[]` for `Join-Path` cmdlet (#24677) (Thanks @ArmaanMcleod!) + +PowerShell 7.6-preview.4 includes the following updated modules: + +- **Microsoft.PowerShell.ThreadJob** v2.2.0 +- **ThreadJob** v2.1.0 +The **ThreadJob** module was renamed to **Microsoft.PowerShell.ThreadJob**. There is no difference +in the functionality of the module. To ensure backward compatibility for scripts that use the old +name, the **ThreadJob** v2.1.0 module is a proxy module that points to the +**Microsoft.PowerShell.ThreadJob** v2.2.0. + +### Engine Updates and Fixes + +- Add `PipelineStopToken` to `Cmdlet` which will be signaled when the pipeline is stopping (#24620) (Thanks @jborean93!) +- Fallback to AppLocker after `WldpCanExecuteFile` (#24912) +- Move .NET method invocation logging to after the needed type conversion is done for method arguments (#25022) +- Fix share completion with provider and spaces (#19440) (Thanks @MartinGC94!) + +### General Cmdlet Updates and Fixes + +- Exclude `-OutVariable` assignments within the same `CommandAst` when inferring variables (#25224) (Thanks @MartinGC94!) +- Fix infinite loop in variable type inference (#25206) (Thanks @MartinGC94!) +- Update `Microsoft.PowerShell.PSResourceGet` version in `PSGalleryModules.csproj` (#25135) +- Add tooltips for hashtable key completions (#17864) (Thanks @MartinGC94!) +- Fix type inference of parameters in classic functions (#25172) (Thanks @MartinGC94!) +- Improve assignment type inference (#21143) (Thanks @MartinGC94!) +- Fix `TypeName.GetReflectionType()` to work when the `TypeName` instance represents a generic type definition within a `GenericTypeName` (#24985) +- Remove the old fuzzy suggestion and fix the local script filename suggestion (#25177) +- Improve variable type inference (#19830) (Thanks @MartinGC94!) +- Fix parameter completion when script requirements fail (#17687) (Thanks @MartinGC94!) +- Improve the completion for attribute arguments (#25129) (Thanks @MartinGC94!) +- Fix completion that relies on pseudobinding in script blocks (#25122) (Thanks @MartinGC94!) +- Don't complete duplicate command names (#21113) (Thanks @MartinGC94!) +- Make `SystemPolicy` public APIs visible but non-op on Unix platforms so that they can be included in `PowerShellStandard.Library` (#25051) +- Set standard handles explicitly when starting a process with `-NoNewWindow` (#25061) +- Fix tooltip for variable expansion and include desc (#25112) (Thanks @jborean93!) +- Add type inference for functions without OutputType attribute and anonymous functions (#21127) (Thanks @MartinGC94!) +- Add completion for variables assigned by command redirection (#25104) (Thanks @MartinGC94!) +- Handle type inference for redirected commands (#21131) (Thanks @MartinGC94!) +- Allow empty prefix string in `Import-Module -Prefix` to override default prefix in manifest (#20409) (Thanks @MartinGC94!) +- Update variable/property assignment completion so it can fallback to type inference (#21134) (Thanks @MartinGC94!) +- Use `Get-Help` approach to find `about_*.help.txt` files with correct locale for completions (#24194) (Thanks @MartinGC94!) +- Use script filepath when completing relative paths for using statements (#20017) (Thanks @MartinGC94!) +- Fix completion of variables assigned inside Do loops (#25076) (Thanks @MartinGC94!) +- Fix completion of provider paths when a path returns itself instead of its children (#24755) (Thanks @MartinGC94!) +- Enable completion of scoped variables without specifying scope (#20340) (Thanks @MartinGC94!) +- Fix issue with incomplete results when completing paths with wildcards in non-filesystem providers (#24757) (Thanks @MartinGC94!) +- Allow DSC parsing through OS architecture translation layers (#24852) (Thanks @bdeb1337!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@ArmaanMcleod, @pressRtowin

+ +
+ +
    +
  • Refactor and add comments to CompletionRequiresQuotes to clarify implementation (#25223) (Thanks @ArmaanMcleod!)
  • +
  • Add QuoteCompletionText method to CompletionHelpers class (#25180) (Thanks @ArmaanMcleod!)
  • +
  • Remove CompletionHelpers escape parameter from CompletionRequiresQuotes (#25178) (Thanks @ArmaanMcleod!)
  • +
  • Refactor CompletionHelpers HandleDoubleAndSingleQuote to have less nesting logic (#25179) (Thanks @ArmaanMcleod!)
  • +
  • Make the use of Oxford commas consistent (#25139)(#25140)(Thanks @pressRtowin!)
  • +
  • Move common completion methods to CompletionHelpers class (#25138) (Thanks @ArmaanMcleod!)
  • +
  • Return Array.Empty instead of collection [] (#25137) (Thanks @ArmaanMcleod!)
  • +
+ +
+ +### Tools + +- Check GH token availability for Get-Changelog (#25133) + +### Tests + +- Add XUnit test for `HandleDoubleAndSingleQuote` in CompletionHelpers class (#25181) (Thanks @ArmaanMcleod!) + +### Build and Packaging Improvements + +
+ +
    +
  • Switch to ubuntu-lastest for CI (#25247)
  • +
  • Update outdated package references (#25026)(#25232)
  • +
  • Bump Microsoft.PowerShell.ThreadJob and ThreadJob modules (#25232)
  • +
  • Bump github/codeql-action from 3.27.9 to 3.28.13 (#25218)(#25231)
  • +
  • Update .NET SDK to 10.0.100-preview.2 (#25154)(#25225)
  • +
  • Remove obsolete template from Windows Packaging CI (#25226)
  • +
  • Bump actions/upload-artifact from 4.5.0 to 4.6.2 (#25220)
  • +
  • Bump agrc/reminder-action from 1.0.15 to 1.0.16 (#25222)
  • +
  • Bump actions/checkout from 2 to 4 (#25221)
  • +
  • Add NoWarn NU1605 to System.ServiceModel.* (#25219)
  • +
  • Bump actions/github-script from 6 to 7 (#25217)
  • +
  • Bump ossf/scorecard-action from 2.4.0 to 2.4.1 (#25216)
  • +
  • Bump super-linter/super-linter from 7.2.1 to 7.3.0 (#25215)
  • +
  • Bump agrc/create-reminder-action from 1.1.16 to 1.1.17 (#25214)
  • +
  • Remove dependabot updates that don't work (#25213)
  • +
  • Update GitHub Actions to work in private GitHub repo (#25197)
  • +
  • Cleanup old release pipelines (#25201)
  • +
  • Update package pipeline windows image version (#25191)
  • +
  • Skip additional packages when generating component manifest (#25102)
  • +
  • Only build Linux for packaging changes (#25103)
  • +
  • Remove Az module installs and AzureRM uninstalls in pipeline (#25118)
  • +
  • Add GitHub Actions workflow to verify PR labels (#25145)
  • +
  • Add back-port workflow using dotnet/arcade (#25106)
  • +
  • Make Component Manifest Updater use neutral target in addition to RID target (#25094)
  • +
  • Make sure the vPack pipeline does not produce an empty package (#24988)
  • +
+ +
+ +### Documentation and Help Content + +- Add 7.4.9 changelog (#25169) +- Create changelog for 7.4.8 (#25089) + +[7.6.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-preview.3...v7.6.0-preview.4 + +## [7.6.0-preview.3] + +### Breaking Changes + +- Remove trailing space from event source name (#24192) (Thanks @MartinGC94!) + +### General Cmdlet Updates and Fixes + +- Add completion single/double quote support for `-Noun` parameter for `Get-Command` (#24977) (Thanks @ArmaanMcleod!) +- Stringify `ErrorRecord` with empty exception message to empty string (#24949) (Thanks @MatejKafka!) +- Add completion single/double quote support for `-PSEdition` parameter for `Get-Module` (#24971) (Thanks @ArmaanMcleod!) +- Error when `New-Item -Force` is passed an invalid directory name (#24936) (Thanks @kborowinski!) +- Allow `Start-Transcript`to use `$Transcript` which is a `PSObject` wrapped string to specify the transcript path (#24963) (Thanks @kborowinski!) +- Add quote handling in `Verb`, `StrictModeVersion`, `Scope` & `PropertyType` Argument Completers with single helper method (#24839) (Thanks @ArmaanMcleod!) +- Improve `Start-Process -Wait` polling efficiency (#24711) (Thanks @jborean93!) +- Convert `InvalidCommandNameCharacters` in `AnalysisCache` to `SearchValues` for more efficient char searching (#24880) (Thanks @ArmaanMcleod!) +- Convert `s_charactersRequiringQuotes` in Completion Completers to `SearchValues` for more efficient char searching (#24879) (Thanks @ArmaanMcleod!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @fMichaleczek, @ArmaanMcleod

+ +
+ +
    +
  • Fix RunspacePool, RunspacePoolInternal and RemoteRunspacePoolInternal IDisposable implementation (#24720) (Thanks @xtqqczze!)
  • +
  • Remove redundant Attribute suffix (#24940) (Thanks @xtqqczze!)
  • +
  • Fix formatting of the XML comment for SteppablePipeline.Clean() (#24941)
  • +
  • Use Environment.ProcessId in SpecialVariables.PID (#24926) (Thanks @fMichaleczek!)
  • +
  • Replace char[] array in CompletionRequiresQuotes with cached SearchValues (#24907) (Thanks @ArmaanMcleod!)
  • +
  • Update IndexOfAny calls with invalid path/filename to SearchValues<char> for more efficient char searching (#24896) (Thanks @ArmaanMcleod!)
  • +
  • Seal internal types in PlatformInvokes (#24826) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Update CODEOWNERS (#24989) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @KyZy7

+ +
+ +
    +
  • Update branch for release - Transitive - false - none (#24995)
  • +
  • Add setup dotnet action to the build composite action (#24996)
  • +
  • Give the pipeline runs meaningful names (#24987)
  • +
  • Fix V-Pack download package name (#24866)
  • +
  • Set LangVersion compiler option to 13.0 in Test.Common.props (#24621) (Thanks @xtqqczze!)
  • +
  • Fix release branch filters (#24933)
  • +
  • Fix GitHub Action filter overmatching (#24929)
  • +
  • Add UseDotnet task for installing dotnet (#24905)
  • +
  • Convert powershell/PowerShell-CI-macos to GitHub Actions (#24914)
  • +
  • Convert powershell/PowerShell-CI-linux to GitHub Actions (#24913)
  • +
  • Convert powershell/PowerShell-Windows-CI to GitHub Actions (#24899)
  • +
  • Fix MSIX stage in release pipeline (#24900)
  • +
  • Update .NET SDK (#24906)
  • +
  • Update metadata.json (#24862)
  • +
  • PMC parse state correctly from update command's response (#24850)
  • +
  • Add EV2 support for publishing PowerShell packages to PMC (#24841)
  • +
  • Remove AzDO credscan as it is now in GitHub (#24842)
  • +
  • Add *.props and sort path filters for windows CI (#24822)
  • +
  • Use work load identity service connection to download makeappx tool from storage account (#24817)
  • +
  • Update path filters for Windows CI (#24809)
  • +
  • Update outdated package references (#24758)
  • +
  • Update metadata.json (#24787) (Thanks @KyZy7!)
  • +
  • Add tool package download in publish nuget stage (#24790)
  • +
  • Fix Changelog content grab during GitHub Release (#24788)
  • +
  • Update metadata.json (#24764)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.1.0 (#24767)
  • +
  • Add a parameter that skips verify packages step (#24763)
  • +
+ +
+ +### Documentation and Help Content + +- Add 7.4.7 Changelog (#24844) +- Create changelog for v7.5.0 (#24808) +- Update Changelog for v7.6.0-preview.2 (#24775) + +[7.6.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-preview.2...v7.6.0-preview.3 + +## [7.6.0-preview.2] - 2025-01-14 + +### General Cmdlet Updates and Fixes + +- Add the `AIShell` module to telemetry collection list (#24747) +- Add helper in `EnumSingleTypeConverter` to get enum names as array (#17785) (Thanks @fflaten!) +- Return correct FileName property for `Get-Item` when listing alternate data streams (#18019) (Thanks @kilasuit!) +- Add `-ExcludeModule` parameter to `Get-Command` (#18955) (Thanks @MartinGC94!) +- Update Named and Statement block type inference to not consider AssignmentStatements and Increment/decrement operators as part of their output (#21137) (Thanks @MartinGC94!) +- Update `DnsNameList` for `X509Certificate2` to use `X509SubjectAlternativeNameExtension.EnumerateDnsNames` Method (#24714) (Thanks @ArmaanMcleod!) +- Add completion of modules by their shortname (#20330) (Thanks @MartinGC94!) +- Fix `Get-ItemProperty` to report non-terminating error for cast exception (#21115) (Thanks @ArmaanMcleod!) +- Add `-PropertyType` argument completer for `New-ItemProperty` (#21117) (Thanks @ArmaanMcleod!) +- Fix a bug in how `Write-Host` handles `XmlNode` object (#24669) (Thanks @brendandburns!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze

+ +
+ +
    +
  • Seal ClientRemoteSessionDSHandlerImpl (#21218) (Thanks @xtqqczze!)
  • +
  • Seal internal type ClientRemoteSessionDSHandlerImpl (#24705) (Thanks @xtqqczze!)
  • +
  • Seal classes in RemotingProtocol2 (#21164) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Added Justin Chung as PowerShell team memeber on releaseTools.psm1 (#24672) + +### Tests + +- Skip CIM ETS member test on older Windows platforms (#24681) + +### Build and Packaging Improvements + +
+ + + +

Updated SDK to 9.0.101

+ +
+ +
    +
  • Update branch for release - Transitive - false - none (#24754)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.1.0 (#24767)
  • +
  • Add a parameter that skips verify packages step (#24763)
  • +
  • Make the AssemblyVersion not change for servicing releases (#24667)
  • +
  • Fixed release pipeline errors and switched to KS3 (#24751)
  • +
  • Update outdated package references (#24580)
  • +
  • Bump actions/upload-artifact from 4.4.3 to 4.5.0 (#24689)
  • +
  • Update .NET feed with new domain as azureedge is retiring (#24703)
  • +
  • Bump super-linter/super-linter from 7.2.0 to 7.2.1 (#24678)
  • +
  • Bump github/codeql-action from 3.27.7 to 3.27.9 (#24674)
  • +
  • Bump actions/dependency-review-action from 4.4.0 to 4.5.0 (#24607)
  • +
+ +
+ +### Documentation and Help Content + +- Update cmdlets WG members (#24275) (Thanks @kilasuit!) + +[7.6.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-preview.1...v7.6.0-preview.2 + +## [7.6.0-preview.1] - 2024-12-16 + +### Breaking Changes + +- Treat large Enum values as numbers in `ConvertTo-Json` (#20999) (Thanks @jborean93!) + +### General Cmdlet Updates and Fixes + +- Add proper error for running `Get-PSSession -ComputerName` on Unix (#21009) (Thanks @jborean93!) +- Resolve symbolic link target relative to the symbolic link instead of the working directory (#15235) (#20943) (Thanks @MatejKafka!) +- Fix up buffer management getting network roots (#24600) (Thanks @jborean93!) +- Support `PSObject` wrapped values in `ArgumentToEncodingTransformationAttribute` (#24555) (Thanks @jborean93!) +- Update PSReadLine to 2.3.6 (#24380) +- Add telemetry to track the use of features (#24247) +- Handle global tool specially when prepending `PSHome` to `PATH` (#24228) +- Fix how processor architecture is validated in `Import-Module` (#24265) +- Make features `PSCommandNotFoundSuggestion`, `PSCommandWithArgs`, and `PSModuleAutoLoadSkipOfflineFiles` stable (#24246) +- Write type data to the pipeline instead of collecting it (#24236) (Thanks @MartinGC94!) +- Add support to `Get-Error` to handle BoundParameters (#20640) +- Fix `Get-FormatData` to not cast a type incorrectly (#21157) +- Delay progress bar in `Copy-Item` and `Remove-Item` cmdlets (#24013) (Thanks @TheSpyGod!) +- Add `-Force` parameter to `Resolve-Path` and `Convert-Path` cmdlets to support wildcard hidden files (#20981) (Thanks @ArmaanMcleod!) +- Use host exe to determine `$PSHOME` location when `SMA.dll` location is not found (#24072) +- Fix `Test-ModuleManifest` so it can use a UNC path (#24115) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @JayBazuzi

+ +
+ +
    +
  • Fix typos in ShowModuleControl.xaml.cs (#24248) (Thanks @eltociear!)
  • +
  • Fix a typo in the build doc (#24172) (Thanks @JayBazuzi!)
  • +
+ +
+ +### Tools + +- Fix devcontainer extensions key (#24359) (Thanks @ThomasNieto!) +- Support new backport branch format (#24378) +- Update markdownLink.yml to not run on release branches (#24323) +- Remove old code that downloads msix for win-arm64 (#24175) + +### Tests + +- Fix cleanup in PSResourceGet test (#24339) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@MartinGC94, @jborean93, @xtqqczze, @alerickson, @iSazonov, @rzippo

+ +
+ +
    +
  • Deploy Box update (#24632)
  • +
  • Remove Regex use (#24235) (Thanks @MartinGC94!)
  • +
  • Improve cim ETS member inference completion (#24235) (Thanks @MartinGC94!)
  • +
  • Emit ProgressRecord in CLIXML minishell output (#21373) (Thanks @jborean93!)
  • +
  • Assign the value returned by the MaybeAdd method
  • (#24652) +
  • Add support for interface static abstract props (#21061) (Thanks @jborean93!)
  • +
  • Change call to optional add in the binder expression (#24451) (Thanks @jborean93!)
  • +
  • Turn off AMSI member invocation on nix release builds (#24451) (Thanks @jborean93!)
  • +
  • Bump github/codeql-action from 3.27.0 to 3.27.6 (#24639)
  • +
  • Update src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs (#24239) (Thanks @jborean93!)
  • +
  • Apply suggestions from code review (#24239) (Thanks @jborean93!)
  • +
  • Add remote runspace check for PushRunspace (#24239) (Thanks @jborean93!)
  • +
  • Set LangVersion compiler option to 13.0 (#24619) (Thanks @xtqqczze!)
  • +
  • Set LangVersion compiler option to 13.0 (#24617) (Thanks @xtqqczze!)
  • +
  • Update metadata.json for PowerShell 7.5 RC1 release (#24589)
  • +
  • Update nuget publish to use Deploy Box (#24596)
  • +
  • Added Deploy Box Product Pathway to GitHub Release and NuGet Release Pipelines (#24583)
  • +
  • Update machine pool for copy blob and upload buildinfo stage (#24587)
  • +
  • Bump .NET 9 and dependencies (#24573)
  • +
  • Bump actions/dependency-review-action from 4.3.4 to 4.4.0 (#24503)
  • +
  • Bump actions/checkout from 4.2.1 to 4.2.2 (#24488)
  • +
  • Bump agrc/reminder-action from 1.0.14 to 1.0.15 (#24384)
  • +
  • Bump actions/upload-artifact from 4.4.0 to 4.4.3 (#24410)
  • +
  • Update branch for release (#24534)
  • +
  • Revert "Update package references (#24414)" (#24532)
  • +
  • Add a way to use only NuGet feed sources (#24528)
  • +
  • Update PSResourceGet to v1.1.0-RC2 (#24512) (Thanks @alerickson!)
  • +
  • Bump .NET to 9.0.100-rc.2.24474.11 (#24509)
  • +
  • Fix seed max value for Container Linux CI (#24510)
  • +
  • Update metadata.json for 7.2.24 and 7.4.6 releases (#24484)
  • +
  • Download package from package build for generating vpack (#24481)
  • +
  • Keep the roff file when gzipping it. (#24450)
  • +
  • Delete the msix blob if it's already there (#24353)
  • +
  • Add PMC mapping for debian 12 (bookworm) (#24413)
  • +
  • Checkin generated manpage (#24423)
  • +
  • Add CodeQL scanning to APIScan build (#24303)
  • +
  • Update package references (#24414)
  • +
  • Update vpack pipeline (#24281)
  • +
  • Bring changes from v7.5.0-preview.5 Release Branch to Master (#24369)
  • +
  • Bump agrc/create-reminder-action from 1.1.15 to 1.1.16 (#24375)
  • +
  • Add BaseUrl to buildinfo json file (#24376)
  • +
  • Update metadata.json (#24352)
  • +
  • Copy to static site instead of making blob public (#24269)
  • +
  • Update Microsoft.PowerShell.PSResourceGet to 1.1.0-preview2 (#24300) (Thanks @alerickson!)
  • +
  • add updated libicu dependency for debian packages (#24301)
  • +
  • add mapping to azurelinux repo (#24290)
  • +
  • Remove the MD5 branch in the strong name signing token calculation (#24288)
  • +
  • Bump .NET 9 to 9.0.100-rc.1.24452.12 (#24273)
  • +
  • Ensure the official build files CodeQL issues (#24278)
  • +
  • Update experimental-feature json files (#24271)
  • +
  • Make some release tests run in a hosted pools (#24270)
  • +
  • Do not build the exe for Global tool shim project (#24263)
  • +
  • Update and add new NuGet package sources for different environments. (#24264)
  • +
  • Bump skitionek/notify-microsoft-teams (#24261)
  • +
  • Create new pipeline for compliance (#24252)
  • +
  • Capture environment better (#24148)
  • +
  • Add specific path for issues in tsaconfig (#24244)
  • +
  • Use Managed Identity for APIScan authentication (#24243)
  • +
  • Add windows signing for pwsh.exe (#24219)
  • +
  • Bump super-linter/super-linter from 7.0.0 to 7.1.0 (#24223)
  • +
  • Update the URLs used in nuget.config files (#24203)
  • +
  • Check Create and Submit in vPack build by default (#24181)
  • +
  • Replace PSVersion source generator with incremental one (#23815) (Thanks @iSazonov!)
  • +
  • Save man files in /usr/share/man instead of /usr/local/share/man (#23855) (Thanks @rzippo!)
  • +
  • Bump super-linter/super-linter from 6.8.0 to 7.0.0 (#24169)
  • +
+ +
+ +### Documentation and Help Content + +- Updated Third Party Notices (#24666) +- Update `HelpInfoUri` for 7.5 (#24610) +- Update changelog for v7.4.6 release (#24496) +- Update to the latest NOTICES file (#24259) +- Update the changelog `preview.md` (#24213) +- Update changelog readme with 7.4 (#24182) (Thanks @ThomasNieto!) +- Fix Markdown linting error (#24204) +- Updated changelog for v7.2.23 (#24196) (Internal 32131) +- Update changelog and `metadata.json` for v7.4.5 release (#24183) +- Bring 7.2 changelogs back to master (#24158) + +[7.6.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.5.0-rc.1...v7.6.0-preview.1 diff --git a/PowerShell-master/CHANGELOG/README.md b/PowerShell-master/CHANGELOG/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c20cd311ff5df1fe38b8763dae11b14f9addcdfd --- /dev/null +++ b/PowerShell-master/CHANGELOG/README.md @@ -0,0 +1,11 @@ +# Changelogs + +- [Current preview changelog](preview.md) +- [7.4 changelog](7.4.md) +- [7.3 changelog](7.3.md) +- [7.2 changelog](7.2.md) +- [7.1 changelog](7.1.md) +- [7.0 changelog](7.0.md) +- [6.2 changelog](6.2.md) +- [6.1 changelog](6.1.md) +- [6.0 changelog](6.0.md) diff --git a/PowerShell-master/CHANGELOG/preview.md b/PowerShell-master/CHANGELOG/preview.md new file mode 100644 index 0000000000000000000000000000000000000000..8e97635bada291583d4f8bb5b33cbb2fbe244d8e --- /dev/null +++ b/PowerShell-master/CHANGELOG/preview.md @@ -0,0 +1,2 @@ +# Preview Changelog + diff --git a/PowerShell-master/CODE_OF_CONDUCT.md b/PowerShell-master/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..686e5e7a090b52f0db9acbe001915d0b9b06b06c --- /dev/null +++ b/PowerShell-master/CODE_OF_CONDUCT.md @@ -0,0 +1,10 @@ +# Microsoft Open Source Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +Resources: + +- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) +- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns +- Employees can reach out at [aka.ms/opensource/moderation-support](https://aka.ms/opensource/moderation-support) diff --git a/PowerShell-master/DotnetRuntimeMetadata.json b/PowerShell-master/DotnetRuntimeMetadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7c4a219146750a5371ee0859e412bdfadb13a97b --- /dev/null +++ b/PowerShell-master/DotnetRuntimeMetadata.json @@ -0,0 +1,15 @@ +{ + "sdk": { + "channel": "9.0.1xx-preview6", + "quality": "daily", + "qualityFallback": "preview", + "packageVersionPattern": "9.0.0-preview.6", + "sdkImageVersion": "11.0.100-preview.1.26104.118", + "nextChannel": "9.0.0-preview.7", + "azureFeed": "", + "sdkImageOverride": "" + }, + "internalfeed": { + "url": "" + } +} diff --git a/PowerShell-master/LICENSE.txt b/PowerShell-master/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2f52a2bad4e27e2d9c68a755abb74cb8943f2fa --- /dev/null +++ b/PowerShell-master/LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PowerShell-master/PowerShell.Common.props b/PowerShell-master/PowerShell.Common.props new file mode 100644 index 0000000000000000000000000000000000000000..d71432aed2feeee1dc07d960d87b899ab5bfbe30 --- /dev/null +++ b/PowerShell-master/PowerShell.Common.props @@ -0,0 +1,234 @@ + + + + + + + + + + + + + + + ^((\d+).(\d+).(\d+))(-(\w+)(.(\d+))?)?$ + $([System.Text.RegularExpressions.Regex]::Match($(ReleaseTag), $(RegexReleaseTag)).Groups[1].Value) + $([System.Text.RegularExpressions.Regex]::Match($(ReleaseTag), $(RegexReleaseTag)).Groups[8].Value) + $([System.Text.RegularExpressions.Regex]::Match($(ReleaseTag), $(RegexReleaseTag)).Groups[6].Value) + + 100 + + 500 + $([MSBuild]::Add($(ReleaseTagSemVersionPart), $(RCIncrementValue))) + + $(ReleaseTag) + + $(ReleaseTagVersionPart).$(ReleaseTagSemVersionPart) + + $(ReleaseTagVersionPart).$(GAIncrementValue) + + $(PSCoreFileVersion) + $([System.Version]::Parse($(PSCoreFileVersion)).Major).$([System.Version]::Parse($(PSCoreFileVersion)).Minor).0.$([System.Version]::Parse($(PSCoreFileVersion)).Revision) + + + + ^v(.+)-(\d+)-g(.+) + $([System.Text.RegularExpressions.Regex]::Match($(PowerShellVersion), $(RegexGitVersion)).Groups[1].Value) + $([System.Text.RegularExpressions.Regex]::Match($(PowerShellVersion), $(RegexGitVersion)).Groups[1].Value) + $([System.Text.RegularExpressions.Regex]::Match($(PowerShellVersion), $(RegexGitVersion)).Groups[2].Value) + $([System.Text.RegularExpressions.Regex]::Match($(PowerShellVersion), $(RegexGitVersion)).Groups[3].Value) + + + $(PSCoreBuildVersion) SHA: $(PSCoreCommitSHA) + $(PSCoreBuildVersion) Commits: $(PSCoreAdditionalCommits) SHA: $(PSCoreCommitSHA) + + + + + $(PSCoreFileVersion) + $(PSCoreFormattedVersion) + $(PSCoreFormattedVersion) + + + $(PSCoreBuildVersion) + + ..\..\assets\Powershell_av_colors.ico + ..\..\assets\Powershell_avatar.ico + ..\..\assets\Powershell_black.ico + + + + + + + + + + + + PowerShell + Microsoft Corporation + (c) Microsoft Corporation. + PowerShell 7 + + net11.0 + preview + + true + true + true + true + en-US + true + true + + true + ../signing/visualstudiopublic.snk + true + true + + + + $(DefineConstants);CORECLR + true + + + + + $(DefineConstants);UNIX + + + + + portable + + + + + + EnvironmentVariable;Global + false + false + + + + + Global + + + + + true + true + + + + AppLocal + + + + + true + true + + + + + true + portable + + + + + true + + full + + + + strict + + + + true + + diff --git a/PowerShell-master/PowerShell.sln b/PowerShell-master/PowerShell.sln new file mode 100644 index 0000000000000000000000000000000000000000..4938316281da53adff9375c3c4736b771bd47b57 --- /dev/null +++ b/PowerShell-master/PowerShell.sln @@ -0,0 +1,180 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +# https://github.com/dotnet/project-system/blob/master/docs/opening-with-new-project-system.md#project-type-guids +VisualStudioVersion = 15.0.26730.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "powershell-win-core", "src\powershell-win-core\powershell-win-core.csproj", "{8359D422-E0C4-4A0D-94EB-3C9DD16B7932}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Management.Automation", "src\System.Management.Automation\System.Management.Automation.csproj", "{AF660EE7-0183-4B79-A93F-221B6AC1C24B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.Commands.Utility", "src\Microsoft.PowerShell.Commands.Utility\Microsoft.PowerShell.Commands.Utility.csproj", "{EAB203E1-2A68-4166-BE54-5C44DE825229}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.CoreCLR.Eventing", "src\Microsoft.PowerShell.CoreCLR.Eventing\Microsoft.PowerShell.CoreCLR.Eventing.csproj", "{981D3972-343D-4E17-935B-037E1C622771}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.ConsoleHost", "src\Microsoft.PowerShell.ConsoleHost\Microsoft.PowerShell.ConsoleHost.csproj", "{8FFE645D-F0C9-4220-9A88-83062ED211D2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.Commands.Management", "src\Microsoft.PowerShell.Commands.Management\Microsoft.PowerShell.Commands.Management.csproj", "{FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.SDK", "src\Microsoft.PowerShell.SDK\Microsoft.PowerShell.SDK.csproj", "{4BC19063-1F66-467B-87DE-80449C72BCD6}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Management.Infrastructure.CimCmdlets", "src\Microsoft.Management.Infrastructure.CimCmdlets\Microsoft.Management.Infrastructure.CimCmdlets.csproj", "{131A8527-92D7-468F-822D-5354229A865C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.Commands.Diagnostics", "src\Microsoft.PowerShell.Commands.Diagnostics\Microsoft.PowerShell.Commands.Diagnostics.csproj", "{439A24FC-8E0A-48B6-8227-44C297311F49}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.WSMan.Management", "src\Microsoft.WSMan.Management\Microsoft.WSMan.Management.csproj", "{8F63D134-E413-4181-936D-D82F3F5F1D85}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.Security", "src\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.csproj", "{C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.WSMan.Runtime", "src\Microsoft.WSMan.Runtime\Microsoft.WSMan.Runtime.csproj", "{D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "powershell-unix", "src\powershell-unix\powershell-unix.csproj", "{73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "xUnit.tests", "test\xUnit\xUnit.tests.csproj", "{08704934-9764-48CE-86DB-BCF0A1CF7899}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PSVersionInfoGenerator", "src\System.Management.Automation\SourceGenerators\PSVersionInfoGenerator\PSVersionInfoGenerator.csproj", "{B22424E8-0516-4FC3-A9CB-D84D15EF0589}" +EndProject +# Configuration mapping comment +# All global configurations must be mapped to project configurations +# +# 4BC19063-1F66-467B-87DE-80449C72BCD6 - Microsoft.PowerShell.SDK +# 8359D422-E0C4-4A0D-94EB-3C9DD16B7932 - PowerShell-Win +# Linux is invalid and mapped to Release +# +# 73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690 - powershell-unix +# Only Linux is valid, all configurations mapped to Linux +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + CodeCoverage|Any CPU = CodeCoverage|Any CPU + Debug|Any CPU = Debug|Any CPU + Linux|Any CPU = Linux|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.Linux|Any CPU.ActiveCfg = Release|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.Linux|Any CPU.Build.0 = Release|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8359D422-E0C4-4A0D-94EB-3C9DD16B7932}.Release|Any CPU.Build.0 = Release|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.Linux|Any CPU.Build.0 = Linux|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF660EE7-0183-4B79-A93F-221B6AC1C24B}.Release|Any CPU.Build.0 = Release|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.Linux|Any CPU.Build.0 = Linux|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EAB203E1-2A68-4166-BE54-5C44DE825229}.Release|Any CPU.Build.0 = Release|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.Debug|Any CPU.Build.0 = Debug|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.Linux|Any CPU.Build.0 = Linux|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.Release|Any CPU.ActiveCfg = Release|Any CPU + {981D3972-343D-4E17-935B-037E1C622771}.Release|Any CPU.Build.0 = Release|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.Linux|Any CPU.Build.0 = Linux|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8FFE645D-F0C9-4220-9A88-83062ED211D2}.Release|Any CPU.Build.0 = Release|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.Linux|Any CPU.Build.0 = Linux|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FCE53A5E-5FAC-48BE-BAD8-2110040B5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.CodeCoverage|Any CPU.ActiveCfg = Release|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.CodeCoverage|Any CPU.Build.0 = Release|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.Linux|Any CPU.ActiveCfg = Release|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.Linux|Any CPU.Build.0 = Release|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4BC19063-1F66-467B-87DE-80449C72BCD6}.Release|Any CPU.Build.0 = Release|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.CodeCoverage|Any CPU.ActiveCfg = Release|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.CodeCoverage|Any CPU.Build.0 = Release|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.Linux|Any CPU.ActiveCfg = Release|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.Linux|Any CPU.Build.0 = Release|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {131A8527-92D7-468F-822D-5354229A865C}.Release|Any CPU.Build.0 = Release|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.Debug|Any CPU.Build.0 = Debug|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.Linux|Any CPU.Build.0 = Linux|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.Release|Any CPU.ActiveCfg = Release|Any CPU + {439A24FC-8E0A-48B6-8227-44C297311F49}.Release|Any CPU.Build.0 = Release|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.Linux|Any CPU.Build.0 = Linux|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8F63D134-E413-4181-936D-D82F3F5F1D85}.Release|Any CPU.Build.0 = Release|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.Linux|Any CPU.Build.0 = Linux|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4F81816-C87A-4ABF-8A37-24AC16A0A6CF}.Release|Any CPU.Build.0 = Release|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.Linux|Any CPU.Build.0 = Linux|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D9CCCB67-4EBE-4854-AB52-C0129DC5BAE4}.Release|Any CPU.Build.0 = Release|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.Linux|Any CPU.Build.0 = Linux|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.Release|Any CPU.ActiveCfg = Release|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.Release|Any CPU.Build.0 = Release|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.Debug|Any CPU.Build.0 = Debug|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.Linux|Any CPU.Build.0 = Linux|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}.Release|Any CPU.Build.0 = Release|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.CodeCoverage|Any CPU.ActiveCfg = CodeCoverage|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.CodeCoverage|Any CPU.Build.0 = CodeCoverage|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.Debug|Any CPU.Build.0 = Debug|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.Linux|Any CPU.ActiveCfg = Linux|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.Linux|Any CPU.Build.0 = Linux|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.Release|Any CPU.ActiveCfg = Release|Any CPU + {08704934-9764-48CE-86DB-BCF0A1CF7899}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9128A855-8499-43C0-9C7C-08ECC47768B0} + EndGlobalSection +EndGlobal diff --git a/PowerShell-master/README.md b/PowerShell-master/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a7b31c475f81404e1ead2cc86bdb0d6b5226381e --- /dev/null +++ b/PowerShell-master/README.md @@ -0,0 +1,135 @@ +# ![logo][] PowerShell + +Welcome to the PowerShell GitHub Community! +[PowerShell](https://learn.microsoft.com/powershell/scripting/overview) is a cross-platform (Windows, Linux, and macOS) automation and configuration tool/framework that works well with your existing tools and is optimized +for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models. +It includes a command-line shell, an associated scripting language, and a framework for processing cmdlets. + +[logo]: assets/ps_black_64.svg?sanitize=true + +## Windows PowerShell vs. PowerShell 7+ + +Although this repository started as a fork of the Windows PowerShell codebase, changes made in this repository are not ported back to Windows PowerShell 5.1. +This also means that [issues tracked here][issues] are only for PowerShell 7.x and higher. +Windows PowerShell specific issues should be reported with the [Feedback Hub app][feedback-hub], by choosing "Apps > PowerShell" in the category. + +[issues]: https://github.com/PowerShell/PowerShell/issues +[feedback-hub]: https://support.microsoft.com/windows/send-feedback-to-microsoft-with-the-feedback-hub-app-f59187f8-8739-22d6-ba93-f66612949332 + +## New to PowerShell? + +If you are new to PowerShell and want to learn more, we recommend reviewing the [getting started][] documentation. + +[getting started]: https://learn.microsoft.com/powershell/scripting/learn/more-powershell-learning + +## Get PowerShell + +PowerShell is supported on Windows, macOS, and a variety of Linux platforms. For +more information, see [Installing PowerShell](https://learn.microsoft.com/powershell/scripting/install/installing-powershell). + +## Upgrading PowerShell + +For best results when upgrading, you should use the same install method you used when you first +installed PowerShell. The update method is different for each platform and install method. + +## Community Dashboard + +[Dashboard](https://aka.ms/PSPublicDashboard) with visualizations for community contributions and project status using PowerShell, Azure, and PowerBI. + +For more information on how and why we built this dashboard, check out this [blog post](https://devblogs.microsoft.com/powershell/powershell-open-source-community-dashboard/). + +## Discussions + +[GitHub Discussions](https://docs.github.com/discussions/quickstart) is a feature to enable free and open discussions within the community +for topics that are not related to code, unlike issues. + +This is an experiment we are trying in our repositories, to see if it helps move discussions out of issues so that issues remain actionable by the team or members of the community. +There should be no expectation that PowerShell team members are regular participants in these discussions. +Individual PowerShell team members may choose to participate in discussions, but the expectation is that community members help drive discussions so that team members +can focus on issues. + +Create or join a [discussion](https://github.com/PowerShell/PowerShell/discussions). + +## Chat + +Want to chat with other members of the PowerShell community? + +There are dozens of topic-specific channels on our community-driven PowerShell Virtual User Group, which you can join on: + +* [Discord](https://discord.gg/PowerShell) +* [IRC](https://web.libera.chat/#powershell) on Libera.Chat +* [Slack](https://aka.ms/psslack) + +## Developing and Contributing + +Want to contribute to PowerShell? Please start with the [Contribution Guide][] to learn how to develop and contribute. + +If you are developing .NET Core C# applications targeting PowerShell Core, [check out our FAQ][] to learn more about the PowerShell SDK NuGet package. + +Also, make sure to check out our [PowerShell-RFC repository](https://github.com/powershell/powershell-rfc) for request-for-comments (RFC) documents to submit and give comments on proposed and future designs. + +[Contribution Guide]: .github/CONTRIBUTING.md +[check out our FAQ]: docs/FAQ.md#where-do-i-get-the-powershell-core-sdk-package + +## Building PowerShell + +| Linux | Windows | macOS | +|--------------------------|----------------------------|------------------------| +| [Instructions][bd-linux] | [Instructions][bd-windows] | [Instructions][bd-macOS] | + +If you have any problems building PowerShell, please start by consulting the developer [FAQ]. + +[bd-linux]: docs/building/linux.md +[bd-windows]: docs/building/windows-core.md +[bd-macOS]: docs/building/macos.md +[FAQ]: docs/FAQ.md + +## Downloading the Source Code + +You can clone the repository: + +```sh +git clone https://github.com/PowerShell/PowerShell.git +``` + +For more information, see [working with the PowerShell repository](https://github.com/PowerShell/PowerShell/tree/master/docs/git). + +## Support + +For support, see the [Support Section][]. + +[Support Section]: https://github.com/PowerShell/PowerShell/tree/master/.github/SUPPORT.md + +## Legal and Licensing + +PowerShell is licensed under the [MIT license][]. + +[MIT license]: https://github.com/PowerShell/PowerShell/tree/master/LICENSE.txt + +### Docker Containers + +> [!Important] +> The PowerShell container images are now [maintained by the .NET team](https://github.com/PowerShell/Announcements/issues/75). The containers at `mcr.microsoft.com/powershell` are currently not maintained. + +License: By requesting and using the Container OS Image for Windows containers, you acknowledge, understand, and consent to the Supplemental License Terms available on [Microsoft Artifact Registry][mcr]. + +[mcr]: https://mcr.microsoft.com/en-us/product/powershell/tags + +### Telemetry + +Please visit our [about_Telemetry](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_telemetry) +topic to read details about telemetry gathered by PowerShell. + +## Governance + +The governance policy for the PowerShell project is described the [PowerShell Governance][gov] document. + +[gov]: https://github.com/PowerShell/PowerShell/blob/master/docs/community/governance.md + +## [Code of Conduct](CODE_OF_CONDUCT.md) + +Please see our [Code of Conduct](CODE_OF_CONDUCT.md) before participating in this project. + +## [Security Policy](.github/SECURITY.md) + +For any security issues, please see our [Security Policy](.github/SECURITY.md). diff --git a/PowerShell-master/Settings.StyleCop b/PowerShell-master/Settings.StyleCop new file mode 100644 index 0000000000000000000000000000000000000000..e10c02bdd1255ac0592c439dc593ecc192eb7ddc --- /dev/null +++ b/PowerShell-master/Settings.StyleCop @@ -0,0 +1,220 @@ + + + + + + + False + + + + + False + + + + + + False + + + + + + False + + + + + + + + + + False + + + + + False + + + + + + + + + + False + + + + + False + + + + + True + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + True + True + + + + + + + False + + + + + + False + + + + + + False + + + + + + False + + + + + False + + + + + + as + at + by + do + go + if + in + is + it + no + of + on + or + to + n + r + l + i + io + fs + lp + dw + h + rs + ps + op + my + sb + vt + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + + False + + + + + + + + + + + False + + + + + + False + + + + + + + diff --git a/PowerShell-master/ThirdPartyNotices.txt b/PowerShell-master/ThirdPartyNotices.txt new file mode 100644 index 0000000000000000000000000000000000000000..8abff24592f9aba318c5f2a015e956c09752657b --- /dev/null +++ b/PowerShell-master/ThirdPartyNotices.txt @@ -0,0 +1,5042 @@ +NOTICES AND INFORMATION +Do Not Translate or Localize + +This software incorporates material from third parties. +Microsoft makes certain open source code available at https://3rdpartysource.microsoft.com, +or you may send a check or money order for US $5.00, including the product name, +the open source component name, platform, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the extent +required to debug changes to any libraries licensed under the GNU Lesser General Public License. + +--------------------------------------------------------- + +Markdig.Signed 0.42.0 - BSD-2-Clause + + + +Copyright (c) . All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Humanizer.Core 2.14.1 - MIT + + +Copyright .NET Foundation and Contributors +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Json.More.Net 2.1.1 - MIT + + +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) .NET Foundation and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +JsonPointer.Net 5.3.1 - MIT + + +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) .NET Foundation and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +JsonSchema.Net 7.4.0 - MIT + + +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) .NET Foundation and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.ApplicationInsights 2.23.0 - MIT + + +(c) Microsoft Corporation + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Bcl.AsyncInterfaces 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.CodeAnalysis.Common 4.14.0 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.CodeAnalysis.CSharp 4.14.0 - MIT + + +(c) Microsoft Corporation +Copyright (c) Microsoft Corporation +ACopyright (c) Microsoft Corporation +CCopyright (c) Microsoft Corporation +DCopyright (c) Microsoft Corporation +OCopyright (c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Extensions.ObjectPool 9.0.9 - MIT + + +Copyright Jorn Zaefferer +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright (c) 2015, Google Inc. +Copyright (c) 2019 David Fowler +Copyright (c) HTML5 Boilerplate +Copyright 2019 The gRPC Authors +Copyright (c) 2016 Richard Morris +Copyright (c) 1998 John D. Polstra +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2013 - 2018 AngleSharp +Copyright (c) 2000-2013 Julian Seward +Copyright (c) 2011-2021 Twitter, Inc. +Copyright (c) 2014-2018 Michael Daines +Copyright (c) 1996-1998 John D. Polstra +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) .NET Foundation Contributors +Copyright (c) 2011-2021 The Bootstrap Authors +Copyright (c) 2019-2023 The Bootstrap Authors +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019-2020 West Wind Technologies +Copyright (c) 2007 John Birrell (jb@freebsd.org) +Copyright (c) 2011 Alex MacCaw (info@eribium.org) +Copyright (c) Nicolas Gallagher and Jonathan Neal +Copyright (c) 2010-2019 Google LLC. http://angular.io/license +Copyright (c) 2011 Nicolas Gallagher (nicolas@nicolasgallagher.com) +Copyright (c) 1989, 1993 The Regents of the University of California +Copyright (c) 1990, 1993 The Regents of the University of California +Copyright OpenJS Foundation and other contributors, https://openjsf.org +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.PowerShell.MarkdownRender 7.2.1 - MIT + + +(c) Microsoft Corporation +(c) Microsoft Corporation. PowerShell's Markdown Rendering project PowerShell Markdown Renderer + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Security.Extensions 1.4.0 - MIT + + +(c) Microsoft Corporation +Copyright (c) Microsoft Corporation + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Win32.Registry.AccessControl 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Win32.SystemEvents 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Windows.Compatibility 9.0.9 - MIT + + +(c) Microsoft Corporation + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Newtonsoft.Json 13.0.4 - MIT + + +Copyright James Newton-King 2008 +Copyright (c) 2007 James Newton-King +Copyright (c) James Newton-King 2008 +Copyright James Newton-King 2008 Json.NET + +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.android-arm.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.android-arm64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.android-x64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.android-x86.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-arm.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-arm64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-bionic-arm64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-bionic-x64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-musl-arm.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-musl-arm64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-musl-x64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.linux-x64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.maccatalyst-arm64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.maccatalyst-x64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.native.System.Data.SqlClient.sni 4.4.0 - MIT + + +(c) 2022 GitHub, Inc. +(c) Microsoft Corporation +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1991-2017 Unicode, Inc. +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) .NET Foundation Contributors +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.osx-arm64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +runtime.osx-x64.runtime.native.System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.CodeDom 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ComponentModel.Composition 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ComponentModel.Composition.Registration 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Configuration.ConfigurationManager 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Data.Odbc 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Data.OleDb 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Data.SqlClient 4.9.0 - MIT + + +(c) Microsoft Corporation + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Diagnostics.EventLog 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Diagnostics.PerformanceCounter 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.DirectoryServices 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.DirectoryServices.AccountManagement 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.DirectoryServices.Protocols 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Drawing.Common 9.0.9 - MIT + + +(c) Microsoft Corporation +Copyright (c) Sven Groot (Ookii.org) 2009 +Copyright (c) .NET Foundation and Contributors + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.IO.Packaging 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.IO.Ports 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Management 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Net.Http.WinHttpHandler 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Private.ServiceModel 4.10.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Reflection.Context 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Runtime.Caching 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Security.Cryptography.Pkcs 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Security.Cryptography.ProtectedData 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Security.Cryptography.Xml 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Security.Permissions 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.Duplex 4.10.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.Http 4.10.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.NetTcp 4.10.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.Primitives 4.10.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.Security 4.10.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.Syndication 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceProcess.ServiceController 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Speech 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Threading.AccessControl 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Web.Services.Description 8.1.2 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) Provided + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Windows.Extensions 9.0.9 - MIT + + +Copyright (c) 2021 +Copyright (c) Six Labors +(c) Microsoft Corporation +Copyright (c) 2022 FormatJS +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright (c) 1998 Microsoft +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 2015 Andrew Gallant +Copyright (c) 2022, Wojciech Mula +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2005-2020 Rich Felker +Copyright (c) 2012-2021 Yann Collet +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2018 Nemanja Mijailovic +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2015-2018, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2011-2015 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2012 - present, Victor Zverovich +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Portions (c) International Organization for Standardization 1986 +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang) Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + + +------------------------------------------------------------------- + +------------------------------------------------------------------- + +Additional - + +------------------------------------------------- +Microsoft.PowerShell.Archive +------------------------------------------------- + +Copyright (c) 2016 Microsoft Corporation. + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +------------------------------------------------- +Microsoft.Management.Infrastructure.Runtime.Unix +Microsoft.Management.Infrastructure +------------------------------------------------- + +Copyright (c) Microsoft Corporation + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------- +• NuGet.Common +• NuGet.Configuration +• NuGet.DependencyResolver.Core +• NuGet.Frameworks +• NuGet.LibraryModel +• NuGet.Packaging +• NuGet.Packaging.Core +• NuGet.Packaging.Core.Types +• NuGet.ProjectModel +• NuGet.Protocol.Core.Types +• NuGet.Protocol.Core.v3 +• NuGet.Repositories +• NuGet.RuntimeModel +• NuGet.Versioning +---------------------------------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +these files except in compliance with the License. You may obtain a copy of the +License at + +https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +------------------------------------------------- +PackageManagement +------------------------------------------------- + +Copyright (c) Microsoft Corporation +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the Software), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------- +PowerShellGet +------------------------------------------------- + +Copyright (c) Microsoft Corporation + +All rights reserved. + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------------------------------- +File: PSReadLine +--------------------------------------------- + +https://github.com/PowerShell/PSReadLine + +Copyright (c) 2013, Jason Shirk + +All rights reserved. + +BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------- +ThreadJob +------------------------------------------------- + +Copyright (c) 2018 Paul Higinbotham + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/PowerShell-master/assets/AppxManifest.xml b/PowerShell-master/assets/AppxManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..50a8c7af45d34aa6803698f68070cecf372c5617 --- /dev/null +++ b/PowerShell-master/assets/AppxManifest.xml @@ -0,0 +1,52 @@ + + + + + + + + $DISPLAYNAME$ + Microsoft Corporation + assets\StoreLogo.png + disabled + disabled + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/assets/Avatar.svg b/PowerShell-master/assets/Avatar.svg new file mode 100644 index 0000000000000000000000000000000000000000..c6f739207734653f244da51b00e9bbcd6a7754cf --- /dev/null +++ b/PowerShell-master/assets/Avatar.svg @@ -0,0 +1,663 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/PowerShell-master/assets/Chibi_Avatar.png b/PowerShell-master/assets/Chibi_Avatar.png new file mode 100644 index 0000000000000000000000000000000000000000..f442f55dd21bb9e461b6036dd6b750f0d0a38b70 Binary files /dev/null and b/PowerShell-master/assets/Chibi_Avatar.png differ diff --git a/PowerShell-master/assets/Chibi_Avatar.svg b/PowerShell-master/assets/Chibi_Avatar.svg new file mode 100644 index 0000000000000000000000000000000000000000..ac678777be2e8bcada2440b46fc2d9bc8c8146bb --- /dev/null +++ b/PowerShell-master/assets/Chibi_Avatar.svg @@ -0,0 +1,351 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/assets/GroupPolicy/InstallPSCorePolicyDefinitions.ps1 b/PowerShell-master/assets/GroupPolicy/InstallPSCorePolicyDefinitions.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..ee3c725b1bdfe11c821754ed7d4fab83bc125117 --- /dev/null +++ b/PowerShell-master/assets/GroupPolicy/InstallPSCorePolicyDefinitions.ps1 @@ -0,0 +1,88 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +<# +.Synopsis + Group Policy tools use administrative template files (.admx, .adml) to populate policy settings in the user interface. + This allows administrators to manage registry-based policy settings. + This script installes PowerShell Core Administrative Templates for Windows. +.Notes + The PowerShellCoreExecutionPolicy.admx and PowerShellCoreExecutionPolicy.adml files are + expected to be at the location specified by the Path parameter with default value of the location of this script. +#> +[CmdletBinding()] +param +( + [ValidateNotNullOrEmpty()] + [string] $Path = $PSScriptRoot +) +Set-StrictMode -Version 3.0 +$ErrorActionPreference = 'Stop' + +function Test-Elevated +{ + [CmdletBinding()] + [OutputType([bool])] + Param() + + # if the current Powershell session was called with administrator privileges, + # the Administrator Group's well-known SID will show up in the Groups for the current identity. + # Note that the SID won't show up unless the process is elevated. + return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") +} +$IsWindowsOs = $PSHOME.EndsWith('\WindowsPowerShell\v1.0', [System.StringComparison]::OrdinalIgnoreCase) -or $IsWindows + +if (-not $IsWindowsOs) +{ + throw 'This script must be run on Windows.' +} + +if (-not (Test-Elevated)) +{ + throw 'This script must be run from an elevated process.' +} + +if ([System.Management.Automation.Platform]::IsNanoServer) +{ + throw 'Group policy definitions are not supported on Nano Server.' +} + +$admxName = 'PowerShellCoreExecutionPolicy.admx' +$admlName = 'PowerShellCoreExecutionPolicy.adml' +$admx = Get-Item -Path (Join-Path -Path $Path -ChildPath $admxName) +$adml = Get-Item -Path (Join-Path -Path $Path -ChildPath $admlName) +$admxTargetPath = Join-Path -Path $env:WINDIR -ChildPath "PolicyDefinitions" +$admlTargetPath = Join-Path -Path $admxTargetPath -ChildPath "en-US" + +$files = @($admx, $adml) +foreach ($file in $files) +{ + if (-not (Test-Path -Path $file)) + { + throw "Could not find $($file.Name) at $Path" + } +} + +Write-Verbose "Copying $admx to $admxTargetPath" +Copy-Item -Path $admx -Destination $admxTargetPath -Force +$admxTargetFullPath = Join-Path -Path $admxTargetPath -ChildPath $admxName +if (Test-Path -Path $admxTargetFullPath) +{ + Write-Verbose "$admxName was installed successfully" +} +else +{ + Write-Error "Could not install $admxName" +} + +Write-Verbose "Copying $adml to $admlTargetPath" +Copy-Item -Path $adml -Destination $admlTargetPath -Force +$admlTargetFullPath = Join-Path -Path $admlTargetPath -ChildPath $admlName +if (Test-Path -Path $admlTargetFullPath) +{ + Write-Verbose "$admlName was installed successfully" +} +else +{ + Write-Error "Could not install $admlName" +} diff --git a/PowerShell-master/assets/GroupPolicy/PowerShellCoreExecutionPolicy.adml b/PowerShell-master/assets/GroupPolicy/PowerShellCoreExecutionPolicy.adml new file mode 100644 index 0000000000000000000000000000000000000000..3068ae57a24a9e7e9e44a953b202f14e7c62f46b --- /dev/null +++ b/PowerShell-master/assets/GroupPolicy/PowerShellCoreExecutionPolicy.adml @@ -0,0 +1,125 @@ + + + PowerShell Core + This file contains the configuration options for PowerShell Core + + + Allow all scripts + Allow only signed scripts + Turn on Script Execution + This policy setting lets you configure the script execution policy, controlling which scripts are allowed to run. + +If you enable this policy setting, the scripts selected in the drop-down list are allowed to run. + +The "Allow only signed scripts" policy setting allows scripts to execute only if they are signed by a trusted publisher. + +The "Allow local scripts and remote signed scripts" policy setting allows any local scrips to run; scripts that originate from the internet must be signed by a trusted publisher. + +The "Allow all scripts" policy setting allows all scripts to run. + +If you disable this policy setting, no scripts are allowed to run. + +Note: This policy setting exists under both "Computer Configuration" and "User Configuration" in the Local Group Policy Editor. The "Computer Configuration" has precedence over "User Configuration." + +If you disable or do not configure this policy setting, it reverts to a per-machine preference setting; the default if that is not configured is "Allow local scripts and remote signed scripts." + PowerShell Core + Allow local scripts and remote signed scripts + At least Microsoft Windows 7 or Windows Server 2008 family + + Turn on Module Logging + + This policy setting allows you to turn on logging for PowerShell Core modules. + + If you enable this policy setting, pipeline execution events for members of the specified modules are recorded in the PowerShell Core log in Event Viewer. Enabling this policy setting for a module is equivalent to setting the LogPipelineExecutionDetails property of the module to True. + + If you disable this policy setting, logging of execution events is disabled for all PowerShell Core modules. Disabling this policy setting for a module is equivalent to setting the LogPipelineExecutionDetails property of the module to False. + + If this policy setting is not configured, the LogPipelineExecutionDetails property of a module determines whether the execution events of a module are logged. By default, the LogPipelineExecutionDetails property of all modules is set to False. + + To add modules to the policy setting list, click Show, and then type the module names in the list. The modules in the list must be installed on the computer. + + Note: This policy setting exists under both Computer Configuration and User Configuration in the Group Policy Editor. The Computer Configuration policy setting takes precedence over the User Configuration policy setting. + + + Turn on PowerShell Transcription + + This policy setting lets you capture the input and output of PowerShell Core commands into text-based transcripts. + + If you enable this policy setting, PowerShell Core will enable transcription logging for PowerShell Core and any other + applications that leverage the PowerShell Core engine. By default, PowerShell Core will record transcript output to each users' My Documents + directory, with a file name that includes 'PowerShell_transcript', along with the computer name and time started. Enabling this policy is equivalent + to calling the Start-Transcript cmdlet on each PowerShell Core session. + + If you disable this policy setting, transcription logging of PowerShell-based applications is disabled by default, although transcripting can still be enabled + through the Start-Transcript cmdlet. + + If you use the OutputDirectory setting to enable transcription logging to a shared location, be sure to limit access to that directory to prevent users + from viewing the transcripts of other users or computers. + + Note: This policy setting exists under both Computer Configuration and User Configuration in the Group Policy Editor. The Computer Configuration policy setting takes precedence over the User Configuration policy setting. + + + Turn on PowerShell Script Block Logging + + This policy setting enables logging of all PowerShell script input to the Microsoft-Windows-PowerShell/Operational event log. If you enable this policy setting, + PowerShell Core will log the processing of commands, script blocks, functions, and scripts - whether invoked interactively, or through automation. + + If you disable this policy setting, logging of PowerShell script input is disabled. + + If you enable the Script Block Invocation Logging, PowerShell additionally logs events when invocation of a command, script block, function, or script + starts or stops. Enabling Invocation Logging generates a high volume of event logs. + + Note: This policy setting exists under both Computer Configuration and User Configuration in the Group Policy Editor. The Computer Configuration policy setting takes precedence over the User Configuration policy setting. + + + Set the default source path for Update-Help + This policy setting allows you to set the default value of the SourcePath parameter on the Update-Help cmdlet. + +If you enable this policy setting, the Update-Help cmdlet will use the specified value as the default value for the SourcePath parameter. This default value can be overridden by specifying a different value with the SourcePath parameter on the Update-Help cmdlet. + +If this policy setting is disabled or not configured, this policy setting does not set a default value for the SourcePath parameter of the Update-Help cmdlet. + +Note: This policy setting exists under both Computer Configuration and User Configuration in the Group Policy Editor. The Computer Configuration policy setting takes precedence over the User Configuration policy setting. + + Console session configuration + Specifies a configuration endpoint in which PowerShell is run. This can be any endpoint registered on the local machine including the default PowerShell remoting endpoints or a custom endpoint having specific user role capabilities. + + + + + + Use Windows PowerShell Policy setting. + Execution Policy + + + Use Windows PowerShell Policy setting. + To turn on logging for one or more modules, click Show, and then type the module names in the list. Wildcards are supported. + Module Names + To turn on logging for the PowerShell Core core modules, type the following module names in the list: + Microsoft.PowerShell.* + Microsoft.WSMan.Management + + + Use Windows PowerShell Policy setting. + + Include invocation headers: + + + Use Windows PowerShell Policy setting. + Log script block invocation start / stop events: + + + Use Windows PowerShell Policy setting. + + + + + + + + + + + + + diff --git a/PowerShell-master/assets/GroupPolicy/PowerShellCoreExecutionPolicy.admx b/PowerShell-master/assets/GroupPolicy/PowerShellCoreExecutionPolicy.admx new file mode 100644 index 0000000000000000000000000000000000000000..0622a8d2695469ce4c8a463339f3dd4d90146aa4 --- /dev/null +++ b/PowerShell-master/assets/GroupPolicy/PowerShellCoreExecutionPolicy.admx @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AllSigned + + + + + RemoteSigned + + + + + Unrestricted + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/assets/Powershell-preview.icns b/PowerShell-master/assets/Powershell-preview.icns new file mode 100644 index 0000000000000000000000000000000000000000..070c392fc86d50e5459093c20a9445a34f30dd1c --- /dev/null +++ b/PowerShell-master/assets/Powershell-preview.icns @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:675b69f086ab2f6e661a50f14d0a4696a6863ddb7b51b8dbc693ece75465ff84 +size 124952 diff --git a/PowerShell-master/assets/Powershell.icns b/PowerShell-master/assets/Powershell.icns new file mode 100644 index 0000000000000000000000000000000000000000..a973b1ebdb48e37910e8b30b7109c4ef3a2d1c99 --- /dev/null +++ b/PowerShell-master/assets/Powershell.icns @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e595e33e8ea5c1d08453e400dc6e5e7c44e67c1577f5be7d4014332342ac6772 +size 273607 diff --git a/PowerShell-master/assets/Powershell_256.png b/PowerShell-master/assets/Powershell_256.png new file mode 100644 index 0000000000000000000000000000000000000000..fea2a31d1e6fdf5221cf26425358ec11b5bf615f Binary files /dev/null and b/PowerShell-master/assets/Powershell_256.png differ diff --git a/PowerShell-master/assets/Powershell_64.png b/PowerShell-master/assets/Powershell_64.png new file mode 100644 index 0000000000000000000000000000000000000000..cf9b5f06b47b5ebfb752f12a300b2e7c809d932f Binary files /dev/null and b/PowerShell-master/assets/Powershell_64.png differ diff --git a/PowerShell-master/assets/Powershell_av_colors.ico b/PowerShell-master/assets/Powershell_av_colors.ico new file mode 100644 index 0000000000000000000000000000000000000000..fa2fa6c7f1a57c00e1f40620cf4cdd4630e161ec --- /dev/null +++ b/PowerShell-master/assets/Powershell_av_colors.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ccc0b5626975eb29ec75247a44bbbc194038a9ec37cca618ef6001549712cf0 +size 120737 diff --git a/PowerShell-master/assets/Powershell_avatar.ico b/PowerShell-master/assets/Powershell_avatar.ico new file mode 100644 index 0000000000000000000000000000000000000000..ee8cf3c78494285847a73d09ad76dc9464ea7511 --- /dev/null +++ b/PowerShell-master/assets/Powershell_avatar.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2356d669e2166997f85bffdfe090278bc2b48f753f94dabd170b003f2fbce81a +size 125384 diff --git a/PowerShell-master/assets/Powershell_black.ico b/PowerShell-master/assets/Powershell_black.ico new file mode 100644 index 0000000000000000000000000000000000000000..ab40f934621a5075e6587769c9c14642ef723712 --- /dev/null +++ b/PowerShell-master/assets/Powershell_black.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:541e130176053ea0e044a6a7a0fa49c70d287f5e81be2c0785471f1ac9586904 +size 127271 diff --git a/PowerShell-master/assets/Powershell_black_64.png b/PowerShell-master/assets/Powershell_black_64.png new file mode 100644 index 0000000000000000000000000000000000000000..4c6e4c51e01b0fefff1a57448e9e86464c191ae0 Binary files /dev/null and b/PowerShell-master/assets/Powershell_black_64.png differ diff --git a/PowerShell-master/assets/README.md b/PowerShell-master/assets/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d557aa285f80d3232a150a0f5f87054622197784 --- /dev/null +++ b/PowerShell-master/assets/README.md @@ -0,0 +1,22 @@ +# Use of Trademarked Logos + +The assets in this folder are trademarked by Microsoft and don't fall under the same [License](https://raw.githubusercontent.com/PowerShell/PowerShell/master/LICENSE.txt) as the source code. + +## Permitted Uses + +Parties interested in using these logos can review the [Use of Microsoft Copyrighted Material](https://www.microsoft.com/en-us/legal/intellectualproperty/permissions) page. +If the use falls into any of those categories, you can move forward with the use and will not need additional permission. + +## Third Party Permission Requests + +If questions remain after reviewing the permitted uses page, please submit a request to [Third Party Permissions](mailto:mscrqs@microsoft.com). +The people supporting this will direct the request depending upon the content. + +If a request needs to be submitted to the [Third Party Permissions](mailto:mscrqs@microsoft.com), the request should include the following: + + - A statement that the [Use of Microsoft Copyrighted Material](https://www.microsoft.com/en-us/legal/intellectualproperty/permissions) was reviewed and did not address the situation. + - A statement that Microsoft (and not a third party) is the owner of the logo at issue. + - Clear identification of the materials to be used (i.e., the picture of the book cover included by the author in the letter request should suffice). + - A description, including URLs of how they found or located the logo. + - A description of how the party intends to use or distribute the logo (i.e., that it is for the book cover of an instructional book on PowerShell). + - A description of how long the party needs to use the logo. diff --git a/PowerShell-master/assets/Square150x150Logo-Preview.png b/PowerShell-master/assets/Square150x150Logo-Preview.png new file mode 100644 index 0000000000000000000000000000000000000000..b72584703c3fa580f023a88a0b2d9c6aaabc205a Binary files /dev/null and b/PowerShell-master/assets/Square150x150Logo-Preview.png differ diff --git a/PowerShell-master/assets/Square150x150Logo.png b/PowerShell-master/assets/Square150x150Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..b93585f7c6db96d8ec5cf89f847e045560c638db Binary files /dev/null and b/PowerShell-master/assets/Square150x150Logo.png differ diff --git a/PowerShell-master/assets/Square44x44Logo-Preview.png b/PowerShell-master/assets/Square44x44Logo-Preview.png new file mode 100644 index 0000000000000000000000000000000000000000..c58e0dffae65a2f027e3bd989d8d973bcb98e593 Binary files /dev/null and b/PowerShell-master/assets/Square44x44Logo-Preview.png differ diff --git a/PowerShell-master/assets/Square44x44Logo.png b/PowerShell-master/assets/Square44x44Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..d44a38ac9c6cb3bd93f2870eaa65287c33451791 Binary files /dev/null and b/PowerShell-master/assets/Square44x44Logo.png differ diff --git a/PowerShell-master/assets/Square44x44Logo.targetsize-48-Preview.png b/PowerShell-master/assets/Square44x44Logo.targetsize-48-Preview.png new file mode 100644 index 0000000000000000000000000000000000000000..c58e0dffae65a2f027e3bd989d8d973bcb98e593 Binary files /dev/null and b/PowerShell-master/assets/Square44x44Logo.targetsize-48-Preview.png differ diff --git a/PowerShell-master/assets/Square44x44Logo.targetsize-48.png b/PowerShell-master/assets/Square44x44Logo.targetsize-48.png new file mode 100644 index 0000000000000000000000000000000000000000..d44a38ac9c6cb3bd93f2870eaa65287c33451791 Binary files /dev/null and b/PowerShell-master/assets/Square44x44Logo.targetsize-48.png differ diff --git a/PowerShell-master/assets/Square44x44Logo.targetsize-48_altform-unplated-Preview.png b/PowerShell-master/assets/Square44x44Logo.targetsize-48_altform-unplated-Preview.png new file mode 100644 index 0000000000000000000000000000000000000000..c58e0dffae65a2f027e3bd989d8d973bcb98e593 Binary files /dev/null and b/PowerShell-master/assets/Square44x44Logo.targetsize-48_altform-unplated-Preview.png differ diff --git a/PowerShell-master/assets/Square44x44Logo.targetsize-48_altform-unplated.png b/PowerShell-master/assets/Square44x44Logo.targetsize-48_altform-unplated.png new file mode 100644 index 0000000000000000000000000000000000000000..d44a38ac9c6cb3bd93f2870eaa65287c33451791 Binary files /dev/null and b/PowerShell-master/assets/Square44x44Logo.targetsize-48_altform-unplated.png differ diff --git a/PowerShell-master/assets/StoreLogo-Preview.png b/PowerShell-master/assets/StoreLogo-Preview.png new file mode 100644 index 0000000000000000000000000000000000000000..b59d9158923ce631bb342986c7bfccbfb2e034bd Binary files /dev/null and b/PowerShell-master/assets/StoreLogo-Preview.png differ diff --git a/PowerShell-master/assets/StoreLogo.png b/PowerShell-master/assets/StoreLogo.png new file mode 100644 index 0000000000000000000000000000000000000000..425a3b1ced2fe735079036d38d5837aa754fcf45 Binary files /dev/null and b/PowerShell-master/assets/StoreLogo.png differ diff --git a/PowerShell-master/assets/additionalAttributions.txt b/PowerShell-master/assets/additionalAttributions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6676ca99cf56e6d2fcaae875206cb670462b6c81 --- /dev/null +++ b/PowerShell-master/assets/additionalAttributions.txt @@ -0,0 +1,192 @@ + +------------------------------------------------------------------- + +------------------------------------------------------------------- + +Additional - + +------------------------------------------------- +Microsoft.PowerShell.Archive +------------------------------------------------- + +Copyright (c) 2016 Microsoft Corporation. + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +------------------------------------------------- +Microsoft.Management.Infrastructure.Runtime.Unix +Microsoft.Management.Infrastructure +------------------------------------------------- + +Copyright (c) Microsoft Corporation + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------- +• NuGet.Common +• NuGet.Configuration +• NuGet.DependencyResolver.Core +• NuGet.Frameworks +• NuGet.LibraryModel +• NuGet.Packaging +• NuGet.Packaging.Core +• NuGet.Packaging.Core.Types +• NuGet.ProjectModel +• NuGet.Protocol.Core.Types +• NuGet.Protocol.Core.v3 +• NuGet.Repositories +• NuGet.RuntimeModel +• NuGet.Versioning +---------------------------------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +these files except in compliance with the License. You may obtain a copy of the +License at + +https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +------------------------------------------------- +PackageManagement +------------------------------------------------- + +Copyright (c) Microsoft Corporation +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the Software), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------- +PowerShellGet +------------------------------------------------- + +Copyright (c) Microsoft Corporation + +All rights reserved. + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------------------------------- +File: PSReadLine +--------------------------------------------- + +https://github.com/PowerShell/PSReadLine + +Copyright (c) 2013, Jason Shirk + +All rights reserved. + +BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------- +ThreadJob +------------------------------------------------- + +Copyright (c) 2018 Paul Higinbotham + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PowerShell-master/assets/av_colors_128.svg b/PowerShell-master/assets/av_colors_128.svg new file mode 100644 index 0000000000000000000000000000000000000000..ab2963937199b9ad2736e24d370cbd8e1b4ec4ee --- /dev/null +++ b/PowerShell-master/assets/av_colors_128.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + diff --git a/PowerShell-master/assets/avatar_128.svg b/PowerShell-master/assets/avatar_128.svg new file mode 100644 index 0000000000000000000000000000000000000000..2948614737c0e9d7d66b95ddd7808dd33356f986 --- /dev/null +++ b/PowerShell-master/assets/avatar_128.svg @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/assets/default.help.txt b/PowerShell-master/assets/default.help.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5b5cefc9cd0d0a0a9566c7791fb0d8b9f13cf0a --- /dev/null +++ b/PowerShell-master/assets/default.help.txt @@ -0,0 +1,108 @@ + +TOPIC + PowerShell Help System + +SHORT DESCRIPTION + Displays help about PowerShell cmdlets and concepts. + +LONG DESCRIPTION + PowerShell Help describes PowerShell cmdlets, functions, scripts, and + modules, and explains concepts, including the elements of the PowerShell + language. + + PowerShell does not include help files, but you can read the help topics + online, or use the Update-Help cmdlet to download help files to your + computer and then use the Get-Help cmdlet to display the help topics at + the command line. + + You can also use the Update-Help cmdlet to download updated help files + as they are released so that your local help content is never obsolete. + + Without help files, Get-Help displays auto-generated help for cmdlets, + functions, and scripts. + + + ONLINE HELP + You can find help for PowerShell online at + https://go.microsoft.com/fwlink/?LinkID=108518. + + To open online help for any cmdlet or function, type: + + Get-Help -Online + + UPDATE-HELP + To download and install help files on your computer: + + 1. Start PowerShell with the "Run as administrator" option. + 2. Type: + + Update-Help + + After the help files are installed, you can use the Get-Help cmdlet to + display the help topics. You can also use the Update-Help cmdlet to + download updated help files so that your local help files are always + up-to-date. + + For more information about the Update-Help cmdlet, type: + + Get-Help Update-Help -Online + + or go to: https://go.microsoft.com/fwlink/?LinkID=210614 + + + GET-HELP + The Get-Help cmdlet displays help at the command line from content in + help files on your computer. Without help files, Get-Help displays basic + help about cmdlets and functions. You can also use Get-Help to display + online help for cmdlets and functions. + + To get help for a cmdlet, type: + + Get-Help + + To get online help, type: + + Get-Help -Online + + The titles of conceptual topics begin with "About_". To get help for a + concept or language element, type: + + Get-Help About_ + + To search for a word or phrase in all help files, type: + + Get-Help + + For more information about the Get-Help cmdlet, type: + + Get-Help Get-Help -Online + + or go to: https://go.microsoft.com/fwlink/?LinkID=113316 + + + EXAMPLES: + Save-Help : Download help files from the internet and save + them on a file share. + + Update-Help : Downloads and installs help files from the + internet or a file share. + + Get-Help Get-Process : Displays help about the Get-Process cmdlet. + + Get-Help Get-Process -Online + : Opens online help for the Get-Process cmdlet. + + Help Get-Process : Displays help about Get-Process one page at a + time. + Get-Process -? : Displays help about the Get-Process cmdlet. + + Get-Help About_Modules : Displays help about PowerShell modules. + + Get-Help remoting : Searches the help topics for the word "remoting." + + SEE ALSO: + about_Updatable_Help + Get-Help + Save-Help + Update-Help + diff --git a/PowerShell-master/assets/macDialog.png b/PowerShell-master/assets/macDialog.png new file mode 100644 index 0000000000000000000000000000000000000000..9405c2d903a67444fa36d2335d5cbdc696234c69 Binary files /dev/null and b/PowerShell-master/assets/macDialog.png differ diff --git a/PowerShell-master/assets/manpage/pwsh.1 b/PowerShell-master/assets/manpage/pwsh.1 new file mode 100644 index 0000000000000000000000000000000000000000..14c191241a900335d229da0a45945afce21fde84 --- /dev/null +++ b/PowerShell-master/assets/manpage/pwsh.1 @@ -0,0 +1,10 @@ +.\" generated with Ronn/v0.7.3 +.\" http://github.com/rtomayko/ronn/tree/0.7.3 +. +.TH "PWSH" "1" "October 2023" "" "" +. +.SH "NAME" +\fBpwsh\fR \- PowerShell command\-line shell and \.NET REPL +. +.SH "SYNOPSIS" +\fBpwsh\fR [\fB\-Login\fR] [ [\fB\-File\fR] \fIfilePath\fR [args] ] [\fB\-Command\fR { \- | \fIscript\-block\fR [\fB\-args\fR \fIarg\-array\fR] | \fIstring\fR [\fICommandParameters\fR] } ] [\fB\-ConfigurationFile\fR \fIfilePath\fR] [\fB\-ConfigurationName\fR \fIstring\fR] [\fB\-CustomPipeName\fR \fIstring\fR] [\fB\-EncodedArguments\fR \fIBase64EncodedArguments\fR] [\fB\-EncodedCommand\fR \fIBase64EncodedCommand\fR] [\fB\-ExecutionPolicy\fR \fIExecutionPolicy\fR] [\fB\-Help\fR] [\fB\-InputFormat\fR {Text | XML}] [\fB\-Interactive\fR] [\fB\-MTA\fR] [\fB\-NoExit\fR] [\fB\-NoLogo\fR] [\fB\-NonInteractive\fR] [\fB\-NoProfile\fR] [\fB\-NoProfileLoadTime\fR] [\fB\-OutputFormat\fR {Text | XML}] [\fB\-SettingsFile\fR \fIfilePath\fR] [\fB\-SSHServerMode\fR] [\fB\-STA\fR] [\fB\-Version\fR] [\fB\-WindowStyle\fR diff --git a/PowerShell-master/assets/manpage/pwsh.1.ronn b/PowerShell-master/assets/manpage/pwsh.1.ronn new file mode 100644 index 0000000000000000000000000000000000000000..98320cc60c8737db36c6cc1c2a8c721650cf7bf9 --- /dev/null +++ b/PowerShell-master/assets/manpage/pwsh.1.ronn @@ -0,0 +1,230 @@ +pwsh(1) -- PowerShell command-line shell and .NET REPL +================================================= + +## SYNOPSIS + +`pwsh` [`-Login`] [ [`-File`] [args] ] +[`-Command` { - | [`-args` ] | +[] } ] [`-ConfigurationFile` ] +[`-ConfigurationName` ] [`-CustomPipeName` ] +[`-EncodedArguments` ] +[`-EncodedCommand` ] +[`-ExecutionPolicy` ] [`-Help`] [`-InputFormat` {Text | XML}] +[`-Interactive`] [`-MTA`] [`-NoExit`] [`-NoLogo`] [`-NonInteractive`] +[`-NoProfile`] [`-NoProfileLoadTime`] [`-OutputFormat` {Text | XML}] +[`-SettingsFile` ] [`-SSHServerMode`] [`-STA`] [`-Version`] +[`-WindowStyle` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Page-1 + + + + + Start/End + User has idea! + + + + + + + + + + + + + + + + + + + User has idea! + + Dynamic connector + + + + Process + User files issue with rationale and use cases + + + + + + + + + + + + + + + + + + + User files issue with rationale and use cases + + Dynamic connector.9 + + + + Process.8 + Maintainers label issue with Area Label + + + + + + + + + + + + + + + + + + + Maintainers label issue with Area Label + + Dynamic connector.13 + No + + + + + No + + Process.12 + Users discuss idea “exhaustively” (TBD by WGs) + + + + + + + + + + + + + + + + + + + Users discuss idea exhaustively” (TBD by WGs) + + Dynamic connector.15 + + + + Decision + Do the WGs think the idea has potential / is worth pursuing? + + + + + + + + + + + + + + + + + + + Do the WGs think the idea has potential / is worth pursuing? + + Dynamic connector.23 + No + + + + + No + + Subprocess + Committee appeals process (TBD) + + + + + + + + + + + + + + + + + + + + + + + Committee appeals process (TBD) + + Dynamic connector.27 + Appeal unsuccessful + + + + + Appeal unsuccessful + + Start/End.26 + Issue is closed, idea not pursued within PS repo + + + + + + + + + + + + + + + + + + + + Issue is closed, idea not pursued within PS repo + + Dynamic connector.30 + Successful appeal + + + + + Successful appeal + + Process.32 + Implement and release the implementation outside of PS + + + + + + + + + + + + + + + + + + + Implement and release the implementation outside of PS + + Process.43 + WGs label “RFC required”; Both paths are (eventually) require... + + + + + + + + + + + + + + + + + + + + WGs label “RFC required”; Both paths are (eventually) required; author(s) can choose to do in any order + + Dynamic connector.46 + + + + Process.45 + Contributor writes and publishes RFC as draft PR in PowerShel... + + + + + + + + + + + + + + + + + + + + Contributor writes and publishes RFC as draft PR in PowerShell-RFC(add reference in original issue) + + Dynamic connector.48 + + + + Process.47 + Contributor publishes PR with WIP and/or prototype code as dr... + + + + + + + + + + + + + + + + + + + + Contributor publishes PR with WIP and/or prototype code as draft PR in PowerShell repo(add reference in original issue, Maintainers add `Proposal` label) + + Dynamic connector.50 + + + + Process.49 + WGs, contributors, and any others have discussion about RFC f... + + + + + + + + + + + + + + + + + + + WGs, contributors, and any others have discussion about RFC for >= 2 months + + Dynamic connector.52 + + + + Process.51 + Author marks RFC PR as non-draft + + + + + + + + + + + + + + + + + + + Author marks RFC PR as non-draft + + Dynamic connector.56 + + + + Decision.55 + Does the code PR meet WG and Maintainer standards? + + + + + + + + + + + + + + + + + + + + Does the code PR meet WG and Maintainer standards? + + Decision.65 + Is the RFC accepted and matching the implemen-tation? + + + + + + + + + + + + + + + + + + + + Is the RFC accepted and matching the implemen-tation? + + Dynamic connector.67 + No + + + + + No + + Dynamic connector.69 + + + + Start/End.68 + Merge as non-experimental code + + + + + + + + + + + + + + + + + + + Merge as non-experimental code + + Dynamic connector.71 + + + + Process.70 + Committee review + + + + + + + + + + + + + + + + + + + Committee review + + Decision.75 + Does the RFC contain all necessary info to merge as experimen... + + + + + + + + + + + + + + + + + + + + Does the RFC contain all necessary info to merge as experimental? + + Decision.77 + Committee votes to approve RFC + + + + + + + + + + + + + + + + + + + Committee votes to approve RFC + + Dynamic connector.79 + Reject + + + + + Reject + + Process.80 + RFC author adds additional info + + + + + + + + + + + + + + + + + + + RFC author adds additional info + + Dynamic connector.87 + Approve + + + + + Approve + + Decision.86 + Is the code ready to go? + + + + + + + + + + + + + + + + + + + Is the code ready to go? + + Dynamic connector.88 + Yes + + + + + Yes + + Dynamic connector.90 + No + + + + + No + + Decision.36 + Do you still think it needs to be in the PS package? + + + + + + + + + + + + + + + + + + + + Do you still think it needs to be in the PS package? + + Dynamic connector.1012 + Yes + + + + + Yes + + Decision.1006 + Can the idea be implemented outside of the PS code repo? + + + + + + + + + + + + + + + + + + + + Can the idea be implemented outside of the PS code repo? + + Dynamic connector.1007 + + + + Dynamic connector.1008 + Yes + + + + + Yes + + Dynamic connector.1001 + + + + Dynamic connector.1014 + + + + Decision.1015 + Do the WGs think an RFC is required? + + + + + + + + + + + + + + + + + + + Do the WGs think an RFC is required? + + Dynamic connector.1016 + Yes + + + + + Yes + + Dynamic connector.1017 + Yes + + + + + Yes + + Dynamic connector.1019 + No + + + + + No + + Process.1018 + WGs label “RFC not required”; Contributor opens a PR to be re... + + + + + + + + + + + + + + + + + + + + WGs label “RFC not required”; Contributor opens a PR to be reviewed by WGs and merged by maintainers + + Dynamic connector.1020 + Yes + + + + + Yes + + Process.1021 + Committee labels RFC PR with “Experimental - Approved” + + + + + + + + + + + + + + + + + + + Committee labels RFC PR with Experimental - Approved + + Dynamic connector.1023 + No + + + + + No + + Dynamic connector.1024 + + + + Dynamic connector.1026 + Yes + + + + + Yes + + Decision.1025 + Has the RFC been marked with “Experimental - Approved”? + + + + + + + + + + + + + + + + + + + + Has the RFC been marked with Experimental - Approved”? + + Dynamic connector.1028 + Yes + + + + + Yes + + Process.1027 + Merge code PR as Experimental Feature + + + + + + + + + + + + + + + + + + + Merge code PR as Experimental Feature + + Dynamic connector.1029 + No + + + + + No + + Dynamic connector.1031 + No + + + + + No + + Process.1030 + Contributor updates code PR based on feedback + + + + + + + + + + + + + + + + + + + Contributor updates code PR based on feedback + + Dynamic connector.1033 + + + + Decision.1032 + Has the code PR been merged as experimental? + + + + + + + + + + + + + + + + + + + + Has the code PR been merged as experimental? + + Dynamic connector.1034 + No + + + + + No + + Dynamic connector.1036 + Yes + + + + + Yes + + Decision.1035 + Does the Committee believe the experimental feature has had e... + + + + + + + + + + + + + + + + + + + + Does the Committee believe the experimental feature has had enough time to bake? + + Dynamic connector.1037 + Yes + + + + + Yes + + Dynamic connector.1038 + + + + Dynamic connector.1040 + + + + Decision.1039 + Does the Committee think the intent of the RFC is reasonable ... + + + + + + + + + + + + + + + + + + + + Does the Committee think the intent of the RFC is reasonable to pursue + + Dynamic connector.1041 + Yes + + + + + Yes + + Dynamic connector.1043 + No + + + + + No + + Start/End.1042 + Process stops + + + + + + + + + + + + + + + + + + + Process stops + + diff --git a/PowerShell-master/docs/community/process_diagram.vsdx b/PowerShell-master/docs/community/process_diagram.vsdx new file mode 100644 index 0000000000000000000000000000000000000000..014c28fa43dc10122fcdd405a56867f857298d6f Binary files /dev/null and b/PowerShell-master/docs/community/process_diagram.vsdx differ diff --git a/PowerShell-master/docs/community/working-group-definitions.md b/PowerShell-master/docs/community/working-group-definitions.md new file mode 100644 index 0000000000000000000000000000000000000000..277fc37f7890ffec71da2c1aa7b0402ab3d1b82a --- /dev/null +++ b/PowerShell-master/docs/community/working-group-definitions.md @@ -0,0 +1,199 @@ +# Working Group Definitions + +This document maintains a list of the current PowerShell [Working Groups (WG)](working-group.md), +as well as their definitions, membership, and a non-exhaustive set of examples of topics that fall +within the purview of that WG. + +For an up-to-date list of the issue/PR labels associated with these WGs, +see [Issue Management](../maintainers/issue-management.md) + +## Desired State Configuration (DSC) + +The Desired State Configuration (DSC) WG manages all facets of DSC in PowerShell 7, +including language features (like the `Configuration` keyword) +and the `PSDesiredStateConfiguration` module. + +Today, DSC is integrated into the PowerShell language, and we need to manage it as such. + +### Members + +* @TravisEz13 +* @theJasonHelmick +* @anmenaga +* @gaelcolas +* @michaeltlombardi +* @SteveL-MSFT + +## Developer Experience + +The PowerShell developer experience includes the **development of modules** (in C#, PowerShell script, etc.), +as well as the experience of **hosting PowerShell and its APIs** in other applications and language runtimes. +Special consideration should be given to topics like **backwards compatibility** with Windows PowerShell +(e.g. with **PowerShell Standard**) and **integration with related developer tools** +(e.g. .NET CLI or the PowerShell extension for Visual Studio Code). + +### Members + +* @JamesWTruher (PS Standard, module authoring) +* @adityapatwardhan (SDK) +* @michaeltlombardi +* @SeeminglyScience +* @bergmeister + +## Engine + +The PowerShell engine is one of the largest and most complex aspects of the codebase. +The Engine WG should be focused on the +**implementation and maintenance of core PowerShell engine code**. +This includes (but is not limited to): + +* The language parser +* The command and parameter binders +* The module and provider systems + * `*-Item` cmdlets + * Providers +* Performance +* Componentization +* AssemblyLoadContext + +It's worth noting that the Engine WG is not responsible for the definition of the PowerShell language. +This should be handled by the Language WG instead. +However, it's expected that many issues will require input from both WGs. + +### Members + +* @daxian-dbw +* @JamesWTruher +* @rkeithhill +* @vexx32 +* @SeeminglyScience +* @IISResetMe +* @powercode +* @kilasuit + +## Interactive UX + +While much of PowerShell can be used through both interactive and non-interactive means, +some of the PowerShell user experience is exclusively interactive. +These topics include (but are not limited to): + +* Console +* Help System +* Tab completion / IntelliSense +* Markdown rendering +* PSReadLine +* Debugging + +### Members + +* @theJasonHelmick +* @daxian-dbw (PSReadline / IntelliSense) +* @adityapatwardhan (Markdown / help system) +* @JamesWTruher (cmdlet design) +* @SeeminglyScience +* @sdwheeler +* @kilasuit +* @FriedrichWeinmann +* @StevenBucher98 + +## Language + +The Language WG is distinct from the Engine WG in that they deal with the abstract definition +of the PowerShell language itself. +While all WGs will be working closely with the PowerShell Committee (and may share members), +it's likely that the Language WG will work especially close with them, +particularly given the long-lasting effects of language decisions. + +### Members + +* @JamesWTruher +* @daxian-dbw +* @SeeminglyScience + +## Remoting + +The Remoting WG should focus on topics like the **PowerShell Remoting Protocol (PSRP)**, +the **protocols implemented under PSRP** (e.g. WinRM and SSH), +and **other protocols used for remoting** (e.g. "pure SSH" as opposed to SSH over PSRP). +Given the commonality of serialization boundaries, the Remoting WG should also focus on +**the PowerShell job system**. + +### Members + +* @anmenaga +* @TravisEz13 + +## Cmdlets and Modules + +The Cmdlet WG should focus on core/inbox modules whose source code lives within the +`PowerShell/PowerShell` repository, +including the proposal of new cmdlets and parameters, improvements and bugfixes to existing +cmdlets/parameters, and breaking changes. + +However, some modules that ship as part of the PowerShell package are managed in other source repositories. +These modules are owned by the maintainers of those individual repositories. +These modules include: + +* [`Microsoft.PowerShell.Archive`](https://github.com/PowerShell/Microsoft.PowerShell.Archive) +* [`PackageManagement` (formerly `OneGet`)](https://github.com/OneGet/oneget) +* [`PowerShellGet`](https://github.com/PowerShell/PowerShellGet) +* [`PSDesiredStateConfiguration`](https://github.com/PowerShell/xPSDesiredStateConfiguration) + (Note: this community repository maintains a slightly different version of this module on the Gallery, + but should be used for future development of `PSDesiredStateConfiguration`.) +* [`PSReadLine`](https://github.com/PowerShell/PSReadLine) +* [`ThreadJob`](https://github.com/PowerShell/Modules/tree/master/Modules/Microsoft.PowerShell.ThreadJob) + +### Members + +* @JamesWTruher +* @SteveL-MSFT +* @jdhitsolutions +* @TobiasPSP +* @doctordns +* @kilasuit + +## Security + +The Security WG should be brought into any issues or pull requests which may have security implications +in order to provide their expertise, concerns, and guidance. + +### Members + +* @TravisEz13 +* @SydneySmithReal +* @anamnavi +* @SteveL-MSFT + +## Explicitly not Working Groups + +Some areas of ownership in PowerShell specifically do not have Working Groups. +For the sake of completeness, these are listed below: + +### Build + +Build includes everything that is needed to build, compile, and package PowerShell. +This bucket is also not oriented a customer-facing deliverable and is already something handled by Maintainers, +so we don't need to address it as part of the WGs. + +* Build + * `build.psm1` + * `install-powershell.ps1` + * Build infrastructure and automation +* Packaging + * Scripts + * Infrastructure + +### Quality + +Similar to the topic of building PowerShell, quality +(including **test code**, **test infrastructure**, and **code coverage**) +should be managed by the PowerShell Maintainers. + +* Test code + * Pester unit tests + * xUnit unit tests +* Test infrastructure + * Nightlies + * CI +* Code coverage +* Pester diff --git a/PowerShell-master/docs/community/working-group.md b/PowerShell-master/docs/community/working-group.md new file mode 100644 index 0000000000000000000000000000000000000000..8b9caea2857f9a1e32e237d523eab4ef7f06bc48 --- /dev/null +++ b/PowerShell-master/docs/community/working-group.md @@ -0,0 +1,197 @@ +# Working Groups + +Working Groups (WGs) are collections of contributors with knowledge of specific components or +technologies in the PowerShell domain. +They are responsible for issue triage/acceptance, code reviews, and providing their expertise to +others in issues, PRs, and RFC discussions. + +The list, description, and membership of the existing Working Groups is available +[here](working-group-definitions.md). + +## Terms + +* **Contributor** is used interchangeably within this doc as anyone participating in issues or + contributing code, RFCs, documentations, tests, bug reports, etc., + regardless of their status with the PowerShell project. +* **Repository Maintainers** are trusted stewards of the PowerShell repository responsible for + maintaining consistency and quality of PowerShell code. + One of their primary responsibilities is merging pull requests after all requirements have been fulfilled. + (Learn more about the Repository Maintainers [here](https://github.com/PowerShell/PowerShell/tree/master/docs/maintainers).) +* The **PowerShell Committee** is responsible for the design and governance of the PowerShell project, + primarily by voting to accept or reject review-for-comment (RFC) documents. + (Learn more about the PowerShell Committee [here](https://github.com/PowerShell/PowerShell/blob/master/docs/community/governance.md#powershell-committee).) +* A **Working Group** is a collection of people responsible for providing expertise on a specific + area of PowerShell in order to help establish consensus within the community and Committee. + The responsibilities of Working Groups are outlined below. + (Note: while some experts within Working Groups may have more specific expertise in a sub-topic + of the team, + the intent is that each team is holistically and collectively responsible for making decisions + within the larger topic space.) + +## Goals + +In designing the WG process, the Committee had a few goals: + +1. Increase the velocity of innovation without compromising the stability of PowerShell +1. Reduce the time spent by contributors on writing/reviewing PRs and RFCs that are not feasible +1. Increase the formal authority of subject matter experts (SMEs) inside and outside of Microsoft +1. Decrease the volume of required technical discussions held by the Committee + +## Process + +This process is represented within the [`process_diagram.vsdx` Visio diagram](process_diagram.vsdx): + +![process_diagram](process_diagram.svg) + +1. A contributor has an idea for PowerShell +1. The contributor files an issue informally describing the idea, + including some rationale as to why it should happen and a few use cases to show how it could work, + as well as to determine viability and value to the community. + This should include examples of expected input and output so that others understand how the feature would function in the real world. +1. The issue gets triaged into an [Area label](https://github.com/PowerShell/PowerShell/blob/master/docs/maintainers/issue-management.md#feature-areas) + by Maintainers. + This area label maps to one or more Working Groups. +1. If the Working Group determines that an idea can be prototyped or built outside of the PowerShell repo + (e.g. as a module), + contributors should start that idea outside of the PowerShell project. + Given that the issue is no longer directly relevant to the PowerShell project, it should be closed + (with a link to the new project, if available). + If the implementation turns out to be successful and particularly popular, + and a contributor believes that it would be overwhelmingly valuable to include in the primary PowerShell package, + they can restart the process in a new issue proposing that the functionality be + incorporated directly into the primary PowerShell package. +1. After the issue is filed, interested contributors should discuss the + feasibility and approach of the idea in the issue. + The Working Group that owns that Area is expected to contribute to this discussion. + Working groups may have their own criteria to consider in their areas. +1. After an appropriately exhaustive discussion/conversation + (i.e. the Working Group has determined that no new arguments are being made), + the Working Group makes a call on whether they believe the idea should continue through this process. + Note: this should be done via a best effort of consensus among the Working Group. + We don't currently have hard requirements for how this should be done, + but some ideas include: + + * a single member of the Working Group makes a proposal as a comment and other members should + "react" on GitHub with up/down thumbs + * Working Groups communicate privately through their own established channel to reach consensus + + It's worth noting that Working Group members who repeatedly speak on behalf of the Working Group without + consensus, they may be censured or removed from the team. + +### Working Groups reject the proposal + +If the Working Group says the idea should not pursued, the process stops. +Some reasons for rejection include (but are not limited to): + +* the idea can be implemented and validated for usefulness and popularity outside of the primary PowerShell repo/package +* the idea is difficult/impossible to implement +* the implementation would introduce undesirable (and possibly breaking) changes to PowerShell +* other reasons specific to individual Working Groups + +In the instance that the contributor feels they have compelling arguments showing that the +Working Group is incorrect in their rejection, +they can appeal to the PowerShell Committee by mentioning `@PowerShell/PowerShell-Committee`, +upon which a maintainer will add the `Review-Committee` label to the issue and reopen it. +Then, the PS Committee will discuss further with the Working Group and others to make a final call on +whether or not the issue should be pursued further. + +Be sure to enumerate your reasons for appeal, as unfounded appeals may be rejected for consideration +by the Committee until reasons are given. + +### Working groups believe the proposal has merit and/or potential + +If the idea passes the preliminary acceptance criteria for the Working Group, +the process proceeds on one of a few different paths: + +#### "RFC Not Required" + +In some cases, a proposed idea is determined by the Working Group to be small, uncontroversial, or simple, +such that an RFC is not required (to be determined by the Working Group). +In these circumstances, the Working Group should mark the issue as "RFC not required", +upon which it can move directly to the code PR phase to be reviewed by Working Groups and Maintainers. + +The Committee still holds the authority to require an RFC if they see an "RFC Not Required" issue +that they feel needs more exposition before merging. + +In cases of minor breaking changes, Maintainers or Working Groups can add the `Review - Committee` label to get +additional opinions from the Committee. + +#### RFC/Prototype Process + +If an idea has any significant design or ecosystem implications, +*cannot* be prototyped or built outside of the PowerShell repo, +and the community and Working Groups agree that the idea is worth pursuing, +a contributor (who may or may not be the original issue filer) must do two things: + +* Write an RFC as a [Draft PR](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests#draft-pull-requests) + into `PowerShell/PowerShell-RFC` +* Prototype the implementation as a [Draft PR](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests#draft-pull-requests) + into `PowerShell/PowerShell` + +In both cases, the intention is to provide Working Groups and other contributors who care about the +idea an opportunity to provide feedback on the design and implementation. + +Either of these two steps can be done first, but both are required in order to have code accepted +into the PowerShell repository, including experimental features. + +Note: When "Draft" is capitalized in this document, I'm referring to the +[Draft pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests#draft-pull-requests) +feature on GitHub. +We intend to use this feature liberally to mark the lifecycle of an idea through to implementation. + +#### RFCs + +The existing RFC process uses folders as a way to move an RFC through a multi-stage process +(Draft -> Experimental -> Accepted/Final). +However, it was difficult to reconcile this process with the benefits of PR reviews. + +With the introduction of Draft PRs on GitHub, we are reorienting the acceptance process around the PR itself. +Going forward, an RFC will have three stages: + +1. A Draft PR, denoting that the RFC is still in the review period, openly soliciting comments, + and that it may continue to be significantly iterated upon with revisions, edits, and responses to + community feedback or concerns. +1. After a minimum of two months of discussion, the RFC/PR author marks the PR as + [ready for review](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/changing-the-stage-of-a-pull-request), + upon which the RFC will enter the Committee's review queue to discuss the RFC contents and comments, + and make a decision on whether it is reasonable to pursue. + If after this review, the Committee determines that the intent of the RFC is not reasonable + (e.g. there may be irreconcilable issues with the design, + or the intent may not fit with the principles of PowerShell), + they will reject the PR and the process terminates. +1. In most cases, the Committee will choose to wait for the code PR to be merged as experimental, + and leverage user feedback or telemetry to determine if the RFC PR should be merged. +1. Finally, the Committee will choose to either merge or close the RFC PR, + marking the RFC as either accepted or rejected, respectively. + +#### Experiments + +Often times, implementing an idea can demonstrate opportunities or challenges that were not well +understood when the idea was formulated. +Similarly, a "simple" code change can have far reaching effects that are not well understood +until you're able to experiment with an idea within working code. + +To that end, it's required that *some* implementation exist before the Committee will consider an +RFC for acceptance. +That way, contributors can compile the PR branch to play with a working iteration of the idea +as a way to understand whether the feature is working as expected and valuable. + +In most cases, as long as an RFC has already been written and published as a draft, +Working Groups or the Committee will approve the feature for incorporation as an experimental feature, +so that it can be trialed with greater usage as part of a preview release. +In addition to increasing the scope of those who can provide real-world feedback on the feature, +this enables us to use telemetry to understand if users are turning off the feature in large numbers. + +Note: today, this will be done on a case-by-case basis, but over time, the Committee will establish +firmer guidelines around when PRs should be merged as experimental. + +Experiments should be complete to the extent that they serve as reasonable indicators of the user experience. +In the case that breaking changes are required of the feature, the break should be made in the prototype +so that users can experiment with whether or not the break has a significant negative effect. + +#### Reporting Working Group members abuse + +Working group members are individuals and in many cases volunteers. +There may be situations where a working group member might exhibit behavior that is objectionable, +exceed the authority defined in this document or violate the [Code of Conduct](../../CODE_OF_CONDUCT.md). +We recommend to report such issues by using the [Report Content](https://docs.github.com/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam) mechanism to bring it to the attention of the maintainers to review. diff --git a/PowerShell-master/docs/debugging/README.md b/PowerShell-master/docs/debugging/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6e1acaaef597f5612687aef615bd9500eca61b22 --- /dev/null +++ b/PowerShell-master/docs/debugging/README.md @@ -0,0 +1,156 @@ +# Visual Studio Code + +The [Visual Studio Code][vscode] editor supports cross-platform debugging. +This is made possible by the [OmniSharp][] extension for VS Code. + +Please review their [detailed instructions][core-debug]. In +addition to being able to build PowerShell, you need: + +- C# Extension for VS Code installed +- .NET Core debugger installed (semi-automatic) +- `powershell` executable in your path (self-host if not on Windows) + +The .NET CLI tools *must* be on your path for Visual Studio Code. +`Start-PSBootstrap` installs the tools to `~/.dotnet` (non-Windows) or `"$env:LocalAppData\Microsoft\dotnet"` (Windows), +but does not add this to your `PATH`. +You can do this in Bash with `export PATH=$PATH:$HOME/.dotnet` or in PowerShell with `$env:path = $env:path+";$env:LocalAppData\Microsoft\dotnet"`. + +Once the extension is installed, you have to open a C# file to force VS Code to +install the actual .NET Core debugger (the editor will tell you to do this if +you attempt to debug and haven't already opened a C# file). + +The committed `.vscode` folder in the root of this repository contains +the `launch.json` and `tasks.json` files which provide Core PowerShell +debugging configurations and a build task. + +The "build" task will run `Start-PSBuild`, emitting the executable to +`PowerShell/debug/powershell` so that the debugger always knows where to find it +(regardless of platform). If you edit this, please do not commit it, as the +default is meant to "just work" for anyone. + +The ".NET Core Launch" configuration will build and start a `powershell` +process, with `justMyCode` disabled, and `stopAtEntry` enabled, thus PowerShell +will stop right at `Main`, and you need to click the green arrow to continue. + +With either Gnome Terminal or XTerm installed, the launch configuration will +launch an external console with PowerShell running interactively. If neither of +these installed, the editor will tell you to do so. + +Alternatively, the ".NET Core Attach" configuration will start listening for a +process named `powershell`, and will attach to it. If you need more fine-grained +control, replace `processName` with `processId` and provide a PID. (Please be +careful not to commit such a change.) + +[core-debug]: https://learn.microsoft.com/dotnet/core/tutorials/with-visual-studio-code#debug +[vscode]: https://code.visualstudio.com/ +[OmniSharp]: https://github.com/OmniSharp/omnisharp-vscode + +## PowerShell + +The `Trace-Command` cmdlet can be used to enable tracing of certain PowerShell +subsystems. Use `Get-TraceSource` for a list of tracers: + +* CmdletProviderClasses +* CommandDiscovery +* CommandSearch +* ConsoleHost +* ConsoleHostRunspaceInit +* ConsoleHostUserInterface +* ConsoleLineOutput +* DisplayDataQuery +* ETS +* FileSystemProvider +* FormatFileLoading +* FormatViewBinding +* LocationGlobber +* MemberResolution +* Modules +* MshSnapinLoadUnload +* ParameterBinderBase +* ParameterBinderController +* ParameterBinding +* PathResolution +* PSDriveInfo +* PSSnapInLoadUnload +* RunspaceInit +* SessionState +* TypeConversion +* TypeMatch + +Then trace it like this: + +```powershell +Trace-Command -Expression { Get-ChildItem . } -Name PathResolution -PSHost +``` + +The `-PSHost` specifies the sink, in this case the console host, +so we can see the tracing messages. +The `-Name` chooses the list of tracers to enable. + +## LLDB with SOS plug-in + +The `./tools/debug.sh` script can be used to launch PowerShell inside of LLDB +with the SOS plug-in provided by .NET Core. This provides an additional way to +debug PowerShell on Linux, but VS Code is recommended for a better user +experience (and its single-stepping capabilities). + +The script is self-documented and contains a link to the +[CoreCLR debugging help][clr-debug] . + +[clr-debug]: https://github.com/dotnet/coreclr/blob/master/Documentation/building/debugging-instructions.md#debugging-coreclr-on-linux + +## `corehost` + +The native executable produced by .NET CLI will produce trace output +if launched with `COREHOST_TRACE=1 ./powershell`. + +## CoreCLR PAL + +The native code in the CLR has debug channels to selectively output +information to the console. These are controlled by the +`PAL_DBG_CHANNELS`, e.g., `export PAL_DBG_CHANNELS="+all.all"`, as +detailed in the `dbgmsg.h` [header][]. + +Enabling `+all.all` is *incredibly* noisy; +you will need to narrow your scope. + +[header]: https://github.com/dotnet/coreclr/blob/release/1.0.0/src/pal/src/include/pal/dbgmsg.h + +## Debugging .NET Core + +The .NET Core libraries downloaded from NuGet and shipped with PowerShell are release versions. +This means that `PAL_DBG_CHANNELS` will not work with them, +and instead you must build and deploy .NET Core built in debug mode. +These instructions are not meant to be comprehensive, +but should prove useful. + +They are currently written for Linux and are meant only as a shortcut means to debug. + +## Build and deploy CoreCLR + +* Clone CoreCLR: `git clone -b release/1.0.0 https://github.com/dotnet/coreclr.git` +* Follow [building instructions](https://github.com/dotnet/coreclr/blob/release/1.0.0/Documentation/building/linux-instructions.md) +* Wait for `./build.sh` to finish +* Overwrite PowerShell libraries: `cp bin/Product/Linux.x64.Debug/*{so,dll} /path/to/powershell/` + +## Build and deploy CoreFX + +* Clone CoreFX: `git clone -b release/1.0.0 https://github.com/dotnet/corefx.git` +* Follow [building instructions](https://github.com/dotnet/corefx/blob/release/1.0.0/Documentation/building/unix-instructions.md) +* Wait for `./build.sh skiptests` to finish +* Overwrite PowerShell libraries: + +> This must be done in a particular order to get the most specific build, +> and each phase must be allowed to overwrite both the previous phase +> and any files previously found (hence the use of `-exec cp`). +> The glob cannot go more than one directory deep, +> as subdirectories can have alternative and unwanted implementations +> of libraries with the same name. + +```sh +dest=/path/to/powershell/ +find bin/AnyOS.AnyCPU.Debug/*/*.dll -exec cp -p {} $dest \; +find bin/Unix.AnyCPU.Debug/*/*.dll -exec cp -p {} $dest \; +find bin/Linux.AnyCPU.Debug/*/*.dll -exec cp -p {} $dest \; +find bin/Linux.x64.Debug/ -name *.so -exec cp -p {} $dest \; +``` diff --git a/PowerShell-master/docs/dev-process/breaking-change-contract.md b/PowerShell-master/docs/dev-process/breaking-change-contract.md new file mode 100644 index 0000000000000000000000000000000000000000..12121b31dfe0b98be9d629dd70c90c66ff985903 --- /dev/null +++ b/PowerShell-master/docs/dev-process/breaking-change-contract.md @@ -0,0 +1,88 @@ +# Breaking Changes + +We have a serious commitment to backwards compatibility with all earlier versions of PowerShell – including the language, cmdlets, APIs and the various protocols (e.g. PowerShell Remoting Protocol) and data formats (e.g. cdxml). + +Below is a summary of our approach to handing breaking changes including what kinds of things constitute breaking changes, how we categorize them, and how we decide what we're willing to take. + +Note that these rules only apply to existing stable features that have shipped in a supported release. New features marked as “in preview” that are still under development may be modified from one preview release to the next. +These are **not** considered breaking changes. + +To help triage breaking changes, we classify them in to four buckets: + +1. Public Contract +1. Reasonable Grey Area +1. Unlikely Grey Area +1. Clearly Non-Public + +## Bucket 1: Public Contract + +Any change that is a clear violation of the public contract. + +### Unacceptable changes + ++ A code change that results in a change to the existing behavior observed for a given input with an API, protocol or the PowerShell language. ++ Renaming or removing a public type, type member, or type parameter; renaming or removing a cmdlet or cmdlet parameter (note: it is possible to rename a cmdlet parameter if a parameter alias is added. + +This is an acceptable solution for PowerShell scripts but may break .NET code that depends on the name of the original member on the cmdlet object type.) + ++ Decreasing the range of accepted values within a given parameter. ++ Changing the value of a public constant or enum member; changing the type of a cmdlet parameter to a more restrictive type. + + Example: A cmdlet with a parameter -p1 that was previously type as [object] cannot be changed to be or a more restrictive type such as [int]. ++ Making an incompatible change to any protocol without increasing the protocol version number. + +### Acceptable changes + ++ Any existing behavior that results in an error message generally may be changed to provide new functionality. ++ A new instance field is added to a type (this impacts .NET serialization but not PowerShell serialization and so is considered acceptable.) ++ Adding new types, new type members and new cmdlets ++ Making changes to the protocols with a protocol version increment. Older versions of the protocol would still need to be maintained to allow communication with earlier systems. This would require that protocol negotiation take place between the two systems. In addition to any protocol code changes, the Microsoft Open Specification program requires that the formal protocol specification for a protocol be updated in a timely manner. An example of a MS protocol specification document (MS-PSRP) can be found at: https://msdn.microsoft.com/library/mt242417.aspx + +## Bucket 2: Reasonable Grey Area + +Change of behavior that customers would have reasonably depended on. + +Examples: + ++ Change in timing/order of events (even when not specified in docs) + + Example: PowerShell events are handled by interleaving their execution with the execution of the main pipeline thread. Where and when this interleaving occurs might change. This order of execution is not specified but is deterministic so changing it might break some scripts. ++ Change in parsing of input and throwing new errors (even if parsing behavior is not specified in the docs) + + Example: a script may be using a JSON parser that is forgiving to minor syntactic errors in the JSON text. Changing that parser to be more rigorous in its processing would result in errors being thrown when no error was generated in the past thus breaking scripts. + +Judiciously making changes in these type of features require judgement: how predictable, obvious, consistent was the behavior? +In general, a significant external preview of the change would need to be done also possibly requiring an RFC to be created to allow for community input on the proposal. + +## Bucket 3: Unlikely Grey Area + +Change of behavior that customers could have depended on, but probably wouldn't. + +Examples: + ++ correcting behavior in a subtle corner case that has no obvious utility. + + + Example: the existing behavior of the PowerShell cd called without arguments is to do nothing. Changing this behavior to be consistent with UNIX shells which typically set the CWD to the user’s home directory + + + Example: changes to formatting for an object type. We have always considered the output formatting of an object to be a user experience issue and thus open for change. Since PowerShell pipes objects not text, changes to the way an object is rendered to text is generally considered to be allowed. + +As with type 2 changes, these require judgement: what is reasonable and what’s not? + +## Bucket 4: Clearly Non-Public + +Changes to surface area or behavior that is clearly internal or non-breaking in theory, but breaks an app. + +Examples: + ++ Changes to internal APIs that break private reflection. ++ Changes to APIs in the `System.Management.Automation.Internal` namespace (even if they are public, they are still considered internal and subject to change). ++ Renaming a parameter set (see related discussion [here](https://github.com/PowerShell/PowerShell/issues/10058)). + +It is impossible to evolve a code base without making such changes, so we don't require up-front approval for these, but we will sometimes have to go back and +revisit such change if there's too much pain inflicted on the ecosystem through a popular app or library. + +## What This Means for Contributors + ++ All bucket 1, 2, and 3 breaking changes require contacting team at @powershell/powershell. ++ If you're not sure into which bucket a given change falls, contact us as well. ++ It doesn't matter if the existing behavior is "wrong", we still need to think through the implications. PowerShell has been in broad use for over 10 years so we be must be extremely sensitive to breaking existing users and scripts. ++ If a change is deemed too breaking, we can help identify alternatives such as introducing a new API or cmdlet and obsoleting the old one. + +Request for clarifications or suggested alterations to this document should be done by opening issues against this document. diff --git a/PowerShell-master/docs/dev-process/coding-guidelines.md b/PowerShell-master/docs/dev-process/coding-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..ef0f671c1a0092eabbebcdcc2936109047a75ff3 --- /dev/null +++ b/PowerShell-master/docs/dev-process/coding-guidelines.md @@ -0,0 +1,233 @@ +# C# Coding Guidelines + +## Coding Conventions + +As a general rule, our coding convention is to follow the style of the surrounding code. +So if a file happens to differ in style from conventions defined here +(e.g. private members are named `m_member` rather than `_member`), +the existing style in that file takes precedence. + +When making changes, you may find some existing code goes against the conventions defined here. +In such cases, please avoid reformatting any existing code when submitting a PR as it obscures the functional changes of the PR. +A separate PR should be submitted for style-only changes. +We also run the [.NET code formatter tool](https://github.com/dotnet/codeformatter) regularly to keep consistent formatting. + +### Naming Conventions + +* Use meaningful, descriptive words for names. + For method names, it's encouraged to use `VerbObject` pair such as **`LoadModule`**. + +* Use `_camelCase` to name internal and private fields and use `readonly` where possible. + Prefix instance fields with `_`, static fields with `s_` and thread static fields with `t_`. + When used on static fields, `readonly` should come after `static` (i.e. `static readonly` not `readonly static`). + +* Use `camelCase` to name non-constant local variables. + +* Use `PascalCase` to name constant local variables and fields. + The only exception is for interop code where the constant should exactly match the name and value of the code you are calling via interop (e.g. `const int ERROR_SUCCESS = 0`). + +* Use `PascalCase` to name types and all other type members. + +### Layout Conventions + +* Use four spaces of indentation (no tabs). + +* Avoid more than one blank empty line at any time. + +* Avoid trailing spaces at the end of a line. + +* Braces usually go on their own lines, + with the exception of single line statements that are properly indented. + +* Namespace imports should be specified at the top of the file, + outside of `namespace` declarations. + +* Fields should be specified at the top within type declarations. + For those that serve as backing fields for properties, + they should be specified next to the corresponding properties. + +* Preprocessor directives like `#if` and `#endif` should be placed at the beginning of a line, + without any leading spaces. + +* File encoding should be `ASCII`. + All `BOM` encodings should be avoided. + Tests that need a `BOM` encoding file should generate the file on the fly. + +### Member Conventions + +* Use of `this` is neither encouraged nor discouraged. + +* Use `nameof()` instead of `""` whenever possible and relevant. + The motivation is to easily and more accurately find references. + +* Always specify the visibility, even if it's the default (i.e. `private string _foo` not `string _foo`). + Visibility should be the first modifier (i.e. `public abstract` not `abstract public`). + +* Make members private where possible. + Avoid declaring public members unless it's absolutely necessary. + +* Public members in a namespace that ends with `Internal`, + for example `System.Management.Automation.Internal` are not considered a supported public API. + Such members are necessarily public as implementation details in code shared between C# and PowerShell script, + or must be available publicly by generated code. + +### Commenting Conventions + +* Place the comment on a separate line, not at the end of a line of code. + +* Begin comment text with an uppercase letter. + It's recommended to end comment text with a period but not required. + +* Add comments where the code is not trivial or could be confusing. + +* Add comments where a reviewer needs help to understand the code. + +* Update/remove existing comments when you are changing the corresponding code. + +* Make sure the added/updated comments are meaningful, accurate and easy to understand. + +### Documentation comments + +* Create documentation using [XML documentation comments](https://learn.microsoft.com/dotnet/csharp/language-reference/xmldoc/) so that Visual Studio and other IDEs can use IntelliSense to show quick information about types or members. + +* Publicly visible types and their members must be documented. + Internal and private members may use doc comments but it is not required. + +* Documentation text should be written using complete sentences ending with full stops. + +## Performance Considerations + +PowerShell has a lot of performance sensitive code as well as a lot of inefficient code. +We have some guidelines that we typically apply widely even in less important code because code and patterns are copied, +and we want certain inefficient code to stay out of the performance critical code. + +Some general guidelines: + +* Avoid LINQ - it can create lots of avoidable garbage. + Instead, iterate through a collection directly using `for` or `foreach` loop. + +* Between `for` and `foreach`, + `for` is slightly preferred when you're uncertain if `foreach` allocates an iterator. + +* Avoid `params` arrays, prefer adding overloads with 1, 2, 3, and maybe more parameters. + +* Be aware of APIs such as `String.Split(params char[])` that do not provide overloads to avoid array allocation. + When calling such APIs, reuse a static array when possible (e.g. `Utils.Separators.Colon`). + +* Avoid using string interpolations and overloads with implicit parameters such as `Culture` and `StringComparison`. + Instead, use overloads with more explicit parameters such as `String.Format(IFormatProvider, String, Object[])` and `Equals(String, String, StringComparison)`. + +* Avoid unnecessary memory allocation in a loop. + Move the memory allocation outside the loop if possible. + +* Avoid gratuitous exceptions as much as possible. + Exception handling can be expensive due to cache misses and page faults when accessing the handling code and data. + Finding and designing away exception-heavy code can result in a decent performance win. + For example, you should stay away from things like using exceptions for control flow. + +* Avoid `if (obj is Example) { example = (Example)obj }` when casting an object to a type. + Instead, use `var example = obj as Example` or the C# 7 syntax `if (obj is Example example) {...}` as appropriate. + In this way you can avoid converting to the type twice. + +* Use generic collections instead of the non-generic ones such as `ArrayList` and `Hashtable` to avoid type casting and unnecessary boxing whenever possible. + +* Use collection constructor overloads that take an initial capacity for collection types that have them. + Internally, `List`, `Dictionary`, + and the other generic collections use one or more arrays to hold valid data. + Whenever resizing is needed, + one or more new arrays double the size of existing arrays are created and items from the existing arrays are copied. + Setting an approximate initial capacity will reduce the number of resizing operations. + +* Use `dict.TryGetValue` instead of `dict.Contains` and `dict[..]` when retrieving value from a `Dictionary`. + In this way you can avoid hashing the key twice. + +* It's OK to use the `+` operator to concatenate one-off short strings. + But when dealing with strings in loops or large amounts of text, + use a `StringBuilder` object. + +## Security Considerations + +Security is an important aspect of PowerShell and we need to be very careful about changes that may introduce security risks, +such as code injection caused by the lack of input validation, +privilege escalation due to the misuse of impersonation, +or data privacy breach with a plain text password. + +Reviewers of a PR should be sensitive to changes that may affect security. +Some security related keywords may serve as good indicators, +such as `password`, `crypto`, `encryption`, `decryption`, `certificate`, `authenticate`, `ssl/tls` and `protected data`. + +When facing a PR with such changes, +the reviewers should request a designated security Subject Matter Expert (SME) to review the PR. +Currently, [@PaulHigin](https://github.com/PaulHigin) and [@TravisEz13](https://github.com/TravisEz13) are our security SMEs. +See [CODEOWNERS](../../.github/CODEOWNERS) for more information about the area experts. + +## Best Practices + +* Avoid hard-coding anything unless it's absolutely necessary. + +* Avoid a method that is too long and complex. + In such case, separate it to multiple methods or even a nested class as you see fit. + +* Use the `using` statement instead of `try/finally` if the only code in the `finally` block is to call the `Dispose` method. + +* Use of object initializers (e.g. `new Example { Name = "Name", ID = 1 }`) is encouraged for better readability, + but not required. + +* Stick to the `DRY` principle -- Don't Repeat Yourself. + * Wrap the commonly used code in methods, + or even put it in a utility class if that makes sense, + so that the same code can be reused (e.g. `StringToBase64Converter.Base64ToString(string)`). + * Check if the code for the same purpose already exists in the code base before inventing your own wheel. + * Avoid repeating literal strings in code. Instead, use `const` variable to hold the string. + * Resource strings used for errors or UI should be put in resource files (`.resx`) so that they can be localized later. + +* Use of new C# language syntax is encouraged. + But avoid refactoring any existing code using new language syntax when submitting a PR + as it obscures the functional changes of the PR. + A separate PR should be submitted for such refactoring without any functional changes. + +* Consider using the `Interlocked` class instead of the `lock` statement to atomically change simple states. The `Interlocked` class provides better performance for updates that must be atomic. + +* Here are some useful links for your reference: + * [Framework Design Guidelines](https://learn.microsoft.com/dotnet/standard/design-guidelines/index) - Naming, Design and Usage guidelines including: + * [Arrays](https://learn.microsoft.com/dotnet/standard/design-guidelines/arrays) + * [Collections](https://learn.microsoft.com/dotnet/standard/design-guidelines/guidelines-for-collections) + * [Exceptions](https://learn.microsoft.com/dotnet/standard/design-guidelines/exceptions) + * [Best Practices for Developing World-Ready Applications](https://learn.microsoft.com/dotnet/core/extensions/best-practices-for-developing-world-ready-apps) - Unicode, Culture, Encoding and Localization. + * [Best Practices for Exceptions](https://learn.microsoft.com/dotnet/standard/exceptions/best-practices-for-exceptions) + * [Best Practices for Using Strings in .NET](https://learn.microsoft.com/dotnet/standard/base-types/best-practices-strings) + * [Best Practices for Regular Expressions in .NET](https://learn.microsoft.com/dotnet/standard/base-types/best-practices) + * [Serialization Guidelines](https://learn.microsoft.com/dotnet/standard/serialization/serialization-guidelines) + * [Managed Threading Best Practices](https://learn.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) + +## Portable Code + +There are 3 primary preprocessor macros we use during builds: + +* `DEBUG` - guard code that should not be included in release builds +* `CORECLR` - guard code that differs between Full CLR and CoreCLR +* `UNIX` - guard code that is specific to Unix (Linux and macOS) + +Any other preprocessor defines found in the source are used for one-off custom builds, +typically to help debug specific scenarios. + +Here are some general guidelines for writing portable code: + +* We are in the process of cleaning up Full CLR specific code (code enclosed in `!CORECLR`), + so do not use `CORECLR` or `!CORECLR` in new code. + PowerShell Core targets .NET Core only and all new changes should support .NET Core only. + +* The PowerShell code base started on Windows and depends on many Win32 APIs through P/Invoke. + Going forward, we try to depend on .NET Core to handle platform differences, + so avoid adding new P/Invoke calls where a suitable alternative exists in .NET Core. + +* Try to minimize the use of `#if UNIX`. + When absolutely necessary, avoid duplicating more code than necessary, + and instead prefer introducing helper functions to minimize the platform differences. + +* When adding platform dependent code (`Windows` vs. `UNIX`), prefer preprocessor directives over runtime checks. + However, runtime checks are acceptable if it would greatly improve readability + without causing performance concerns in performance-sensitive code. + +* We produce a single binary for all UNIX variants, + so runtime checks are currently necessary for some of them (e.g. macOS vs. Linux). diff --git a/PowerShell-master/docs/dev-process/resx-files.md b/PowerShell-master/docs/dev-process/resx-files.md new file mode 100644 index 0000000000000000000000000000000000000000..ec9eace54fe4ec8cde9d385c5fb33e586a2585e2 --- /dev/null +++ b/PowerShell-master/docs/dev-process/resx-files.md @@ -0,0 +1,40 @@ +# Resources + +Resources are `.resx` files with string values that we use for error messages and such. +They live in `src\\resources` folders. + +At the moment `dotnet cli` doesn't support generating C# bindings (strongly typed resource files). + +We are using our own `Start-ResGen` to generate them. + +Usually it's called as part of the regular build with + +```powershell +Start-PSBuild -ResGen +``` + +If you see compilation errors related to resources, try to call `Start-ResGen` explicitly. + +```powershell +Start-ResGen +``` + +## Editing `.resx` files + +**Don't edit** `.resx` files from Visual Studio. +It will try to create `.cs` files for you and you will get whole bunch of hard-to-understand errors. + +To edit a resource file, use any **plain text editor**. +A resource file is a simple XML file, and it's easy to edit. + +## Convert `.txt` resource files into `.resx` files + +`dotnet cli` doesn't support embedding old-fashioned `.txt` resource. +You can do a one-time conversion of `.txt` resources into `.resx` files with a helper function: + +```powershell +# example, converting all .txt resources under src\Microsoft.WSMan.Management\resources +Convert-TxtResourceToXml -Path src\Microsoft.WSMan.Management\resources +``` + +`.resx` files would be placed next to `.txt` files. diff --git a/PowerShell-master/docs/git/README.md b/PowerShell-master/docs/git/README.md new file mode 100644 index 0000000000000000000000000000000000000000..46b5eee4c62aedfd81f4d96ad151882caebcca03 --- /dev/null +++ b/PowerShell-master/docs/git/README.md @@ -0,0 +1,102 @@ +# Working with PowerShell repository + +## Get the code for the first time + +```sh +git clone https://github.com/PowerShell/PowerShell.git --branch=master +``` + +## Branches + +* Don't commit your changes directly to master. + It will make the collaborative workflow messy. +* Checkout a new local branch from `master` for every change you want to make (bugfix, feature). +* Use lowercase-with-dashes for naming. +* Follow [Linus' recommendations][Linus] about history. + * "People can (and probably should) rebase their _private_ trees (their own work). That's a _cleanup_. But never other peoples code. That's a 'destroy history'... + You must never EVER destroy other peoples history. You must not rebase commits other people did. + Basically, if it doesn't have your sign-off on it, it's off limits: you can't rebase it, because it's not yours." + +### Understand branches + +* **master** is the branch with the latest and greatest changes. + It could be unstable. +* Send your pull requests to **master**. + +### Sync your local repository + +Use **git rebase** instead of **git merge** and **git pull**, when you're updating your feature-branch. + +```sh +# fetch updates all remote branch references in the repository +# --all : tells it to do it for all remotes (handy, when you use your fork) +# -p : tells it to remove obsolete remote branch references (when they are removed from remote) +git fetch --all -p + +# rebase on origin/master will rewrite your branch history +git rebase origin/master +``` + +### More complex scenarios + +Covering all possible git scenarios is behind the scope of the current document. +Git has excellent documentation and lots of materials available online. + +We are leaving a few links here: + +[Linus]:https://web.archive.org/web/20230522041845/https://wincent.com/wiki/git_rebase%3A_you're_doing_it_wrong + +## Tags + +If you are looking for the source code for a particular release, +you will find it via **tags**. + +* `git tag` will show you list of all tags. +* Find the tag that corresponds to the release. +* Use `git checkout ` to get this version. + +**Note:** [checking out a tag][tag] will move the repository to a [DETACHED HEAD][HEAD] state. + +[tag]:https://git-scm.com/book/en/v2/Git-Basics-Tagging#Checking-out-Tags +[HEAD]:https://www.git-tower.com/learn/git/faq/detached-head-when-checkout-commit + +If you want to make changes, based on tag's version (i.e. a hotfix), +checkout a new branch from this DETACHED HEAD state. + +```sh +git checkout -b vors/hotfix +``` + +## Recommended Git configurations + +We highly recommend these configurations to help deal with whitespace, +rebasing, and general use of Git. + +> Auto-corrects your command when it's sure (`stats` to `status`) + +```sh +git config --global help.autoCorrect -1 +``` + +> Refuses to merge when pulling, and only pushes to branch with same name. + +```sh +git config --global pull.ff only +git config --global push.default current +``` + +> Shows shorter commit hashes and always shows reference names in the log. + +```sh +git config --global log.abbrevCommit true +git config --global log.decorate short +``` + +> Ignores whitespace changes and uses more information when merging. + +```sh +git config --global apply.ignoreWhitespace change +git config --global rerere.enabled true +git config --global rerere.autoUpdate true +git config --global am.threeWay true +``` diff --git a/PowerShell-master/docs/git/basics.md b/PowerShell-master/docs/git/basics.md new file mode 100644 index 0000000000000000000000000000000000000000..aa7629cf746070c59317b99e3311de8da902a5ea --- /dev/null +++ b/PowerShell-master/docs/git/basics.md @@ -0,0 +1,77 @@ +# Getting started with Git + +We are using Git version 2.9.0, but any recent version should be good. +It's recommended to learn the `git` command-line tool for full +cross-platform experience and a deeper understanding of Git itself. + +## Install + +### Windows + +Install [Git for Windows][]. + +During the installation process, choose these recommended settings: + +* Use Git from the Windows Command Prompt +* Use OpenSSH +* Checkout Windows-style, commit Unix-style line endings +* Use Windows' default console window +* Enable file system caching + +[Git for Windows]: https://git-scm.com/download/win + +### Linux + +Install by using the package manager on your system. +A list of all the package managers and commands can be found [here][linux-git-dl]. + +### Interactive tutorials + +There are (too) many Git tutorials on the internet. Here we post +references to our favorites. + +#### Hello World + +If you're new to Git, learn the following commands: `checkout`, `branch`, +`pull`, `push`, `merge`. + +Use GitHub's [Hello World][] to learn how to create a feature branch, commit +changes, and issue a pull request. + +[Hello World]: https://guides.github.com/activities/hello-world/ + +#### Githug + +[Githug](https://github.com/Gazler/githug) is a great gamified way to +learn Git in couple hours. After finishing 50+ real-world scenarios +you will have a pretty good idea about what and when you can do with +Git. + +## Authentication + +### Windows + +On Windows, the best way to use Git securely is [Git Credential Manager for Windows][manager]. +It's included in the official Git installer for Windows. + +#### Linux and macOS + +If you do not have a preferred method of authentication, enable the storage +credential helper, which will cache your credentials in plaintext on your +system, so use a [token][]. + +```sh +git config --global credential.helper store +``` + +Alternatively, you can use [SSH key][]. +In this case, you may want to use git-ssh even for HTTPS Git URLs. + +```none +git config --global url.git@github.com:.insteadOf https://github.com/ +``` + +[SSH key]: https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/#generating-a-new-ssh-key +[token]: https://help.github.com/articles/creating-an-access-token-for-command-line-use/ +[manager]: https://github.com/Microsoft/Git-Credential-Manager-for-Windows +[linux-git-dl]: https://git-scm.com/download/linux diff --git a/PowerShell-master/docs/host-powershell/README.md b/PowerShell-master/docs/host-powershell/README.md new file mode 100644 index 0000000000000000000000000000000000000000..174f986dfa4717f6c16c210210e49d40ea8128af --- /dev/null +++ b/PowerShell-master/docs/host-powershell/README.md @@ -0,0 +1,47 @@ +# Host PowerShell Core in .NET Core Applications + +## PowerShell Core v6.0.1 and Later + +The runtime assemblies for Windows, Linux and OSX are now published in NuGet package version 6.*. + +Please see the [.NET Core Sample Application](#net-core-sample-application) section for an example that uses PowerShell Core NuGet packages. + +## .NET Core Sample Application + +Note: The .NET Core `2.1` runtime and .NET Core SDK `2.1` or higher is required for the examples below: + +- [sample](./sample) + +You can find the sample application project `MyApp` in each of the above 2 sample folders. You can quickly test-run it using `dotnet run`. +To build the sample project properly for distribution, run the following command (make sure the required .NET Core SDK is in use): + +```powershell +dotnet publish .\MyApp --configuration release +``` + +This builds it for the runtimes specified by the `RuntimeIdentifiers` property in the `.csproj` file. +Then you can run the `MyApp` binary from the publish folder and see the results: + +```none +PS:> .\MyApp.exe + +Evaluating 'Get-Command Write-Output' in PS Core Runspace + +Write-Output + +Evaluating '([S.M.A.ActionPreference], [S.M.A.AliasAttribute]).FullName' in PS Core Runspace + +System.Management.Automation.ActionPreference +System.Management.Automation.AliasAttribute +``` + +## Special Hosting Scenario For Native Host + +There is a special hosting scenario for native hosts, +where Trusted Platform Assemblies (TPA) do not include PowerShell assemblies, +such as the in-box `powershell.exe` in Nano Server and the Azure DSC host. + +For such hosting scenarios, the native host needs to bootstrap by calling [`PowerShellAssemblyLoadContextInitializer.SetPowerShellAssemblyLoadContext`](https://learn.microsoft.com/dotnet/api/system.management.automation.powershellassemblyloadcontextinitializer.setpowershellassemblyloadcontext). +When using this API, the native host can pass in the path to the directory that contains PowerShell assemblies. +A handler will then be registered to the [`Resolving`](https://github.com/dotnet/corefx/blob/d6678e9653defe3cdfff26b2ff62135b6b22c77f/src/System.Runtime.Loader/ref/System.Runtime.Loader.cs#L38) +event of the default load context to deal with the loading of assemblies from that directory. diff --git a/PowerShell-master/docs/host-powershell/sample/MyApp/MyApp.csproj b/PowerShell-master/docs/host-powershell/sample/MyApp/MyApp.csproj new file mode 100644 index 0000000000000000000000000000000000000000..ab507b5acfcfe6f13ffd3c12ef8bf5f45c99d697 --- /dev/null +++ b/PowerShell-master/docs/host-powershell/sample/MyApp/MyApp.csproj @@ -0,0 +1,16 @@ + + + + netcoreapp2.1 + MyApp + Exe + win10-x64;linux-x64;osx-x64 + + + + + + + + + diff --git a/PowerShell-master/docs/host-powershell/sample/MyApp/Program.cs b/PowerShell-master/docs/host-powershell/sample/MyApp/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..fc54fa2d7098e727c2a1c74239f892158eb4b1da --- /dev/null +++ b/PowerShell-master/docs/host-powershell/sample/MyApp/Program.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Application.Test +{ + public class Program + { + /// + /// Managed entry point shim, which starts the actual program. + /// + public static int Main(string[] args) + { + using (PowerShell ps = PowerShell.Create()) + { + Console.WriteLine("\nEvaluating 'Get-Command Write-Output' in PS Core Runspace\n"); + var results = ps.AddScript("Get-Command Write-Output").Invoke(); + Console.WriteLine(results[0].ToString()); + + ps.Commands.Clear(); + + Console.WriteLine("\nEvaluating '([S.M.A.ActionPreference], [S.M.A.AliasAttribute]).FullName' in PS Core Runspace\n"); + results = ps.AddScript("([System.Management.Automation.ActionPreference], [System.Management.Automation.AliasAttribute]).FullName").Invoke(); + foreach (dynamic result in results) + { + Console.WriteLine(result.ToString()); + } + } + + return 0; + } + } +} diff --git a/PowerShell-master/docs/host-powershell/sample/NuGet.config.md b/PowerShell-master/docs/host-powershell/sample/NuGet.config.md new file mode 100644 index 0000000000000000000000000000000000000000..bf2b4c3f6887db7fe721e17463121d8e829b8348 --- /dev/null +++ b/PowerShell-master/docs/host-powershell/sample/NuGet.config.md @@ -0,0 +1,16 @@ +# Nuget.config creation + +Create a filed called `nuget.config` at this location with this content: + +```xml + + + + + + + + + + +``` diff --git a/PowerShell-master/docs/maintainers/Images/merge-commit-confirm.png b/PowerShell-master/docs/maintainers/Images/merge-commit-confirm.png new file mode 100644 index 0000000000000000000000000000000000000000..2dc450cf71f5fb40aa5681a484bec9f293338413 Binary files /dev/null and b/PowerShell-master/docs/maintainers/Images/merge-commit-confirm.png differ diff --git a/PowerShell-master/docs/maintainers/Images/merge-commit.png b/PowerShell-master/docs/maintainers/Images/merge-commit.png new file mode 100644 index 0000000000000000000000000000000000000000..18b3b4548a5b3427a9f4b0a035fb40df5b6e161e Binary files /dev/null and b/PowerShell-master/docs/maintainers/Images/merge-commit.png differ diff --git a/PowerShell-master/docs/maintainers/Images/squash-confirm.png b/PowerShell-master/docs/maintainers/Images/squash-confirm.png new file mode 100644 index 0000000000000000000000000000000000000000..e92ad4739c6fb2671e5d62235b50a5fa2fe79f6e Binary files /dev/null and b/PowerShell-master/docs/maintainers/Images/squash-confirm.png differ diff --git a/PowerShell-master/docs/maintainers/Images/squash-merge.png b/PowerShell-master/docs/maintainers/Images/squash-merge.png new file mode 100644 index 0000000000000000000000000000000000000000..1df47f010d87f41f26d3ebe30ff04caab0372e44 Binary files /dev/null and b/PowerShell-master/docs/maintainers/Images/squash-merge.png differ diff --git a/PowerShell-master/docs/maintainers/README.md b/PowerShell-master/docs/maintainers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ebba4b022582fe1d62b1e8ea70f6f57a89ddf46e --- /dev/null +++ b/PowerShell-master/docs/maintainers/README.md @@ -0,0 +1,106 @@ +# Repository Maintainers + +Repository Maintainers are trusted stewards of the PowerShell repository responsible for maintaining consistency and quality of PowerShell code. +One of their primary responsibilities is merging pull requests after all requirements have been fulfilled. + +They have [write access](https://docs.github.com/en/free-pro-team@latest/github/setting-up-and-managing-organizations-and-teams/repository-permission-levels-for-an-organization) to the PowerShell repositories which gives them the power to: + +1. `git push` to the official PowerShell repository +1. Merge [pull requests](https://docs.github.com/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) +1. Assign labels, milestones, and people to [issues](https://guides.github.com/features/issues/) and [pull requests](https://docs.github.com/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) + +## Table of Contents + +- [Current Repository Maintainers](#current-repository-maintainers) +- [Repository Maintainer Responsibilities](#repository-maintainer-responsibilities) +- [Issue Management Process](#issue-management-process) +- [Pull Request Workflow](#pull-request-workflow) +- [Becoming a Repository Maintainer](#becoming-a-repository-maintainer) + +## Current Repository Maintainers + + + +- Aditya Patwardhan ([adityapatwardhan](https://github.com/adityapatwardhan)) +- Andrew Menagarishvili ([anmenaga](https://github.com/anmenaga)) +- Dongbo Wang ([daxian-dbw](https://github.com/daxian-dbw)) +- Ilya Sazonov ([iSazonov](https://github.com/iSazonov)) +- Robert Holt ([rjmholt](https://github.com/rjmholt)) +- Travis Plunk ([TravisEz13](https://github.com/TravisEz13)) + +## Former Repository Maintainers + + + +- Andy Jordan ([andyleejordan](https://github.com/andyleejordan)) +- Jason Shirk ([lzybkr](https://github.com/lzybkr)) +- Mike Richmond ([mirichmo](https://github.com/mirichmo)) +- Sergei Vorobev ([vors](https://github.com/vors)) + +## Repository Maintainer Responsibilities + +Repository Maintainers enable rapid contributions while maintaining a high level of quality in PowerShell by ensuring that all development processes are being followed correctly. + +If you are a Repository Maintainer, you: + +1. **MUST** abide by the [Code of Conduct](../../CODE_OF_CONDUCT.md) and report suspected violations to the [PowerShell Committee][ps-committee] +1. **MUST** ensure that each contributor has signed a valid Microsoft Contributor License Agreement (CLA) +1. **MUST** verify compliance with any third party code license terms (e.g., requiring attribution, etc.) if the contribution contains third party code. +1. **MUST** make sure that [any change requiring approval from the PowerShell Committee](../community/governance.md#changes-that-require-an-rfc) has gone through the proper [RFC][RFC-repo] or approval process +1. **MUST** validate that code reviews have been conducted before merging a pull request when no code is written +1. **MUST** validate that tests and documentation have been written before merging a pull request that contains new functionality +1. **SHOULD** add [the correct labels][issue-management] to issues and pull requests +1. **SHOULD** make sure the correct [Area Experts](../community/governance.md#area-experts) are assigned to relevant pull requests and issues. + This includes adding extra reviewers when it makes sense + (e.g. a pull request that adds remoting capabilities might require a security expert) +1. **SHOULD** validate that the names and email addresses in the git commits reasonably match identity of the person submitting the pull request +1. **SHOULD** make sure contributors are following the [contributor guidelines][CONTRIBUTING] +1. **SHOULD** ask people to resend a pull request, if it [doesn't target `master`](../../.github/CONTRIBUTING.md#lifecycle-of-a-pull-request) +1. **SHOULD** wait for the [CI system][ci-system] build to pass for pull requests + (unless, for instance, the pull request is being submitted to fix broken CI) +1. **SHOULD** encourage contributors to refer to issues in their pull request description (e.g. `Resolves issue #123`). + If a user did not create an issue prior to submitting their pull request, their pull request should not be rejected. + However, they should be reminded to create an issue in the future to frontload any potential problems with the work and to minimize duplication of efforts. +1. **SHOULD** encourage contributors to create meaningful titles for all PRs. + Edit the title if necessary to provide clarity on the problem +1. **SHOULD** encourage contributors to write meaningful, descriptive git commits +1. **SHOULD NOT** merge pull requests with a failed CI build + (unless, for instance, the pull request is being submitted to fix broken CI) +1. **SHOULD NOT** merge pull requests without the status check passing from the Microsoft CLA bot + (unless the CLA bot is broken, and CLA signing can be confirmed through other means) +1. **SHOULD NOT** merge pull requests too quickly after they're submitted. + Even if the pull request meets all the requirements, people should have time to give their input + (unless the pull request is particularly urgent for some reason) +1. **SHOULD NOT** merge your own pull requests. + If a Repository Maintainer opens a pull request, another Maintainer should merge it unless there are extreme, short-term circumstances requiring a merge or another Maintainer has given explicit sign-off without merging + +## Issue Management Process + +Please see [Issue Management][issue-management] + +## Pull Request Workflow + +Please see [Contributing][CONTRIBUTING] + +## Maintainer Best Practices + +Please see [Best Practices][best-practice] + +## Becoming a Repository Maintainer + +Repository Maintainers currently consist mostly of Microsoft employees. +It is expected that over time, regular trusted contributors to the PowerShell repository will be made Repository Maintainers. +Eligibility is heavily dependent on the level of contribution and expertise: individuals who contribute consistently in meaningful ways to the project will be recognized accordingly. + +At any point in time, the existing Repository Maintainers can unanimously nominate a strong community member to become a Repository Maintainer. +Nominations are brought to the PowerShell Committee to understand the reasons and justification. +A simple majority of the PowerShell Committee is required to veto the nomination. +When a nominee has been approved, a PR will be submitted by a current Maintainer to update this document to add the nominee's name to +the [Current Repository Maintainers](#current-repository-maintainers) with justification as the description of the PR to serve as the public announcement. + +[RFC-repo]: https://github.com/PowerShell/PowerShell-RFC +[ci-system]: ../testing-guidelines/testing-guidelines.md#ci-system +[issue-management]: issue-management.md +[CONTRIBUTING]: ../../.github/CONTRIBUTING.md +[best-practice]: best-practice.md +[ps-committee]: ../community/governance.md#powershell-committee diff --git a/PowerShell-master/docs/maintainers/best-practice.md b/PowerShell-master/docs/maintainers/best-practice.md new file mode 100644 index 0000000000000000000000000000000000000000..2496e1ae42ba3a4ee09b0be63e1d4a026567bd34 --- /dev/null +++ b/PowerShell-master/docs/maintainers/best-practice.md @@ -0,0 +1,50 @@ +# Maintainer Best Practices + +## PR Types + +- Feature-work PR: A PR that implements an RFC, which usually involves relatively large set of changes. +- Regular PR: A bug fix or an enhancement change that are not backed by an RFC. + +## Review PRs + +- Ask the author to reword the PR title based on guidelines in [Contributing](../../.github/CONTRIBUTING.md). +- Ask the author to apply `[feature]` tag to trigger full test builds if it's necessary. +- Label the PR with `Breaking-Change`, `Documentation Needed` and `Area-XXX` as appropriate. +- When labelling a PR with `Review-Committee`, leave a detailed comment to summarize the issue you want the committee to look into. + It's recommended to include examples to explain/demonstrate behaviors. + +## Merge PRs + +- Use `Squash and merge` by default to keep clean commit history in Master branch. + + ![Squash Merge Example](./Images/squash-merge.png)    ![Squash Confirm Example](./Images/squash-confirm.png) + +- Use `Create a merge commit` for feature-work PRs **only if** the commit history of the PR is reasonably clean. + After using this option, GitHub will make it your default option for merging a PR. + Do remember to change the default back to `Squash and merge` as it will be useful next time. + + ![Merge Commit Example](./Images/merge-commit.png)    ![Merge Confirm Example](./Images/merge-commit-confirm.png) + +- Avoid `Rebase and merge` unless you have a strong argument for using it. + +- Before clicking `Confirm squash and merge` or `Confirm merge`, + make sure you run through the following steps: + + 1. The commit title should be a short summary of the PR. + + - When merging with the `Squash and merge` option, + the PR title will be used as the commit title by default. + **Reword the title as needed** to make sure it makes sense (can be used without change in `CHANGELOG.md`). + + - When merging with the `Create a merge commit` option, + the default commit title would be `Merge pull request XXX from YYY`. + **Replace it with a short summary of the PR**, and add the PR number to the end, like `(#1234)`. + + 1. The optional extended description is required for feature-work PRs, or regular PRs with breaking changes. + For other PRs, it's not required but good to have based on the judgement of the maintainer. + + - If a PR introduces breaking changes from the previous stable release, + make sure you put the tag `[breaking change]` at the first line of the extended description, + and start the description text from the second line. + + 1. Use the present tense and imperative mood for both the commit title and description. diff --git a/PowerShell-master/docs/maintainers/issue-management.md b/PowerShell-master/docs/maintainers/issue-management.md new file mode 100644 index 0000000000000000000000000000000000000000..0cc8eb00e374d43e272fa3401c73d8bb2bcbf8e7 --- /dev/null +++ b/PowerShell-master/docs/maintainers/issue-management.md @@ -0,0 +1,110 @@ +# Issue Management + +## Security Vulnerabilities + +If you believe that there is a security vulnerability in PowerShell, +first follow the [vulnerability issue reporting policy](../../.github/SECURITY.md) before submitting an issue. + +## Long-living issue labels + +Issue labels for PowerShell/PowerShell can be found [here](https://github.com/powershell/powershell/labels). + +### Issue and PR Labels + +Issues are opened for many different reasons. +We use the following labels for issue classifications: + +* `Issue-Announcement`: the issue is for discussing an [Announcement](https://github.com/PowerShell/Announcements) +* `Issue-Bug`: the issue is reporting a bug +* `Issue-Code Cleanup`: the issue is for cleaning up the code with no impact on functionality +* `Issue-Discussion`: the issue may not have a clear classification yet. + The issue may generate an [RFC][ln-rfc] or may be reclassified as a bug or enhancement. +* `Issue-Enhancement`: the issue is more of a feature request than a bug. +* `Issue-Meta`: an issue used to track multiple issues. +* `Issue-Question`: ideally support can be provided via other mechanisms, + but sometimes folks do open an issue to get a question answered and we will use this label for such issues. + +[ln-rfc]: https://github.com/PowerShell/PowerShell-RFC + +When an issue is resolved, the following labels are used to describe the resolution: + +* `Resolution-Answered`: the issue was an `Issue-Question` and was answered. +* `Resolution-By Design`: the issue is not considered a bug, the behavior is working as designed. +* `Resolution-Duplicate`: the issue is a duplicate - there must be a comment linking to another issue. +* `Resolution-External`: the issue cannot be address by this repo. Should be addressed externally. +* `Resolution-Fixed`: the issue has been fixed and should be referenced from a PR. +* `Resolution-Won't Fix`: the issue may be considered a bug or enhancement but won't be fixed. + If there is an inadequate explanation as to why the issue was closed, + anyone should feel free to reopen the issue. + +### Feature areas + +These labels describe what feature area of PowerShell that an issue affects. +Those labels denoted by `WG-*` are owned by a Working Group (WG) defined +[here](../community/working-group-definitions.md): + +* `Area-Maintainers-Build`: build issues +* `Area-Cmdlets-Core`: cmdlets in the Microsoft.PowerShell.Core module +* `Area-Cmdlets-Utility`: cmdlets in the Microsoft.PowerShell.Utility module +* `Area-Cmdlets-Management`: cmdlets in the Microsoft.PowerShell.Management module +* `Area-Documentation`: PowerShell *repo* documentation issues, general PowerShell doc issues go [here](https://github.com/PowerShell/PowerShell-Docs/issues) +* `Area-DSC`: DSC related issues +* `Area-PowerShellGet`: PowerShellGet related issues +* `Area-SideBySide`: side by side support +* `WG-DevEx-Portability`: anything related to authoring cross-platform or cross-architecture + modules, cmdlets, and scripts +* `WG-DevEx-SDK`: anything related to hosting PowerShell as a runtime, PowerShell's APIs, + PowerShell Standard, or the development of modules and cmdlets +* `WG-Engine`: core PowerShell engine, interpreter, and runtime +* `WG-Engine-Performance`: core PowerShell engine, interpreter, and runtime performance +* `WG-Engine-Providers`: built-in PowerShell providers such as FileSystem, Certificates, + Registry, etc. (or anything returned by `Get-PSProvider`) +* `WG-Interactive-Console`: the console experience +* `WG-Interactive-Debugging`: debugging PowerShell script +* `WG-Interactive-HelpSystem`: anything related to the help infrastructure and formatting of help +* `WG-Interactive-IntelliSense`: tab completion +* `WG-Interactive-PSReadline`: PSReadline related issues +* `WG-Language`: parser, language semantics +* `WG-Quality-Test`: issues in a test or in test infrastructure +* `WG-Remoting`: PSRP issues with any transport layer +* `WG-Security`: security related areas such as [JEA](https://github.com/powershell/JEA) + +### Operating Systems + +These are for issues that are specific to certain Operating Systems: + +* `OS-Linux` +* `OS-macOS` +* `OS-Windows` +* `OS-WSL`: Windows Subsystem for Linux + +### Process Tags + +The following labels are used on PRs: + +* `Review - Needed` : The PR is being reviewed. Please see [Pull Request - Code Review](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---code-review) +* `Review - Waiting on Author` : The PR was reviewed by the team and requires changes or comments from the author before being accepted. +* `Review - Abandoned` : The PR was not updated for a significant number of days (the exact number could vary over time). + Maintainers should look into such PRs and re-evaluate them. +* `Review - Committee` : The PR/Issue needs a review from [powershell-committee](../community/governance.md#powershell-committee) + +### Miscellaneous labels + +* `Blocked` : An issue cannot be addressed due to external factors, + but should not be closed because those external factors are temporary. +* `BVT/DRT` : An issue affecting or exposed by tests that have not been open sourced. +* `Changelog Needed` : The PR requires an addition to the changelog, + and should be removed when it has been added. +* `Committee-Reviewed` : The PR/Issue has been reviewed by the [powershell-committee](../community/governance.md#powershell-committee) +* `Compliance` : Issues with the compliance label are required to be fixed either in the long term or short term for + Microsoft to continue to sign and release packages from the project as official Microsoft packages. + The time frame in which it needs to be fixed should be identified in the issue. +* `Documentation Needed` : The PR has changes that require a documentation change or new documentation added to [PowerShell-Docs](https://github.com/powershell/powershell-docs) +* `First-Time-Issue` : An issue that is identified as being easy and a good candidate for first time contributors +* `Hackathon` or `Hacktoberfest` : An issue that would be a good candidate for hackathons such as `Hacktoberfest` or `Hackillinois` +* `Porting` : An issue that affects a feature not yet ported to other platforms. +* `Up-for-Grabs` : We've acknowledged the issue but have no immediate plans to address it. + If you're looking for a way to contribute, these issues can be a good place to start. +* `Usability` : This label is used to help us filter issues that might be higher priority + because they more directly affect the usability of a particular feature or area. +* `Waiting - DotNetCore` : An issue waiting on a fix/change in DotNetCore. diff --git a/PowerShell-master/docs/maintainers/releasing.md b/PowerShell-master/docs/maintainers/releasing.md new file mode 100644 index 0000000000000000000000000000000000000000..ccb4e5529d7b075e4fc094d0476a408d28f65a51 --- /dev/null +++ b/PowerShell-master/docs/maintainers/releasing.md @@ -0,0 +1,222 @@ +# PowerShell Core Releasing Process + +## Release Steps + +When creating a release milestone, you should send meeting invites to maintainers to book the release day and the previous day. +This is to make sure they have enough time to work on the release. + +The following release procedure should be started on the previous day of the target release day. +This is to make sure we have enough buffer time to publish the release on the target day. + +Before starting the following release procedure, open an issue and list all those steps as to-do tasks. +Check the task when you finish one. +This is to help track the release preparation work. + +> Note: Step 2, 3 and 4 can be done in parallel. + +1. Create a branch named `release-` in our private repository. + All release related changes should happen in this branch. +1. Prepare packages + - [Build release packages](#building-packages). + - Sign the MSI packages and DEB/RPM packages. + - Install and verify the packages. +1. Update documentation, scripts and Dockerfiles + - Summarize the changelog for the release. It should be reviewed by PM(s) to make it more user-friendly. + - Update [CHANGELOG.md](../../CHANGELOG.md) with the finalized changelog draft. + - Update other documents and scripts to use the new package names and links. +1. Verify the release Dockerfiles. +1. [Create NuGet packages](#nuget-packages) and publish them to [powershell-core feed][ps-core-feed]. +1. [Create the release tag](#release-tag) and push the tag to `PowerShell/PowerShell` repository. +1. Create the draft and publish the release in GitHub. +1. Merge the `release-` branch to `master` in `powershell/powershell` and delete the `release-` branch. +1. Publish Linux packages to Microsoft YUM/APT repositories. +1. [Update the homebrew formula](#homebrew) for the macOS package. + This task usually will be taken care of by the community, + so we can wait for one day or two and see if the homebrew formula has already been updated, + and only do the update if it hasn't. + +## Building Packages + +> Note: Linux and Windows packages are taken care of by our release build pipeline in VSTS, +while the macOS package needs to be built separately on a macOS. + +The release build should be started based on the `release` branch. +The release Git tag won't be created until all release preparation tasks are done, +so the to-be-used release tag should be passed to the release build as an argument. + +> When creating the packages, please ensure that the file path does not contain user names. +That is, clone to `/PowerShell` on Unix, and `C:\PowerShell` for Windows. +The debug symbols include the absolute path to the sources when built, +so it should appear `/PowerShell/src/powershell/System.Management.Automation`, +not `/home/username/src/PowerShell/...`. + +### Packaging Overview + +The `tools/packaging` module contains a `Start-PSPackage` function to build packages. +It **requires** that PowerShell Core has been built via `Start-PSBuild` from the `build.psm1` module. + +#### Windows + +`Start-PSPackage` supports creating ZIP and MSIX packages for Windows. +When called without `-Type` on Windows, it defaults to creating both ZIP and MSIX packages. +The packages *must* be published in release mode, +so make sure `-Configuration Release` is specified when running `Start-PSBuild`. + +Note that PowerShell is always self-contained, thus using it does not require installing it. +The output of `Start-PSBuild` includes a `pwsh.exe` executable which can simply be launched. + +#### Linux / macOS + +The `Start-PSPackage` function delegates to `New-UnixPackage`. + +For **Linux** (Debian-based distributions), it relies on the [Effing Package Management][fpm] project, +which makes building packages a breeze. + +For **macOS**, it uses native packaging tools (`pkgbuild` and `productbuild`) from Xcode Command Line Tools, +eliminating the need for Ruby or fpm. + +For **Linux** (Red Hat-based distributions), it uses `rpmbuild` directly. + +The PowerShell man-page is generated from the Markdown-like file +[`assets/pwsh.1.ronn`][man] using [Ronn][]. +The function `Start-PSBootstrap -Package` will install these tools. + +To modify any property of the packages, edit the `New-UnixPackage` function. +Please also refer to the function for details on the package properties +(such as the description, maintainer, vendor, URL, +license, category, dependencies, and file layout). + +> Note that the only configuration on Linux and macOS is `Linux`, +> which is release (i.e. not debug) configuration. + +To support side-by-side Unix packages, we use the following design: + +We will maintain a `powershell` package +which owns the `/usr/bin/pwsh` symlink, +is the latest version, and is upgradeable. +This is the only package named `powershell` +and similarly is the only package owning any symlinks, +executables, or man-pages named `powershell`. +Until we have a package repository, +this package will contain actual PowerShell bits +(i.e. it is not a meta-package). +These bits are installed to `/opt/microsoft/powershell/6.0.0-alpha.8/`, +where the version will change with each update +(and is the prerelease version). +On macOS, the prefix is `/usr/local`, +instead of `/opt/microsoft` because it is derived from BSD. + +> When we have access to package repositories where dependencies can be properly resolved, +> this `powershell` package can become a meta-package which auto-installs the latest package, +> and so only owns the symlink. + +For explicitly versioned packages, say for PowerShell 6.0, +we will maintain separate packages named in the form `powershell6.0`, +which owns the binary `powershell6.0`, the symlink `powershell6.0`, +the man-page `powershell6.0`, +and is installed to `/opt/microsoft/powershell/6.0/`. +Specifically this package owns nothing named `powershell`, +as only the `powershell` package owns those files. +This package is upgradeable, but should only be updated with hot-fixes. +This is a necessary consequence of Unix package managers, +as files among packages *cannot* conflict. +From a user-experience perspective, +if the user requires a specific version of PowerShell, +they should not be required to use an absolute path, +and instead should be given a binary with the version in the name. +This pattern is followed by many other languages +(Python being the most obvious example). +This same pattern can be followed for versions 6.1, 7.0, etc., +and can be used for patch version (e.g. 6.0.1). +Use `Start-PSPackage -Name powershell6.0` to generate +the versioned `powershell6.0` package. +Without `-Name` specified, the primary `powershell` +package will instead be created. + +[fpm]: https://github.com/jordansissel/fpm +[man]: ../../assets/manpage/pwsh.1.ronn +[ronn]: https://github.com/rtomayko/ronn + +### Build and Packaging Examples + +On macOS or a supported Linux distro, run the following commands: + +```powershell +# Install dependencies +Start-PSBootstrap -Package + +# Build for v6.0.0-beta.1 release +Start-PSBuild -Clean -Crossgen -PSModuleRestore -ReleaseTag v6.0.0-beta.1 + +# Create package for v6.0.0-beta.1 release +Start-PSPackage -ReleaseTag v6.0.0-beta.1 +``` + +On Windows, the `-Runtime` parameter should be specified for `Start-PSBuild` to indicate what version of OS the build is targeting. + +```powershell +# Install dependencies +Start-PSBootstrap -Package + +# Build for v6.0.0-beta.1 release targeting Windows universal package, set -Runtime to win7-x64 +Start-PSBuild -Clean -CrossGen -PSModuleRestore -Runtime win7-x64 -Configuration Release -ReleaseTag v6.0.0-beta.1 +``` + +```powershell +# Create packages for v6.0.0-beta.1 release targeting Windows universal package. +# 'win7-x64' / 'win7-x86' should be used for -WindowsRuntime. +Start-PSPackage -Type zip -ReleaseTag v6.0.0-beta.1 -WindowsRuntime 'win7-x64' +Start-PSPackage -Type msix -ReleaseTag v6.0.0-beta.1 -WindowsRuntime 'win7-x64' +``` + +## NuGet Packages + +The NuGet packages for hosting PowerShell for Windows and non-Windows are being built-in our release build pipeline. +The assemblies from the individual Windows and Linux builds are consumed and packed into NuGet packages. +These are then released to [powershell-core feed][ps-core-feed]. + +[ps-core-feed]: https://powershell.myget.org/gallery/powershell-core + +## Release Tag + +PowerShell releases use [Semantic Versioning][semver]. +Until we hit 6.0, each sprint results in a bump to the build number, +so `v6.0.0-alpha.7` goes to `v6.0.0-alpha.8`. + +When a particular commit is chosen as a release, +we create an [annotated tag][tag] that names the release. +An annotated tag has a message (like a commit), +and is *not* the same as a lightweight tag. +Create one with `git tag -a v6.0.0-alpha.7 -m `, +and use the release changelogs as the message. +Our convention is to prepend the `v` to the semantic version. +The summary (first line) of the annotated tag message should be the full release title, +e.g. 'v6.0.0-alpha.7 release of PowerShellCore'. + +When the annotated tag is finalized, push it with `git push --tags`. +GitHub will see the tag and present it as an option when creating a new [release][]. +Start the release, use the annotated tag's summary as the title, +and save the release as a draft while you upload the binary packages. + +[semver]: https://semver.org/ +[tag]: https://git-scm.com/book/en/v2/Git-Basics-Tagging +[release]: https://help.github.com/articles/creating-releases/ + +## Homebrew + +After the release, update homebrew formula. +You need macOS to do it. + +There are 2 homebrew formulas: main and preview. + +### Main + +Update it on stable releases. + +1. Wait for a PR to show up in https://github.com/powershell/homebrew-tap, review and merge it. + +### Preview + +Update it on preview releases. + +1. Wait for a PR to show up in https://github.com/powershell/homebrew-tap, review and merge it. diff --git a/PowerShell-master/docs/testing-guidelines/Images/AppVeyor-Github.png b/PowerShell-master/docs/testing-guidelines/Images/AppVeyor-Github.png new file mode 100644 index 0000000000000000000000000000000000000000..4031d25cf784a251bf060744346cb6bfd677ace8 Binary files /dev/null and b/PowerShell-master/docs/testing-guidelines/Images/AppVeyor-Github.png differ diff --git a/PowerShell-master/docs/testing-guidelines/Images/AzDevOps-Success.png b/PowerShell-master/docs/testing-guidelines/Images/AzDevOps-Success.png new file mode 100644 index 0000000000000000000000000000000000000000..29fff47fdec3857aa2124a0931b55e431cee84ed Binary files /dev/null and b/PowerShell-master/docs/testing-guidelines/Images/AzDevOps-Success.png differ diff --git a/PowerShell-master/docs/testing-guidelines/Images/CoverageReportFilter.PNG b/PowerShell-master/docs/testing-guidelines/Images/CoverageReportFilter.PNG new file mode 100644 index 0000000000000000000000000000000000000000..83a73342687a3c738da3d91deec951e8e0cf4141 --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/Images/CoverageReportFilter.PNG @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c55a6ab894b0b40a65938f77c8f9df7721cda4d610609013a8d41e1ab244bb42 +size 457561 diff --git a/PowerShell-master/docs/testing-guidelines/Images/CoverageReportTop.PNG b/PowerShell-master/docs/testing-guidelines/Images/CoverageReportTop.PNG new file mode 100644 index 0000000000000000000000000000000000000000..638f389f9141ab8dd68c203c45a7435db24843ce --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/Images/CoverageReportTop.PNG @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc8fd41be0560cbf99126e6a2d4cd8d71ef113d85285db6045e913cfdce83aca +size 333004 diff --git a/PowerShell-master/docs/testing-guidelines/PowerShellCoreTestStatus.md b/PowerShell-master/docs/testing-guidelines/PowerShellCoreTestStatus.md new file mode 100644 index 0000000000000000000000000000000000000000..ff8d225b7aaf5bf392bbb3be1f3988bdd7fc4dcc --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/PowerShellCoreTestStatus.md @@ -0,0 +1,334 @@ +# PowerShell Core Test Status + +Testing has been a major part of PowerShell since its inception and PowerShell Core is no exception to that. We will continue to add tests to the repository over time, but we did not want to wait for the + +## Test Information + +Here are some statistics about our current test coverage: + +- More than 3000 tests have been created and are part of the repository +- More than 2200 tests are run as part of our CI system + - More than 1000 tests have been created to validate the PowerShell Core Engine and Language + - More than 1200 tests have been created to validate the PowerShell Core cmdlets + +## PowerShell Cmdlets +The follow table represents the test coverage of the PowerShell Core Cmdlets in relation to the delivery platform as of 2016-08-17: + +| Name | Linux | Windows | Test Coverage | +|---|---|---|:---:| +|Get-Acl||delivered|| +|Set-Acl||delivered|| +|Export-Alias|delivered|delivered|yes| +|Get-Alias|delivered|delivered|adhoc| +|Import-Alias|delivered|delivered|yes| +|New-Alias|delivered|delivered|yes| +|Set-Alias|delivered|delivered|yes| +|Compress-Archive|delivered|delivered|yes| +|Expand-Archive|delivered|delivered|yes| +|Register-ArgumentCompleter|delivered|delivered|yes| +|Get-AuthenticodeSignature||delivered|| +|Set-AuthenticodeSignature||delivered|| +|Export-BinaryMiLog||delivered|| +|Import-BinaryMiLog||delivered|| +|Get-ChildItem|delivered|delivered|yes| +|Get-CimAssociatedInstance||delivered|| +|Get-CimClass||delivered|yes| +|Register-CimIndicationEvent||delivered|| +|Get-CimInstance||delivered|| +|New-CimInstance||delivered|| +|Remove-CimInstance||delivered|| +|Set-CimInstance||delivered|| +|Invoke-CimMethod||delivered|| +|Get-CimSession||delivered|| +|New-CimSession||delivered|| +|Remove-CimSession||delivered|| +|New-CimSessionOption||delivered|| +|Export-Clixml|delivered|delivered|yes| +|Import-Clixml|delivered|delivered|yes| +|Find-Command|delivered|delivered|adhoc| +|Get-Command|delivered|delivered|yes| +|Invoke-Command|delivered|delivered|yes| +|Measure-Command|delivered|delivered|yes| +|Rename-Computer||delivered|| +|Restart-Computer||delivered|| +|Stop-Computer||delivered|| +|Get-ComputerInfo||delivered|| +|Test-Connection||delivered|| +|Add-Content|delivered|delivered|yes| +|Clear-Content|delivered|delivered|yes| +|Get-Content|delivered|delivered|yes| +|Set-Content|delivered|delivered|yes| +|Get-Credential|delivered|delivered|adhoc| +|ConvertFrom-Csv|delivered|delivered|yes| +|ConvertTo-Csv|delivered|delivered|yes| +|Export-Csv|delivered|delivered|yes| +|Import-Csv|delivered|delivered|yes| +|Get-Culture|delivered|delivered|yes| +|Format-Custom|delivered|delivered|yes| +|Get-Date|delivered|delivered|yes| +|Set-Date|delivered|delivered|| +|Write-Debug|delivered|delivered|yes| +|Wait-Debugger|delivered|delivered|| +|Out-Default|delivered|delivered|adhoc| +|Find-DscResource|delivered|delivered|| +|Register-EngineEvent|delivered|delivered|yes| +|Write-Error|delivered|delivered|yes| +|Get-Event|delivered|delivered|yes| +|New-Event|delivered|delivered|yes| +|Remove-Event|delivered|delivered|yes| +|Unregister-Event|delivered|delivered|yes| +|Wait-Event|delivered|delivered|yes| +|Get-EventSubscriber|delivered|delivered|yes| +|Get-ExecutionPolicy|delivered|delivered|yes| +|Set-ExecutionPolicy|delivered|delivered|yes| +|Invoke-Expression|delivered|delivered|yes| +|Out-File|delivered|delivered|yes| +|Unblock-File||delivered|| +|New-FileCatalog||delivered|yes| +|Test-FileCatalog||delivered|yes| +|Get-FileHash|delivered|delivered|yes| +|Export-FormatData|delivered|delivered|yes| +|Get-FormatData|delivered|delivered|yes| +|Update-FormatData|delivered|delivered|yes| +|New-Guid|delivered|delivered|yes| +|Get-Help|delivered|delivered|yes| +|Save-Help|delivered|delivered|adhoc| +|Update-Help|delivered|delivered|adhoc| +|Format-Hex|delivered|delivered|yes| +|Add-History|delivered|delivered|adhoc| +|Clear-History|delivered|delivered|adhoc| +|Get-History|delivered|delivered|adhoc| +|Invoke-History|delivered|delivered|adhoc| +|Get-Host|delivered|delivered|yes| +|Out-Host|delivered|delivered|yes| +|Read-Host|delivered|delivered|adhoc| +|Write-Host|delivered|delivered|yes| +|Write-Information|delivered|delivered|adhoc| +|Get-InstalledModule|delivered|delivered|yes| +|Get-InstalledScript|delivered|delivered|| +|Clear-Item|delivered|delivered|adhoc| +|Copy-Item|delivered|delivered|yes| +|Get-Item|delivered|delivered|yes| +|Invoke-Item|delivered|delivered|yes| +|Move-Item|delivered|delivered|adhoc| +|New-Item|delivered|delivered|yes| +|Remove-Item|delivered|delivered|yes| +|Rename-Item|delivered|delivered|adhoc| +|Set-Item|delivered|delivered|adhoc| +|Clear-ItemProperty|delivered|delivered|adhoc| +|Copy-ItemProperty|delivered|delivered|adhoc| +|Get-ItemProperty|delivered|delivered|yes| +|Move-ItemProperty|delivered|delivered|| +|New-ItemProperty|delivered|delivered|adhoc| +|Remove-ItemProperty|delivered|delivered|adhoc| +|Rename-ItemProperty|delivered|delivered|adhoc| +|Set-ItemProperty|delivered|delivered|yes| +|Get-ItemPropertyValue|delivered|delivered|| +|Debug-Job|delivered|delivered|adhoc| +|Get-Job|delivered|delivered|adhoc| +|Receive-Job|delivered|delivered|yes| +|Remove-Job|delivered|delivered|adhoc| +|Start-Job|delivered|delivered|yes| +|Stop-Job|delivered|delivered|adhoc| +|Wait-Job|delivered|delivered|adhoc| +|ConvertFrom-Json|delivered|delivered|yes| +|ConvertTo-Json|delivered|delivered|yes| +|Format-List|delivered|delivered|yes| +|Get-LocalGroup||delivered|| +|New-LocalGroup||delivered|| +|Remove-LocalGroup||delivered|| +|Rename-LocalGroup||delivered|| +|Set-LocalGroup||delivered|| +|Add-LocalGroupMember||delivered|| +|Get-LocalGroupMember||delivered|| +|Remove-LocalGroupMember||delivered|| +|Import-LocalizedData|delivered|delivered|yes| +|Disable-LocalUser||delivered|| +|Enable-LocalUser||delivered|| +|Get-LocalUser||delivered|| +|New-LocalUser||delivered|| +|Remove-LocalUser||delivered|| +|Rename-LocalUser||delivered|| +|Set-LocalUser||delivered|| +|Get-Location|delivered|delivered|yes| +|Pop-Location|delivered|delivered|yes| +|Push-Location|delivered|delivered|yes| +|Set-Location|delivered|delivered|yes| +|Get-LogProperties||delivered|| +|Set-LogProperties||delivered|| +|Add-Member|delivered|delivered|yes| +|Get-Member|delivered|delivered|yes| +|Find-Module|delivered|delivered|adhoc| +|Get-Module|delivered|delivered|yes| +|Import-Module|delivered|delivered|yes| +|Install-Module|delivered|delivered|adhoc| +|New-Module|delivered|delivered|yes| +|Publish-Module|delivered|delivered|| +|Remove-Module|delivered|delivered|yes| +|Save-Module|delivered|delivered|adhoc| +|Uninstall-Module|delivered|delivered|| +|Update-Module|delivered|delivered|| +|New-ModuleManifest|delivered|delivered|yes| +|Test-ModuleManifest|delivered|delivered|| +|Update-ModuleManifest|delivered|delivered|| +|Export-ModuleMember|delivered|delivered|yes| +|Out-Null|delivered|delivered|yes| +|Compare-Object|delivered|delivered|yes| +|ForEach-Object|delivered|delivered|yes| +|Group-Object|delivered|delivered|yes| +|Measure-Object|delivered|delivered|yes| +|New-Object|delivered|delivered|yes| +|Select-Object|delivered|delivered|yes| +|Sort-Object|delivered|delivered|yes| +|Tee-Object|delivered|delivered|yes| +|Where-Object|delivered|delivered|yes| +|Register-ObjectEvent|delivered|delivered|yes| +|Write-Output|delivered|delivered|yes| +|Find-Package|delivered|delivered|yes| +|Get-Package|delivered|delivered|yes| +|Install-Package|delivered|delivered|yes| +|Save-Package|delivered|delivered|yes| +|Uninstall-Package|delivered|delivered|yes| +|Find-PackageProvider|delivered|delivered|yes| +|Get-PackageProvider|delivered|delivered|yes| +|Import-PackageProvider|delivered|delivered|yes| +|Install-PackageProvider|delivered|delivered|yes| +|Get-PackageSource|delivered|delivered|yes| +|Register-PackageSource|delivered|delivered|yes| +|Set-PackageSource|delivered|delivered|yes| +|Unregister-PackageSource|delivered|delivered|yes| +|Convert-Path|delivered|delivered|adhoc| +|Join-Path|delivered|delivered|yes| +|Resolve-Path|delivered|delivered|adhoc| +|Split-Path|delivered|delivered|yes| +|Test-Path|delivered|delivered|yes| +|Import-PowerShellDataFile|delivered|delivered|yes| +|Debug-Process|delivered|delivered|| +|Get-Process|delivered|delivered|yes| +|Start-Process|delivered|delivered|yes| +|Stop-Process|delivered|delivered|yes| +|Wait-Process|delivered|delivered|| +|Write-Progress|delivered|delivered|yes| +|Disable-PSBreakpoint|delivered|delivered|| +|Enable-PSBreakpoint|delivered|delivered|| +|Get-PSBreakpoint|delivered|delivered|yes| +|Remove-PSBreakpoint|delivered|delivered|yes| +|Set-PSBreakpoint|delivered|delivered|yes| +|Get-PSCallStack|delivered|delivered|adhoc| +|Set-PSDebug|delivered|delivered|yes| +|Get-PSDrive|delivered|delivered|yes| +|New-PSDrive|delivered|delivered|yes| +|Remove-PSDrive|delivered|delivered|yes| +|Enter-PSHostProcess|delivered|delivered|yes| +|Exit-PSHostProcess|delivered|delivered|yes| +|Get-PSHostProcessInfo|delivered|delivered|fails on Linux| +|Get-PSProvider|delivered|delivered|yes| +|Get-PSReadlineKeyHandler|delivered|delivered|yes| +|Remove-PSReadlineKeyHandler|delivered|delivered|| +|Set-PSReadlineKeyHandler|delivered|delivered|yes| +|Get-PSReadlineOption|delivered|delivered|yes| +|Set-PSReadlineOption|delivered|delivered|yes| +|Get-PSRepository|delivered|delivered|| +|Register-PSRepository|delivered|delivered|| +|Set-PSRepository|delivered|delivered|| +|Unregister-PSRepository|delivered|delivered|| +|New-PSRoleCapabilityFile|delivered|delivered|| +|Connect-PSSession|delivered|delivered|adhoc| +|Disconnect-PSSession|delivered|delivered|adhoc| +|Enter-PSSession|delivered|delivered|adhoc| +|Exit-PSSession|delivered|delivered|adhoc| +|Get-PSSession|delivered|delivered|adhoc| +|New-PSSession|delivered|delivered|yes| +|Receive-PSSession|delivered|delivered|adhoc| +|Remove-PSSession|delivered|delivered|yes| +|Get-PSSessionCapability|delivered|delivered|| +|Disable-PSSessionConfiguration|delivered|delivered|| +|Enable-PSSessionConfiguration|delivered|delivered|| +|Get-PSSessionConfiguration|delivered|delivered|| +|Register-PSSessionConfiguration|delivered|delivered|yes| +|Set-PSSessionConfiguration|delivered|delivered|| +|Unregister-PSSessionConfiguration|delivered|delivered|yes| +|New-PSSessionConfigurationFile|delivered|delivered|yes| +|Test-PSSessionConfigurationFile|delivered|delivered|| +|New-PSSessionOption|delivered|delivered|| +|Disable-PSTrace||delivered|| +|Enable-PSTrace||delivered|| +|New-PSTransportOption|delivered|delivered|| +|Disable-PSWSManCombinedTrace||delivered|| +|Enable-PSWSManCombinedTrace||delivered|| +|Get-Random|delivered|delivered|yes| +|Invoke-RestMethod|delivered|delivered|yes| +|Find-RoleCapability|delivered|delivered|| +|Debug-Runspace|delivered|delivered|| +|Get-Runspace|delivered|delivered|yes| +|Disable-RunspaceDebug|delivered|delivered|| +|Enable-RunspaceDebug|delivered|delivered|| +|Get-RunspaceDebug|delivered|delivered|yes| +|Find-Script|delivered|delivered|| +|Install-Script|delivered|delivered|| +|Publish-Script|delivered|delivered|| +|Save-Script|delivered|delivered|| +|Uninstall-Script|delivered|delivered|| +|Update-Script|delivered|delivered|| +|New-ScriptFileInfo|delivered|delivered|| +|Test-ScriptFileInfo|delivered|delivered|| +|Update-ScriptFileInfo|delivered|delivered|| +|ConvertFrom-SddlString||delivered|| +|ConvertFrom-SecureString|delivered|delivered|yes| +|ConvertTo-SecureString|delivered|delivered|yes| +|Get-Service||delivered|| +|New-Service||delivered|| +|Restart-Service||delivered|| +|Resume-Service||delivered|| +|Set-Service||delivered|| +|Start-Service||delivered|| +|Stop-Service||delivered|| +|Suspend-Service||delivered|| +|Start-Sleep|delivered|delivered|yes| +|Set-StrictMode|delivered|delivered|yes| +|Out-String|delivered|delivered|yes| +|Select-String|delivered|delivered|yes| +|ConvertFrom-StringData|delivered|delivered|yes| +|Format-Table|delivered|delivered|yes| +|New-TemporaryFile|delivered|delivered|yes| +|New-TimeSpan|delivered|delivered|yes| +|Get-TimeZone||delivered|yes| +|Set-TimeZone||delivered|yes| +|Start-Trace||delivered|| +|Stop-Trace||delivered|| +|Start-Transcript|delivered|delivered|yes| +|Stop-Transcript|delivered|delivered|yes| +|Add-Type|delivered|delivered|yes| +|Get-TypeData|delivered|delivered|yes| +|Remove-TypeData|delivered|delivered|yes| +|Update-TypeData|delivered|delivered|yes| +|Get-UICulture|delivered|delivered|yes| +|Get-Unique|delivered|delivered|yes| +|Clear-Variable|delivered|delivered|yes| +|Get-Variable|delivered|delivered|yes| +|New-Variable|delivered|delivered|yes| +|Remove-Variable|delivered|delivered|yes| +|Set-Variable|delivered|delivered|yes| +|Write-Verbose|delivered|delivered|yes| +|Write-Warning|delivered|delivered|yes| +|Invoke-WebRequest|delivered|delivered|yes| +|Format-Wide|delivered|delivered|yes| +|Get-WinEvent||delivered|yes| +|New-WinEvent||delivered|| +|Connect-WSMan||delivered|| +|Disconnect-WSMan||delivered|| +|Test-WSMan||delivered|| +|Invoke-WSManAction||delivered|| +|Disable-WSManCredSSP||delivered|| +|Enable-WSManCredSSP||delivered|| +|Get-WSManCredSSP||delivered|| +|Get-WSManInstance||delivered|| +|New-WSManInstance||delivered|| +|Remove-WSManInstance||delivered|| +|Set-WSManInstance||delivered|| +|Set-WSManQuickConfig||delivered|| +|New-WSManSessionOption||delivered|| +|Disable-WSManTrace||delivered|| +|Enable-WSManTrace||delivered|| +|ConvertTo-Xml|delivered|delivered|yes| +|Select-xml|delivered|delivered|yes| diff --git a/PowerShell-master/docs/testing-guidelines/TestRoadmap.md b/PowerShell-master/docs/testing-guidelines/TestRoadmap.md new file mode 100644 index 0000000000000000000000000000000000000000..aea71be5aec2548530cff1489c39f91525da4c98 --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/TestRoadmap.md @@ -0,0 +1,193 @@ +# Overview +While we have done a fairly good job providing adequate coverage for the highest priority areas of PowerShell Core, we still have lots of gaps when we compare what is available in the OSS project vs what we have available as part of the Windows release test infrastructure. +This is to be expected as that infrastructure was built up over more than a decade. +It is not clear, however, how many of the current tests actually provide value, and how much duplication we have. +In any event, there is still a large difference in what we have in PowerShell Core and our older tests. + +# Data Visibility +In both PowerShell Core or our proprietary tests we can't actually determine how and what cmdlets and engine functions (language/scripting/debugging/remoting) are being tested because we do not gather any usage telemetry on what our tests are doing during test execution. +We have no way via automation to determine how thoroughly we are testing our code except by inspecting the actual tests or looking at code coverage data (which isn't gathered often and only available on full PowerShell). +Further, this doesn't provide us data with regard to the test quality, only that we've covered a specific block of code. +The areas of greatest risk are those where we have no data at all, by collecting coverage data we can illuminate those code paths that are not being used and fill those gaps with new tests. + +## Telemetry and Logging +While we have some telemetry feeds on Windows, we have _no_ telemetry capabilities on non-Windows platforms. +We should enable telemetry on PowerShell Core on all platforms and review the usage data as soon as possible. +This will provide us much needed visibility in how PowerShell Core is being used and can help us identify areas we should track more closely. +We already have infrastructure in place to allow us see how PowerShell Core is being used, by collecting telemetry from PowerShell Core, we can improve our confidence as we drive to production quality. + +### Logging +The code which on Windows create ETW logging has been completely stubbed out on Linux/macOS. +We should take advantage of the native logging mechanisms on Linux/macOS and implement a logger similar to the ETW logger on Windows using Syslog (or equivalent). +We could use this data during test runs to identify test gaps. +Simply by capturing the cmdlets and their parameters which are invoked during test would illuminate the gaps we have in our current tests, and allow us to easily fill them. +It is not sufficient to support only one platform because we have many tests which determine at runtime whether or not it should run based on OS, so data from Windows will not be the same as that from Linux or MacOS. +We can also determine engine coverage gaps by measuring test of operators and other language elements. +Without that data, we are simply shooting in the dark. + +## Code coverage +Even in our lab (STEX) environment we run tests to get code coverage data irregularly, and PowerShell Core has _no_ tools to gather code coverage data. +We need to investigate possible solutions for code coverage on PowerShell Core. +There are a small number of solutions available: +* [OpenCover](https://github.com/OpenCover/opencover) + * OpenCover is currently used by corefx to produce code coverage data, also visualization is available via [CoverAlls](https://coveralls.io/github/OpenCover/opencover). + We should investigate `OpenCover` and determine it's feasibility for us. + Unfortunately I haven't been able to find a solution for Linux +* DotCover + * I have contacted `JetBrains` to see if they have any solutions which may be used with .NET Core. + +If we can get code coverage on PowerShell Core on Windows, we would at least be able to have _some_ data to illuminate our test gaps. + +Running code coverage more often on full PowerShell is something that we should consider, if it will help us close existing test coverage gaps, but the issue is _not_ test coverage for full PowerShell, but rather PowerShell Core where we have only a small percentage of tests in comparison. + +## Daily Test Runs +We currently run only those tests which are tagged `CI` excluding the tag `SLOW` as part of our continuous integration systems. +This means roughly 1/3rd of our github tests are not being run on any regular schedule. +In order to provide us with higher confidence in our code, we should be running *ALL* of our tests on a regular basis. +However, running the tests is only the first step, we need an easy way to be notified of test failures, and to track progress of those runs over time. +Tracking this over time affords us the ability to see how our test count increases, implying an improvement in coverage. +It also provides us mechanism whereby we can see trends in instability. + +### Pending and Skipped Tests +We currently have approximately 300 tests which are marked either as `skipped` or `pending`. +`Pending` tests represent those tests which should be run but are not currently being executed, usually because the underlying functionality is not present. +Over time, the number of `Pending` tests should drive to zero, and we should be tracking the list of tests which are marked `pending` and track those to be sure that they do not spend too long in this state. +`Skipped` tests due to platform applicability are certainly valid, and it is important that we track how many tests are skipped and for what reason. +A test which is skipped for all platforms should be considered carefully as to whether it should exist at all. +In either case, `pending` or `skipped` tests should be tracked over time so we can determine whether we are improving our ability to measure quality. + +In the best case, the _total_ number of tests is the same across all platforms. +The count of Skipped/Pending tests would naturally be different as not all tests will be applicable to every platform, but if we can have consistency of test count across platforms, it will be easier to compare test results on one platform vs another. + +## Remoting Considerations +Given that one of the targeted scenarios is to manage heterogeneous environments remotely, we need a test environment which encompasses the available platforms and protocols. +Our current test infrastructure does not have comprehensive support for remote testing except for loopback operations. +We need a matrix of protocols and platforms to ensure that we have adequate coverage to ensure quality. + +In addition to loopback tests using both WSMan and SSH protocols, we should have the following _minimum_ matrix of client/server connections for both WSMan and SSH (where available) protocols. +* Windows Client->Nano Server +* Windows Client->Linux Server +* Linux Client -> Windows Server +* macOS Client -> Nano Client +* PowerShell Core Client -> Full PowerShell Server +* Full PowerShell Client -> PowerShell Core Server +* Downlevel Full PowerShell Client -> PowerShell Core Server + +### Challenges +* On Windows, we have cmdlets to enable and disable remote access, those cmdlets do not exist on non-Windows platforms (they rely on configuration stored in the registry), nor do we support configuration for the SSH protocol. +We need to be sure that we can easily enable remoting for the non-Windows platforms and support both WSMan _and_ SSH configurations. +* Our current multi-machine tests do not test the connection code, they simply execute test code remotely and retrieve results and assume a good connection. +The infrastructure used for these tests is STEX which is not an open environment. +We will need to create automation to create and configure the test systems in the test matrix and then invoke tests on them. +It is not clear that our current CI systems can accommodate our needs here as Azure DevOps can supply us with all of the OS images needed. +We may need to create our own heterogeneous environment in Azure, or look to other teams (MS Build Lab/Jenkins) for assistance. + +We need to investigate whether there are solutions available, and if not, design/implement an environment to meet our needs. + +# Reporting +Currently, we report against the simplest of KPI: +* is the CI build error free (which is part of the PR/Merge process - and reported on our landing page) + +There are a number of KPIs which we could report on: +* Code KPIs + * What is the coverage (% blocks covered) of our `CI` tests + * What is the coverage of all tests + * How long is the CI system taking + * build time + * test time + * What is the percentage of pull requests pass `CI` tests + * What is the trend for `pending` tests +* Process KPIs + * What is the time delta between a posted PR (with no test errors) and merge + * How many revisions are needed before a PR is accepted + * How many PRs are rejected +* Product KPIs + * What is the usage of PowerShell Core on the various platforms + * What are the common operations performed by PowerShell Core (cmdlet usage) + * How many remote connections are created in a session + +## Reporting Priorities +1. As a baseline, we should report code coverage on current Full PowerShell from the latest Windows release +2. We should report on code coverage as soon as possible. +This is the tool that will enable us to at least determine where we have _no_ data and illuminate test gaps. +3. We should track our CI execution time, which will allow us to keep an eye on our code submission workflow and how much our developers are waiting for builds + +### Public Dashboard +Because we collect the test results as a build artifact, it is possible to collect and collate this data and provide a number of dash-board reports. +Since we are an OSS project, it makes sense that our reports should be also public. +A public dashboard provides evidence that we are not collecting PII, increasing trust in the project and shows that we are using data to drive product decisions. +We could easily create a web presence in Azure which would enable us to provide reporting on the current and historical state of our tests. +Now that we are running all of our tests on a nightly basis, we should be communicating the results of those test runs. +PowerBI could be used to create the visualizations, which would reduce the time and effort. + +In order to achieve this we need to: +* Designate an Azure instance to run services and populate Azure tables: + * Create tools to retrieve and transform git data + * Create tools to retrieve and transform the test data +* Create PowerBI queries to visualize our KPIs + +# Release Criteria +We must start defining the release criteria for a production ready release of PowerShell Core, as an initial proposal: +* No open issues for the release +* 80% code coverage of high use cmdlets (cmdlets used by 70% of users, as captured via telemetry) +* 90% code coverage of language elements (coverage error code paths may not be 100%) +* 60% code Coverage on Windows via Github tests +* 100% of our minimum remoting matrix tested +* Acceptance by 50% PowerShell MVPs (via Survey) +* Acceptance by Partners (via Survey) + +A couple of assumptions have been made for this list: +1) we actually know the high use cmdlets - this implies we have telemetry to determine our cmdlet use +2) we have designated our Partners + +# Microsoft Release Process +If PowerShell Core is targeted to be released as part of Windows Server or Nano, we will have additional requirements which must be met with regard to acceptance by the Windows org of the PowerShell Core package. +This represents additional work which needs planning and allocated resources. + +## Replace STEX tests with PowerShell Core tests +Currently we have two distinct set of test artifacts, those used in PowerShell Core and our traditional lab (STEX) based tests. +We are creating new tests for PowerShell Core using the existing tests as guidance, but this is creating duplication between the two sets so we need to find ways to invoke our current PowerShell Core tests as part of our STEX based runs. +When we do this, we can start to delete our existing tests and reduce the maintenance burden due to duplicated tests. + +**Proposal** + +* Create a way to invoke our github based tests in lab runs + +## Historical Tests +The PowerShell team created roughly 90,000 tests since the beginning of the project starting in 2003. +Initially tests were created in a C# framework which was used internally at Microsoft. +After that, a number of script based frameworks were created to run script based tests. +We have decided not to release those for a number of reasons: +* All the frameworks have a core assumption of running in the Microsoft Lab environment and rely on internal Microsoft tools +* All the frameworks rely on specific logging file formats used by internal Microsoft reporting tools +* Some of the frameworks have limitations which we can avoid by recasting/recreating them as `Pester` or `xUnit` tests + +While, these reasons are not insurmountable, releasing these tests with their custom frameworks does not help us with our desire to promulgate open solutions. +Further, by creating/releasing `xUnit` and `Pester` tests we can take the opportunity to review existing tests and improve them, or eliminate them if they are poor, or duplicate tests. +It is obvious that the review of more than 90,000 tests is an enormous undertaking, and will take some time, and we are committed to creating a set of tests which can provide confidence that PowerShell Core has the same quality as earlier releases of PowerShell. + +## Challenges ## +While there is a test gap between what is available on Github vs what is available via our internal proprietary tests, it may be possible to use our existing tests (and frameworks) against PowerShell Core. +This is an attractive potential because we have very high confidence of our current tests. +Moreover, we could also collect code coverage data during a test pass. +It would be expected to have a number of test failures because different functionality between PowerShell Core and Full PowerShell but collecting this data would enable us to enumerate those difference. +Unfortunately, the current logging mechanism used in our in-lab tests are not available in PowerShell Core, and a new logging mechanism would need to be created + +**Proposal** + +* Investigate the effort to run our historical tests in a PowerShell Core environment + +# Action Plan +This document represents a number of initiatives, all of which will take resources. +Below is my suggestion for prioritization to reduce risk and improve confidence in our overall quality: + +1. Implement telemetry feeds for PowerShell Core +2. Implement data collection feeds from our CI systems +3. Create a public dashboard to visualize our KPIs + * including data from 1, 2 above +4. Implement Code Coverage on PowerShell Core +5. Design/Implement remoting test infrastructure +6. Replace in-lab tests with PowerShell Core tests +7. Investigate feasibility of running current in-lab tests on PowerShell Core + +These are [tracked](https://github.com/PowerShell/PowerShell/issues?utf8=%E2%9C%93&q=is%3Aissue%20%23testability%20) as issues diff --git a/PowerShell-master/docs/testing-guidelines/WritingPesterTests.md b/PowerShell-master/docs/testing-guidelines/WritingPesterTests.md new file mode 100644 index 0000000000000000000000000000000000000000..5225dd94a223b9cd5be74f65097aab04ef4d0f40 --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/WritingPesterTests.md @@ -0,0 +1,396 @@ +# Writing Pester Tests + +Note that this document does not replace the documents found in the [Pester](https://github.com/pester/pester) project. +This is just some quick tips and suggestions for creating Pester tests for this project. +The Pester community is vibrant and active, if you have questions about Pester or creating tests, the [Pester Wiki](https://github.com/pester/pester/wiki) has a lot of great information. +As of January 2018, PowerShell Core is using Pester version 4 which has some changes from earlier versions. +See [Migrating from Pester 3 to Pester 4](https://github.com/pester/Pester/wiki/Migrating-from-Pester-3-to-Pester-4) for more information. + +When creating tests, keep the following in mind: + +- Tests should not be overly complicated and test too many things. + - Boil down your tests to their essence, test only what you need. +- Tests should be as simple as they can. +- Tests should generally not rely on any other test. + +## Examples + +Here's the simplest of tests: + +```powershell +Describe "A variable can be assigned and retrieved" { + It "Creates a variable and makes sure its value is correct" { + $a = 1 + $a | Should -Be 1 + } +} +``` + +If you need to do type checking, that can be done as well: + +```powershell +Describe "One is really one" { + It "Compare 1 to 1" { + $a = 1 + $a | Should -Be 1 + } + It "1 is really an int" { + $i = 1 + $i | Should -BeOfType System.Int32 + } +} +``` + +If you are checking for proper errors, use the `Should -Throw -ErrorId` Pester syntax. +It checks against `FullyQualifiedErrorId` property, which is recommended because it does not change based on culture as an error message might. + +```powershell +... +It "Get-Item on a nonexisting file should have error PathNotFound" { + { Get-Item "ThisFileCannotPossiblyExist" -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" +} +``` + +Note that if `Get-Item` were to succeed, the test will fail. + +However, if you need to check the `InnerException` or other members of the ErrorRecord, you should use `-PassThru` parameter: + +```powershell +It "InnerException sample" { + $e = { Invoke-WebRequest https://expired.badssl.com/ } | Should -Throw -ErrorId "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" -PassThru + $e.Exception.InnerException.NativeErrorCode | Should -Be 12175 +} +``` + +## Describe/Context/It + +For creation of PowerShell tests, the `Describe` block is the level of granularity suggested and one of three tags should be used: `CI`, `Feature`, or `Scenario`. + +If the tag is not provided, the build process will fail. + +### Describe + +Creates a logical group of tests. +All `Mocks` and `TestDrive` contents defined within a `Describe` block are scoped to that `Describe`; +they will no longer be present when the `Describe` block exits. +A `Describe` block may contain any number of `Context` and `It` blocks. + +### Context + +Provides logical grouping of `It` blocks within a single `Describe` block. Any `Mocks` defined inside a `Context` are removed at the end of the `Context` scope, as are any files or folders added to the `TestDrive` during the `Context` block's execution. + +Any `BeforeEach` or `AfterEach` blocks defined inside a `Context` also only apply to tests within that `Context`. + +### It + +The `It` block is intended to be used inside of a `Describe` or `Context` block. If you are familiar with the AAA pattern (Arrange-Act-Assert), the body of the `It` block is the appropriate location for an assert. + +The convention is to assert a single expectation for each `It` block. The code inside of the `It` block should throw a terminating error if the expectation of the test is not met and thus cause the test to fail. + +The name of the `It` block should expressively state the expectation of the test. + +## Admin privileges in tests + +Tests that require admin privileges **on Windows** must be additionally marked with `RequireAdminOnWindows` Pester tag. + +In the Azure DevOps Windows CI, we run two different passes: + +- The pass with exclusion of `RequireAdminOnWindows` tagged tests. +- The pass where only `RequireAdminOnWindows` tagged tests are being executed. + +In each case, tests are executed with appropriate privileges. + +Tests that need to be run with sudo **on Unix systems** must be additionally marked with `RequireSudoOnUnix` Pester tag. + +`RequireSudoOnUnix` tag takes precedence over all other tags like `CI`, `Feature`, etc. (which are ignored when `RequireSudoOnUnix` is present). +Tests tagged with `RequireSudoOnUnix` will run as a separate pass for any Unix test. + +## Selected Features + +### Test Drive + +A `PSDrive` is available for file activity during a test and this drive is limited to the scope of a single `Describe` block. The contents of the drive are cleared when a `Context` block is exited. + +A test may need to work with file operations and validate certain types of file activities. It is usually desirable not to perform file activity tests that will produce side effects outside of an individual test. + +Pester creates a `PSDrive` inside the user's temporary drive that is accessible via `TestDrive:` or `$TestDrive`. **Pester will remove** this drive after the test completes. +You may use this drive to isolate the file operations of your test to a temporary store. + +The following example illustrates the feature: + +```powershell +function Add-Footer($path, $footer) { + Add-Content $path -Value $footer +} + +Describe "Add-Footer" { + $testPath="TestDrive:\test.txt" + Set-Content $testPath -value "my test text." + Add-Footer $testPath "-Footer" + $result = Get-Content $testPath + + It "adds a footer" { + (-join $result) | Should -BeExactly "my test text.-Footer" + } +} +``` + +When this test completes, the contents of the `TestDrive:` will be removed. + +### Parameter Generation + +```powershell +$testCases = @( + @{ a = 0; b = 1; ExpectedResult = 1 } + @{ a = 1; b = 0; ExpectedResult = 1 } + @{ a = 1; b = 1; ExpectedResult = 0 } + @{ a = 0; b = 0; ExpectedResult = 0 } + ) + +Describe "A test" { + It " -xor should be " -TestCases $testCases { + param ($a, $b, $ExpectedResult) + $a -xor $b | Should -Be $ExpectedResult + } +} +``` + +### Mocking + +Mocks the behavior of an existing command with an alternate implementation. This creates new behavior for any existing command within the scope of a `Describe` or `Context` block. +The function allows you to specify a script block that will become the command's new behavior. + +The following example illustrates simple use: + +```powershell +Context "Get-Random is not random" { + Mock Get-Random { return 3 } + + It "Get-Random returns 3" { + Get-Random | Should -Be 3 + } +} +``` + +More information may be found [here](https://github.com/pester/Pester/wiki/Mock). + +### Free Code in a Describe block + +Code execution in Pester can be very subtle and can cause issues when executing test code. The execution of code which lays outside of the usual code blocks may not happen as you expect. Consider the following: + +```powershell +Describe it { + Write-Host -For DarkRed "Before Context" + Context "subsection" { + Write-Host -for DarkRed "Before BeforeAll" + BeforeAll { write-host -for Blue "In Context BeforeAll" } + Write-Host -for DarkRed "After BeforeAll" + + Write-Host -for DarkRed "Before AfterAll" + AfterAll { Write-Host -for Blue "In Context AfterAll" } + Write-Host -for DarkRed "After AfterAll" + + BeforeEach { Write-Host -for Blue "In BeforeEach" } + AfterEach { Write-Host -for Blue "In AfterEach" } + + Write-Host -for DarkRed "Before It" + It "should not be a surprise" { + 1 | should -Be 1 + } + Write-Host -for DarkRed "After It" + } + Write-Host -for DarkRed "After Context" + Write-Host -for DarkGreen "Before Describe BeforeAll" + BeforeAll { Write-Host -for DarkGreen "In Describe BeforeAll" } + AfterAll { Write-Host -for DarkGreen "In Describe AfterAll" } +} +``` + +Now, when run, you can see the execution schedule: + +``` +PS# invoke-pester c:\temp\pester.demo.tests.ps1 +Describing it +In Describe BeforeAll +Before Context + Context subsection +In Context BeforeAll +Before BeforeAll +After BeforeAll +Before AfterAll +After AfterAll +Before It +In BeforeEach + [+] should not be a surprise 79ms +In AfterEach +After It +In Context AfterAll +After Context +Before Describe BeforeAll +In Describe AfterAll +Tests completed in 79ms +Passed: 1 Failed: 0 Skipped: 0 Pending: 0 +``` + +The `Describe` - `BeforeAll` block is executed before any other code even though it was at the bottom of the `Describe` block. +So if some state is set elsewhere in the `Describe` block, that state will not yet be visible (as the code will not yet been run). + +Notice, too, that the `BeforeAll` block in `Context` is executed before any other code in that block. +Generally, you should have code reside in one of the code block elements of `BeforeAll`, `BeforeEach`, `AfterEach` and/or `AfterAll`, especially if those blocks rely on some state set by free code elsewhere in the block. + +### Skipping Tests in Bulk + +Sometimes it is beneficial to skip all the tests in a particular `Describe` block. +For example, tests which are not applicable to a platform could be skipped, and they would be reported as skipped. + +The following is an example of how this may be done: + +```powershell +Describe "Should not run these tests on non-Windows platforms" { + BeforeAll { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + if ( ! $IsWindows ) { + $PSDefaultParameterValues["it:skip"] = $true + } + } + AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParameterValues + } + Context "Block 1" { + It "This block 1 test 1" { + 1 | should -Be 1 + } + It "This is block 1 test 2" { + 1 | should -Be 1 + } + } + Context "Block 2" { + It "This block 2 test 1" { + 2 | should -Be 1 + } + It "This is block 2 test 2" { + 2 | should -Be 1 + } + } +} +``` + +Here is the output when run on a Linux distribution: + +``` +Describing Should not run these tests on non-Windows platforms + Context Block 1 + [!] This block 1 test 1 691ms + [!] This is block 1 test 2 114ms + Context Block 2 + [!] This block 2 test 1 73ms + [!] This is block 2 test 2 6ms +``` + +and here is the output when run on a Windows distribution: + +``` +Describing Should not run these tests on non-Windows platforms + Context Block 1 + [+] This block 1 test 1 86ms + [+] This is block 1 test 2 33ms + Context Block 2 + [-] This block 2 test 1 52ms + Expected: {1} + But was: {2} + 22: 2 | should -Be 1 + at , : line 22 + [-] This is block 2 test 2 77ms + Expected: {1} + But was: {2} + 25: 2 | should -Be 1 + at , : line 25 +``` + +This technique uses the `$PSDefaultParameterValues` feature of PowerShell to temporarily set the `It` block parameter `-skip` to true (or in the case of Windows, it is not set at all) + +### Multi-line strings + +You may want to have a test like: + +```powershell +It 'tests multi-line string' { + Get-MultiLineString | Should -Be @' +first line +second line +'@ +} +``` + +There are problems with using multi-line strings with verifying the output results. +The reason for it are line-ends. + +They cause problems for two reasons: + +- They are different on different platforms (`\r\n` on Windows and `\n` on Unix). +- Even on the same system, they depend on the way how the repo was cloned (local git configuration). + +Particularly, in the default Azure DevOps CI Windows image, you will get `\n` line ends in all your files. +That causes problems, because at runtime `Get-MultiLineString` would likely produce `\r\n` line ends on Windows. + +Some workaround could be added, but they are sub-optimal and make reading test code harder. + +```powershell +function normalizeEnds([string]$text) +{ + $text -replace "`r`n?|`n", "`r`n" +} + +It 'tests multi-line string' { + normalizeEnds (Get-MultiLineString) | Should -Be (normalizeEnds @' +first line +second line +'@) +} +``` + +When appropriate, you can avoid creating multi-line strings at the first place. +These commands create an array of strings: + +- `Get-Content` +- `Out-String -Stream` + +## Pester Do and Don't + +### Do + +1. Name your file `.tests.ps1`. +2. Keep tests simple: + - Test only what you need. + - Reduce dependencies. +3. Be sure to tag your `Describe` blocks based on their purpose: + - Tag `CI` indicates that it will be run as part of the continuous integration process. These should be unit test like, and generally take less than a second. + - Tag `Feature` indicates a higher level feature test (we will run these on a regular basis), for example, tests which go to remote resources, or test broader functionality. + - Tag `Scenario` indicates tests of integration with other features (these will be run on a less regular basis and test even broader functionality than feature tests. +4. Make sure that `Describe`/`Context`/`It` descriptions are useful. + - The error message should not be the place where you describe the test. +5. Use `Context` to group tests. + - Multiple `Context` blocks can help you group your test suite into logical sections. +6. Use `BeforeAll`/`BeforeEach`/`AfterEach`/`AfterAll` instead of custom initiators. +7. Use `Should -Throw -ErrorId` to check for expected errors. +8. Use `-TestCases` when iterating over multiple `It` blocks. +9. Use code coverage functionality where appropriate. +10. Use `Mock` functionality when you don't have your entire environment. +11. Avoid free code in a `Describe` block. + - Use `BeforeAll`/`BeforeEach`/`AfterEach`/`AfterAll`. + - See [Free Code in a Describe block](WritingPesterTests.md#free-code-in-a-describe-block) +12. Avoid creating or using test files outside of `TESTDRIVE:`. + - `TESTDRIVE:` has automatic clean-up. +13. Keep in mind that we are creating cross platform tests. + - Avoid using the registry. + - Avoid using COM. +14. Avoid being too specific about the _count_ of a resource as these can change platform to platform. + - Example: Avoid checking for the count of loaded format files, but rather check for format data for a specific type. + +### Don't + +1. Don't have too many evaluations in a single `It` block. + - The first `Should` failure will stop that block. +2. Don't use `Should` outside of an `It` Block. +3. Don't use the word "Error" or "Fail" to test a positive case. + - Example: Rephrase the negative sentence `"Get-ChildItem TESTDRIVE: shouldn't fail"` to the following positive case `"Get-ChildItem should be able to retrieve file listing from TESTDRIVE"`. diff --git a/PowerShell-master/docs/testing-guidelines/getting-code-coverage.md b/PowerShell-master/docs/testing-guidelines/getting-code-coverage.md new file mode 100644 index 0000000000000000000000000000000000000000..0f2bc8eb98368376d37f73c6c2d3d96ef4abe59a --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/getting-code-coverage.md @@ -0,0 +1,172 @@ +# Getting Code Coverage Analysis for PowerShell + +**Note: Code coverage is currently only supported on Windows, since we use OpenCover.** + +The PowerShell code base is configured to build with code coverage support using [OpenCover]. + +You can see the testing coverage of the current [`master`] branch build at any time at [codecov.io]. + +To run test coverage analysis of PowerShell on your own branch/machine, +you will need to take the following steps +(and be aware that running the code coverage analysis can take as long as 8 hours). + +## Running tests with code coverage analysis + +**First**: Open PowerShell in an **elevated** session. +OpenCover needs elevated privileges to work. + +Now, in PowerShell: + +```powershell +# Go to your PowerShell build directory root +PS> Set-Location "C:\Path\to\powershell\build\dir" + +# Import the PowerShell build module +PS> Import-Module .\build.psm1 + +# Build PowerShell. You may need to add other flags here like +# -ResGen or -Restore +PS> Start-PSBuild -Configuration CodeCoverage -Clean -PsModuleRestore + +# Now ensure Pester is installed +PS> Restore-PSPester + +# We also need to build the test executor +PS> Publish-PSTestTools + +# Import the OpenCover module +PS> Import-Module $PWD\test\tools\OpenCover + +# Install OpenCover to a temporary directory +PS> Install-OpenCover -TargetDirectory $env:TEMP -Force + +# Finally, run the tests with code coverage analysis. +# If you want to run only the continuous integration tests, +# add -CIOnly, which will take less time +PS> Invoke-OpenCover -OutputLog coverage.xml -OpenCoverPath $env:TEMP\OpenCover +``` + +## Examining the code coverage data + +Once the code coverage test run is done, you'll want to examine the data: + +```powershell +# Collect the coverage data using Get-CodeCoverage from the OpenCover +# module that was imported above. This operation is generally expensive +# to compute, so worth storing in a variable +PS> $coverageData = Get-CodeCoverage .\coverage.xml + +# Take a look at a summary of the results +PS> $coverageData.CoverageSummary + +NumSequencePoints : 298237 +VisitedSequencePoints : 125949 +NumBranchPoints : 101477 +VisitedBranchPoints : 39389 +SequenceCoverage : 42.23 +BranchCoverage : 38.82 +MaxCyclomaticComplexity : 393 +MinCyclomaticComplexity : 1 +VisitedClasses : 1990 +NumClasses : 3187 +VisitedMethods : 15115 +NumMethods : 32517 + +# You can also view results by assembly +PS> $coverageData.Assembly | Format-Table AssemblyName,Branch,Sequence + +AssemblyName Branch Sequence +------------ ------ -------- +pwsh 100 100 +Microsoft.PowerShell.ConsoleHost 21.58 23.32 +System.Management.Automation 41.22 45.01 +Microsoft.PowerShell.CoreCLR.Eventing 1.88 2.03 +Microsoft.PowerShell.Security 17.32 20.09 +Microsoft.PowerShell.Commands.Utility 20.14 21.39 +Microsoft.PowerShell.Commands.Management 43.05 43.39 +Microsoft.WSMan.Management 52.58 56.98 +Microsoft.WSMan.Runtime 80.95 80.33 +Microsoft.PowerShell.Commands.Diagnostics 0 0 +``` + +If you have made changes to tests or code +and run a second code coverage run, +you can also compare code coverage results: + +```powershell +PS> $cov1 = Get-CodeCoverage ./coverage1.xml +PS> $cov2 = Get-CodeCoverage ./coverage2.xml +PS> Compare-CodeCoverage -Run1 $cov1 -Run2 $cov2 + +AssemblyName Sequence SequenceDelta Branch BranchDelta +------------ -------- ------------- ------ ----------- +Microsoft.PowerShell.Security 20.09 -30.12 17.32 -31.63 +Microsoft.PowerShell.Commands.Management 43.39 9.10 43.05 11.59 +System.Management.Automation 45.04 -10.63 41.23 -11.07 +Microsoft.PowerShell.Commands.Utility 21.39 -47.22 20.14 -46.47 +Microsoft.PowerShell.Commands.Diagnostics 0 -51.91 0 -48.62 +Microsoft.PowerShell.ConsoleHost 23.32 -22.28 21.58 -22.47 +pwsh 100 0.00 100 0.00 +Microsoft.WSMan.Management 57.73 48.23 53.02 43.22 +Microsoft.WSMan.Runtime 80.33 -19.67 80.95 -19.05 +Microsoft.PowerShell.CoreCLR.Eventing 2.03 -32.74 1.88 -26.01 +``` + +To get file-specific coverage data, +you can use `Compare-FileCoverage`: + +```powershell +PS> Compare-FileCoverage -ReferenceCoverage $cov2 -DifferenceCoverage $cov1 -FileName LanguagePrimitives.cs + +FileName ReferenceCoverage DifferenceCoverage CoverageDelta +-------- ----------------- ------------------ ------------- +LanguagePrimitives.cs 53.68 69.03 15.34 +``` + +You can see more ways to use `Compare-CodeCoverage` and `Compare-FileCoverage` +by running: + +```powershell +PS> Get-Help Compare-CodeCoverage -Full +# Or +PS> Get-Help Compare-FileCoverage -Full +``` + +## Visualizing code coverage + +For a more detailed, graphical representation of the code coverage results, +you can use the ReportGenerator package. +This generates an HTML report of the coverage from the XML file +and will provide much more detail about the coverage analysis. +The package is available on [NuGet], +and you can install and run it as follows: + +```powershell +# Install ReportGenerator +PS> Find-Package ReportGenerator ` +>> -ProviderName Nuget ` +>> -Source "https://nuget.org/api/v2" ` +>> | Install-Package -Scope CurrentUser + +# Get the ReportGenerator executable path +# Make sure use the appropriate version number in the path +$ReportGenExe = "$HOME\AppData\Local\PackageManagement\NuGet\Packages\ReportGenerator.\tools\ReportGenerator.exe" + +# Run ReportGenerator +& $ReportGenExe -report:coverage.xml -targetdir:C:\temp\Coverage + +# Finally, open the report in your browser +Invoke-Item C:\temp\Coverage\index.htm +``` + +This should open a screen in the browser like this: +![Coverage report browser page](Images/CoverageReportTop.PNG) + +The main report, which is below the summary and risk hot spots, has +a filter functionality as well (when "Enable Filtering" is clicked on): +![Coverage report with filter on](Images/CoverageReportFilter.PNG) + +[OpenCover]: https://github.com/OpenCover/opencover +[codecov.io]: https://codecov.io +[`master`]: https://github.com/PowerShell/PowerShell +[NuGet]: https://nuget.org/packages/ReportGenerator diff --git a/PowerShell-master/docs/testing-guidelines/testing-guidelines.md b/PowerShell-master/docs/testing-guidelines/testing-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..e00c8352ee7b8195fc0b6c147b2f82a216495170 --- /dev/null +++ b/PowerShell-master/docs/testing-guidelines/testing-guidelines.md @@ -0,0 +1,174 @@ +# Testing Guidelines + +Testing is a critical and required part of the PowerShell project. + +The Microsoft PowerShell team created nearly 100,000 tests over the last 12 years which we run as part of the release process for Windows PowerShell. +Having all of those tests available for the initial release of PowerShell was not feasible, +and we have targeted those tests which we believe will provide us the ability to catch regressions in the areas which have had the largest changes for PowerShell. +It is our intent to continue to release more and more of our tests until we have the coverage we need. + +For creating new tests, please review the [documents](https://github.com/PowerShell/PowerShell/tree/master/docs/testing-guidelines) on how to create tests for PowerShell. +There is a best practices document for [writing Pester tests](https://github.com/PowerShell/PowerShell/tree/master/docs/testing-guidelines/WritingPesterTests.md). +When adding new tests, place them in the directories as [outlined below](#test-layout). + +## CI System + +We use [Azure DevOps](https://azure.microsoft.com/en-us/solutions/devops) as a continuous integration (CI) system for Windows +and non-Windows platforms. + +In the `README.md` at the top of the repository, you can see Azure CI badge. +It indicates the last build status of `master` branch. +Hopefully, it's green: + +![AzDevOps-Success.png](Images/AzDevOps-Success.png) + +This badge is **clickable**; you can open corresponding build page with logs, artifacts, and tests results. +From there you can easily navigate to the build history. + +### Getting CI Results + +CI System builds and runs tests on every pull request and provides quick feedback about it. + +![AppVeyor-Github](Images/AppVeyor-Github.png) + +These green check boxes and red crosses are **clickable** as well. +They will bring you to the corresponding page with details. + +## Test Frameworks + +### Pester + +Our script-based test framework is [Pester](https://github.com/Pester/Pester). +This is the framework which we are using internally at Microsoft for new script-based tests, +and a large number of the tests which are part of the PowerShell project have been migrated from that test base. +Pester tests can be used to test most of PowerShell behavior (even some API operations can easily be tested in Pester). + +Substantial changes were required, to get Pester executing on non-Windows systems. +These changes are not yet in the official Pester code base. +Some features of Pester may not be available or may have incorrect behavior. +Please make sure to create issues in [PowerShell/PowerShell](https://github.com/PowerShell/PowerShell/issues) (not Pester) for anything that you find. + +#### Test Tags + +The Pester framework allows `Describe` blocks to be tagged, and our CI system relies on those tags to invoke our tests. + +One of the following tags must be used: + +* `CI` - this tag indicates that the tests in the `Describe` block will be executed as part of the CI/PR process +* `Scenario` - this tag indicates a larger scale test interacting with multiple areas of functionality and/or remote resources, these tests are also run daily. +* `Feature` - tests with this tag will not be executed as part of the CI/PR process, + but they will be executed on a daily basis as part of a `cron` driven build. + They indicate that the test will be validating more behavior, + or will be using remote network resources (ex: package management tests) + +Additionally, the tag: + +* `SLOW` indicates that the test takes a somewhat longer time to execute (97% of our `CI` tests take 100ms or less), a test which takes longer than 1 second should be considered as a candidate for being tagged `Slow` + +#### Requesting additional tests for a PR + +In our CI systems, we normally run only run tests tagged with `CI`. +If in the first line of the last (most recent) commit description you add `[Feature]`, +we will ensure that we will also run the tests tagged with `Feature`. +When you would want to do this: + +- You have added or changed a `Feature` test. +- A maintainer asks you to run the `Feature` tests. +- Based on experience, you are confident that a maintainer will ask you to run the `Feature` tests. + +#### Validating packaging changes for a PR + +By default, our CI system does a build and run tests for a PR and does not exercise code to create a package. +If your PR includes changes to packaging, you can have the CI system exercise the packaging code by +using `[Package]` as the first line in the commit message. +When you would want to do this: + +- You made change to PowerShell Core packaging +- A maintainer asks you to run as `[Package]` + +### xUnit + +For those tests which are not easily run via Pester, we have decided to use [xUnit](https://xunit.net/) as the test framework. +Currently, we have a minuscule number of tests which are run by using xUnit. + +## Running tests outside of CI + +When working on new features or fixes, it is natural to want to run those tests locally before making a PR. +These helper functions are part of the build.psm1 module to help with that: + +* `Start-PSPester` will execute all Pester tests which are run by the CI system +* `Start-PSxUnit` will execute the available xUnit tests run by the CI system + +Our CI system runs these as well; there should be no difference between running these on your dev system, versus in CI. + +When running tests in this way, be sure that you have started PowerShell with `-noprofile` as some tests will fail if the +environment is not the default or has any customization. + +For example, to run all the Pester tests for CI (assuming you are at the root of the PowerShell repo): + +```PowerShell +Import-Module ./build.psm1 +Start-PSPester +``` + +If you wish to run specific tests, that is possible as well: + +```PowerShell +Start-PSPester -Path test/powershell/engine/Api +``` + +Or a specific Pester test file: + +```PowerShell +Start-PSPester -Path test/powershell/engine/Api/XmlAdapter.Tests.ps1 +``` + +### What happens after your PR? + +When your PR has successfully passed the CI test gates, your changes will be used to create PowerShell binaries which can be run +in Microsoft's internal test frameworks. +The tests that you created for your change and the library of historical tests will be run to determine if any regressions are present. +If these tests find regressions, you'll be notified that your PR is not ready, and provided with enough information to investigate why the failure happened. + +## Test Layout + +We have taken a functional approach to the layout of our Pester tests and you should place new tests in their appropriate location. +If you are making a fix to a cmdlet in a module, the test belongs in the module directory. +If you are unsure, you can make it part of your PR, or create an issue. + +The current layout of tests is: + +* test/powershell/engine +* test/powershell/engine/Api +* test/powershell/engine/Basic +* test/powershell/engine/ETS +* test/powershell/engine/Help +* test/powershell/engine/Logging +* test/powershell/engine/Module +* test/powershell/engine/ParameterBinding +* test/powershell/engine/Remoting +* test/powershell/engine/Runspace +* test/powershell/engine/Logging/MessageAnalyzer +* test/powershell/Host +* test/powershell/Host/ConsoleHost +* test/powershell/Host/TabCompletion +* test/powershell/Language +* test/powershell/Modules +* test/powershell/Provider +* test/powershell/SDK +* test/powershell/Security +* test/powershell/Language/Classes +* test/powershell/Language/Interop +* test/powershell/Language/Operators +* test/powershell/Language/Parser +* test/powershell/Language/Interop/DotNet +* test/powershell/Language/Scripting +* test/powershell/Language/Scripting/Debugging +* test/powershell/Language/Scripting/NativeExecution +* test/powershell/Modules/Microsoft.PowerShell.Archive +* test/powershell/Modules/Microsoft.PowerShell.Core +* test/powershell/Modules/Microsoft.PowerShell.Diagnostics +* test/powershell/Modules/Microsoft.PowerShell.Management +* test/powershell/Modules/Microsoft.PowerShell.Security +* test/powershell/Modules/Microsoft.PowerShell.Utility +* test/powershell/Modules/PSReadLine diff --git a/PowerShell-master/dsc/pwsh.profile.dsc.resource.json b/PowerShell-master/dsc/pwsh.profile.dsc.resource.json new file mode 100644 index 0000000000000000000000000000000000000000..aa5f5c29eee61ce4cd2e40800a852c5b09401bc1 --- /dev/null +++ b/PowerShell-master/dsc/pwsh.profile.dsc.resource.json @@ -0,0 +1,126 @@ +{ + "$schema": "https://aka.ms/dsc/schemas/v3/bundled/resource/manifest.json", + "description": "Manage PowerShell profiles.", + "tags": [ + "Linux", + "Windows", + "macOS", + "PowerShell" + ], + "type": "Microsoft.PowerShell/Profile", + "version": "0.1.0", + "get": { + "executable": "pwsh", + "args": [ + "-NoLogo", + "-NonInteractive", + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + "./pwsh.profile.resource.ps1", + "-operation", + "get" + ], + "input": "stdin" + }, + "set": { + "executable": "pwsh", + "args": [ + "-NoLogo", + "-NonInteractive", + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + "./pwsh.profile.resource.ps1", + "-operation", + "set" + ], + "input": "stdin" + }, + "export": { + "executable": "pwsh", + "args": [ + "-NoLogo", + "-NonInteractive", + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + "./pwsh.profile.resource.ps1", + "-operation", + "export" + ], + "input": "stdin" + }, + "exitCodes": { + "0": "Success", + "1": "Error", + "2": "Input not supported for export operation" + }, + "schema": { + "embedded": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Profile", + "description": "Manage PowerShell profiles.", + "type": "object", + "unevaluatedProperties": false, + "required": [ + "profileType" + ], + "properties": { + "profileType": { + "type": "string", + "title": "Profile Type", + "description": "Defines which profile to manage. Valid values are: 'AllUsersCurrentHost', 'AllUsersAllHosts', 'CurrentUserAllHosts', and 'CurrentUserCurrentHost'.", + "enum": [ + "AllUsersCurrentHost", + "AllUsersAllHosts", + "CurrentUserAllHosts", + "CurrentUserCurrentHost" + ] + }, + "profilePath": { + "title": "Profile Path", + "description": "The full path to the profile file.", + "type": "string", + "readOnly": true + }, + "content": { + "title": "Content", + "description": "Defines the content of the profile. If you don't specify this property, the resource doesn't manage the file contents. If you specify this property as an empty string, the resource removes all content from the file. If you specify this property as a non-empty string, the resource sets the file contents to the specified string. The resources retains newlines from this property without any modification.", + "type": [ "string", "null" ] + }, + "_exist": { + "$ref": "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/v3/resource/properties/exist.json" + }, + "_name": { + "$ref": "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/v3/resource/properties/name.json" + } + }, + "$defs": { + "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/v3/resource/properties/exist.json": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/v3/resource/properties/exist.json", + "title": "Instance should exist", + "description": "Indicates whether the DSC resource instance should exist.", + "type": "boolean", + "default": true, + "enum": [ + false, + true + ] + }, + "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/v3/resource/properties/name.json": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/v3/resource/properties/name.json", + "title": "Exported instance name", + "description": "Returns a generated name for the resource instance from an export operation.", + "readOnly": true, + "type": "string" + } + } + } + } +} diff --git a/PowerShell-master/dsc/pwsh.profile.resource.ps1 b/PowerShell-master/dsc/pwsh.profile.resource.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..ad9cfa4a63af38c42faa11d8b436077fc8594f1a --- /dev/null +++ b/PowerShell-master/dsc/pwsh.profile.resource.ps1 @@ -0,0 +1,179 @@ +## Copyright (c) Microsoft Corporation. All rights reserved. +## Licensed under the MIT License. + +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [ValidateSet('get', 'set', 'export')] + [string]$Operation, + [Parameter(ValueFromPipeline)] + [string[]]$UserInput +) + +Begin { + enum ProfileType { + AllUsersCurrentHost + AllUsersAllHosts + CurrentUserAllHosts + CurrentUserCurrentHost + } + + function New-PwshResource { + param( + [Parameter(Mandatory = $true)] + [ProfileType] $ProfileType, + + [Parameter(ParameterSetName = 'WithContent')] + [string] $Content, + + [Parameter(ParameterSetName = 'WithContent')] + [bool] $Exist + ) + + # Create the PSCustomObject with properties + $resource = [PSCustomObject]@{ + profileType = $ProfileType + content = $null + profilePath = GetProfilePath -profileType $ProfileType + _exist = $false + } + + # Add ToJson method + $resource | Add-Member -MemberType ScriptMethod -Name 'ToJson' -Value { + return ([ordered] @{ + profileType = $this.profileType + content = $this.content + profilePath = $this.profilePath + _exist = $this._exist + }) | ConvertTo-Json -Compress -EnumsAsStrings + } + + # Constructor logic - if Content and Exist parameters are provided (WithContent parameter set) + if ($PSCmdlet.ParameterSetName -eq 'WithContent') { + $resource.content = $Content + $resource._exist = $Exist + } else { + # Default constructor logic - read from file system + $fileExists = Test-Path $resource.profilePath + if ($fileExists) { + $resource.content = Get-Content -Path $resource.profilePath + } else { + $resource.content = $null + } + $resource._exist = $fileExists + } + + return $resource + } + + function GetProfilePath { + param ( + [ProfileType] $profileType + ) + + $path = switch ($profileType) { + 'AllUsersCurrentHost' { $PROFILE.AllUsersCurrentHost } + 'AllUsersAllHosts' { $PROFILE.AllUsersAllHosts } + 'CurrentUserAllHosts' { $PROFILE.CurrentUserAllHosts } + 'CurrentUserCurrentHost' { $PROFILE.CurrentUserCurrentHost } + } + + return $path + } + + function ExportOperation { + $allUserCurrentHost = New-PwshResource -ProfileType 'AllUsersCurrentHost' + $allUsersAllHost = New-PwshResource -ProfileType 'AllUsersAllHosts' + $currentUserAllHost = New-PwshResource -ProfileType 'CurrentUserAllHosts' + $currentUserCurrentHost = New-PwshResource -ProfileType 'CurrentUserCurrentHost' + + # Cannot use the ToJson() method here as we are adding a note property + $allUserCurrentHost | Add-Member -NotePropertyName '_name' -NotePropertyValue 'AllUsersCurrentHost' -PassThru | ConvertTo-Json -Compress -EnumsAsStrings + $allUsersAllHost | Add-Member -NotePropertyName '_name' -NotePropertyValue 'AllUsersAllHosts' -PassThru | ConvertTo-Json -Compress -EnumsAsStrings + $currentUserAllHost | Add-Member -NotePropertyName '_name' -NotePropertyValue 'CurrentUserAllHosts' -PassThru | ConvertTo-Json -Compress -EnumsAsStrings + $currentUserCurrentHost | Add-Member -NotePropertyName '_name' -NotePropertyValue 'CurrentUserCurrentHost' -PassThru | ConvertTo-Json -Compress -EnumsAsStrings + } + + function GetOperation { + param ( + [Parameter(Mandatory = $true)] + $InputResource, + [Parameter()] + [switch] $AsJson + ) + + $profilePath = GetProfilePath -profileType $InputResource.profileType.ToString() + + $actualState = New-PwshResource -ProfileType $InputResource.profileType + + $actualState.profilePath = $profilePath + + $exists = Test-Path $profilePath + + if ($InputResource._exist -and $exists) { + $content = Get-Content -Path $profilePath + $actualState.Content = $content + } elseif ($InputResource._exist -and -not $exists) { + $actualState.Content = $null + $actualState._exist = $false + } elseif (-not $InputResource._exist -and $exists) { + $actualState.Content = Get-Content -Path $profilePath + $actualState._exist = $true + } else { + $actualState.Content = $null + $actualState._exist = $false + } + + if ($AsJson) { + return $actualState.ToJson() + } else { + return $actualState + } + } + + function SetOperation { + param ( + $InputResource + ) + + $actualState = GetOperation -InputResource $InputResource + + if ($InputResource._exist) { + if (-not $actualState._exist) { + $null = New-Item -Path $actualState.profilePath -ItemType File -Force + } + + if ($null -ne $InputResource.content) { + Set-Content -Path $actualState.profilePath -Value $InputResource.content + } + } elseif ($actualState._exist) { + Remove-Item -Path $actualState.profilePath -Force + } + } +} +End { + $inputJson = $input | ConvertFrom-Json + + if ($inputJson) { + $InputResource = New-PwshResource -ProfileType $inputJson.profileType -Content $inputJson.content -Exist $inputJson._exist + } + + switch ($Operation) { + 'get' { + GetOperation -InputResource $InputResource -AsJson + } + 'set' { + SetOperation -InputResource $InputResource + } + 'export' { + if ($inputJson) { + Write-Error "Input not supported for export operation" + exit 2 + } + + ExportOperation + } + } + + exit 0 +} diff --git a/PowerShell-master/es-metadata.yml b/PowerShell-master/es-metadata.yml new file mode 100644 index 0000000000000000000000000000000000000000..24da115c11445cc5c876e5f702d07a90ce08456a --- /dev/null +++ b/PowerShell-master/es-metadata.yml @@ -0,0 +1,12 @@ +schemaVersion: 1.0.0 +providers: +- provider: InventoryAsCode + version: 1.0.0 + metadata: + isProduction: true + accountableOwners: + service: cef1de07-99d6-45df-b907-77d0066032ec + routing: + defaultAreaPath: + org: msazure + path: One\MGMT\Compute\Powershell\Powershell\Powershell Core\pwsh diff --git a/PowerShell-master/experimental-feature-linux.json b/PowerShell-master/experimental-feature-linux.json new file mode 100644 index 0000000000000000000000000000000000000000..31f7b965a5b321c77452ed49e3a72500e4935060 --- /dev/null +++ b/PowerShell-master/experimental-feature-linux.json @@ -0,0 +1,9 @@ +[ + "PSFeedbackProvider", + "PSLoadAssemblyFromNativeCode", + "PSNativeWindowsTildeExpansion", + "PSProfileDSCResource", + "PSSerializeJSONLongEnumAsNumber", + "PSRedirectToVariable", + "PSSubsystemPluginModel" +] diff --git a/PowerShell-master/experimental-feature-windows.json b/PowerShell-master/experimental-feature-windows.json new file mode 100644 index 0000000000000000000000000000000000000000..31f7b965a5b321c77452ed49e3a72500e4935060 --- /dev/null +++ b/PowerShell-master/experimental-feature-windows.json @@ -0,0 +1,9 @@ +[ + "PSFeedbackProvider", + "PSLoadAssemblyFromNativeCode", + "PSNativeWindowsTildeExpansion", + "PSProfileDSCResource", + "PSSerializeJSONLongEnumAsNumber", + "PSRedirectToVariable", + "PSSubsystemPluginModel" +] diff --git a/PowerShell-master/global.json b/PowerShell-master/global.json new file mode 100644 index 0000000000000000000000000000000000000000..ef31c0723fffb1f66f3360df2284e1cb324e17f0 --- /dev/null +++ b/PowerShell-master/global.json @@ -0,0 +1,5 @@ +{ + "sdk": { + "version": "11.0.100-preview.2.26159.112" + } +} diff --git a/PowerShell-master/nuget.config b/PowerShell-master/nuget.config new file mode 100644 index 0000000000000000000000000000000000000000..388a65572dd1d20625911c0acb3731dcb6ca9110 --- /dev/null +++ b/PowerShell-master/nuget.config @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/PowerShell-master/src/GlobalTools/PowerShell.Windows.x64/PowerShell.Windows.x64.csproj b/PowerShell-master/src/GlobalTools/PowerShell.Windows.x64/PowerShell.Windows.x64.csproj new file mode 100644 index 0000000000000000000000000000000000000000..8449c58ebb08bb612a7a301d0a13649173a1fb79 --- /dev/null +++ b/PowerShell-master/src/GlobalTools/PowerShell.Windows.x64/PowerShell.Windows.x64.csproj @@ -0,0 +1,33 @@ + + + + Exe + net11.0 + enable + enable + true + win-x64 + pwsh + $(PackageVersion) + true + ../../signing/visualstudiopublic.snk + + + + + + Modules\%(RecursiveDir)\%(FileName)%(Extension) + PreserveNewest + PreserveNewest + + + + + + + + + + + + diff --git a/PowerShell-master/src/GlobalTools/PowerShell.Windows.x64/Powershell_64.png b/PowerShell-master/src/GlobalTools/PowerShell.Windows.x64/Powershell_64.png new file mode 100644 index 0000000000000000000000000000000000000000..cf9b5f06b47b5ebfb752f12a300b2e7c809d932f Binary files /dev/null and b/PowerShell-master/src/GlobalTools/PowerShell.Windows.x64/Powershell_64.png differ diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..2e914a2299a1bf04a048300e46d9be0e105ddae4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Microsoft.Windows.DSC.CoreConfProviders,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs new file mode 100644 index 0000000000000000000000000000000000000000..e794fd929d11499c8ff127b47708bc2d6442a5f7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -0,0 +1,585 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Management.Automation; +using System.Threading; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Async operation base class, it will issue async operation through + /// 1...* CimSession object(s), processing the async results, extended + /// pssemantics operations, and manage the lifecycle of created + /// CimSession object(s). + /// + /// + internal abstract class CimAsyncOperation : IDisposable + { + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + protected CimAsyncOperation() + { + this.moreActionEvent = new ManualResetEventSlim(false); + this.actionQueue = new ConcurrentQueue(); + this._disposed = 0; + this.operationCount = 0; + } + + #endregion + + #region Event handler + + /// + /// + /// Handler used to handle new action event from + /// object. + /// + /// + /// + /// object raised the event + /// + /// Event argument. + protected void NewCmdletActionHandler(object cimSession, CmdletActionEventArgs actionArgs) + { + DebugHelper.WriteLogEx("Disposed {0}, action type = {1}", 0, this.Disposed, actionArgs.Action); + + if (this.Disposed) + { + if (actionArgs.Action is CimSyncAction) + { + // unblock the thread waiting for response + (actionArgs.Action as CimSyncAction).OnComplete(); + } + + return; + } + + bool isEmpty = this.actionQueue.IsEmpty; + this.actionQueue.Enqueue(actionArgs.Action); + if (isEmpty) + { + this.moreActionEvent.Set(); + } + } + + /// + /// + /// Handler used to handle new operation event from + /// object. + /// + /// + /// + /// object raised the event. + /// + /// Event argument. + protected void OperationCreatedHandler(object cimSession, OperationEventArgs actionArgs) + { + DebugHelper.WriteLogEx(); + + lock (this.a_lock) + { + this.operationCount++; + } + } + + /// + /// + /// Handler used to handle operation deletion event from + /// object. + /// + /// + /// + /// object raised the event. + /// + /// Event argument. + protected void OperationDeletedHandler(object cimSession, OperationEventArgs actionArgs) + { + DebugHelper.WriteLogEx(); + + lock (this.a_lock) + { + this.operationCount--; + if (this.operationCount == 0) + { + this.moreActionEvent.Set(); + } + } + } + + #endregion + + /// + /// + /// process all actions in the action queue + /// + /// + /// + /// Wrapper of cmdlet, for details. + /// + public void ProcessActions(CmdletOperationBase cmdletOperation) + { + if (!this.actionQueue.IsEmpty) + { + CimBaseAction action; + while (GetActionAndRemove(out action)) + { + action.Execute(cmdletOperation); + if (this.Disposed) + { + break; + } + } + } + } + + /// + /// + /// Process remaining actions until all operations are completed or + /// current cmdlet is terminated by user. + /// + /// + /// + /// Wrapper of cmdlet, for details. + /// + public void ProcessRemainActions(CmdletOperationBase cmdletOperation) + { + DebugHelper.WriteLogEx(); + + while (true) + { + ProcessActions(cmdletOperation); + if (!this.IsActive()) + { + DebugHelper.WriteLogEx("Either disposed or all operations completed.", 2); + break; + } + + try + { + this.moreActionEvent.Wait(); + this.moreActionEvent.Reset(); + } + catch (ObjectDisposedException ex) + { + // This might happen if this object is being disposed, + // while another thread is processing the remaining actions + DebugHelper.WriteLogEx("moreActionEvent was disposed: {0}.", 2, ex); + break; + } + } + + ProcessActions(cmdletOperation); + } + + #region helper methods + + /// + /// + /// Get action object from action queue. + /// + /// + /// Next action to execute. + /// True indicates there is an valid action, otherwise false. + protected bool GetActionAndRemove(out CimBaseAction action) + { + return this.actionQueue.TryDequeue(out action); + } + + /// + /// + /// Add temporary object to cache. + /// + /// + /// Cimsession wrapper object. + protected void AddCimSessionProxy(CimSessionProxy sessionproxy) + { + lock (cimSessionProxyCacheLock) + { + this.cimSessionProxyCache ??= new List(); + + if (!this.cimSessionProxyCache.Contains(sessionproxy)) + { + this.cimSessionProxyCache.Add(sessionproxy); + } + } + } + + /// + /// + /// Are there active operations? + /// + /// + /// True for having active operations, otherwise false. + protected bool IsActive() + { + DebugHelper.WriteLogEx("Disposed {0}, Operation Count {1}", 2, this.Disposed, this.operationCount); + bool isActive = (!this.Disposed) && (this.operationCount > 0); + return isActive; + } + + /// + /// Create object. + /// + /// + protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy) + { + CimSessionProxy proxy = new(originalProxy); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Create object. + /// + /// + protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy, bool passThru) + { + CimSessionProxy proxy = new CimSessionProxySetCimInstance(originalProxy, passThru); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Create object. + /// + /// + protected CimSessionProxy CreateCimSessionProxy(CimSession session) + { + CimSessionProxy proxy = new(session); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Create object. + /// + /// + protected CimSessionProxy CreateCimSessionProxy(CimSession session, bool passThru) + { + CimSessionProxy proxy = new CimSessionProxySetCimInstance(session, passThru); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Create object, and + /// add the proxy into cache. + /// + /// + protected CimSessionProxy CreateCimSessionProxy(string computerName) + { + CimSessionProxy proxy = new(computerName); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Create object, and + /// add the proxy into cache. + /// + /// + /// + /// + protected CimSessionProxy CreateCimSessionProxy(string computerName, CimInstance cimInstance) + { + CimSessionProxy proxy = new(computerName, cimInstance); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Create object, and + /// add the proxy into cache. + /// + /// + /// + /// + protected CimSessionProxy CreateCimSessionProxy(string computerName, CimInstance cimInstance, bool passThru) + { + CimSessionProxy proxy = new CimSessionProxySetCimInstance(computerName, cimInstance, passThru); + this.SubscribeEventAndAddProxytoCache(proxy); + return proxy; + } + + /// + /// Subscribe event from proxy and add proxy to cache. + /// + /// + protected void SubscribeEventAndAddProxytoCache(CimSessionProxy proxy) + { + this.AddCimSessionProxy(proxy); + SubscribeToCimSessionProxyEvent(proxy); + } + + /// + /// + /// Subscribe to the events issued by . + /// + /// + /// + protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) + { + DebugHelper.WriteLogEx(); + + proxy.OnNewCmdletAction += this.NewCmdletActionHandler; + proxy.OnOperationCreated += this.OperationCreatedHandler; + proxy.OnOperationDeleted += this.OperationDeletedHandler; + } + + /// + /// Retrieve the base object out if wrapped in psobject. + /// + /// + /// + protected object GetBaseObject(object value) + { + if (value is not PSObject psObject) + { + return value; + } + else + { + object baseObject = psObject.BaseObject; + if (baseObject is not object[] arrayObject) + { + return baseObject; + } + else + { + object[] arraybaseObject = new object[arrayObject.Length]; + for (int i = 0; i < arrayObject.Length; i++) + { + arraybaseObject[i] = GetBaseObject(arrayObject[i]); + } + + return arraybaseObject; + } + } + } + + /// + /// Retrieve the reference object or reference array object. + /// The returned object has to be either CimInstance or CImInstance[] type, + /// if not thrown exception. + /// + /// + /// Output the cimtype of the value, either Reference or ReferenceArray. + /// The object. + protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) + { + if (value is PSReference cimReference) + { + object baseObject = GetBaseObject(cimReference.Value); + if (baseObject is not CimInstance cimInstance) + { + return null; + } + + referenceType = CimType.Reference; + return cimInstance; + } + else + { + if (value is not object[] cimReferenceArray) + { + return null; + } + else if (cimReferenceArray[0] is not PSReference) + { + return null; + } + + CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length]; + for (int i = 0; i < cimReferenceArray.Length; i++) + { + if (cimReferenceArray[i] is not PSReference tempCimReference) + { + return null; + } + + object baseObject = GetBaseObject(tempCimReference.Value); + cimInstanceArray[i] = baseObject as CimInstance; + if (cimInstanceArray[i] == null) + { + return null; + } + } + + referenceType = CimType.ReferenceArray; + return cimInstanceArray; + } + } + #endregion + + #region IDisposable + + /// + /// + /// Indicates whether this object was disposed or not + /// + /// + protected bool Disposed + { + get + { + return this._disposed == 1; + } + } + + private int _disposed; + + /// + /// + /// Dispose() calls Dispose(true). + /// Implement IDisposable. Do not make this method virtual. + /// A derived class should not be able to override this method. + /// + /// + public void Dispose() + { + Dispose(true); + + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SuppressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + /// + /// + /// Dispose(bool disposing) executes in two distinct scenarios. + /// If disposing equals true, the method has been called directly + /// or indirectly by a user's code. Managed and unmanaged resources + /// can be disposed. + /// If disposing equals false, the method has been called by the + /// runtime from inside the finalizer and you should not reference + /// other objects. Only unmanaged resources can be disposed. + /// + /// + /// Whether it is directly called. + protected virtual void Dispose(bool disposing) + { + if (Interlocked.CompareExchange(ref this._disposed, 1, 0) == 0) + { + if (disposing) + { + // free managed resources + Cleanup(); + } + // free native resources if there are any + } + } + + /// + /// + /// Clean up managed resources. + /// + /// + private void Cleanup() + { + DebugHelper.WriteLogEx(); + + // unblock thread that waiting for more actions + this.moreActionEvent.Set(); + CimBaseAction action; + while (GetActionAndRemove(out action)) + { + DebugHelper.WriteLog("Action {0}", 2, action); + + if (action is CimSyncAction) + { + // unblock the thread waiting for response + (action as CimSyncAction).OnComplete(); + } + } + + if (this.cimSessionProxyCache != null) + { + List temporaryProxy; + lock (this.cimSessionProxyCache) + { + temporaryProxy = new List(this.cimSessionProxyCache); + this.cimSessionProxyCache.Clear(); + } + + // clean up all proxy objects + foreach (CimSessionProxy proxy in temporaryProxy) + { + DebugHelper.WriteLog("Dispose proxy ", 2); + proxy.Dispose(); + } + } + + this.moreActionEvent.Dispose(); + this.ackedEvent?.Dispose(); + + DebugHelper.WriteLog("Cleanup complete.", 2); + } + + #endregion + + #region private members + + /// + /// Lock object. + /// + private readonly object a_lock = new(); + + /// + /// Number of active operations. + /// + private uint operationCount; + + /// + /// Event to notify ps thread that more action is available. + /// + private readonly ManualResetEventSlim moreActionEvent; + + /// + /// The following is the definition of action queue. + /// The queue holding all actions to be executed in the context of either + /// ProcessRecord or EndProcessing. + /// + private readonly ConcurrentQueue actionQueue; + + /// + /// Lock object. + /// + private readonly object cimSessionProxyCacheLock = new(); + + /// + /// Cache all objects related to + /// the current operation. + /// + private List cimSessionProxyCache; + + #endregion + + #region protected members + /// + /// Event to notify ps thread that either a ACK message sent back + /// or a error happened. Currently only used by + /// . + /// + protected ManualResetEventSlim ackedEvent; + #endregion + + #region const strings + internal const string ComputerNameArgument = @"ComputerName"; + internal const string CimSessionArgument = @"CimSession"; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs new file mode 100644 index 0000000000000000000000000000000000000000..4702e47e2f2bc638d7685e5f7b77d7f686f40fa9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Threading; +using Microsoft.Management.Infrastructure.Options; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Base action class, implemented to write results to pipeline. + /// + internal abstract class CimBaseAction + { + /// + /// Initializes a new instance of the class. + /// + protected CimBaseAction() + { + } + + /// + /// + /// Execute the write operation to given cmdlet object + /// + /// + /// + /// cmdlet wrapper object, to which write result. + /// for details. + /// + public virtual void Execute(CmdletOperationBase cmdlet) + { + } + + /// + /// + /// object that related to current action. + /// It may used by action, such as , + /// since later on action may require namespace, and proxy object to reuse + /// , object. + /// + /// + protected XOperationContextBase Context { get; set; } + } + + /// + /// + /// Synchronous action class, implemented to write results to pipeline + /// and block current thread until the action is completed. + /// + /// + internal class CimSyncAction : CimBaseAction, IDisposable + { + /// + /// Initializes a new instance of the class. + /// + public CimSyncAction() + { + this.completeEvent = new ManualResetEventSlim(false); + this.responseType = CimResponseType.None; + } + + /// + /// + /// Block current thread until action completed + /// + /// + /// Response from user. + public virtual CimResponseType GetResponse() + { + this.Block(); + return responseType; + } + + /// + /// + /// Set the response result. + /// + /// + internal CimResponseType ResponseType + { + set { this.responseType = value; } + } + + /// + /// + /// Call this method when the action is completed or + /// the operation is terminated. + /// + /// + internal virtual void OnComplete() + { + this.completeEvent.Set(); + } + + /// + /// + /// Block current thread. + /// + /// + protected virtual void Block() + { + this.completeEvent.Wait(); + this.completeEvent.Dispose(); + } + + #region members + + /// + /// Action completed event. + /// + private readonly ManualResetEventSlim completeEvent; + + /// + /// Response result. + /// + protected CimResponseType responseType; + + #endregion + + #region IDisposable interface + /// + /// IDisposable interface. + /// + private bool _disposed; + + /// + /// + /// Dispose() calls Dispose(true). + /// Implement IDisposable. Do not make this method virtual. + /// A derived class should not be able to override this method. + /// + /// + public void Dispose() + { + Dispose(true); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SuppressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + /// + /// + /// Dispose(bool disposing) executes in two distinct scenarios. + /// If disposing equals true, the method has been called directly + /// or indirectly by a user's code. Managed and unmanaged resources + /// can be disposed. + /// If disposing equals false, the method has been called by the + /// runtime from inside the finalizer and you should not reference + /// other objects. Only unmanaged resources can be disposed. + /// + /// + /// Whether it is directly called. + protected virtual void Dispose(bool disposing) + { + // Check to see if Dispose has already been called. + if (!this._disposed) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if (disposing) + { + // Dispose managed resources. + this.completeEvent?.Dispose(); + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + + // Note disposing has been done. + _disposed = true; + } + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..89f7478b51380b76ca24de021d765bcac4fd337b --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -0,0 +1,910 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Net; +using System.Text; +using Microsoft.Management.Infrastructure.Options; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + #region Parameter Set Resolving Classes + + /// + /// + /// Define class ParameterDefinitionEntry. + /// + /// + internal class ParameterDefinitionEntry + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + internal ParameterDefinitionEntry(string parameterSetName, bool mandatory) + { + this.IsMandatory = mandatory; + this.ParameterSetName = parameterSetName; + } + + /// + /// Property ParameterSetName. + /// + internal string ParameterSetName { get; } + + /// + /// Whether the parameter is mandatory to the set. + /// + internal bool IsMandatory { get; } + } + + /// + /// + /// Define class ParameterSetEntry. + /// + /// + internal class ParameterSetEntry + { + /// + /// Initializes a new instance of the class. + /// + /// + internal ParameterSetEntry(uint mandatoryParameterCount) + { + this.MandatoryParameterCount = mandatoryParameterCount; + this.IsDefaultParameterSet = false; + reset(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal ParameterSetEntry(ParameterSetEntry toClone) + { + this.MandatoryParameterCount = toClone.MandatoryParameterCount; + this.IsDefaultParameterSet = toClone.IsDefaultParameterSet; + reset(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + internal ParameterSetEntry(uint mandatoryParameterCount, bool isDefault) + { + this.MandatoryParameterCount = mandatoryParameterCount; + this.IsDefaultParameterSet = isDefault; + reset(); + } + + /// + /// Reset the internal status. + /// + internal void reset() + { + this.SetMandatoryParameterCount = this.SetMandatoryParameterCountAtBeginProcess; + this.IsValueSet = this.IsValueSetAtBeginProcess; + } + + /// + /// Property DefaultParameterSet + /// + internal bool IsDefaultParameterSet { get; } + + /// + /// Property MandatoryParameterCount + /// + internal uint MandatoryParameterCount { get; } = 0; + + /// + /// Property IsValueSet + /// + internal bool IsValueSet { get; set; } + + /// + /// Property IsValueSetAtBeginProcess + /// + internal bool IsValueSetAtBeginProcess { get; set; } + + /// + /// Property SetMandatoryParameterCount + /// + internal uint SetMandatoryParameterCount { get; set; } = 0; + + /// + /// Property SetMandatoryParameterCountAtBeginProcess + /// + internal uint SetMandatoryParameterCountAtBeginProcess { get; set; } = 0; + } + + /// + /// Define class ParameterBinder. + /// + internal class ParameterBinder + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + internal ParameterBinder( + Dictionary> parameters, + Dictionary sets) + { + this.CloneParameterEntries(parameters, sets); + } + + #region Two dictionaries used to determine the bound parameter set + + /// + /// Define the parameter definition entries, + /// each parameter may belong a set of parameterSets, each parameter set + /// are defined by a . + /// + private Dictionary> parameterDefinitionEntries; + + /// + /// + /// Define parameter set entries, + /// each cmdlet has a list of parameter set, each has number of mandatory parameters, etc. + /// This data structure is used to track the number of mandatory parameter has been set for + /// current parameterset, whether the parameter set was been set by user. + /// + /// + private Dictionary parameterSetEntries; + + #endregion + + /// + /// + /// Used to remember the set of parameterset were set + /// if any conflict occurred with current parameter, + /// throw exception + /// + /// + private List parametersetNamesList = new(); + + /// + /// Parameter names list. + /// + private readonly List parameterNamesList = new(); + + /// + /// + /// Used to remember the set of parameterset were set before begin process + /// if any conflict occurred with current parameter, + /// throw exception + /// + /// + private List parametersetNamesListAtBeginProcess = new(); + + /// + /// Parameter names list before begin process. + /// + private readonly List parameterNamesListAtBeginProcess = new(); + + /// + /// + /// Reset the status of parameter set entries + /// + /// + internal void reset() + { + foreach (KeyValuePair setEntry in parameterSetEntries) + { + setEntry.Value.reset(); + } + + this.parametersetNamesList.Clear(); + foreach (string parametersetName in this.parametersetNamesListAtBeginProcess) + { + this.parametersetNamesList.Add(parametersetName); + } + + this.parameterNamesList.Clear(); + foreach (string parameterName in this.parameterNamesListAtBeginProcess) + { + this.parameterNamesList.Add(parameterName); + } + } + + /// + /// + /// A given parameter's value was set by cmdlet caller, + /// check and change the status of parameter set, + /// throw exception if confliction occurred + /// + /// + /// + /// Throw if conflict parameter was set. + internal void SetParameter(string parameterName, bool isBeginProcess) + { + DebugHelper.WriteLogEx("ParameterName = {0}, isBeginProcess = {1}", 0, parameterName, isBeginProcess); + + if (this.parameterNamesList.Contains(parameterName)) + { + DebugHelper.WriteLogEx("ParameterName {0} is already bound ", 1, parameterName); + return; + } + else + { + this.parameterNamesList.Add(parameterName); + if (isBeginProcess) + { + this.parameterNamesListAtBeginProcess.Add(parameterName); + } + } + + if (this.parametersetNamesList.Count == 0) + { + List nameset = new(); + foreach (ParameterDefinitionEntry parameterDefinitionEntry in this.parameterDefinitionEntries[parameterName]) + { + DebugHelper.WriteLogEx("parameterset name = '{0}'; mandatory = '{1}'", 1, parameterDefinitionEntry.ParameterSetName, parameterDefinitionEntry.IsMandatory); + ParameterSetEntry psEntry = this.parameterSetEntries[parameterDefinitionEntry.ParameterSetName]; + if (psEntry == null) + continue; + + if (parameterDefinitionEntry.IsMandatory) + { + psEntry.SetMandatoryParameterCount++; + if (isBeginProcess) + { + psEntry.SetMandatoryParameterCountAtBeginProcess++; + } + + DebugHelper.WriteLogEx("parameterset name = '{0}'; SetMandatoryParameterCount = '{1}'", 1, parameterDefinitionEntry.ParameterSetName, psEntry.SetMandatoryParameterCount); + } + + if (!psEntry.IsValueSet) + { + psEntry.IsValueSet = true; + if (isBeginProcess) + { + psEntry.IsValueSetAtBeginProcess = true; + } + } + + nameset.Add(parameterDefinitionEntry.ParameterSetName); + } + + this.parametersetNamesList = nameset; + if (isBeginProcess) + { + this.parametersetNamesListAtBeginProcess = nameset; + } + } + else + { + List nameset = new(); + foreach (ParameterDefinitionEntry entry in this.parameterDefinitionEntries[parameterName]) + { + if (this.parametersetNamesList.Contains(entry.ParameterSetName)) + { + nameset.Add(entry.ParameterSetName); + if (entry.IsMandatory) + { + ParameterSetEntry psEntry = this.parameterSetEntries[entry.ParameterSetName]; + psEntry.SetMandatoryParameterCount++; + if (isBeginProcess) + { + psEntry.SetMandatoryParameterCountAtBeginProcess++; + } + + DebugHelper.WriteLogEx("parameterset name = '{0}'; SetMandatoryParameterCount = '{1}'", + 1, + entry.ParameterSetName, + psEntry.SetMandatoryParameterCount); + } + } + } + + if (nameset.Count == 0) + { + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); + } + else + { + this.parametersetNamesList = nameset; + if (isBeginProcess) + { + this.parametersetNamesListAtBeginProcess = nameset; + } + } + } + } + + /// + /// Get the parameter set name based on current binding results. + /// + /// + internal string GetParameterSet() + { + DebugHelper.WriteLogEx(); + + string boundParameterSetName = null; + string defaultParameterSetName = null; + List noMandatoryParameterSet = new(); + + // Looking for parameter set which have mandatory parameters + foreach (string parameterSetName in this.parameterSetEntries.Keys) + { + ParameterSetEntry entry = this.parameterSetEntries[parameterSetName]; + DebugHelper.WriteLogEx( + "parameterset name = {0}, {1}/{2} mandatory parameters.", + 1, + parameterSetName, + entry.SetMandatoryParameterCount, + entry.MandatoryParameterCount); + + // Ignore the parameter set which has no mandatory parameter firstly + if (entry.MandatoryParameterCount == 0) + { + if (entry.IsDefaultParameterSet) + { + defaultParameterSetName = parameterSetName; + } + + if (entry.IsValueSet) + { + noMandatoryParameterSet.Add(parameterSetName); + } + + continue; + } + + if ((entry.SetMandatoryParameterCount == entry.MandatoryParameterCount) && + this.parametersetNamesList.Contains(parameterSetName)) + { + if (boundParameterSetName != null) + { + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); + } + + boundParameterSetName = parameterSetName; + } + } + + // Looking for parameter set which has no mandatory parameters + if (boundParameterSetName == null) + { + // throw if there are > 1 parameter set + if (noMandatoryParameterSet.Count > 1) + { + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); + } + else if (noMandatoryParameterSet.Count == 1) + { + boundParameterSetName = noMandatoryParameterSet[0]; + } + } + + // Looking for default parameter set + boundParameterSetName ??= defaultParameterSetName; + + // throw if still can not find the parameter set name + if (boundParameterSetName == null) + { + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); + } + + return boundParameterSetName; + } + + /// + /// Deep clone the parameter entries to member variable. + /// + private void CloneParameterEntries( + Dictionary> parameters, + Dictionary sets) + { + this.parameterDefinitionEntries = parameters; + this.parameterSetEntries = new Dictionary(); + foreach (KeyValuePair parameterSet in sets) + { + this.parameterSetEntries.Add(parameterSet.Key, new ParameterSetEntry(parameterSet.Value)); + } + } + } + + #endregion + + /// + /// Base command for all cim cmdlets. + /// + public class CimBaseCommand : Cmdlet, IDisposable + { + #region resolve parameter set name + /// + /// + /// Check set parameters and set ParameterSetName + /// + /// + /// Following are special types to be handled + /// Microsoft.Management.Infrastructure.Options.PacketEncoding + /// Microsoft.Management.Infrastructure.Options.ImpersonationType + /// UInt32 + /// Authentication.None (default value)? + /// ProxyType.None + /// + /// + internal void CheckParameterSet() + { + if (this.parameterBinder != null) + { + try + { + this.ParameterSetName = this.parameterBinder.GetParameterSet(); + } + finally + { + this.parameterBinder.reset(); + } + } + + DebugHelper.WriteLog("current parameterset is: " + this.ParameterSetName, 4); + } + + /// + /// Redirect to parameterBinder to set one parameter. + /// + /// + internal void SetParameter(object value, string parameterName) + { + // Ignore the null value being set, + // Null value could be set by caller unintentionally, + // or by powershell to reset the parameter to default value + // before the next parameter binding, and ProcessRecord call + if (value == null) + { + return; + } + + this.parameterBinder?.SetParameter(parameterName, this.AtBeginProcess); + } + #endregion + + #region constructors + + /// + /// Initializes a new instance of the class. + /// + internal CimBaseCommand() + { + this.disposed = false; + this.parameterBinder = null; + } + + /// + /// Initializes a new instance of the class. + /// + internal CimBaseCommand(Dictionary> parameters, + Dictionary sets) + { + this.disposed = false; + this.parameterBinder = new ParameterBinder(parameters, sets); + } + + #endregion + + #region override functions of Cmdlet + + /// + /// StopProcessing method. + /// + protected override void StopProcessing() + { + Dispose(); + } + + #endregion + + #region IDisposable interface + /// + /// IDisposable interface. + /// + private bool disposed; + + /// + /// + /// Dispose() calls Dispose(true). + /// Implement IDisposable. Do not make this method virtual. + /// A derived class should not be able to override this method. + /// + /// + public void Dispose() + { + Dispose(true); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SuppressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + /// + /// + /// Dispose(bool disposing) executes in two distinct scenarios. + /// If disposing equals true, the method has been called directly + /// or indirectly by a user's code. Managed and unmanaged resources + /// can be disposed. + /// If disposing equals false, the method has been called by the + /// runtime from inside the finalizer and you should not reference + /// other objects. Only unmanaged resources can be disposed. + /// + /// + /// Whether it is directly called. + protected void Dispose(bool disposing) + { + // Check to see if Dispose has already been called. + if (!this.disposed) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if (disposing) + { + DisposeInternal(); + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + + // Note disposing has been done. + disposed = true; + } + } + + /// + /// Clean up resources. + /// + protected virtual void DisposeInternal() + { + // Dispose managed resources. + this.operation?.Dispose(); + } + #endregion + + #region private members + + /// + /// Parameter binder used to resolve parameter set name. + /// + private readonly ParameterBinder parameterBinder; + + /// + /// + /// Async operation handler + /// + /// + private CimAsyncOperation operation; + + /// + /// Lock object. + /// + private readonly object myLock = new(); + + /// + /// This flag is introduced to resolve the parameter set name + /// during process record + /// Whether at begin process time, false means in processrecord. + /// + private bool atBeginProcess = true; + + internal bool AtBeginProcess + { + get + { + return this.atBeginProcess; + } + + set + { + this.atBeginProcess = value; + } + } + #endregion + + #region internal properties + + /// + /// + /// Set object, to which + /// current cmdlet will delegate all operations. + /// + /// + internal CimAsyncOperation AsyncOperation + { + get + { + return this.operation; + } + + set + { + lock (this.myLock) + { + Debug.Assert(this.operation == null, "Caller should verify that operation is null"); + this.operation = value; + } + } + } + + /// + /// + /// Get current ParameterSetName of the cmdlet + /// + /// + internal string ParameterSetName { get; private set; } + + /// + /// Gets/Sets cmdlet operation wrapper object. + /// + internal virtual CmdletOperationBase CmdletOperation + { + get; + set; + } + + /// + /// + /// Throw terminating error + /// + /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + internal void ThrowTerminatingError(Exception exception, string operation) + { + ErrorRecord errorRecord = new(exception, operation, ErrorCategory.InvalidOperation, this); + this.CmdletOperation.ThrowTerminatingError(errorRecord); + } + + #endregion + + #region internal const strings + + /// + /// Alias CN - computer name. + /// + internal const string AliasCN = "CN"; + + /// + /// Alias ServerName - computer name. + /// + internal const string AliasServerName = "ServerName"; + + /// + /// Alias OT - operation timeout. + /// + internal const string AliasOT = "OT"; + + /// + /// Session set name. + /// + internal const string SessionSetName = "SessionSet"; + + /// + /// Computer set name. + /// + internal const string ComputerSetName = "ComputerSet"; + + /// + /// Class name computer set name. + /// + internal const string ClassNameComputerSet = "ClassNameComputerSet"; + + /// + /// Resource Uri computer set name. + /// + internal const string ResourceUriComputerSet = "ResourceUriComputerSet"; + + /// + /// computer set name. + /// + internal const string CimInstanceComputerSet = "CimInstanceComputerSet"; + + /// + /// Query computer set name. + /// + internal const string QueryComputerSet = "QueryComputerSet"; + + /// + /// Class name session set name. + /// + internal const string ClassNameSessionSet = "ClassNameSessionSet"; + + /// + /// Resource Uri session set name. + /// + internal const string ResourceUriSessionSet = "ResourceUriSessionSet"; + + /// + /// session set name. + /// + internal const string CimInstanceSessionSet = "CimInstanceSessionSet"; + + /// + /// Query session set name. + /// + internal const string QuerySessionSet = "QuerySessionSet"; + + /// + /// computer set name. + /// + internal const string CimClassComputerSet = "CimClassComputerSet"; + + /// + /// session set name. + /// + internal const string CimClassSessionSet = "CimClassSessionSet"; + + #region Session related parameter set name + + internal const string ComputerNameSet = "ComputerNameSet"; + internal const string SessionIdSet = "SessionIdSet"; + internal const string InstanceIdSet = "InstanceIdSet"; + internal const string NameSet = "NameSet"; + internal const string CimSessionSet = "CimSessionSet"; + internal const string WSManParameterSet = "WSManParameterSet"; + internal const string DcomParameterSet = "DcomParameterSet"; + internal const string ProtocolNameParameterSet = "ProtocolTypeSet"; + #endregion + + #region register cimindication parameter set name + internal const string QueryExpressionSessionSet = "QueryExpressionSessionSet"; + internal const string QueryExpressionComputerSet = "QueryExpressionComputerSet"; + #endregion + + /// + /// Credential parameter set. + /// + internal const string CredentialParameterSet = "CredentialParameterSet"; + + /// + /// Certificate parameter set. + /// + internal const string CertificateParameterSet = "CertificateParameterSet"; + + /// + /// CimInstance parameter alias. + /// + internal const string AliasCimInstance = "CimInstance"; + + #endregion + + #region internal helper function + + /// + /// + /// Throw invalid AuthenticationType + /// + /// + /// + /// + /// + internal void ThrowInvalidAuthenticationTypeError( + string operationName, + string parameterName, + PasswordAuthenticationMechanism authentication) + { + string message = string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidAuthenticationTypeWithNullCredential, + authentication, + ImpersonatedAuthenticationMechanism.None, + ImpersonatedAuthenticationMechanism.Negotiate, + ImpersonatedAuthenticationMechanism.Kerberos, + ImpersonatedAuthenticationMechanism.NtlmDomain); + PSArgumentOutOfRangeException exception = new( + parameterName, authentication, message); + ThrowTerminatingError(exception, operationName); + } + + /// + /// Throw conflict parameter error. + /// + /// + /// + /// + internal void ThrowConflictParameterWasSet( + string operationName, + string parameterName, + string conflictParameterName) + { + string message = string.Format(CultureInfo.CurrentUICulture, + CimCmdletStrings.ConflictParameterWasSet, + parameterName, conflictParameterName); + PSArgumentException exception = new(message, parameterName); + ThrowTerminatingError(exception, operationName); + } + + /// + /// + /// Throw not found property error + /// + /// + internal void ThrowInvalidProperty( + IEnumerable propertiesList, + string className, + string parameterName, + string operationName, + IDictionary actualValue) + { + StringBuilder propList = new(); + foreach (string property in propertiesList) + { + if (propList.Length > 0) + { + propList.Append(','); + } + + propList.Append(property); + } + + string message = string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.CouldNotFindPropertyFromGivenClass, + className, propList); + PSArgumentOutOfRangeException exception = new( + parameterName, actualValue, message); + ThrowTerminatingError(exception, operationName); + } + + /// + /// Create credentials based on given authentication type and PSCredential. + /// + /// + /// + /// + internal CimCredential CreateCimCredentials(PSCredential psCredentials, + PasswordAuthenticationMechanism passwordAuthentication, + string operationName, + string parameterName) + { + DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, psCredentials, passwordAuthentication, operationName, parameterName); + + CimCredential credentials = null; + if (psCredentials != null) + { + NetworkCredential networkCredential = psCredentials.GetNetworkCredential(); + DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); + credentials = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); + } + else + { + ImpersonatedAuthenticationMechanism impersonatedAuthentication; + switch (passwordAuthentication) + { + case PasswordAuthenticationMechanism.Default: + impersonatedAuthentication = ImpersonatedAuthenticationMechanism.None; + break; + case PasswordAuthenticationMechanism.Negotiate: + impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Negotiate; + break; + case PasswordAuthenticationMechanism.Kerberos: + impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Kerberos; + break; + case PasswordAuthenticationMechanism.NtlmDomain: + impersonatedAuthentication = ImpersonatedAuthenticationMechanism.NtlmDomain; + break; + default: + ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication); + return null; + } + + credentials = new CimCredential(impersonatedAuthentication); + } + + DebugHelper.WriteLogEx("return credential {0}", 1, credentials); + return credentials; + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs new file mode 100644 index 0000000000000000000000000000000000000000..0ab4988c57dd711d1c41ef572418f23a3484851d --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System.Collections.Generic; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Implements operations of get-AssociatedInstance cmdlet. + /// + /// + internal sealed class CimGetAssociatedInstance : CimAsyncOperation + { + /// + /// Initializes a new instance of the class. + /// + public CimGetAssociatedInstance() + : base() + { + } + + /// + /// + /// Base on parametersetName to retrieve associated ciminstances + /// + /// + /// object. + public void GetCimAssociatedInstance(GetCimAssociatedInstanceCommand cmdlet) + { + IEnumerable computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); + // use the namespace from parameter + string nameSpace = cmdlet.Namespace; + if ((nameSpace == null) && (cmdlet.ResourceUri == null)) + { + // try to use namespace of ciminstance, then fall back to default namespace + nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace); + } + + List proxys = new(); + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ComputerSetName: + foreach (string computerName in computerNames) + { + CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet); + proxys.Add(proxy); + } + + break; + case CimBaseCommand.SessionSetName: + foreach (CimSession session in cmdlet.CimSession) + { + CimSessionProxy proxy = CreateSessionProxy(session, cmdlet); + proxys.Add(proxy); + } + + break; + default: + return; + } + + foreach (CimSessionProxy proxy in proxys) + { + proxy.EnumerateAssociatedInstancesAsync( + nameSpace, + cmdlet.CimInstance, + cmdlet.Association, + cmdlet.ResultClassName, + null, + null); + } + } + + #region private methods + + /// + /// + /// Set properties + /// + /// + /// + /// + private static void SetSessionProxyProperties( + ref CimSessionProxy proxy, + GetCimAssociatedInstanceCommand cmdlet) + { + proxy.OperationTimeout = cmdlet.OperationTimeoutSec; + proxy.KeyOnly = cmdlet.KeyOnly; + if (cmdlet.ResourceUri != null) + { + proxy.ResourceUri = cmdlet.ResourceUri; + } + } + + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + string computerName, + CimInstance cimInstance, + GetCimAssociatedInstanceCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + CimSession session, + GetCimAssociatedInstanceCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(session); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + #endregion + + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs new file mode 100644 index 0000000000000000000000000000000000000000..c775325094b71eeac1deac1b7ba74034eaeee98f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -0,0 +1,208 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System.Collections.Generic; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Containing all information originated from + /// the parameters of + /// + internal class CimGetCimClassContext : XOperationContextBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + internal CimGetCimClassContext( + string theClassName, + string theMethodName, + string thePropertyName, + string theQualifierName) + { + this.ClassName = theClassName; + this.MethodName = theMethodName; + this.PropertyName = thePropertyName; + this.QualifierName = theQualifierName; + } + + /// + /// + /// The following is the definition of the input parameter "ClassName". + /// + /// + /// Wildcard expansion should be allowed. + /// + /// + public string ClassName { get; set; } + + /// + /// + /// The following is the definition of the input parameter "MethodName", + /// Which may contains wildchar. + /// Then Filter the by given methodname + /// + /// + internal string MethodName { get; } + + /// + /// + /// The following is the definition of the input parameter "PropertyName", + /// Which may contains wildchar. + /// Filter the by given property name. + /// + /// + internal string PropertyName { get; } + + /// + /// + /// The following is the definition of the input parameter "QualifierName", + /// Which may contains wildchar. + /// Filter the by given methodname + /// + /// + internal string QualifierName { get; } + } + + /// + /// + /// Implements operations of get-cimclass cmdlet. + /// + /// + internal sealed class CimGetCimClass : CimAsyncOperation + { + /// + /// Initializes a new instance of the class. + /// + public CimGetCimClass() + : base() + { + } + + /// + /// + /// Base on parametersetName to retrieve + /// + /// + /// object. + public void GetCimClass(GetCimClassCommand cmdlet) + { + List proxys = new(); + string nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); + string className = cmdlet.ClassName ?? @"*"; + CimGetCimClassContext context = new( + cmdlet.ClassName, + cmdlet.MethodName, + cmdlet.PropertyName, + cmdlet.QualifierName); + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ComputerSetName: + { + IEnumerable computerNames = ConstValue.GetComputerNames( + cmdlet.ComputerName); + foreach (string computerName in computerNames) + { + CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet); + proxy.ContextObject = context; + proxys.Add(proxy); + } + } + + break; + case CimBaseCommand.SessionSetName: + { + foreach (CimSession session in cmdlet.CimSession) + { + CimSessionProxy proxy = CreateSessionProxy(session, cmdlet); + proxy.ContextObject = context; + proxys.Add(proxy); + } + } + + break; + default: + return; + } + + if (WildcardPattern.ContainsWildcardCharacters(className)) + { + // retrieve all classes and then filter based on + // classname, propertyname, methodname, and qualifiername + foreach (CimSessionProxy proxy in proxys) + { + proxy.EnumerateClassesAsync(nameSpace); + } + } + else + { + foreach (CimSessionProxy proxy in proxys) + { + proxy.GetClassAsync(nameSpace, className); + } + } + } + + #region private methods + + /// + /// + /// Set properties + /// + /// + /// + /// + private static void SetSessionProxyProperties( + ref CimSessionProxy proxy, + GetCimClassCommand cmdlet) + { + proxy.OperationTimeout = cmdlet.OperationTimeoutSec; + proxy.Amended = cmdlet.Amended; + } + + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + string computerName, + GetCimClassCommand cmdlet) + { + CimSessionProxy proxy = new CimSessionProxyGetCimClass(computerName); + this.SubscribeEventAndAddProxytoCache(proxy); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + CimSession session, + GetCimClassCommand cmdlet) + { + CimSessionProxy proxy = new CimSessionProxyGetCimClass(session); + this.SubscribeEventAndAddProxytoCache(proxy); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + #endregion + + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs new file mode 100644 index 0000000000000000000000000000000000000000..371b06d9356db8825898923bac7dce84d4d6336e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; +using System.Text; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// A class used to add pstypename to partial ciminstance + /// for , if -KeyOnly + /// or -SelectProperties is been specified, then add a pstypename: + /// "Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance" + /// + internal class FormatPartialCimInstance : IObjectPreProcess + { + /// + /// Partial ciminstance pstypename. + /// + internal const string PartialPSTypeName = @"Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance"; + + /// + /// Add pstypename to the resultobject if necessary. + /// + /// + /// + public object Process(object resultObject) + { + if (resultObject is CimInstance) + { + PSObject obj = PSObject.AsPSObject(resultObject); + obj.TypeNames.Insert(0, PartialPSTypeName); + return obj; + } + + return resultObject; + } + } + + /// + /// + /// Implements operations of get-ciminstance cmdlet. + /// + /// + internal class CimGetInstance : CimAsyncOperation + { + /// + /// Initializes a new instance of the class. + /// + /// Constructor + /// + /// + public CimGetInstance() : base() + { + } + + /// + /// + /// Base on parametersetName to retrieve ciminstances + /// + /// + /// object. + public void GetCimInstance(GetCimInstanceCommand cmdlet) + { + GetCimInstanceInternal(cmdlet); + } + + /// + /// + /// Refactor to be reused by Get-CimInstance;Remove-CimInstance;Set-CimInstance + /// + /// + /// + protected void GetCimInstanceInternal(CimBaseCommand cmdlet) + { + IEnumerable computerNames = ConstValue.GetComputerNames( + GetComputerName(cmdlet)); + string nameSpace; + List proxys = new(); + bool isGetCimInstanceCommand = cmdlet is GetCimInstanceCommand; + CimInstance targetCimInstance = null; + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimInstanceComputerSet: + foreach (string computerName in computerNames) + { + targetCimInstance = GetCimInstanceParameter(cmdlet); + CimSessionProxy proxy = CreateSessionProxy(computerName, targetCimInstance, cmdlet); + if (isGetCimInstanceCommand) + { + SetPreProcess(proxy, cmdlet as GetCimInstanceCommand); + } + + proxys.Add(proxy); + } + + break; + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.QueryComputerSet: + case CimBaseCommand.ResourceUriComputerSet: + foreach (string computerName in computerNames) + { + CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet); + if (isGetCimInstanceCommand) + { + SetPreProcess(proxy, cmdlet as GetCimInstanceCommand); + } + + proxys.Add(proxy); + } + + break; + case CimBaseCommand.ClassNameSessionSet: + case CimBaseCommand.CimInstanceSessionSet: + case CimBaseCommand.QuerySessionSet: + case CimBaseCommand.ResourceUriSessionSet: + foreach (CimSession session in GetCimSession(cmdlet)) + { + CimSessionProxy proxy = CreateSessionProxy(session, cmdlet); + if (isGetCimInstanceCommand) + { + SetPreProcess(proxy, cmdlet as GetCimInstanceCommand); + } + + proxys.Add(proxy); + } + + break; + default: + break; + } + + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.ClassNameSessionSet: + nameSpace = ConstValue.GetNamespace(GetNamespace(cmdlet)); + if (IsClassNameQuerySet(cmdlet)) + { + string query = CreateQuery(cmdlet); + DebugHelper.WriteLogEx(@"Query = {0}", 1, query); + foreach (CimSessionProxy proxy in proxys) + { + proxy.QueryInstancesAsync(nameSpace, + ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)), + query); + } + } + else + { + foreach (CimSessionProxy proxy in proxys) + { + proxy.EnumerateInstancesAsync(nameSpace, GetClassName(cmdlet)); + } + } + + break; + case CimBaseCommand.CimInstanceComputerSet: + case CimBaseCommand.CimInstanceSessionSet: + { + CimInstance instance = GetCimInstanceParameter(cmdlet); + nameSpace = ConstValue.GetNamespace(instance.CimSystemProperties.Namespace); + foreach (CimSessionProxy proxy in proxys) + { + proxy.GetInstanceAsync(nameSpace, instance); + } + } + + break; + case CimBaseCommand.QueryComputerSet: + case CimBaseCommand.QuerySessionSet: + nameSpace = ConstValue.GetNamespace(GetNamespace(cmdlet)); + foreach (CimSessionProxy proxy in proxys) + { + proxy.QueryInstancesAsync(nameSpace, + ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)), + GetQuery(cmdlet)); + } + + break; + case CimBaseCommand.ResourceUriSessionSet: + case CimBaseCommand.ResourceUriComputerSet: + foreach (CimSessionProxy proxy in proxys) + { + proxy.EnumerateInstancesAsync(GetNamespace(cmdlet), GetClassName(cmdlet)); + } + + break; + default: + break; + } + } + + #region bridge methods to read properties from cmdlet + + protected static string[] GetComputerName(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).ComputerName; + } + else if (cmdlet is RemoveCimInstanceCommand) + { + return (cmdlet as RemoveCimInstanceCommand).ComputerName; + } + else if (cmdlet is SetCimInstanceCommand) + { + return (cmdlet as SetCimInstanceCommand).ComputerName; + } + + return null; + } + + protected static string GetNamespace(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).Namespace; + } + else if (cmdlet is RemoveCimInstanceCommand) + { + return (cmdlet as RemoveCimInstanceCommand).Namespace; + } + else if (cmdlet is SetCimInstanceCommand) + { + return (cmdlet as SetCimInstanceCommand).Namespace; + } + + return null; + } + + protected static CimSession[] GetCimSession(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).CimSession; + } + else if (cmdlet is RemoveCimInstanceCommand) + { + return (cmdlet as RemoveCimInstanceCommand).CimSession; + } + else if (cmdlet is SetCimInstanceCommand) + { + return (cmdlet as SetCimInstanceCommand).CimSession; + } + + return null; + } + + protected static string GetClassName(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).ClassName; + } + + return null; + } + + protected static string GetQuery(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).Query; + } + else if (cmdlet is RemoveCimInstanceCommand) + { + return (cmdlet as RemoveCimInstanceCommand).Query; + } + else if (cmdlet is SetCimInstanceCommand) + { + return (cmdlet as SetCimInstanceCommand).Query; + } + + return null; + } + + internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) + { + DebugHelper.WriteLogEx(); + if (cmdlet is GetCimInstanceCommand cmd) + { + if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null) + { + return true; + } + } + + return false; + } + + protected static string CreateQuery(CimBaseCommand cmdlet) + { + DebugHelper.WriteLogEx(); + if (cmdlet is GetCimInstanceCommand cmd) + { + StringBuilder propertyList = new(); + if (cmd.SelectProperties == null) + { + propertyList.Append('*'); + } + else + { + foreach (string property in cmd.SelectProperties) + { + if (propertyList.Length > 0) + { + propertyList.Append(','); + } + + propertyList.Append(property); + } + } + + return (cmd.Filter == null) ? + string.Format(CultureInfo.CurrentUICulture, queryWithoutWhere, propertyList, cmd.ClassName) : + string.Format(CultureInfo.CurrentUICulture, queryWithWhere, propertyList, cmd.ClassName, cmd.Filter); + } + + return null; + } + + protected static string GetQueryDialect(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).QueryDialect; + } + else if (cmdlet is RemoveCimInstanceCommand) + { + return (cmdlet as RemoveCimInstanceCommand).QueryDialect; + } + else if (cmdlet is SetCimInstanceCommand) + { + return (cmdlet as SetCimInstanceCommand).QueryDialect; + } + + return null; + } + + protected static CimInstance GetCimInstanceParameter(CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + return (cmdlet as GetCimInstanceCommand).CimInstance; + } + else if (cmdlet is RemoveCimInstanceCommand) + { + return (cmdlet as RemoveCimInstanceCommand).CimInstance; + } + else if (cmdlet is SetCimInstanceCommand) + { + return (cmdlet as SetCimInstanceCommand).CimInstance; + } + + return null; + } + #endregion + + #region help methods + + /// + /// + /// Set properties + /// + /// + /// + /// + private static void SetSessionProxyProperties( + ref CimSessionProxy proxy, + CimBaseCommand cmdlet) + { + if (cmdlet is GetCimInstanceCommand) + { + GetCimInstanceCommand getCimInstance = cmdlet as GetCimInstanceCommand; + proxy.KeyOnly = getCimInstance.KeyOnly; + proxy.Shallow = getCimInstance.Shallow; + proxy.OperationTimeout = getCimInstance.OperationTimeoutSec; + if (getCimInstance.ResourceUri != null) + { + proxy.ResourceUri = getCimInstance.ResourceUri; + } + } + else if (cmdlet is RemoveCimInstanceCommand) + { + RemoveCimInstanceCommand removeCimInstance = cmdlet as RemoveCimInstanceCommand; + proxy.OperationTimeout = removeCimInstance.OperationTimeoutSec; + if (removeCimInstance.ResourceUri != null) + { + proxy.ResourceUri = removeCimInstance.ResourceUri; + } + + CimRemoveCimInstanceContext context = new( + ConstValue.GetNamespace(removeCimInstance.Namespace), + proxy); + proxy.ContextObject = context; + } + else if (cmdlet is SetCimInstanceCommand) + { + SetCimInstanceCommand setCimInstance = cmdlet as SetCimInstanceCommand; + proxy.OperationTimeout = setCimInstance.OperationTimeoutSec; + if (setCimInstance.ResourceUri != null) + { + proxy.ResourceUri = setCimInstance.ResourceUri; + } + + CimSetCimInstanceContext context = new( + ConstValue.GetNamespace(setCimInstance.Namespace), + setCimInstance.Property, + proxy, + cmdlet.ParameterSetName, + setCimInstance.PassThru); + proxy.ContextObject = context; + } + } + + /// + /// + /// Create and set properties. + /// + /// + /// + /// + /// + protected CimSessionProxy CreateSessionProxy( + string computerName, + CimBaseCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// + /// Create and set properties. + /// + /// + /// + /// + /// + /// + protected CimSessionProxy CreateSessionProxy( + string computerName, + CimInstance cimInstance, + CimBaseCommand cmdlet, + bool passThru) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance, passThru); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + protected CimSessionProxy CreateSessionProxy( + CimSession session, + CimBaseCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(session); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + /// + protected CimSessionProxy CreateSessionProxy( + string computerName, + CimInstance cimInstance, + CimBaseCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + protected CimSessionProxy CreateSessionProxy( + CimSession session, + CimBaseCommand cmdlet, + bool passThru) + { + CimSessionProxy proxy = CreateCimSessionProxy(session, passThru); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Set object to proxy to pre-process + /// the result object if necessary. + /// + /// + /// + private static void SetPreProcess(CimSessionProxy proxy, GetCimInstanceCommand cmdlet) + { + if (cmdlet.KeyOnly || (cmdlet.SelectProperties != null)) + { + proxy.ObjectPreProcess = new FormatPartialCimInstance(); + } + } + #endregion + + #region const strings + /// + /// Wql query format with where clause. + /// + private const string queryWithWhere = @"SELECT {0} FROM {1} WHERE {2}"; + + /// + /// Wql query format without where clause. + /// + private const string queryWithoutWhere = @"SELECT {0} FROM {1}"; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs new file mode 100644 index 0000000000000000000000000000000000000000..899e67495cc06e5af57d90f59386c79ebdc3843f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -0,0 +1,382 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.ComponentModel; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Abstract Cimindication event args, which containing all elements related to + /// an Cimindication. + /// + /// + public abstract class CimIndicationEventArgs : EventArgs + { + /// + /// + /// Returns an Object value for an operation context + /// + /// + public object Context + { + get + { + return context; + } + } + + internal object context; + } + + /// + /// Cimindication exception event args, which containing occurred exception. + /// + public class CimIndicationEventExceptionEventArgs : CimIndicationEventArgs + { + /// + /// + /// Returns an exception + /// + /// + public Exception Exception { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public CimIndicationEventExceptionEventArgs(Exception theException) + { + context = null; + this.Exception = theException; + } + } + + /// + /// Cimindication event args, which containing all elements related to + /// an Cimindication. + /// + public class CimIndicationEventInstanceEventArgs : CimIndicationEventArgs + { + /// + /// Get ciminstance of the indication object. + /// + public CimInstance NewEvent + { + get + { + return result?.Instance; + } + } + + /// + /// Get MachineId of the indication object. + /// + public string MachineId + { + get + { + return result?.MachineId; + } + } + + /// + /// Get BookMark of the indication object. + /// + public string Bookmark + { + get + { + return result?.Bookmark; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CimIndicationEventInstanceEventArgs(CimSubscriptionResult result) + { + context = null; + this.result = result; + } + + /// + /// + /// subscription result + /// + /// + private readonly CimSubscriptionResult result; + } + + /// + /// + /// A public class used to start/stop the subscription to specific indication source, + /// and listen to the incoming indications, event + /// will be raised for each cimindication. + /// + /// + public class CimIndicationWatcher + { + /// + /// Status of object. + /// + internal enum Status + { + Default, + Started, + Stopped + } + + /// + /// + /// CimIndication arrived event + /// + /// + public event EventHandler CimIndicationArrived; + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + public CimIndicationWatcher( + string computerName, + string theNamespace, + string queryDialect, + string queryExpression, + uint operationTimeout) + { + ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); + computerName = ConstValue.GetComputerName(computerName); + theNamespace = ConstValue.GetNamespace(theNamespace); + Initialize(computerName, null, theNamespace, queryDialect, queryExpression, operationTimeout); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + public CimIndicationWatcher( + CimSession cimSession, + string theNamespace, + string queryDialect, + string queryExpression, + uint operationTimeout) + { + ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); + ValidationHelper.ValidateNoNullArgument(cimSession, cimSessionParameterName); + theNamespace = ConstValue.GetNamespace(theNamespace); + Initialize(null, cimSession, theNamespace, queryDialect, queryExpression, operationTimeout); + } + + /// + /// + /// Initialize + /// + /// + private void Initialize( + string theComputerName, + CimSession theCimSession, + string theNameSpace, + string theQueryDialect, + string theQueryExpression, + uint theOperationTimeout) + { + enableRaisingEvents = false; + status = Status.Default; + myLock = new object(); + cimRegisterCimIndication = new CimRegisterCimIndication(); + cimRegisterCimIndication.OnNewSubscriptionResult += NewSubscriptionResultHandler; + + this.cimSession = theCimSession; + this.nameSpace = theNameSpace; + this.queryDialect = ConstValue.GetQueryDialectWithDefault(theQueryDialect); + this.queryExpression = theQueryExpression; + this.operationTimeout = theOperationTimeout; + this.computerName = theComputerName; + } + + /// + /// + /// Handler of new subscription result + /// + /// + /// + /// + private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs args) + { + EventHandler temp = this.CimIndicationArrived; + if (temp != null) + { + // raise the event + if (args is CimSubscriptionResultEventArgs resultArgs) + temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result)); + else if (args is CimSubscriptionExceptionEventArgs exceptionArgs) + { + temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); + } + } + } + + /// + /// + /// Will be called by admin\monad\src\eengine\EventManager.cs: + /// PSEventManager::ProcessNewSubscriber to start to listen to the Cim Indication. + /// + /// + /// If set EnableRaisingEvents to false, which will be ignored + /// + /// + [Browsable(false)] + public bool EnableRaisingEvents + { + get + { + return enableRaisingEvents; + } + + set + { + DebugHelper.WriteLogEx(); + if (value && !enableRaisingEvents) + { + enableRaisingEvents = value; + Start(); + } + } + } + + private bool enableRaisingEvents; + + /// + /// + /// Start the subscription + /// + /// + public void Start() + { + DebugHelper.WriteLogEx(); + + lock (myLock) + { + if (status == Status.Default) + { + if (this.cimSession == null) + { + cimRegisterCimIndication.RegisterCimIndication( + this.computerName, + this.nameSpace, + this.queryDialect, + this.queryExpression, + this.operationTimeout); + } + else + { + cimRegisterCimIndication.RegisterCimIndication( + this.cimSession, + this.nameSpace, + this.queryDialect, + this.queryExpression, + this.operationTimeout); + } + + status = Status.Started; + } + } + } + + /// + /// + /// Unsubscribe the subscription + /// + /// + public void Stop() + { + DebugHelper.WriteLogEx("Status = {0}", 0, this.status); + + lock (this.myLock) + { + if (status == Status.Started) + { + if (this.cimRegisterCimIndication != null) + { + DebugHelper.WriteLog("Dispose CimRegisterCimIndication object", 4); + this.cimRegisterCimIndication.Dispose(); + } + + status = Status.Stopped; + } + } + } + + #region internal method + /// + /// Set the cmdlet object to throw ThrowTerminatingError + /// in case there is a subscription failure. + /// + /// + internal void SetCmdlet(Cmdlet cmdlet) + { + if (this.cimRegisterCimIndication != null) + { + this.cimRegisterCimIndication.Cmdlet = cmdlet; + } + } + #endregion + + #region private members + /// + /// + /// CimRegisterCimIndication object + /// + /// + private CimRegisterCimIndication cimRegisterCimIndication; + + /// + /// The status of object. + /// + private Status status; + + /// + /// Lock started field. + /// + private object myLock; + + /// + /// CimSession parameter name. + /// + private const string cimSessionParameterName = "cimSession"; + + /// + /// QueryExpression parameter name. + /// + private const string queryExpressionParameterName = "queryExpression"; + + #region parameters + /// + /// + /// parameters used to start the subscription + /// + /// + private string computerName; + private CimSession cimSession; + private string nameSpace; + private string queryDialect; + private string queryExpression; + private uint operationTimeout; + #endregion + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs new file mode 100644 index 0000000000000000000000000000000000000000..50f4d12dd7468ace07963abcfbddae450b9563eb --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -0,0 +1,453 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Implements operations of invoke-cimmethod cmdlet. + /// + /// + internal sealed class CimInvokeCimMethod : CimAsyncOperation + { + /// + /// Containing all necessary information originated from + /// the parameters of + /// + internal class CimInvokeCimMethodContext : XOperationContextBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + internal CimInvokeCimMethodContext(string theNamespace, + string theMethodName, + CimMethodParametersCollection theCollection, + CimSessionProxy theProxy) + { + this.proxy = theProxy; + this.MethodName = theMethodName; + this.ParametersCollection = theCollection; + this.nameSpace = theNamespace; + } + + /// + /// namespace + /// + internal string MethodName { get; } + + /// + /// parameters collection + /// + internal CimMethodParametersCollection ParametersCollection { get; } + } + + /// + /// Initializes a new instance of the class. + /// + public CimInvokeCimMethod() + : base() + { + } + + /// + /// + /// Base on parametersetName to retrieve ciminstances + /// + /// + /// object. + public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) + { + IEnumerable computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); + string nameSpace; + List proxys = new(); + string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cmdlet.MethodName); + + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimInstanceComputerSet: + foreach (string computerName in computerNames) + { + proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet)); + } + + break; + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.CimClassComputerSet: + case CimBaseCommand.ResourceUriComputerSet: + case CimBaseCommand.QueryComputerSet: + foreach (string computerName in computerNames) + { + proxys.Add(CreateSessionProxy(computerName, cmdlet)); + } + + break; + case CimBaseCommand.ClassNameSessionSet: + case CimBaseCommand.CimClassSessionSet: + case CimBaseCommand.QuerySessionSet: + case CimBaseCommand.CimInstanceSessionSet: + case CimBaseCommand.ResourceUriSessionSet: + foreach (CimSession session in cmdlet.CimSession) + { + CimSessionProxy proxy = CreateSessionProxy(session, cmdlet); + proxys.Add(proxy); + } + + break; + default: + break; + } + + CimMethodParametersCollection paramsCollection = + CreateParametersCollection(cmdlet.Arguments, cmdlet.CimClass, cmdlet.CimInstance, cmdlet.MethodName); + + // Invoke methods + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.ClassNameSessionSet: + case CimBaseCommand.ResourceUriSessionSet: + case CimBaseCommand.ResourceUriComputerSet: + { + string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.ClassName); + if (cmdlet.ResourceUri != null) + { + nameSpace = cmdlet.Namespace; + } + else + { + nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); + } + + foreach (CimSessionProxy proxy in proxys) + { + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + proxy.InvokeMethodAsync( + nameSpace, + cmdlet.ClassName, + cmdlet.MethodName, + paramsCollection); + } + } + + break; + case CimBaseCommand.CimClassComputerSet: + case CimBaseCommand.CimClassSessionSet: + { + string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.CimClass.CimSystemProperties.ClassName); + nameSpace = ConstValue.GetNamespace(cmdlet.CimClass.CimSystemProperties.Namespace); + foreach (CimSessionProxy proxy in proxys) + { + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + proxy.InvokeMethodAsync( + nameSpace, + cmdlet.CimClass.CimSystemProperties.ClassName, + cmdlet.MethodName, + paramsCollection); + } + } + + break; + case CimBaseCommand.QueryComputerSet: + case CimBaseCommand.QuerySessionSet: + nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); + foreach (CimSessionProxy proxy in proxys) + { + // create context object + CimInvokeCimMethodContext context = new( + nameSpace, + cmdlet.MethodName, + paramsCollection, + proxy); + proxy.ContextObject = context; + // firstly query instance and then invoke method upon returned instances + proxy.QueryInstancesAsync(nameSpace, ConstValue.GetQueryDialectWithDefault(cmdlet.QueryDialect), cmdlet.Query); + } + + break; + case CimBaseCommand.CimInstanceComputerSet: + case CimBaseCommand.CimInstanceSessionSet: + { + string target = cmdlet.CimInstance.ToString(); + if (cmdlet.ResourceUri != null) + { + nameSpace = cmdlet.Namespace; + } + else + { + nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace); + } + + foreach (CimSessionProxy proxy in proxys) + { + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + proxy.InvokeMethodAsync( + nameSpace, + cmdlet.CimInstance, + cmdlet.MethodName, + paramsCollection); + } + } + + break; + default: + break; + } + } + + /// + /// + /// Invoke cimmethod on given + /// + /// + /// + public void InvokeCimMethodOnCimInstance(CimInstance cimInstance, XOperationContextBase context, CmdletOperationBase operation) + { + DebugHelper.WriteLogEx(); + CimInvokeCimMethodContext cimInvokeCimMethodContext = context as CimInvokeCimMethodContext; + Debug.Assert(cimInvokeCimMethodContext != null, "CimInvokeCimMethod::InvokeCimMethodOnCimInstance should has CimInvokeCimMethodContext != NULL."); + + string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cimInvokeCimMethodContext.MethodName); + if (!operation.ShouldProcess(cimInstance.ToString(), action)) + { + return; + } + + CimSessionProxy proxy = CreateCimSessionProxy(cimInvokeCimMethodContext.Proxy); + proxy.InvokeMethodAsync( + cimInvokeCimMethodContext.Namespace, + cimInstance, + cimInvokeCimMethodContext.MethodName, + cimInvokeCimMethodContext.ParametersCollection); + } + + #region private methods + + /// + /// + /// Set properties + /// + /// + /// + /// + private static void SetSessionProxyProperties( + ref CimSessionProxy proxy, + InvokeCimMethodCommand cmdlet) + { + proxy.OperationTimeout = cmdlet.OperationTimeoutSec; + if (cmdlet.ResourceUri != null) + { + proxy.ResourceUri = cmdlet.ResourceUri; + } + } + + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + string computerName, + InvokeCimMethodCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + string computerName, + CimInstance cimInstance, + InvokeCimMethodCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + CimSession session, + InvokeCimMethodCommand cmdlet) + { + CimSessionProxy proxy = CreateCimSessionProxy(session); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// + /// Create with given key properties. + /// And/or object. + /// + /// + /// + /// + /// + /// + /// + /// See CimProperty.Create. + /// CimProperty.Create. + private CimMethodParametersCollection CreateParametersCollection( + IDictionary parameters, + CimClass cimClass, + CimInstance cimInstance, + string methodName) + { + DebugHelper.WriteLogEx(); + + CimMethodParametersCollection collection = null; + if (parameters == null) + { + return collection; + } + else if (parameters.Count == 0) + { + return collection; + } + + collection = new CimMethodParametersCollection(); + IDictionaryEnumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + string parameterName = enumerator.Key.ToString(); + + const CimFlags parameterFlags = CimFlags.In; + object parameterValue = GetBaseObject(enumerator.Value); + + DebugHelper.WriteLog(@"Create parameter name= {0}, value= {1}, flags= {2}.", 4, + parameterName, + parameterValue, + parameterFlags); + + CimMethodParameter parameter = null; + CimMethodDeclaration declaration = null; + string className = null; + if (cimClass != null) + { + className = cimClass.CimSystemProperties.ClassName; + declaration = cimClass.CimClassMethods[methodName]; + if (declaration == null) + { + throw new ArgumentException(string.Format( + CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethod, methodName, className)); + } + } + else if (cimInstance != null) + { + className = cimInstance.CimClass.CimSystemProperties.ClassName; + declaration = cimInstance.CimClass.CimClassMethods[methodName]; + } + + if (declaration != null) + { + CimMethodParameterDeclaration paramDeclaration = declaration.Parameters[parameterName]; + if (paramDeclaration == null) + { + throw new ArgumentException(string.Format( + CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethodParameter, parameterName, methodName, className)); + } + + parameter = CimMethodParameter.Create( + parameterName, + parameterValue, + paramDeclaration.CimType, + parameterFlags); + // FIXME: check in/out qualifier + // parameterFlags = paramDeclaration.Qualifiers; + } + else + { + if (parameterValue == null) + { + // try the best to get the type while value is null + parameter = CimMethodParameter.Create( + parameterName, + parameterValue, + CimType.String, + parameterFlags); + } + else + { + CimType referenceType = CimType.Unknown; + object referenceObject = GetReferenceOrReferenceArrayObject(parameterValue, ref referenceType); + if (referenceObject != null) + { + parameter = CimMethodParameter.Create( + parameterName, + referenceObject, + referenceType, + parameterFlags); + } + else + { + parameter = CimMethodParameter.Create( + parameterName, + parameterValue, + parameterFlags); + } + } + } + + if (parameter != null) + collection.Add(parameter); + } + + return collection; + } + #endregion + + #region const strings + /// + /// Operation target. + /// + private const string targetClass = @"{0}"; + + /// + /// Action. + /// + private const string actionTemplate = @"Invoke-CimMethod: {0}"; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs new file mode 100644 index 0000000000000000000000000000000000000000..beb3e551d331d2ed64ec21169078483076b4ab27 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -0,0 +1,363 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Containing all information originated from + /// the parameters of + /// + internal class CimNewCimInstanceContext : XOperationContextBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + internal CimNewCimInstanceContext( + CimSessionProxy theProxy, + string theNamespace) + { + this.proxy = theProxy; + this.nameSpace = theNamespace; + } + } + + /// + /// + /// Implements operations of new-ciminstance cmdlet. + /// + /// + internal sealed class CimNewCimInstance : CimAsyncOperation + { + /// + /// Initializes a new instance of the class. + /// + /// Constructor + /// + /// + public CimNewCimInstance() + : base() + { + } + + /// + /// + /// Base on parametersetName to create ciminstances, + /// either remotely or locally + /// + /// + /// object. + public void NewCimInstance(NewCimInstanceCommand cmdlet) + { + DebugHelper.WriteLogEx(); + + string nameSpace; + CimInstance cimInstance = null; + try + { + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.ClassNameSessionSet: + { + nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); + cimInstance = CreateCimInstance(cmdlet.ClassName, + nameSpace, + cmdlet.Key, + cmdlet.Property, + cmdlet); + } + + break; + case CimBaseCommand.ResourceUriSessionSet: + case CimBaseCommand.ResourceUriComputerSet: + { + nameSpace = cmdlet.Namespace; // passing null is ok for resourceUri set + cimInstance = CreateCimInstance("DummyClass", + nameSpace, + cmdlet.Key, + cmdlet.Property, + cmdlet); + } + + break; + case CimBaseCommand.CimClassComputerSet: + case CimBaseCommand.CimClassSessionSet: + { + nameSpace = ConstValue.GetNamespace(cmdlet.CimClass.CimSystemProperties.Namespace); + cimInstance = CreateCimInstance(cmdlet.CimClass, + cmdlet.Property, + cmdlet); + } + + break; + default: + return; + } + } + catch (ArgumentNullException e) + { + cmdlet.ThrowTerminatingError(e, action); + return; + } + catch (ArgumentException e) + { + cmdlet.ThrowTerminatingError(e, action); + return; + } + + // return if create client only ciminstance + if (cmdlet.ClientOnly) + { + cmdlet.CmdletOperation.WriteObject(cimInstance, null); + return; + } + + string target = cimInstance.ToString(); + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + // create ciminstance on server + List proxys = new(); + + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.CimClassComputerSet: + case CimBaseCommand.ResourceUriComputerSet: + { + IEnumerable computerNames = ConstValue.GetComputerNames( + cmdlet.ComputerName); + foreach (string computerName in computerNames) + { + proxys.Add(CreateSessionProxy(computerName, cmdlet)); + } + } + + break; + case CimBaseCommand.CimClassSessionSet: + case CimBaseCommand.ClassNameSessionSet: + case CimBaseCommand.ResourceUriSessionSet: + foreach (CimSession session in cmdlet.CimSession) + { + proxys.Add(CreateSessionProxy(session, cmdlet)); + } + + break; + } + + foreach (CimSessionProxy proxy in proxys) + { + proxy.ContextObject = new CimNewCimInstanceContext(proxy, nameSpace); + proxy.CreateInstanceAsync(nameSpace, cimInstance); + } + } + + #region Get CimInstance after creation (on server) + + /// + /// + /// Get full from server based on the key + /// + /// + /// + internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase context) + { + DebugHelper.WriteLogEx(); + + if (context is not CimNewCimInstanceContext newCimInstanceContext) + { + DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1); + return; + } + + CimSessionProxy proxy = CreateCimSessionProxy(newCimInstanceContext.Proxy); + string nameSpace = cimInstance.CimSystemProperties.Namespace ?? newCimInstanceContext.Namespace; + proxy.GetInstanceAsync(nameSpace, cimInstance); + } + + #endregion + + #region private methods + + /// + /// + /// Set properties + /// + /// + /// + /// + private static void SetSessionProxyProperties( + ref CimSessionProxy proxy, + NewCimInstanceCommand cmdlet) + { + proxy.OperationTimeout = cmdlet.OperationTimeoutSec; + if (cmdlet.ResourceUri != null) + { + proxy.ResourceUri = cmdlet.ResourceUri; + } + } + + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + string computerName, + NewCimInstanceCommand cmdlet) + { + CimSessionProxy proxy = new CimSessionProxyNewCimInstance(computerName, this); + this.SubscribeEventAndAddProxytoCache(proxy); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + CimSession session, + NewCimInstanceCommand cmdlet) + { + CimSessionProxy proxy = new CimSessionProxyNewCimInstance(session, this); + this.SubscribeEventAndAddProxytoCache(proxy); + SetSessionProxyProperties(ref proxy, cmdlet); + return proxy; + } + + /// + /// + /// Create with given properties. + /// + /// + /// + /// + /// + /// + /// + /// See CimProperty.Create. + /// CimProperty.Create. + private CimInstance CreateCimInstance( + string className, + string cimNamespace, + IEnumerable key, + IDictionary properties, + NewCimInstanceCommand cmdlet) + { + CimInstance cimInstance = new(className, cimNamespace); + if (properties == null) + { + return cimInstance; + } + + List keys = new(); + if (key != null) + { + foreach (string keyName in key) + { + keys.Add(keyName); + } + } + + IDictionaryEnumerator enumerator = properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + CimFlags flag = CimFlags.None; + string propertyName = enumerator.Key.ToString().Trim(); + if (keys.Contains(propertyName, StringComparer.OrdinalIgnoreCase)) + { + flag = CimFlags.Key; + } + + object propertyValue = GetBaseObject(enumerator.Value); + + DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag); + + if (propertyValue is PSReference cimReference) + { + CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag); + cimInstance.CimInstanceProperties.Add(newProperty); + } + else + { + CimProperty newProperty = CimProperty.Create( + propertyName, + propertyValue, + flag); + cimInstance.CimInstanceProperties.Add(newProperty); + } + } + + return cimInstance; + } + + /// + /// + /// Create with given properties. + /// + /// + /// + /// + /// + /// + /// See CimProperty.Create. + /// CimProperty.Create. + private CimInstance CreateCimInstance( + CimClass cimClass, + IDictionary properties, + NewCimInstanceCommand cmdlet) + { + CimInstance cimInstance = new(cimClass); + if (properties == null) + { + return cimInstance; + } + + List notfoundProperties = new(); + foreach (string property in properties.Keys) + { + if (cimInstance.CimInstanceProperties[property] == null) + { + notfoundProperties.Add(property); + cmdlet.ThrowInvalidProperty(notfoundProperties, cmdlet.CimClass.CimSystemProperties.ClassName, @"Property", action, properties); + return null; + } + + object propertyValue = GetBaseObject(properties[property]); + cimInstance.CimInstanceProperties[property].Value = propertyValue; + } + + return cimInstance; + } + + #endregion + + #region const strings + /// + /// Action. + /// + private const string action = @"New-CimInstance"; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs new file mode 100644 index 0000000000000000000000000000000000000000..48b887f00b453c83312082a016a9ba8f8ddaab6c --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using Microsoft.Management.Infrastructure.Options; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Prompt user the message coming from provider. + /// + /// + /// At the same time class will prepare the + /// message for -whatif parameter, while the message represents + /// what will happen if execute the operation, but not do the operation. + /// For example, Remove-CimInstance, the whatif message will like, + /// "CIM Instance: Win32_Process@{Key=1} will be deleted." + /// + /// + internal sealed class CimPromptUser : CimSyncAction + { + /// + /// Initializes a new instance of the class. + /// + public CimPromptUser(string message, + CimPromptType prompt) + { + this.Message = message; + this.prompt = prompt; + } + + /// + /// + /// Prompt user with the given message and prepared whatif message. + /// + /// + /// + /// cmdlet wrapper object, to which write result. + /// for details. + /// + public override void Execute(CmdletOperationBase cmdlet) + { + ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); + + bool yestoall = false; + bool notoall = false; + bool result = false; + + switch (this.prompt) + { + case CimPromptType.Critical: + // NOTES: prepare the whatif message and caption + try + { + result = cmdlet.ShouldContinue(Message, "caption", ref yestoall, ref notoall); + if (yestoall) + { + this.responseType = CimResponseType.YesToAll; + } + else if (notoall) + { + this.responseType = CimResponseType.NoToAll; + } + else if (result) + { + this.responseType = CimResponseType.Yes; + } + else if (!result) + { + this.responseType = CimResponseType.No; + } + } + catch + { + this.responseType = CimResponseType.NoToAll; + throw; + } + finally + { + // unblocking the waiting thread + this.OnComplete(); + } + + break; + case CimPromptType.Normal: + try + { + result = cmdlet.ShouldProcess(Message); + if (result) + { + this.responseType = CimResponseType.Yes; + } + else if (!result) + { + this.responseType = CimResponseType.No; + } + } + catch + { + this.responseType = CimResponseType.NoToAll; + throw; + } + finally + { + // unblocking the waiting thread + this.OnComplete(); + } + + break; + default: + break; + } + + this.OnComplete(); + } + + #region members + + /// + /// Prompt message. + /// + public string Message { get; } + + /// + /// Prompt type -Normal or Critical. + /// + private readonly CimPromptType prompt; + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs new file mode 100644 index 0000000000000000000000000000000000000000..692a5f123e83bfaaf3c54553c0c3e075ebc2e26f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -0,0 +1,348 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Globalization; +using System.Management.Automation; +using System.Threading; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Subscription result event args + /// + /// + internal abstract class CimSubscriptionEventArgs : EventArgs + { + /// + /// + /// Returns an Object value for an operation context + /// + /// + public object Context + { + get + { + return context; + } + } + + protected object context; + } + + /// + /// + /// Subscription result event args + /// + /// + internal class CimSubscriptionResultEventArgs : CimSubscriptionEventArgs + { + /// + /// + /// subscription result + /// + /// + public CimSubscriptionResult Result { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public CimSubscriptionResultEventArgs( + CimSubscriptionResult theResult) + { + this.context = null; + this.Result = theResult; + } + } + + /// + /// + /// Subscription result event args + /// + /// + internal class CimSubscriptionExceptionEventArgs : CimSubscriptionEventArgs + { + /// + /// + /// subscription result + /// + /// + public Exception Exception { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public CimSubscriptionExceptionEventArgs( + Exception theException) + { + this.context = null; + this.Exception = theException; + } + } + + /// + /// + /// Implements operations of register-cimindication cmdlet. + /// + /// + internal sealed class CimRegisterCimIndication : CimAsyncOperation + { + /// + /// + /// New subscription result event + /// + /// + public event EventHandler OnNewSubscriptionResult; + + /// + /// Initializes a new instance of the class. + /// + public CimRegisterCimIndication() + : base() + { + this.ackedEvent = new ManualResetEventSlim(false); + } + + /// + /// Start an indication subscription target to the given computer. + /// + /// Null stands for localhost. + /// + /// + /// + /// + public void RegisterCimIndication( + string computerName, + string nameSpace, + string queryDialect, + string queryExpression, + uint operationTimeout) + { + DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); + this.TargetComputerName = computerName; + CimSessionProxy proxy = CreateSessionProxy(computerName, operationTimeout); + proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression); + WaitForAckMessage(); + } + + /// + /// Start an indication subscription through a given . + /// + /// Cannot be null. + /// + /// + /// + /// + /// Throw if cimSession is null. + public void RegisterCimIndication( + CimSession cimSession, + string nameSpace, + string queryDialect, + string queryExpression, + uint operationTimeout) + { + DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); + + ArgumentNullException.ThrowIfNull(cimSession, string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, nameof(cimSession))); + + this.TargetComputerName = cimSession.ComputerName; + CimSessionProxy proxy = CreateSessionProxy(cimSession, operationTimeout); + proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression); + WaitForAckMessage(); + } + + #region override methods + + /// + /// + /// Subscribe to the events issued by . + /// + /// + /// + protected override void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) + { + DebugHelper.WriteLog("SubscribeToCimSessionProxyEvent", 4); + // Raise event instead of write object to ps + proxy.OnNewCmdletAction += this.CimIndicationHandler; + proxy.OnOperationCreated += this.OperationCreatedHandler; + proxy.OnOperationDeleted += this.OperationDeletedHandler; + proxy.EnableMethodResultStreaming = false; + } + + /// + /// + /// Handler used to handle new action event from + /// object. + /// + /// + /// + /// object raised the event + /// + /// Event argument. + private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actionArgs) + { + DebugHelper.WriteLogEx("action is {0}. Disposed {1}", 0, actionArgs.Action, this.Disposed); + + if (this.Disposed) + { + return; + } + + // NOTES: should move after this.Disposed, but need to log the exception + if (actionArgs.Action is CimWriteError cimWriteError) + { + this.Exception = cimWriteError.Exception; + if (!this.ackedEvent.IsSet) + { + // an exception happened + DebugHelper.WriteLogEx("an exception happened", 0); + this.ackedEvent.Set(); + return; + } + + EventHandler temp = this.OnNewSubscriptionResult; + if (temp != null) + { + DebugHelper.WriteLog("Raise an exception event", 2); + + temp(this, new CimSubscriptionExceptionEventArgs(this.Exception)); + } + + DebugHelper.WriteLog("Got an exception: {0}", 2, Exception); + } + + if (actionArgs.Action is CimWriteResultObject cimWriteResultObject) + { + if (cimWriteResultObject.Result is CimSubscriptionResult result) + { + EventHandler temp = this.OnNewSubscriptionResult; + if (temp != null) + { + DebugHelper.WriteLog("Raise an result event", 2); + temp(this, new CimSubscriptionResultEventArgs(result)); + } + } + else + { + if (!this.ackedEvent.IsSet) + { + // an ACK message returned + DebugHelper.WriteLogEx("an ack message happened", 0); + this.ackedEvent.Set(); + return; + } + else + { + DebugHelper.WriteLogEx("an ack message should not happen here", 0); + } + } + } + } + + /// + /// Block the ps thread until ACK message or Error happened. + /// + private void WaitForAckMessage() + { + DebugHelper.WriteLogEx(); + this.ackedEvent.Wait(); + if (this.Exception != null) + { + DebugHelper.WriteLogEx("error happened", 0); + if (this.Cmdlet != null) + { + DebugHelper.WriteLogEx("Throw Terminating error", 1); + + // throw terminating error + ErrorRecord errorRecord = ErrorToErrorRecord.ErrorRecordFromAnyException( + new InvocationContext(this.TargetComputerName, null), this.Exception, null); + this.Cmdlet.ThrowTerminatingError(errorRecord); + } + else + { + DebugHelper.WriteLogEx("Throw exception", 1); + // throw exception out + throw this.Exception; + } + } + + DebugHelper.WriteLogEx("ACK happened", 0); + } + #endregion + + #region internal property + /// + /// The cmdlet object who issue this subscription, + /// to throw ThrowTerminatingError + /// in case there is a subscription failure. + /// + /// + internal Cmdlet Cmdlet + { + get; + set; + } + + /// + /// Target computername. + /// + internal string TargetComputerName + { + get; + set; + } + + #endregion + + #region private methods + /// + /// + /// Create and set properties + /// + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + string computerName, + uint timeout) + { + CimSessionProxy proxy = CreateCimSessionProxy(computerName); + proxy.OperationTimeout = timeout; + return proxy; + } + + /// + /// Create and set properties. + /// + /// + /// + /// + private CimSessionProxy CreateSessionProxy( + CimSession session, + uint timeout) + { + CimSessionProxy proxy = CreateCimSessionProxy(session); + proxy.OperationTimeout = timeout; + return proxy; + } + #endregion + + #region private members + + /// + /// Exception occurred while start the subscription. + /// + internal Exception Exception { get; private set; } + + #endregion + + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs new file mode 100644 index 0000000000000000000000000000000000000000..a6182166170e6dbade67ed15521d8193a56f5864 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System.Collections.Generic; +using System.Diagnostics; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Containing all necessary information originated from + /// the parameters of + /// + internal class CimRemoveCimInstanceContext : XOperationContextBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + internal CimRemoveCimInstanceContext(string theNamespace, + CimSessionProxy theProxy) + { + this.proxy = theProxy; + this.nameSpace = theNamespace; + } + } + + /// + /// + /// Implements operations of remove-ciminstance cmdlet. + /// + /// + internal sealed class CimRemoveCimInstance : CimGetInstance + { + /// + /// Initializes a new instance of the class. + /// + public CimRemoveCimInstance() + : base() + { + } + + /// + /// + /// Base on parametersetName to retrieve ciminstances + /// + /// + /// object. + public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet) + { + DebugHelper.WriteLogEx(); + + IEnumerable computerNames = ConstValue.GetComputerNames( + GetComputerName(cmdlet)); + List proxys = new(); + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimInstanceComputerSet: + foreach (string computerName in computerNames) + { + proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet)); + } + + break; + case CimBaseCommand.CimInstanceSessionSet: + foreach (CimSession session in GetCimSession(cmdlet)) + { + proxys.Add(CreateSessionProxy(session, cmdlet)); + } + + break; + default: + break; + } + + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimInstanceComputerSet: + case CimBaseCommand.CimInstanceSessionSet: + string nameSpace = null; + if (cmdlet.ResourceUri != null) + { + nameSpace = GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace; + } + else + { + nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace); + } + + string target = cmdlet.CimInstance.ToString(); + foreach (CimSessionProxy proxy in proxys) + { + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + proxy.DeleteInstanceAsync(nameSpace, cmdlet.CimInstance); + } + + break; + case CimBaseCommand.QueryComputerSet: + case CimBaseCommand.QuerySessionSet: + GetCimInstanceInternal(cmdlet); + break; + default: + break; + } + } + + /// + /// + /// Remove from namespace specified in cmdlet + /// + /// + /// + internal void RemoveCimInstance(CimInstance cimInstance, XOperationContextBase context, CmdletOperationBase cmdlet) + { + DebugHelper.WriteLogEx(); + + string target = cimInstance.ToString(); + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + CimRemoveCimInstanceContext removeContext = context as CimRemoveCimInstanceContext; + Debug.Assert(removeContext != null, "CimRemoveCimInstance::RemoveCimInstance should has CimRemoveCimInstanceContext != NULL."); + + CimSessionProxy proxy = CreateCimSessionProxy(removeContext.Proxy); + proxy.DeleteInstanceAsync(removeContext.Namespace, cimInstance); + } + + #region const strings + /// + /// Action. + /// + private const string action = @"Remove-CimInstance"; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs new file mode 100644 index 0000000000000000000000000000000000000000..389c45c8314e84f22e9f31fb8843c8c0bf2ce522 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -0,0 +1,496 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Globalization; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + #region AsyncResultType + /// + /// + /// Async result type + /// + /// + public enum AsyncResultType + { + Result, + Exception, + Completion + } + #endregion + + #region CimResultContext + /// + /// Cim Result Context. + /// + internal class CimResultContext + { + /// + /// Initializes a new instance of the class. + /// + /// + internal CimResultContext(object ErrorSource) + { + this.ErrorSource = ErrorSource; + } + + /// + /// ErrorSource property. + /// + internal object ErrorSource { get; } + } + #endregion + + #region AsyncResultEventArgsBase + /// + /// + /// Base class of async result event argument + /// + /// + internal abstract class AsyncResultEventArgsBase : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + protected AsyncResultEventArgsBase( + CimSession session, + IObservable observable, + AsyncResultType resultType) + { + this.session = session; + this.observable = observable; + this.resultType = resultType; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + protected AsyncResultEventArgsBase( + CimSession session, + IObservable observable, + AsyncResultType resultType, + CimResultContext cimResultContext) + { + this.session = session; + this.observable = observable; + this.resultType = resultType; + this.context = cimResultContext; + } + + public readonly CimSession session; + public readonly IObservable observable; + public readonly AsyncResultType resultType; + + // property ErrorSource + public readonly CimResultContext context; + } + + #endregion + + #region AsyncResult*Args + /// + /// + /// operation successfully completed event argument + /// + /// + internal class AsyncResultCompleteEventArgs : AsyncResultEventArgsBase + { + /// + /// Initializes a new instance of the class. + /// + /// object. + /// + public AsyncResultCompleteEventArgs( + CimSession session, + IObservable observable) + : base(session, observable, AsyncResultType.Completion) + { + } + } + + /// + /// + /// async result argument with object + /// + /// + internal class AsyncResultObjectEventArgs : AsyncResultEventArgsBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public AsyncResultObjectEventArgs( + CimSession session, + IObservable observable, + object resultObject) + : base(session, observable, AsyncResultType.Result) + { + this.resultObject = resultObject; + } + + public readonly object resultObject; + } + + /// + /// + /// operation completed with exception event argument + /// + /// + internal class AsyncResultErrorEventArgs : AsyncResultEventArgsBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public AsyncResultErrorEventArgs( + CimSession session, + IObservable observable, + Exception error) + : base(session, observable, AsyncResultType.Exception) + { + this.error = error; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + public AsyncResultErrorEventArgs( + CimSession session, + IObservable observable, + Exception error, + CimResultContext cimResultContext) + : base(session, observable, AsyncResultType.Exception, cimResultContext) + { + this.error = error; + } + + public readonly Exception error; + } + #endregion + + #region CimResultObserver + /// + /// + /// Observer to consume results from asynchronous operations, such as, + /// EnumerateInstancesAsync operation of object. + /// + /// + /// (See https://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Contract/) + /// for the IObserver/IObservable contact + /// - the only possible sequence is OnNext* (OnCompleted|OnError)? + /// - callbacks are serialized + /// - Subscribe never throws + /// + /// + /// object type + internal class CimResultObserver : IObserver + { + /// + /// Define an Event based on the NewActionHandler. + /// + public event EventHandler OnNewResult; + + /// + /// Initializes a new instance of the class. + /// + /// object that issued the operation. + /// Operation that can be observed. + public CimResultObserver(CimSession session, IObservable observable) + { + this.CurrentSession = session; + this.observable = observable; + } + + /// + /// Initializes a new instance of the class. + /// + /// object that issued the operation. + /// Operation that can be observed. + public CimResultObserver(CimSession session, + IObservable observable, + CimResultContext cimResultContext) + { + this.CurrentSession = session; + this.observable = observable; + this.context = cimResultContext; + } + + /// + /// + /// Operation completed successfully + /// + /// + public virtual void OnCompleted() + { + // callbacks should never throw any exception to + // protocol layer, otherwise the client process will be + // terminated because of unhandled exception, same with + // OnNext, OnError + try + { + AsyncResultCompleteEventArgs completeArgs = new( + this.CurrentSession, this.observable); + this.OnNewResult(this, completeArgs); + } + catch (Exception ex) + { + this.OnError(ex); + DebugHelper.WriteLogEx("{0}", 0, ex); + } + } + + /// + /// + /// Operation completed with an error + /// + /// + /// Error object. + public virtual void OnError(Exception error) + { + try + { + AsyncResultErrorEventArgs errorArgs = new( + this.CurrentSession, this.observable, error, this.context); + this.OnNewResult(this, errorArgs); + } + catch (Exception ex) + { + // !!ignore the exception + DebugHelper.WriteLogEx("{0}", 0, ex); + } + } + + /// + /// Deliver the result value. + /// + /// + protected void OnNextCore(object value) + { + DebugHelper.WriteLogEx("value = {0}.", 1, value); + try + { + AsyncResultObjectEventArgs resultArgs = new( + this.CurrentSession, this.observable, value); + this.OnNewResult(this, resultArgs); + } + catch (Exception ex) + { + this.OnError(ex); + DebugHelper.WriteLogEx("{0}", 0, ex); + } + } + + /// + /// + /// Operation got a new result object + /// + /// + /// Result object. + public virtual void OnNext(T value) + { + DebugHelper.WriteLogEx("value = {0}.", 1, value); + // do not allow null value + if (value == null) + { + return; + } + + this.OnNextCore(value); + } + + #region members + + /// + /// Session object of the operation. + /// + protected CimSession CurrentSession { get; } + + /// + /// Async operation that can be observed. + /// + private readonly IObservable observable; + + /// + /// object used during delivering result. + /// + private readonly CimResultContext context; + #endregion + } + + /// + /// CimSubscriptionResultObserver class definition. + /// + internal class CimSubscriptionResultObserver : CimResultObserver + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public CimSubscriptionResultObserver(CimSession session, IObservable observable) + : base(session, observable) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + public CimSubscriptionResultObserver( + CimSession session, + IObservable observable, + CimResultContext context) + : base(session, observable, context) + { + } + + /// + /// Override the OnNext method. + /// + /// + public override void OnNext(CimSubscriptionResult value) + { + DebugHelper.WriteLogEx(); + base.OnNextCore(value); + } + } + + /// + /// CimMethodResultObserver class definition. + /// + internal class CimMethodResultObserver : CimResultObserver + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public CimMethodResultObserver(CimSession session, IObservable observable) + : base(session, observable) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public CimMethodResultObserver( + CimSession session, + IObservable observable, + CimResultContext context) + : base(session, observable, context) + { + } + + /// + /// Override the OnNext method. + /// + /// + public override void OnNext(CimMethodResultBase value) + { + DebugHelper.WriteLogEx(); + const string PSTypeCimMethodResult = @"Microsoft.Management.Infrastructure.CimMethodResult"; + const string PSTypeCimMethodStreamedResult = @"Microsoft.Management.Infrastructure.CimMethodStreamedResult"; + const string PSTypeCimMethodResultTemplate = @"{0}#{1}#{2}"; + + string resultObjectPSType = null; + PSObject resultObject = null; + if (value is CimMethodResult methodResult) + { + resultObjectPSType = PSTypeCimMethodResult; + resultObject = new PSObject(); + foreach (CimMethodParameter param in methodResult.OutParameters) + { + resultObject.Properties.Add(new PSNoteProperty(param.Name, param.Value)); + } + } + else + { + if (value is CimMethodStreamedResult methodStreamedResult) + { + resultObjectPSType = PSTypeCimMethodStreamedResult; + resultObject = new PSObject(); + resultObject.Properties.Add(new PSNoteProperty(@"ParameterName", methodStreamedResult.ParameterName)); + resultObject.Properties.Add(new PSNoteProperty(@"ItemType", methodStreamedResult.ItemType)); + resultObject.Properties.Add(new PSNoteProperty(@"ItemValue", methodStreamedResult.ItemValue)); + } + } + + if (resultObject != null) + { + resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName)); + resultObject.TypeNames.Insert(0, resultObjectPSType); + resultObject.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, PSTypeCimMethodResultTemplate, resultObjectPSType, ClassName, MethodName)); + base.OnNextCore(resultObject); + } + } + + /// + /// Methodname. + /// + internal string MethodName + { + get; + set; + } + + /// + /// Classname. + /// + internal string ClassName + { + get; + set; + } + } + + /// + /// IgnoreResultObserver class definition. + /// + internal class IgnoreResultObserver : CimResultObserver + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public IgnoreResultObserver(CimSession session, IObservable observable) + : base(session, observable) + { + } + + /// + /// Override the OnNext method. + /// + /// + public override void OnNext(CimInstance value) + { + DebugHelper.WriteLogEx(); + } + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs new file mode 100644 index 0000000000000000000000000000000000000000..b8ebc9adaefea2eaaf368ad7d6adc196f2a10636 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -0,0 +1,1247 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using Microsoft.Management.Infrastructure.Options; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + #region CimSessionWrapper + + internal class CimSessionWrapper + { + #region members + + /// + /// Id of the cimsession. + /// + public uint SessionId { get; } + + /// + /// InstanceId of the cimsession. + /// + public Guid InstanceId { get; } + + /// + /// Name of the cimsession. + /// + public string Name { get; } + + /// + /// Computer name of the cimsession. + /// + public string ComputerName { get; } + + /// + /// Wrapped cimsession object. + /// + public CimSession CimSession { get; } + + /// + /// Computer name of the cimsession. + /// + public string Protocol + { + get + { + switch (protocol) + { + case ProtocolType.Dcom: + return "DCOM"; + case ProtocolType.Default: + case ProtocolType.Wsman: + default: + return "WSMAN"; + } + } + } + + internal ProtocolType GetProtocolType() + { + return protocol; + } + + private readonly ProtocolType protocol; + + /// + /// PSObject that wrapped the cimSession. + /// + private PSObject psObject; + + #endregion + + internal CimSessionWrapper( + uint theSessionId, + Guid theInstanceId, + string theName, + string theComputerName, + CimSession theCimSession, + ProtocolType theProtocol) + { + this.SessionId = theSessionId; + this.InstanceId = theInstanceId; + this.Name = theName; + this.ComputerName = theComputerName; + this.CimSession = theCimSession; + this.psObject = null; + this.protocol = theProtocol; + } + + internal PSObject GetPSObject() + { + if (psObject == null) + { + psObject = new PSObject(this.CimSession); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.SessionId)); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.namePropName, this.Name)); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.instanceidPropName, this.InstanceId)); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.computernamePropName, this.ComputerName)); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.protocolPropName, this.Protocol)); + } + else + { + psObject.Properties[CimSessionState.idPropName].Value = this.SessionId; + psObject.Properties[CimSessionState.namePropName].Value = this.Name; + psObject.Properties[CimSessionState.instanceidPropName].Value = this.InstanceId; + psObject.Properties[CimSessionState.computernamePropName].Value = this.ComputerName; + psObject.Properties[CimSessionState.protocolPropName].Value = this.Protocol; + } + + return psObject; + } + } + + #endregion + + #region CimSessionState + + /// + /// + /// Class used to hold all cimsession related status data related to a runspace. + /// Including the CimSession cache, session counters for generating session name. + /// + /// + internal class CimSessionState : IDisposable + { + #region private members + + /// + /// Default session name. + /// If a name is not passed, then the session is given the name CimSession, + /// where is the next available session number. + /// For example, CimSession1, CimSession2, etc... + /// + internal static readonly string CimSessionClassName = "CimSession"; + + /// + /// CimSession object name. + /// + internal static readonly string CimSessionObject = "{CimSession Object}"; + + /// + /// + /// CimSession object path, which is identifying a cimsession object + /// + /// + internal static readonly string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; + + /// + /// Id property name of cimsession wrapper object. + /// + internal static readonly string idPropName = "Id"; + + /// + /// Instanceid property name of cimsession wrapper object. + /// + internal static readonly string instanceidPropName = "InstanceId"; + + /// + /// Name property name of cimsession wrapper object. + /// + internal static readonly string namePropName = "Name"; + + /// + /// Computer name property name of cimsession object. + /// + internal static readonly string computernamePropName = "ComputerName"; + + /// + /// Protocol name property name of cimsession object. + /// + internal static readonly string protocolPropName = "Protocol"; + + /// + /// + /// Session counter bound to current runspace. + /// + /// + private uint sessionNameCounter; + + /// + /// + /// Dictionary used to holds all CimSessions in current runspace by session name. + /// + /// + private readonly Dictionary> curCimSessionsByName; + + /// + /// + /// Dictionary used to holds all CimSessions in current runspace by computer name. + /// + /// + private readonly Dictionary> curCimSessionsByComputerName; + + /// + /// + /// Dictionary used to holds all CimSessions in current runspace by instance ID. + /// + /// + private readonly Dictionary curCimSessionsByInstanceId; + + /// + /// + /// Dictionary used to holds all CimSessions in current runspace by session id. + /// + /// + private readonly Dictionary curCimSessionsById; + + /// + /// + /// Dictionary used to link CimSession object with PSObject. + /// + /// + private readonly Dictionary curCimSessionWrapper; + + #endregion + + /// + /// Initializes a new instance of the class. + /// + internal CimSessionState() + { + sessionNameCounter = 1; + curCimSessionsByName = new Dictionary>( + StringComparer.OrdinalIgnoreCase); + curCimSessionsByComputerName = new Dictionary>( + StringComparer.OrdinalIgnoreCase); + curCimSessionsByInstanceId = new Dictionary(); + curCimSessionsById = new Dictionary(); + curCimSessionWrapper = new Dictionary(); + } + + /// + /// + /// Get sessions count. + /// + /// + /// The count of session objects in current runspace. + internal int GetSessionsCount() + { + return this.curCimSessionsById.Count; + } + + /// + /// + /// Generates an unique session id. + /// + /// + /// Unique session id under current runspace. + internal uint GenerateSessionId() + { + return this.sessionNameCounter++; + } + #region IDisposable + + /// + /// + /// Indicates whether this object was disposed or not. + /// + /// + private bool _disposed; + + /// + /// + /// Dispose() calls Dispose(true). + /// Implement IDisposable. Do not make this method virtual. + /// A derived class should not be able to override this method. + /// + /// + public void Dispose() + { + Dispose(true); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SuppressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + /// + /// + /// Dispose(bool disposing) executes in two distinct scenarios. + /// If disposing equals true, the method has been called directly + /// or indirectly by a user's code. Managed and unmanaged resources + /// can be disposed. + /// If disposing equals false, the method has been called by the + /// runtime from inside the finalizer and you should not reference + /// other objects. Only unmanaged resources can be disposed. + /// + /// + /// Whether it is directly called. + protected virtual void Dispose(bool disposing) + { + if (!this._disposed) + { + if (disposing) + { + // free managed resources + Cleanup(); + this._disposed = true; + } + // free native resources if there are any + } + } + + /// + /// + /// Performs application-defined tasks associated with freeing, releasing, or + /// resetting unmanaged resources. + /// + /// + public void Cleanup() + { + foreach (CimSession session in curCimSessionWrapper.Keys) + { + session.Dispose(); + } + + curCimSessionWrapper.Clear(); + curCimSessionsByName.Clear(); + curCimSessionsByComputerName.Clear(); + curCimSessionsByInstanceId.Clear(); + curCimSessionsById.Clear(); + sessionNameCounter = 1; + } + + #endregion + + #region Add CimSession to/remove CimSession from cache + + /// + /// + /// Add new CimSession object to cache. + /// + /// + /// + /// + /// + /// + /// + /// + /// + internal PSObject AddObjectToCache( + CimSession session, + uint sessionId, + Guid instanceId, + string name, + string computerName, + ProtocolType protocol) + { + CimSessionWrapper wrapper = new( + sessionId, instanceId, name, computerName, session, protocol); + + HashSet objects; + if (!this.curCimSessionsByComputerName.TryGetValue(computerName, out objects)) + { + objects = new HashSet(); + this.curCimSessionsByComputerName.Add(computerName, objects); + } + + objects.Add(wrapper); + + if (!this.curCimSessionsByName.TryGetValue(name, out objects)) + { + objects = new HashSet(); + this.curCimSessionsByName.Add(name, objects); + } + + objects.Add(wrapper); + + this.curCimSessionsByInstanceId.Add(instanceId, wrapper); + this.curCimSessionsById.Add(sessionId, wrapper); + this.curCimSessionWrapper.Add(session, wrapper); + return wrapper.GetPSObject(); + } + + /// + /// + /// Generates remove session message by given wrapper object. + /// + /// + /// + internal string GetRemoveSessionObjectTarget(PSObject psObject) + { + string message = string.Empty; + if (psObject.BaseObject is CimSession) + { + uint id = 0x0; + Guid instanceId = Guid.Empty; + string name = string.Empty; + string computerName = string.Empty; + if (psObject.Properties[idPropName].Value is uint) + { + id = Convert.ToUInt32(psObject.Properties[idPropName].Value, null); + } + + if (psObject.Properties[instanceidPropName].Value is Guid) + { + instanceId = (Guid)psObject.Properties[instanceidPropName].Value; + } + + if (psObject.Properties[namePropName].Value is string) + { + name = (string)psObject.Properties[namePropName].Value; + } + + if (psObject.Properties[computernamePropName].Value is string) + { + computerName = (string)psObject.Properties[computernamePropName].Value; + } + + message = string.Format(CultureInfo.CurrentUICulture, SessionObjectPath, id, instanceId, name, computerName); + } + + return message; + } + + /// + /// + /// Remove given object from cache. + /// + /// + /// + internal void RemoveOneSessionObjectFromCache(PSObject psObject) + { + DebugHelper.WriteLogEx(); + + if (psObject.BaseObject is CimSession) + { + RemoveOneSessionObjectFromCache(psObject.BaseObject as CimSession); + } + } + + /// + /// + /// Remove given object from cache. + /// + /// + /// + internal void RemoveOneSessionObjectFromCache(CimSession session) + { + DebugHelper.WriteLogEx(); + + if (!this.curCimSessionWrapper.ContainsKey(session)) + { + return; + } + + CimSessionWrapper wrapper = this.curCimSessionWrapper[session]; + string name = wrapper.Name; + string computerName = wrapper.ComputerName; + + DebugHelper.WriteLog("name {0}, computername {1}, id {2}, instanceId {3}", 1, name, computerName, wrapper.SessionId, wrapper.InstanceId); + + HashSet objects; + if (this.curCimSessionsByComputerName.TryGetValue(computerName, out objects)) + { + objects.Remove(wrapper); + } + + if (this.curCimSessionsByName.TryGetValue(name, out objects)) + { + objects.Remove(wrapper); + } + + RemoveSessionInternal(session, wrapper); + } + + /// + /// + /// Remove given object from partial of the cache only. + /// + /// + /// + /// + private void RemoveSessionInternal(CimSession session, CimSessionWrapper wrapper) + { + DebugHelper.WriteLogEx(); + + this.curCimSessionsByInstanceId.Remove(wrapper.InstanceId); + this.curCimSessionsById.Remove(wrapper.SessionId); + this.curCimSessionWrapper.Remove(session); + session.Dispose(); + } + + #endregion + + #region Query CimSession from cache + + /// + /// + /// Add ErrorRecord to list. + /// + /// + /// + /// + /// + private static void AddErrorRecord( + ref List errRecords, + string propertyName, + object propertyValue) + { + errRecords.Add( + new ErrorRecord( + new CimException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.CouldNotFindCimsessionObject, propertyName, propertyValue)), + string.Empty, + ErrorCategory.ObjectNotFound, + null)); + } + + /// + /// Query session list by given id array. + /// + /// + /// List of session wrapper objects. + internal IEnumerable QuerySession( + IEnumerable ids, + out IEnumerable errorRecords) + { + HashSet sessions = new(); + HashSet sessionIds = new(); + List errRecords = new(); + errorRecords = errRecords; + // NOTES: use template function to implement this will save duplicate code + foreach (uint id in ids) + { + if (this.curCimSessionsById.ContainsKey(id)) + { + if (sessionIds.Add(id)) + { + sessions.Add(this.curCimSessionsById[id].GetPSObject()); + } + } + else + { + AddErrorRecord(ref errRecords, idPropName, id); + } + } + + return sessions; + } + + /// + /// Query session list by given instance id array. + /// + /// + /// List of session wrapper objects. + internal IEnumerable QuerySession( + IEnumerable instanceIds, + out IEnumerable errorRecords) + { + HashSet sessions = new(); + HashSet sessionIds = new(); + List errRecords = new(); + errorRecords = errRecords; + foreach (Guid instanceid in instanceIds) + { + if (this.curCimSessionsByInstanceId.ContainsKey(instanceid)) + { + CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[instanceid]; + if (!sessionIds.Contains(wrapper.SessionId)) + { + sessionIds.Add(wrapper.SessionId); + sessions.Add(wrapper.GetPSObject()); + } + } + else + { + AddErrorRecord(ref errRecords, instanceidPropName, instanceid); + } + } + + return sessions; + } + + /// + /// Query session list by given name array. + /// + /// + /// List of session wrapper objects. + internal IEnumerable QuerySession(IEnumerable nameArray, + out IEnumerable errorRecords) + { + HashSet sessions = new(); + HashSet sessionIds = new(); + List errRecords = new(); + errorRecords = errRecords; + foreach (string name in nameArray) + { + bool foundSession = false; + WildcardPattern pattern = new(name, WildcardOptions.IgnoreCase); + foreach (KeyValuePair> kvp in this.curCimSessionsByName) + { + if (pattern.IsMatch(kvp.Key)) + { + HashSet wrappers = kvp.Value; + foundSession = wrappers.Count > 0; + foreach (CimSessionWrapper wrapper in wrappers) + { + if (!sessionIds.Contains(wrapper.SessionId)) + { + sessionIds.Add(wrapper.SessionId); + sessions.Add(wrapper.GetPSObject()); + } + } + } + } + + if (!foundSession && !WildcardPattern.ContainsWildcardCharacters(name)) + { + AddErrorRecord(ref errRecords, namePropName, name); + } + } + + return sessions; + } + + /// + /// Query session list by given computer name array. + /// + /// + /// List of session wrapper objects. + internal IEnumerable QuerySessionByComputerName( + IEnumerable computernameArray, + out IEnumerable errorRecords) + { + HashSet sessions = new(); + HashSet sessionIds = new(); + List errRecords = new(); + errorRecords = errRecords; + foreach (string computername in computernameArray) + { + bool foundSession = false; + if (this.curCimSessionsByComputerName.ContainsKey(computername)) + { + HashSet wrappers = this.curCimSessionsByComputerName[computername]; + foundSession = wrappers.Count > 0; + foreach (CimSessionWrapper wrapper in wrappers) + { + if (!sessionIds.Contains(wrapper.SessionId)) + { + sessionIds.Add(wrapper.SessionId); + sessions.Add(wrapper.GetPSObject()); + } + } + } + + if (!foundSession) + { + AddErrorRecord(ref errRecords, computernamePropName, computername); + } + } + + return sessions; + } + + /// + /// Query session list by given session objects array. + /// + /// + /// List of session wrapper objects. + internal IEnumerable QuerySession(IEnumerable cimsessions, + out IEnumerable errorRecords) + { + HashSet sessions = new(); + HashSet sessionIds = new(); + List errRecords = new(); + errorRecords = errRecords; + foreach (CimSession cimsession in cimsessions) + { + if (this.curCimSessionWrapper.ContainsKey(cimsession)) + { + CimSessionWrapper wrapper = this.curCimSessionWrapper[cimsession]; + if (!sessionIds.Contains(wrapper.SessionId)) + { + sessionIds.Add(wrapper.SessionId); + sessions.Add(wrapper.GetPSObject()); + } + } + else + { + AddErrorRecord(ref errRecords, CimSessionClassName, CimSessionObject); + } + } + + return sessions; + } + + /// + /// Query session wrapper object. + /// + /// + /// Session wrapper. + internal CimSessionWrapper QuerySession(CimSession cimsession) + { + CimSessionWrapper wrapper; + this.curCimSessionWrapper.TryGetValue(cimsession, out wrapper); + return wrapper; + } + + /// + /// Query session object with given CimSessionInstanceID. + /// + /// + /// CimSession object. + internal CimSession QuerySession(Guid cimSessionInstanceId) + { + if (this.curCimSessionsByInstanceId.ContainsKey(cimSessionInstanceId)) + { + CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[cimSessionInstanceId]; + return wrapper.CimSession; + } + + return null; + } + #endregion + } + + #endregion + + #region CimSessionBase + + /// + /// + /// Base class of all session operation classes. + /// All sessions created will be held in a ConcurrentDictionary:cimSessions. + /// It manages the lifecycle of the sessions being created for each + /// runspace according to the state of the runspace. + /// + /// + internal class CimSessionBase + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public CimSessionBase() + { + this.sessionState = cimSessions.GetOrAdd( + CurrentRunspaceId, + (Guid instanceId) => + { + if (Runspace.DefaultRunspace != null) + { + Runspace.DefaultRunspace.StateChanged += DefaultRunspace_StateChanged; + } + + return new CimSessionState(); + }); + } + + #endregion + + #region members + + /// + /// + /// Thread safe static dictionary to store session objects associated + /// with each runspace, which is identified by a GUID. NOTE: cmdlet + /// can running parallelly under more than one runspace(s). + /// + /// + internal static readonly ConcurrentDictionary cimSessions + = new(); + + /// + /// + /// Default runspace Id. + /// + /// + internal static readonly Guid defaultRunspaceId = Guid.Empty; + + /// + /// + /// Object used to hold all CimSessions and status data bound + /// to current runspace. + /// + /// + internal CimSessionState sessionState; + + /// + /// Get current runspace id. + /// + private static Guid CurrentRunspaceId + { + get + { + if (Runspace.DefaultRunspace != null) + { + return Runspace.DefaultRunspace.InstanceId; + } + else + { + return CimSessionBase.defaultRunspaceId; + } + } + } + #endregion + + public static CimSessionState GetCimSessionState() + { + CimSessionState state = null; + cimSessions.TryGetValue(CurrentRunspaceId, out state); + return state; + } + + /// + /// + /// Clean up the dictionaries if the runspace is closed or broken. + /// + /// + /// Runspace. + /// Event args. + private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e) + { + Runspace runspace = (Runspace)sender; + switch (e.RunspaceStateInfo.State) + { + case RunspaceState.Broken: + case RunspaceState.Closed: + CimSessionState state; + if (cimSessions.TryRemove(runspace.InstanceId, out state)) + { + DebugHelper.WriteLog(string.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, runspace.InstanceId, e.RunspaceStateInfo.State)); + state.Dispose(); + } + + runspace.StateChanged -= DefaultRunspace_StateChanged; + break; + default: + break; + } + } + } + + #endregion + + #region CimTestConnection + + #endregion + + #region CimNewSession + + /// + /// + /// CimNewSession is the class to create cimSession + /// based on given NewCimSessionCommand. + /// + /// + internal class CimNewSession : CimSessionBase, IDisposable + { + /// + /// CimTestCimSessionContext. + /// + internal class CimTestCimSessionContext : XOperationContextBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + internal CimTestCimSessionContext( + CimSessionProxy theProxy, + CimSessionWrapper wrapper) + { + this.proxy = theProxy; + this.CimSessionWrapper = wrapper; + this.nameSpace = null; + } + + /// + /// Namespace + /// + internal CimSessionWrapper CimSessionWrapper { get; } + } + + /// + /// Initializes a new instance of the class. + /// + internal CimNewSession() : base() + { + this.cimTestSession = new CimTestSession(); + this.Disposed = false; + } + + /// + /// Create a new base on given cmdlet + /// and its parameter. + /// + /// + /// + /// + internal void NewCimSession(NewCimSessionCommand cmdlet, + CimSessionOptions sessionOptions, + CimCredential credential) + { + DebugHelper.WriteLogEx(); + + IEnumerable computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); + foreach (string computerName in computerNames) + { + CimSessionProxy proxy; + if (sessionOptions == null) + { + DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); + sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, + cmdlet.OperationTimeoutSec, credential); + } + + proxy = new CimSessionProxyTestConnection(computerName, sessionOptions); + string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName; + CimSessionWrapper wrapper = new(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol); + CimTestCimSessionContext context = new(proxy, wrapper); + proxy.ContextObject = context; + // Skip test the connection if user intend to + if (cmdlet.SkipTestConnection.IsPresent) + { + AddSessionToCache(proxy.CimSession, context, new CmdletOperationBase(cmdlet)); + } + else + { + // CimSession will be returned as part of TestConnection + this.cimTestSession.TestCimSession(computerName, proxy); + } + } + } + + /// + /// + /// Add session to global cache, + /// + /// + /// + /// + /// + internal void AddSessionToCache(CimSession cimSession, XOperationContextBase context, CmdletOperationBase cmdlet) + { + DebugHelper.WriteLogEx(); + + CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; + uint sessionId = this.sessionState.GenerateSessionId(); + string originalSessionName = testCimSessionContext.CimSessionWrapper.Name; + string sessionName = originalSessionName ?? string.Create(CultureInfo.CurrentUICulture, $"{CimSessionState.CimSessionClassName}{sessionId}"); + + // detach CimSession from the proxy object + CimSession createdCimSession = testCimSessionContext.Proxy.Detach(); + PSObject psObject = this.sessionState.AddObjectToCache( + createdCimSession, + sessionId, + createdCimSession.InstanceId, + sessionName, + testCimSessionContext.CimSessionWrapper.ComputerName, + testCimSessionContext.Proxy.Protocol); + cmdlet.WriteObject(psObject, null); + } + + /// + /// + /// Process all actions in the action queue. + /// + /// + /// + /// Wrapper of cmdlet, for details. + /// + public void ProcessActions(CmdletOperationBase cmdletOperation) + { + this.cimTestSession.ProcessActions(cmdletOperation); + } + + /// + /// + /// Process remaining actions until all operations are completed or + /// current cmdlet is terminated by user. + /// + /// + /// + /// Wrapper of cmdlet, for details. + /// + public void ProcessRemainActions(CmdletOperationBase cmdletOperation) + { + this.cimTestSession.ProcessRemainActions(cmdletOperation); + } + + #region private members + /// + /// + /// object. + /// + /// + private readonly CimTestSession cimTestSession; + #endregion // private members + + #region IDisposable + + /// + /// + /// Indicates whether this object was disposed or not. + /// + /// + protected bool Disposed { get; private set; } + + /// + /// + /// Dispose() calls Dispose(true). + /// Implement IDisposable. Do not make this method virtual. + /// A derived class should not be able to override this method. + /// + /// + public void Dispose() + { + Dispose(true); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SuppressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + /// + /// + /// Dispose(bool disposing) executes in two distinct scenarios. + /// If disposing equals true, the method has been called directly + /// or indirectly by a user's code. Managed and unmanaged resources + /// can be disposed. + /// If disposing equals false, the method has been called by the + /// runtime from inside the finalizer and you should not reference + /// other objects. Only unmanaged resources can be disposed. + /// + /// + /// Whether it is directly called. + protected virtual void Dispose(bool disposing) + { + if (!this.Disposed) + { + if (disposing) + { + // free managed resources + this.cimTestSession.Dispose(); + this.Disposed = true; + } + // free native resources if there are any + } + } + #endregion + } + + #endregion + + #region CimGetSession + + /// + /// + /// Get CimSession based on given id/instanceid/computername/name. + /// + /// + internal class CimGetSession : CimSessionBase + { + /// + /// Initializes a new instance of the class. + /// + public CimGetSession() : base() + { + } + + /// + /// Get objects based on the given cmdlet + /// and its parameter. + /// + /// + public void GetCimSession(GetCimSessionCommand cmdlet) + { + DebugHelper.WriteLogEx(); + + IEnumerable sessionToGet = null; + IEnumerable errorRecords = null; + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.ComputerNameSet: + if (cmdlet.ComputerName == null) + { + sessionToGet = this.sessionState.QuerySession(ConstValue.DefaultSessionName, out errorRecords); + } + else + { + sessionToGet = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); + } + + break; + case CimBaseCommand.SessionIdSet: + sessionToGet = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); + break; + case CimBaseCommand.InstanceIdSet: + sessionToGet = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords); + break; + case CimBaseCommand.NameSet: + sessionToGet = this.sessionState.QuerySession(cmdlet.Name, out errorRecords); + break; + default: + break; + } + + if (sessionToGet != null) + { + foreach (PSObject psobject in sessionToGet) + { + cmdlet.WriteObject(psobject); + } + } + + if (errorRecords != null) + { + foreach (ErrorRecord errRecord in errorRecords) + { + cmdlet.WriteError(errRecord); + } + } + } + + #region helper methods + + #endregion + } + + #endregion + + #region CimRemoveSession + + /// + /// + /// Get CimSession based on given id/instanceid/computername/name. + /// + /// + internal class CimRemoveSession : CimSessionBase + { + /// + /// Remove session action string. + /// + internal static readonly string RemoveCimSessionActionName = "Remove CimSession"; + + /// + /// Initializes a new instance of the class. + /// + public CimRemoveSession() : base() + { + } + + /// + /// Remove the objects based on given cmdlet + /// and its parameter. + /// + /// + public void RemoveCimSession(RemoveCimSessionCommand cmdlet) + { + DebugHelper.WriteLogEx(); + + IEnumerable sessionToRemove = null; + IEnumerable errorRecords = null; + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimSessionSet: + sessionToRemove = this.sessionState.QuerySession(cmdlet.CimSession, out errorRecords); + break; + case CimBaseCommand.ComputerNameSet: + sessionToRemove = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); + break; + case CimBaseCommand.SessionIdSet: + sessionToRemove = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); + break; + case CimBaseCommand.InstanceIdSet: + sessionToRemove = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords); + break; + case CimBaseCommand.NameSet: + sessionToRemove = this.sessionState.QuerySession(cmdlet.Name, out errorRecords); + break; + default: + break; + } + + if (sessionToRemove != null) + { + foreach (PSObject psobject in sessionToRemove) + { + if (cmdlet.ShouldProcess(this.sessionState.GetRemoveSessionObjectTarget(psobject), RemoveCimSessionActionName)) + { + this.sessionState.RemoveOneSessionObjectFromCache(psobject); + } + } + } + + if (errorRecords != null) + { + foreach (ErrorRecord errRecord in errorRecords) + { + cmdlet.WriteError(errRecord); + } + } + } + } + + #endregion + + #region CimTestSession + + /// + /// Class , which is used to + /// test cimsession and execute async operations. + /// + internal class CimTestSession : CimAsyncOperation + { + /// + /// Initializes a new instance of the class. + /// + internal CimTestSession() + : base() + { + } + + /// + /// Test the session connection with + /// given object. + /// + /// + /// + internal void TestCimSession( + string computerName, + CimSessionProxy proxy) + { + DebugHelper.WriteLogEx(); + this.SubscribeEventAndAddProxytoCache(proxy); + proxy.TestConnectionAsync(); + } + } + + #endregion + +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..5cdc168ae242a18224b7f8d355237789319588d7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -0,0 +1,2313 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.Management.Infrastructure.Generic; +using Microsoft.Management.Infrastructure.Options; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + #region Context base class + + /// + /// Context base class for cross operations + /// for example, some cmdlets need to query instance first and then + /// remove instance, those scenarios need context object transferred + /// from one operation to another. + /// + internal abstract class XOperationContextBase + { + /// + /// namespace + /// + internal string Namespace + { + get + { + return this.nameSpace; + } + } + + protected string nameSpace; + + /// + /// + /// Session proxy. + /// + /// + internal CimSessionProxy Proxy + { + get + { + return this.proxy; + } + } + + protected CimSessionProxy proxy; + } + + /// + /// Class provides all information regarding the + /// current invocation to the .NET API. + /// + internal class InvocationContext + { + /// + /// Initializes a new instance of the class. + /// + /// + internal InvocationContext(CimSessionProxy proxy) + { + if (proxy != null) + { + this.ComputerName = proxy.CimSession.ComputerName; + this.TargetCimInstance = proxy.TargetCimInstance; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal InvocationContext(string computerName, CimInstance targetCimInstance) + { + this.ComputerName = computerName; + this.TargetCimInstance = targetCimInstance; + } + + /// + /// + /// ComputerName of the session + /// + /// + /// + /// return value could be null + /// + internal virtual string ComputerName { get; } + + /// + /// + /// CimInstance on which the current operation against. + /// + /// + /// + /// return value could be null + /// + internal virtual CimInstance TargetCimInstance { get; } + } + #endregion + + #region Preprocessing of result object interface + /// + /// Defines a method to preprocessing an result object before sending to + /// output pipeline. + /// + [ComVisible(false)] + internal interface IObjectPreProcess + { + /// + /// Performs pre processing of given result object. + /// + /// + /// Pre-processed object. + object Process(object resultObject); + } + #endregion + + #region Eventargs class + /// + /// + /// CmdletActionEventArgs holds a CimBaseAction object + /// + /// + internal sealed class CmdletActionEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// CimBaseAction object bound to the event. + public CmdletActionEventArgs(CimBaseAction action) + { + this.Action = action; + } + + public readonly CimBaseAction Action; + } + + /// + /// OperationEventArgs holds a cancellation object, and an operation. + /// + internal sealed class OperationEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// Object used to cancel the operation. + /// Async observable operation. + public OperationEventArgs(IDisposable operationCancellation, + IObservable operation, + bool theSuccess) + { + this.operationCancellation = operationCancellation; + this.operation = operation; + this.success = theSuccess; + } + + public readonly IDisposable operationCancellation; + public readonly IObservable operation; + public readonly bool success; + } + + #endregion + + /// + /// + /// Wrapper of object. + /// A CimSessionProxy object can only execute one operation at specific moment. + /// + /// + internal class CimSessionProxy : IDisposable + { + #region static members + + /// + /// + /// global operation counter + /// + /// + private static long gOperationCounter = 0; + + /// + /// Temporary CimSession cache lock. + /// + private static readonly object temporarySessionCacheLock = new(); + + /// + /// temporary CimSession cache + /// Temporary CimSession means the session is created by cimcmdlets, + /// which is not created by cmdlet. + /// Due to some cmdlet, such as + /// might need to split the operation into multiple stages, i.e., query + /// CimInstance firstly, then remove the CimInstance resulted from query, + /// such that the temporary CimSession need to be shared between + /// multiple objects, introducing a + /// temporary session cache is necessary to control the lifetime of the + /// temporary CimSession objects. + /// + /// Once the reference count of the CimSession is decreased to 0, + /// then call Dispose on it. + /// + /// + private static readonly Dictionary temporarySessionCache = new(); + + /// + /// + /// Add to temporary cache. + /// If CimSession already present in cache, then increase the refcount by 1, + /// otherwise insert it into the cache. + /// + /// + /// CimSession to be added. + internal static void AddCimSessionToTemporaryCache(CimSession session) + { + if (session != null) + { + lock (temporarySessionCacheLock) + { + if (temporarySessionCache.ContainsKey(session)) + { + temporarySessionCache[session]++; + DebugHelper.WriteLogEx(@"Increase cimsession ref count {0}", 1, temporarySessionCache[session]); + } + else + { + temporarySessionCache.Add(session, 1); + DebugHelper.WriteLogEx(@"Add cimsession to cache. Ref count {0}", 1, temporarySessionCache[session]); + } + } + } + } + + /// + /// Wrapper function to remove CimSession from cache + /// + /// + /// Whether need to dispose the object. + private static void RemoveCimSessionFromTemporaryCache(CimSession session, + bool dispose) + { + if (session != null) + { + bool removed = false; + lock (temporarySessionCacheLock) + { + if (temporarySessionCache.ContainsKey(session)) + { + temporarySessionCache[session]--; + DebugHelper.WriteLogEx(@"Decrease cimsession ref count {0}", 1, temporarySessionCache[session]); + if (temporarySessionCache[session] == 0) + { + removed = true; + temporarySessionCache.Remove(session); + } + } + } + // there is a race condition that if + // one thread is waiting to add CimSession to cache, + // while current thread is removing the CimSession, + // then invalid CimSession may be added to cache. + // Ignored this scenario in CimCmdlet implementation, + // since the code inside cimcmdlet will not hit this + // scenario anyway. + if (removed && dispose) + { + DebugHelper.WriteLogEx(@"Dispose cimsession ", 1); + session.Dispose(); + } + } + } + + /// + /// + /// Remove from temporary cache. + /// If CimSession already present in cache, then decrease the refcount by 1, + /// otherwise ignore. + /// If refcount became 0, call dispose on the object. + /// + /// + /// CimSession to be added. + internal static void RemoveCimSessionFromTemporaryCache(CimSession session) + { + RemoveCimSessionFromTemporaryCache(session, true); + } + #endregion + + #region Event definitions + + /// + /// Define an Event based on the NewActionHandler. + /// + public event EventHandler OnNewCmdletAction; + + /// + /// Event triggered when a new operation is started. + /// + public event EventHandler OnOperationCreated; + + /// + /// Event triggered when a new operation is completed, + /// either success or failed. + /// + public event EventHandler OnOperationDeleted; + + #endregion + + #region constructors + + /// + /// Initializes a new instance of the class. + /// + /// + /// Then create wrapper object by given CimSessionProxy object. + /// + /// + public CimSessionProxy(CimSessionProxy proxy) + { + DebugHelper.WriteLogEx("protocol = {0}", 1, proxy.Protocol); + + CreateSetSession(null, proxy.CimSession, null, proxy.OperationOptions, proxy.IsTemporaryCimSession); + this.Protocol = proxy.Protocol; + this.OperationTimeout = proxy.OperationTimeout; + this.isDefaultSession = proxy.isDefaultSession; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name. + /// Then create wrapper object. + /// + /// + public CimSessionProxy(string computerName) + { + CreateSetSession(computerName, null, null, null, false); + this.isDefaultSession = computerName == ConstValue.NullComputerName; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name + /// and session options. + /// Then create wrapper object. + /// + /// + /// + public CimSessionProxy(string computerName, CimSessionOptions sessionOptions) + { + CreateSetSession(computerName, null, sessionOptions, null, false); + this.isDefaultSession = computerName == ConstValue.NullComputerName; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name + /// and cimInstance. Then create wrapper object. + /// + /// + /// + public CimSessionProxy(string computerName, CimInstance cimInstance) + { + DebugHelper.WriteLogEx("ComputerName {0}; cimInstance.CimSessionInstanceID = {1}; cimInstance.CimSessionComputerName = {2}.", + 0, + computerName, + cimInstance.GetCimSessionInstanceId(), + cimInstance.GetCimSessionComputerName()); + + if (computerName != ConstValue.NullComputerName) + { + CreateSetSession(computerName, null, null, null, false); + return; + } + + Debug.Assert(cimInstance != null, "Caller should verify cimInstance != null"); + + // computerName is null, fallback to create session from cimInstance + CimSessionState state = CimSessionBase.GetCimSessionState(); + if (state != null) + { + CimSession session = state.QuerySession(cimInstance.GetCimSessionInstanceId()); + if (session != null) + { + DebugHelper.WriteLogEx("Found the session from cache with InstanceID={0}.", 0, cimInstance.GetCimSessionInstanceId()); + CreateSetSession(null, session, null, null, false); + return; + } + } + + string cimsessionComputerName = cimInstance.GetCimSessionComputerName(); + CreateSetSession(cimsessionComputerName, null, null, null, false); + this.isDefaultSession = cimsessionComputerName == ConstValue.NullComputerName; + + DebugHelper.WriteLogEx("Create a temp session with computerName = {0}.", 0, cimsessionComputerName); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name, + /// session options. + /// + /// + /// + /// Used when create async operation. + public CimSessionProxy(string computerName, CimSessionOptions sessionOptions, CimOperationOptions operOptions) + { + CreateSetSession(computerName, null, sessionOptions, operOptions, false); + this.isDefaultSession = computerName == ConstValue.NullComputerName; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name. + /// Then create wrapper object. + /// + /// + /// Used when create async operation. + public CimSessionProxy(string computerName, CimOperationOptions operOptions) + { + CreateSetSession(computerName, null, null, operOptions, false); + this.isDefaultSession = computerName == ConstValue.NullComputerName; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create wrapper object by given session object. + /// + /// + public CimSessionProxy(CimSession session) + { + CreateSetSession(null, session, null, null, false); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create wrapper object by given session object. + /// + /// + /// Used when create async operation. + public CimSessionProxy(CimSession session, CimOperationOptions operOptions) + { + CreateSetSession(null, session, null, operOptions, false); + } + + /// + /// Initialize CimSessionProxy object. + /// + /// + /// + /// + /// + private void CreateSetSession( + string computerName, + CimSession cimSession, + CimSessionOptions sessionOptions, + CimOperationOptions operOptions, + bool temporaryCimSession) + { + DebugHelper.WriteLogEx("computername {0}; cimsession {1}; sessionOptions {2}; operationOptions {3}.", 0, computerName, cimSession, sessionOptions, operOptions); + + lock (this.stateLock) + { + this.CancelOperation = null; + this.operation = null; + } + + InitOption(operOptions); + this.Protocol = ProtocolType.Wsman; + this.IsTemporaryCimSession = temporaryCimSession; + + if (cimSession != null) + { + this.CimSession = cimSession; + CimSessionState state = CimSessionBase.GetCimSessionState(); + if (state != null) + { + CimSessionWrapper wrapper = state.QuerySession(cimSession); + if (wrapper != null) + { + this.Protocol = wrapper.GetProtocolType(); + } + } + } + else + { + if (sessionOptions != null) + { + if (sessionOptions is DComSessionOptions) + { + string defaultComputerName = ConstValue.IsDefaultComputerName(computerName) ? ConstValue.NullComputerName : computerName; + this.CimSession = CimSession.Create(defaultComputerName, sessionOptions); + this.Protocol = ProtocolType.Dcom; + } + else + { + this.CimSession = CimSession.Create(computerName, sessionOptions); + } + } + else + { + this.CimSession = CreateCimSessionByComputerName(computerName); + } + + this.IsTemporaryCimSession = true; + } + + if (this.IsTemporaryCimSession) + { + AddCimSessionToTemporaryCache(this.CimSession); + } + + this.invocationContextObject = new InvocationContext(this); + DebugHelper.WriteLog("Protocol {0}, Is temporary session ? {1}", 1, this.Protocol, this.IsTemporaryCimSession); + } + + #endregion + + #region set operation options + + /// + /// Gets or sets a value indicating whether to retrieve localized information for the CIM class. + /// + public bool Amended + { + get => OperationOptions.Flags.HasFlag(CimOperationFlags.LocalizedQualifiers); + + set + { + if (value) + { + OperationOptions.Flags |= CimOperationFlags.LocalizedQualifiers; + } + else + { + OperationOptions.Flags &= ~CimOperationFlags.LocalizedQualifiers; + } + } + } + + /// + /// Set timeout value (seconds) of the operation. + /// + public uint OperationTimeout + { + get + { + return (uint)this.OperationOptions.Timeout.TotalSeconds; + } + + set + { + DebugHelper.WriteLogEx("OperationTimeout {0},", 0, value); + + this.OperationOptions.Timeout = TimeSpan.FromSeconds((double)value); + } + } + + /// + /// Set resource URI of the operation. + /// + public Uri ResourceUri + { + get + { + return this.OperationOptions.ResourceUri; + } + + set + { + DebugHelper.WriteLogEx("ResourceUri {0},", 0, value); + + this.OperationOptions.ResourceUri = value; + } + } + + /// + /// Enable/Disable the method result streaming, + /// it is enabled by default. + /// + public bool EnableMethodResultStreaming + { + get + { + return this.OperationOptions.EnableMethodResultStreaming; + } + + set + { + DebugHelper.WriteLogEx("EnableMethodResultStreaming {0}", 0, value); + this.OperationOptions.EnableMethodResultStreaming = value; + } + } + + /// + /// Enable/Disable prompt user streaming, + /// it is enabled by default. + /// + public bool EnablePromptUser + { + set + { + DebugHelper.WriteLogEx("EnablePromptUser {0}", 0, value); + if (value) + { + this.OperationOptions.PromptUser = this.PromptUser; + } + } + } + + /// + /// Enable the pssemantics. + /// + private void EnablePSSemantics() + { + DebugHelper.WriteLogEx(); + + // this.options.PromptUserForceFlag... + // this.options.WriteErrorMode + this.OperationOptions.WriteErrorMode = CimCallbackMode.Inquire; + + // !!!NOTES: Does not subscribe to PromptUser for CimCmdlets now + // since cmdlet does not provider an approach + // to let user select how to handle prompt message + // this can be enabled later if needed. + this.OperationOptions.WriteError = this.WriteError; + this.OperationOptions.WriteMessage = this.WriteMessage; + this.OperationOptions.WriteProgress = this.WriteProgress; + } + + /// + /// Set keyonly property. + /// + public SwitchParameter KeyOnly + { + set { this.OperationOptions.KeysOnly = value.IsPresent; } + } + + /// + /// Set Shallow flag. + /// + public SwitchParameter Shallow + { + set + { + if (value.IsPresent) + { + this.OperationOptions.Flags = CimOperationFlags.PolymorphismShallow; + } + else + { + this.OperationOptions.Flags = CimOperationFlags.None; + } + } + } + + /// + /// Initialize the operation option. + /// + private void InitOption(CimOperationOptions operOptions) + { + DebugHelper.WriteLogEx(); + + if (operOptions != null) + { + this.OperationOptions = new CimOperationOptions(operOptions); + } + else + { + this.OperationOptions ??= new CimOperationOptions(); + } + + this.EnableMethodResultStreaming = true; + this.EnablePSSemantics(); + } + + #endregion + + #region misc operations + + /// + /// Caller call Detach to retrieve the session + /// object and control the lifecycle of the CimSession object. + /// + /// + public CimSession Detach() + { + DebugHelper.WriteLogEx(); + + // Remove the CimSession from cache but don't dispose it + RemoveCimSessionFromTemporaryCache(this.CimSession, false); + CimSession sessionToReturn = this.CimSession; + this.CimSession = null; + this.IsTemporaryCimSession = false; + return sessionToReturn; + } + + /// + /// Add a new operation to cache. + /// + /// + /// + private void AddOperation(IObservable operation) + { + DebugHelper.WriteLogEx(); + + lock (this.stateLock) + { + Debug.Assert(this.Completed, "Caller should verify that there is no operation in progress"); + this.operation = operation; + } + } + + /// + /// Remove object from cache. + /// + /// + private void RemoveOperation(IObservable operation) + { + DebugHelper.WriteLogEx(); + + lock (this.stateLock) + { + Debug.Assert(this.operation == operation, "Caller should verify that the operation to remove is the operation in progress"); + + this.DisposeCancelOperation(); + + if (this.operation != null) + { + this.operation = null; + } + + if (this.CimSession != null && this.ContextObject == null) + { + DebugHelper.WriteLog("Dispose this proxy object @ RemoveOperation"); + this.Dispose(); + } + } + } + + /// + /// + /// Trigger an event that new action available + /// + /// + /// + protected void FireNewActionEvent(CimBaseAction action) + { + DebugHelper.WriteLogEx(); + + CmdletActionEventArgs actionArgs = new(action); + if (!PreNewActionEvent(actionArgs)) + { + return; + } + + EventHandler temp = this.OnNewCmdletAction; + if (temp != null) + { + temp(this.CimSession, actionArgs); + } + else + { + DebugHelper.WriteLog("Ignore action since OnNewCmdletAction is null.", 5); + } + + this.PostNewActionEvent(actionArgs); + } + + /// + /// + /// Trigger an event that new operation is created + /// + /// + /// + /// + private void FireOperationCreatedEvent( + IDisposable cancelOperation, + IObservable operation) + { + DebugHelper.WriteLogEx(); + + OperationEventArgs args = new( + cancelOperation, operation, false); + this.OnOperationCreated?.Invoke(this.CimSession, args); + + this.PostOperationCreateEvent(args); + } + + /// + /// + /// Trigger an event that an operation is deleted + /// + /// + /// + private void FireOperationDeletedEvent( + IObservable operation, + bool success) + { + DebugHelper.WriteLogEx(); + this.WriteOperationCompleteMessage(this.operationName); + OperationEventArgs args = new( + null, operation, success); + PreOperationDeleteEvent(args); + this.OnOperationDeleted?.Invoke(this.CimSession, args); + + this.PostOperationDeleteEvent(args); + this.RemoveOperation(operation); + this.operationName = null; + } + + #endregion + + #region PSExtension callback functions + + /// + /// + /// WriteMessage callback + /// + /// + /// + /// + internal void WriteMessage(uint channel, string message) + { + DebugHelper.WriteLogEx("Channel = {0} message = {1}", 0, channel, message); + try + { + CimWriteMessage action = new(channel, message); + this.FireNewActionEvent(action); + } + catch (Exception ex) + { + DebugHelper.WriteLogEx("{0}", 0, ex); + } + } + + /// + /// + /// Write operation start verbose message + /// + /// + /// + /// + internal void WriteOperationStartMessage(string operation, Hashtable parameterList) + { + DebugHelper.WriteLogEx(); + StringBuilder parameters = new(); + if (parameterList != null) + { + foreach (string key in parameterList.Keys) + { + if (parameters.Length > 0) + { + parameters.Append(','); + } + + parameters.Append(CultureInfo.CurrentUICulture, $@"'{key}' = {parameterList[key]}"); + } + } + + string operationStartMessage = string.Format(CultureInfo.CurrentUICulture, + CimCmdletStrings.CimOperationStart, + operation, + (parameters.Length == 0) ? "null" : parameters.ToString()); + WriteMessage((uint)CimWriteMessageChannel.Verbose, operationStartMessage); + } + + /// + /// + /// Write operation complete verbose message + /// + /// + /// + internal void WriteOperationCompleteMessage(string operation) + { + DebugHelper.WriteLogEx(); + string operationCompleteMessage = string.Format(CultureInfo.CurrentUICulture, + CimCmdletStrings.CimOperationCompleted, + operation); + WriteMessage((uint)CimWriteMessageChannel.Verbose, operationCompleteMessage); + } + + /// + /// + /// WriteProgress callback + /// + /// + /// + /// + /// + /// + /// + public void WriteProgress(string activity, + string currentOperation, + string statusDescription, + uint percentageCompleted, + uint secondsRemaining) + { + DebugHelper.WriteLogEx("activity:{0}; currentOperation:{1}; percentageCompleted:{2}; secondsRemaining:{3}", + 0, activity, currentOperation, percentageCompleted, secondsRemaining); + + try + { + CimWriteProgress action = new( + activity, + (int)this.operationID, + currentOperation, + statusDescription, + percentageCompleted, + secondsRemaining); + this.FireNewActionEvent(action); + } + catch (Exception ex) + { + DebugHelper.WriteLogEx("{0}", 0, ex); + } + } + + /// + /// + /// WriteError callback + /// + /// + /// + /// + public CimResponseType WriteError(CimInstance instance) + { + DebugHelper.WriteLogEx("Error:{0}", 0, instance); + try + { + CimWriteError action = new(instance, this.invocationContextObject); + this.FireNewActionEvent(action); + return action.GetResponse(); + } + catch (Exception ex) + { + DebugHelper.WriteLogEx("{0}", 0, ex); + return CimResponseType.NoToAll; + } + } + + /// + /// PromptUser callback. + /// + /// + /// + /// + public CimResponseType PromptUser(string message, CimPromptType prompt) + { + DebugHelper.WriteLogEx("message:{0} prompt:{1}", 0, message, prompt); + try + { + CimPromptUser action = new(message, prompt); + this.FireNewActionEvent(action); + return action.GetResponse(); + } + catch (Exception ex) + { + DebugHelper.WriteLogEx("{0}", 0, ex); + return CimResponseType.NoToAll; + } + } + #endregion + + #region Async result handler + + /// + /// + /// Handle async event triggered by + /// + /// + /// Object triggered the event. + /// Async result event argument. + internal void ResultEventHandler( + object observer, + AsyncResultEventArgsBase resultArgs) + { + DebugHelper.WriteLogEx(); + switch (resultArgs.resultType) + { + case AsyncResultType.Completion: + { + DebugHelper.WriteLog("ResultEventHandler::Completion", 4); + + AsyncResultCompleteEventArgs args = resultArgs as AsyncResultCompleteEventArgs; + this.FireOperationDeletedEvent(args.observable, true); + } + + break; + case AsyncResultType.Exception: + { + AsyncResultErrorEventArgs args = resultArgs as AsyncResultErrorEventArgs; + DebugHelper.WriteLog("ResultEventHandler::Exception {0}", 4, args.error); + + using (CimWriteError action = new(args.error, this.invocationContextObject, args.context)) + { + this.FireNewActionEvent(action); + } + + this.FireOperationDeletedEvent(args.observable, false); + } + + break; + case AsyncResultType.Result: + { + AsyncResultObjectEventArgs args = resultArgs as AsyncResultObjectEventArgs; + DebugHelper.WriteLog("ResultEventHandler::Result {0}", 4, args.resultObject); + object resultObject = args.resultObject; + if (!this.isDefaultSession) + { + AddShowComputerNameMarker(resultObject); + } + + if (this.ObjectPreProcess != null) + { + resultObject = this.ObjectPreProcess.Process(resultObject); + } +#if DEBUG + resultObject = PostProcessCimInstance(resultObject); +#endif + CimWriteResultObject action = new(resultObject, this.ContextObject); + this.FireNewActionEvent(action); + } + + break; + default: + break; + } + } + + /// + /// This method adds a note property to , + /// which will cause the default PowerShell formatting and output + /// to include PSComputerName column/property in the display. + /// + /// + private static void AddShowComputerNameMarker(object o) + { + if (o == null) + { + return; + } + + PSObject pso = PSObject.AsPSObject(o); + if (pso.BaseObject is not CimInstance) + { + return; + } + + PSNoteProperty psShowComputerNameProperty = new(ConstValue.ShowComputerNameNoteProperty, true); + pso.Members.Add(psShowComputerNameProperty); + } + +#if DEBUG + private static readonly bool isCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive(); + + private static bool GetIsCliXmlTestabilityHookActive() + { + return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CDXML_CLIXML_TEST")); + } + + private static object PostProcessCimInstance(object resultObject) + { + DebugHelper.WriteLogEx(); + if (isCliXmlTestabilityHookActive && (resultObject is CimInstance)) + { + string serializedForm = PSSerializer.Serialize(resultObject as CimInstance, depth: 1); + object deserializedObject = PSSerializer.Deserialize(serializedForm); + object returnObject = (deserializedObject is PSObject) ? (deserializedObject as PSObject).BaseObject : deserializedObject; + DebugHelper.WriteLogEx("Deserialized object is {0}, type {1}", 1, returnObject, returnObject.GetType()); + return returnObject; + } + + return resultObject; + } +#endif + #endregion + + #region Async operations + + /// + /// + /// create a cim instance asynchronously + /// + /// + /// + /// + public void CreateInstanceAsync(string namespaceName, CimInstance instance) + { + Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.OperationOptions.EnableMethodResultStreaming); + this.CheckAvailability(); + this.TargetCimInstance = instance; + this.operationName = CimCmdletStrings.CimOperationNameCreateInstance; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"instance", instance); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncResult asyncResult = this.CimSession.CreateInstanceAsync(namespaceName, instance, this.OperationOptions); + ConsumeCimInstanceAsync(asyncResult, new CimResultContext(instance)); + } + + /// + /// Delete a cim instance asynchronously. + /// + /// + /// + public void DeleteInstanceAsync(string namespaceName, CimInstance instance) + { + Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + DebugHelper.WriteLogEx("namespace = {0}; classname = {1};", 0, namespaceName, instance.CimSystemProperties.ClassName); + this.CheckAvailability(); + this.TargetCimInstance = instance; + this.operationName = CimCmdletStrings.CimOperationNameDeleteInstance; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"instance", instance); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncStatus asyncResult = this.CimSession.DeleteInstanceAsync(namespaceName, instance, this.OperationOptions); + ConsumeObjectAsync(asyncResult, new CimResultContext(instance)); + } + + /// + /// Get cim instance asynchronously. + /// + /// + /// + public void GetInstanceAsync(string namespaceName, CimInstance instance) + { + Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + DebugHelper.WriteLogEx("namespace = {0}; classname = {1}; keyonly = {2}", 0, namespaceName, instance.CimSystemProperties.ClassName, this.OperationOptions.KeysOnly); + this.CheckAvailability(); + this.TargetCimInstance = instance; + this.operationName = CimCmdletStrings.CimOperationNameGetInstance; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"instance", instance); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncResult asyncResult = this.CimSession.GetInstanceAsync(namespaceName, instance, this.OperationOptions); + ConsumeCimInstanceAsync(asyncResult, new CimResultContext(instance)); + } + + /// + /// Modify cim instance asynchronously. + /// + /// + /// + public void ModifyInstanceAsync(string namespaceName, CimInstance instance) + { + Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + DebugHelper.WriteLogEx("namespace = {0}; classname = {1}", 0, namespaceName, instance.CimSystemProperties.ClassName); + this.CheckAvailability(); + this.TargetCimInstance = instance; + this.operationName = CimCmdletStrings.CimOperationNameModifyInstance; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"instance", instance); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncResult asyncResult = this.CimSession.ModifyInstanceAsync(namespaceName, instance, this.OperationOptions); + ConsumeObjectAsync(asyncResult, new CimResultContext(instance)); + } + + /// + /// Enumerate cim instance associated with the + /// given instance asynchronously. + /// + /// + /// + /// + /// + /// + /// + public void EnumerateAssociatedInstancesAsync( + string namespaceName, + CimInstance sourceInstance, + string associationClassName, + string resultClassName, + string sourceRole, + string resultRole) + { + Debug.Assert(sourceInstance != null, "Caller should verify that sourceInstance != NULL."); + DebugHelper.WriteLogEx("Instance class {0}, association class {1}", 0, sourceInstance.CimSystemProperties.ClassName, associationClassName); + this.CheckAvailability(); + this.TargetCimInstance = sourceInstance; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateAssociatedInstances; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"sourceInstance", sourceInstance); + this.operationParameters.Add(@"associationClassName", associationClassName); + this.operationParameters.Add(@"resultClassName", resultClassName); + this.operationParameters.Add(@"sourceRole", sourceRole); + this.operationParameters.Add(@"resultRole", resultRole); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateAssociatedInstancesAsync(namespaceName, sourceInstance, associationClassName, resultClassName, sourceRole, resultRole, this.OperationOptions); + ConsumeCimInstanceAsync(asyncResult, new CimResultContext(sourceInstance)); + } + + /// + /// Enumerate cim instance asynchronously. + /// + /// + /// + public void EnumerateInstancesAsync(string namespaceName, string className) + { + DebugHelper.WriteLogEx("KeyOnly {0}", 0, this.OperationOptions.KeysOnly); + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateInstances; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"className", className); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateInstancesAsync(namespaceName, className, this.OperationOptions); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); + ConsumeCimInstanceAsync(asyncResult, new CimResultContext(errorSource)); + } + + /// + /// + /// Enumerate referencing instance associated with + /// the given instance asynchronously + /// + /// + /// + /// + /// + /// + public void EnumerateReferencingInstancesAsync( + string namespaceName, + CimInstance sourceInstance, + string associationClassName, + string sourceRole) + { + this.CheckAvailability(); + } + + /// + /// + /// Query cim instance asynchronously + /// + /// + /// + /// + /// + public void QueryInstancesAsync( + string namespaceName, + string queryDialect, + string queryExpression) + { + DebugHelper.WriteLogEx("KeyOnly = {0}", 0, this.OperationOptions.KeysOnly); + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameQueryInstances; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"queryDialect", queryDialect); + this.operationParameters.Add(@"queryExpression", queryExpression); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.QueryInstancesAsync(namespaceName, queryDialect, queryExpression, this.OperationOptions); + ConsumeCimInstanceAsync(asyncResult, null); + } + + /// + /// Enumerate cim class asynchronously. + /// + /// + /// + public void EnumerateClassesAsync(string namespaceName) + { + DebugHelper.WriteLogEx("namespace {0}", 0, namespaceName); + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateClasses; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, null, this.OperationOptions); + ConsumeCimClassAsync(asyncResult, null); + } + + /// + /// Enumerate cim class asynchronously. + /// + /// + /// + public void EnumerateClassesAsync(string namespaceName, string className) + { + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateClasses; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"className", className); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, className, this.OperationOptions); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); + ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); + } + + /// + /// Get cim class asynchronously. + /// + /// + /// + public void GetClassAsync(string namespaceName, string className) + { + DebugHelper.WriteLogEx("namespace = {0}, className = {1}", 0, namespaceName, className); + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameGetClass; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"className", className); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncResult asyncResult = this.CimSession.GetClassAsync(namespaceName, className, this.OperationOptions); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); + ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); + } + + /// + /// Invoke method of a given cim instance asynchronously. + /// + /// + /// + /// + /// + public void InvokeMethodAsync( + string namespaceName, + CimInstance instance, + string methodName, + CimMethodParametersCollection methodParameters) + { + Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.OperationOptions.EnableMethodResultStreaming); + this.CheckAvailability(); + this.TargetCimInstance = instance; + this.operationName = CimCmdletStrings.CimOperationNameInvokeMethod; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"instance", instance); + this.operationParameters.Add(@"methodName", methodName); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.InvokeMethodAsync(namespaceName, instance, methodName, methodParameters, this.OperationOptions); + ConsumeCimInvokeMethodResultAsync(asyncResult, instance.CimSystemProperties.ClassName, methodName, new CimResultContext(instance)); + } + + /// + /// Invoke static method of a given class asynchronously. + /// + /// + /// + /// + /// + public void InvokeMethodAsync( + string namespaceName, + string className, + string methodName, + CimMethodParametersCollection methodParameters) + { + DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.OperationOptions.EnableMethodResultStreaming); + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameInvokeMethod; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"className", className); + this.operationParameters.Add(@"methodName", methodName); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + CimAsyncMultipleResults asyncResult = this.CimSession.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.OperationOptions); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); + ConsumeCimInvokeMethodResultAsync(asyncResult, className, methodName, new CimResultContext(errorSource)); + } + + /// + /// + /// Subscribe to cim indication asynchronously + /// + /// + /// + /// + /// + public void SubscribeAsync( + string namespaceName, + string queryDialect, + string queryExpression) + { + DebugHelper.WriteLogEx("QueryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); + this.CheckAvailability(); + this.TargetCimInstance = null; + this.operationName = CimCmdletStrings.CimOperationNameSubscribeIndication; + this.operationParameters.Clear(); + this.operationParameters.Add(@"namespaceName", namespaceName); + this.operationParameters.Add(@"queryDialect", queryDialect); + this.operationParameters.Add(@"queryExpression", queryExpression); + this.WriteOperationStartMessage(this.operationName, this.operationParameters); + + this.OperationOptions.Flags |= CimOperationFlags.ReportOperationStarted; + CimAsyncMultipleResults asyncResult = this.CimSession.SubscribeAsync(namespaceName, queryDialect, queryExpression, this.OperationOptions); + ConsumeCimSubscriptionResultAsync(asyncResult, null); + } + + /// + /// + /// Test connection asynchronously + /// + /// + public void TestConnectionAsync() + { + DebugHelper.WriteLogEx("Start test connection", 0); + this.CheckAvailability(); + this.TargetCimInstance = null; + CimAsyncResult asyncResult = this.CimSession.TestConnectionAsync(); + // ignore the test connection result objects + ConsumeCimInstanceAsync(asyncResult, true, null); + } + + #endregion + + #region pre action APIs + /// + /// Called before new action event. + /// + /// + protected virtual bool PreNewActionEvent(CmdletActionEventArgs args) + { + return true; + } + /// + /// Called before operation delete event. + /// + /// + protected virtual void PreOperationDeleteEvent(OperationEventArgs args) + { + } + #endregion + + #region post action APIs + + /// + /// Called after new action event. + /// + /// + protected virtual void PostNewActionEvent(CmdletActionEventArgs args) + { + } + /// + /// Called after operation create event. + /// + /// + protected virtual void PostOperationCreateEvent(OperationEventArgs args) + { + } + /// + /// Called after operation delete event. + /// + /// + protected virtual void PostOperationDeleteEvent(OperationEventArgs args) + { + } + #endregion + + #region members + + /// + /// + /// Unique operation ID + /// + /// + private long operationID; + + /// + /// The CimSession object managed by this proxy object, + /// which is either created by constructor OR passed in by caller. + /// The session will be closed while disposing this proxy object + /// if it is created by constructor. + /// + internal CimSession CimSession { get; private set; } + + /// + /// The current CimInstance object, against which issued + /// current operation, it could be null. + /// + internal CimInstance TargetCimInstance { get; private set; } + + internal bool IsTemporaryCimSession { get; private set; } + + /// + /// The CimOperationOptions object, which specifies the options + /// of the operation against the session object. + /// Caller can control the timeout, method streaming support, and + /// extended ps semantics support, etc. + /// The setting MUST be set before start new operation on the + /// this proxy object. + /// + internal CimOperationOptions OperationOptions { get; private set; } + + /// + /// All operations completed. + /// + private bool Completed + { + get { return this.operation == null; } + } + + /// + /// Lock object used to lock + /// operation & cancelOperation members. + /// + private readonly object stateLock = new(); + + /// + /// The operation issued by cimSession. + /// + private IObservable operation; + + /// + /// The current operation name. + /// + private string operationName; + + /// + /// The current operation parameters. + /// + private readonly Hashtable operationParameters = new(); + + /// + /// Handler used to cancel operation. + /// + private IDisposable _cancelOperation; + + /// + /// CancelOperation disposed flag. + /// + private int _cancelOperationDisposed = 0; + + /// + /// Dispose the cancel operation. + /// + private void DisposeCancelOperation() + { + DebugHelper.WriteLogEx("CancelOperation Disposed = {0}", 0, this._cancelOperationDisposed); + if (Interlocked.CompareExchange(ref this._cancelOperationDisposed, 1, 0) == 0) + { + if (this._cancelOperation != null) + { + DebugHelper.WriteLog("CimSessionProxy::Dispose async operation.", 4); + this._cancelOperation.Dispose(); + this._cancelOperation = null; + } + } + } + + /// + /// Set the cancel operation. + /// + private IDisposable CancelOperation + { + get + { + return this._cancelOperation; + } + + set + { + DebugHelper.WriteLogEx(); + this._cancelOperation = value; + Interlocked.Exchange(ref this._cancelOperationDisposed, 0); + } + } + + /// + /// Current protocol name + /// DCOM or WSMAN. + /// + internal ProtocolType Protocol { get; private set; } + + /// + /// Cross operation context object. + /// + internal XOperationContextBase ContextObject { get; set; } + + /// + /// Invocation context object. + /// + private InvocationContext invocationContextObject; + + /// + /// A preprocess object to pre-processing the result object, + /// for example, adding PSTypeName, etc. + /// + internal IObjectPreProcess ObjectPreProcess { get; set; } + + /// + /// is if this was + /// created to handle the "default" session, in cases where cmdlets are invoked without + /// ComputerName and/or CimSession parameters. + /// + private readonly bool isDefaultSession; + + #endregion + + #region IDisposable + + /// + /// IDisposable interface. + /// + private int _disposed; + + // Implement IDisposable. + // Do not make this method virtual. + // A derived class should not be able to override this method. + public void Dispose() + { + Dispose(true); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SuppressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + // Dispose(bool disposing) executes in two distinct scenarios. + // If disposing equals true, the method has been called directly + // or indirectly by a user's code. Managed and unmanaged resources + // can be disposed. + // If disposing equals false, the method has been called by the + // runtime from inside the finalizer and you should not reference + // other objects. Only unmanaged resources can be disposed. + protected virtual void Dispose(bool disposing) + { + DebugHelper.WriteLogEx("Disposed = {0}", 0, this.IsDisposed); + + if (Interlocked.CompareExchange(ref this._disposed, 1, 0) == 0) + { + if (disposing) + { + // Dispose managed resources. + this.DisposeCancelOperation(); + + if (this.OperationOptions != null) + { + this.OperationOptions.Dispose(); + this.OperationOptions = null; + } + + DisposeTemporaryCimSession(); + } + } + } + + public bool IsDisposed + { + get + { + return this._disposed == 1; + } + } + + /// + /// + /// Dispose temporary . + /// + /// + private void DisposeTemporaryCimSession() + { + if (this.IsTemporaryCimSession && this.CimSession != null) + { + // remove the cimsession from temporary cache + RemoveCimSessionFromTemporaryCache(this.CimSession); + this.IsTemporaryCimSession = false; + this.CimSession = null; + } + } + #endregion + + #region helper methods + + /// + /// + /// Consume the results of async operations + /// + /// + /// + /// + protected void ConsumeCimInstanceAsync(IObservable asyncResult, + CimResultContext cimResultContext) + { + ConsumeCimInstanceAsync(asyncResult, false, cimResultContext); + } + + /// + /// + /// Consume the CimInstance results of async operations. + /// + /// + /// + /// + /// + protected void ConsumeCimInstanceAsync( + IObservable asyncResult, + bool ignoreResultObjects, + CimResultContext cimResultContext) + { + CimResultObserver observer; + if (ignoreResultObjects) + { + observer = new IgnoreResultObserver(this.CimSession, asyncResult); + } + else + { + observer = new CimResultObserver(this.CimSession, asyncResult, cimResultContext); + } + + observer.OnNewResult += this.ResultEventHandler; + this.operationID = Interlocked.Increment(ref gOperationCounter); + this.AddOperation(asyncResult); + this.CancelOperation = asyncResult.Subscribe(observer); + this.FireOperationCreatedEvent(this.CancelOperation, asyncResult); + } + + /// + /// + /// Consume the results of async operations + /// + /// + /// + /// + protected void ConsumeObjectAsync(IObservable asyncResult, + CimResultContext cimResultContext) + { + CimResultObserver observer = new( + this.CimSession, asyncResult, cimResultContext); + + observer.OnNewResult += this.ResultEventHandler; + this.operationID = Interlocked.Increment(ref gOperationCounter); + this.AddOperation(asyncResult); + this.CancelOperation = asyncResult.Subscribe(observer); + DebugHelper.WriteLog("FireOperationCreatedEvent"); + this.FireOperationCreatedEvent(this.CancelOperation, asyncResult); + } + + /// + /// + /// Consume the of async operations + /// + /// + /// + /// + protected void ConsumeCimClassAsync(IObservable asyncResult, + CimResultContext cimResultContext) + { + CimResultObserver observer = new( + this.CimSession, asyncResult, cimResultContext); + + observer.OnNewResult += this.ResultEventHandler; + this.operationID = Interlocked.Increment(ref gOperationCounter); + this.AddOperation(asyncResult); + this.CancelOperation = asyncResult.Subscribe(observer); + this.FireOperationCreatedEvent(this.CancelOperation, asyncResult); + } + + /// + /// + /// Consume the of async operations + /// + /// + /// + /// + protected void ConsumeCimSubscriptionResultAsync( + IObservable asyncResult, + CimResultContext cimResultContext) + { + CimSubscriptionResultObserver observer = new( + this.CimSession, asyncResult, cimResultContext); + observer.OnNewResult += this.ResultEventHandler; + this.operationID = Interlocked.Increment(ref gOperationCounter); + this.AddOperation(asyncResult); + this.CancelOperation = asyncResult.Subscribe(observer); + this.FireOperationCreatedEvent(this.CancelOperation, asyncResult); + } + + /// + /// + /// Consume the of async operations + /// + /// + /// + /// + /// + /// + protected void ConsumeCimInvokeMethodResultAsync( + IObservable asyncResult, + string className, + string methodName, + CimResultContext cimResultContext) + { + CimMethodResultObserver observer = new(this.CimSession, asyncResult, cimResultContext) + { + ClassName = className, + MethodName = methodName + }; + + observer.OnNewResult += this.ResultEventHandler; + this.operationID = Interlocked.Increment(ref gOperationCounter); + this.AddOperation(asyncResult); + this.CancelOperation = asyncResult.Subscribe(observer); + this.FireOperationCreatedEvent(this.CancelOperation, asyncResult); + } + + /// + /// + /// Check whether current proxy object is available + /// + /// + private void CheckAvailability() + { + DebugHelper.WriteLogEx(); + + AssertSession(); + lock (this.stateLock) + { + if (!this.Completed) + { + throw new InvalidOperationException(CimCmdletStrings.OperationInProgress); + } + } + + DebugHelper.WriteLog("KeyOnly {0},", 1, this.OperationOptions.KeysOnly); + } + + /// + /// + /// Check the wrapped object + /// + /// + private void AssertSession() + { + if (this.IsDisposed || (this.CimSession == null)) + { + DebugHelper.WriteLogEx("Invalid CimSessionProxy object, disposed? {0}; session object {1}", 1, this.IsDisposed, this.CimSession); + throw new ObjectDisposedException(this.ToString()); + } + } + + /// + /// + /// Create based on the given computerName + /// + /// + /// + private CimSession CreateCimSessionByComputerName(string computerName) + { + DebugHelper.WriteLogEx("ComputerName {0}", 0, computerName); + + CimSessionOptions option = CreateCimSessionOption(computerName, 0, null); + if (option is DComSessionOptions) + { + DebugHelper.WriteLog("Create dcom cimSession"); + this.Protocol = ProtocolType.Dcom; + return CimSession.Create(ConstValue.NullComputerName, option); + } + else + { + DebugHelper.WriteLog("Create wsman cimSession"); + return CimSession.Create(computerName, option); + } + } + + /// + /// + /// Create based on the given computerName, + /// timeout and credential + /// + /// + /// + /// + /// + /// + internal static CimSessionOptions CreateCimSessionOption(string computerName, + uint timeout, CimCredential credential) + { + DebugHelper.WriteLogEx(); + + CimSessionOptions option; + if (ConstValue.IsDefaultComputerName(computerName)) + { + DebugHelper.WriteLog("<<<<<<<<<< Use protocol DCOM {0}", 1, computerName); + option = new DComSessionOptions(); + } + else + { + DebugHelper.WriteLog("<<<<<<<<<< Use protocol WSMAN {0}", 1, computerName); + option = new WSManSessionOptions(); + } + + if (timeout != 0) + { + option.Timeout = TimeSpan.FromSeconds((double)timeout); + } + + if (credential != null) + { + option.AddDestinationCredentials(credential); + } + + DebugHelper.WriteLogEx("returned option :{0}.", 1, option); + return option; + } + + #endregion + + } + + #region class CimSessionProxyTestConnection + /// + /// + /// Write session to pipeline after test connection success + /// + /// + internal class CimSessionProxyTestConnection : CimSessionProxy + { + #region constructors + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name + /// and session options. + /// Then create wrapper object. + /// + /// + /// + public CimSessionProxyTestConnection(string computerName, CimSessionOptions sessionOptions) + : base(computerName, sessionOptions) + { + } + + #endregion + + #region pre action APIs + + /// + /// Called after operation delete event. + /// + /// + protected override void PreOperationDeleteEvent(OperationEventArgs args) + { + DebugHelper.WriteLogEx("test connection result {0}", 0, args.success); + + if (args.success) + { + // test connection success, write session object to pipeline + CimWriteResultObject result = new(this.CimSession, this.ContextObject); + this.FireNewActionEvent(result); + } + } + + #endregion + } + + #endregion + + #region class CimSessionProxyGetCimClass + + /// + /// + /// Write CimClass to pipeline if the CimClass satisfied + /// the given conditions + /// + /// + internal class CimSessionProxyGetCimClass : CimSessionProxy + { + #region constructors + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name. + /// Then create wrapper object. + /// + /// + public CimSessionProxyGetCimClass(string computerName) + : base(computerName) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name + /// and session options. + /// Then create wrapper object. + /// + /// + /// + public CimSessionProxyGetCimClass(CimSession session) + : base(session) + { + } + + #endregion + + #region pre action APIs + /// + /// Called before new action event. + /// + /// + protected override bool PreNewActionEvent(CmdletActionEventArgs args) + { + DebugHelper.WriteLogEx(); + + if (args.Action is not CimWriteResultObject) + { + // allow all other actions + return true; + } + + CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject; + if (writeResultObject.Result is not CimClass cimClass) + { + return true; + } + + DebugHelper.WriteLog("class name = {0}", 1, cimClass.CimSystemProperties.ClassName); + + CimGetCimClassContext context = this.ContextObject as CimGetCimClassContext; + Debug.Assert(context != null, "Caller should verify that CimGetCimClassContext != NULL."); + + WildcardPattern pattern; + if (WildcardPattern.ContainsWildcardCharacters(context.ClassName)) + { + pattern = new WildcardPattern(context.ClassName, WildcardOptions.IgnoreCase); + if (!pattern.IsMatch(cimClass.CimSystemProperties.ClassName)) + { + return false; + } + } + + if (context.PropertyName != null) + { + bool match = false; + if (cimClass.CimClassProperties != null) + { + pattern = new WildcardPattern(context.PropertyName, WildcardOptions.IgnoreCase); + foreach (CimPropertyDeclaration decl in cimClass.CimClassProperties) + { + DebugHelper.WriteLog("--- property name : {0}", 1, decl.Name); + if (pattern.IsMatch(decl.Name)) + { + match = true; + break; + } + } + } + + if (!match) + { + DebugHelper.WriteLog("Property name does not match: {0}", 1, context.PropertyName); + return match; + } + } + + if (context.MethodName != null) + { + bool match = false; + if (cimClass.CimClassMethods != null) + { + pattern = new WildcardPattern(context.MethodName, WildcardOptions.IgnoreCase); + foreach (CimMethodDeclaration decl in cimClass.CimClassMethods) + { + DebugHelper.WriteLog("--- method name : {0}", 1, decl.Name); + if (pattern.IsMatch(decl.Name)) + { + match = true; + break; + } + } + } + + if (!match) + { + DebugHelper.WriteLog("Method name does not match: {0}", 1, context.MethodName); + return match; + } + } + + if (context.QualifierName != null) + { + bool match = false; + if (cimClass.CimClassQualifiers != null) + { + pattern = new WildcardPattern(context.QualifierName, WildcardOptions.IgnoreCase); + foreach (CimQualifier qualifier in cimClass.CimClassQualifiers) + { + DebugHelper.WriteLog("--- qualifier name : {0}", 1, qualifier.Name); + if (pattern.IsMatch(qualifier.Name)) + { + match = true; + break; + } + } + } + + if (!match) + { + DebugHelper.WriteLog("Qualifier name does not match: {0}", 1, context.QualifierName); + return match; + } + } + + DebugHelper.WriteLog("CimClass '{0}' is qualified.", 1, cimClass.CimSystemProperties.ClassName); + return true; + } + #endregion + } + + #endregion + + #region class CimSessionProxyNewCimInstance + + /// + /// + /// Get full if create successfully. + /// + /// + internal class CimSessionProxyNewCimInstance : CimSessionProxy + { + #region constructors + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name. + /// Then create wrapper object. + /// + public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance operation) + : base(computerName) + { + this.NewCimInstanceOperation = operation; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Create by given computer name + /// and session options. + /// Then create wrapper object. + /// + /// + /// + public CimSessionProxyNewCimInstance(CimSession session, CimNewCimInstance operation) + : base(session) + { + this.NewCimInstanceOperation = operation; + } + + #endregion + + #region pre action APIs + /// + /// Called before new action event. + /// + /// + protected override bool PreNewActionEvent(CmdletActionEventArgs args) + { + DebugHelper.WriteLogEx(); + + if (args.Action is not CimWriteResultObject) + { + // allow all other actions + return true; + } + + CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject; + if (writeResultObject.Result is not CimInstance cimInstance) + { + return true; + } + + DebugHelper.WriteLog("Going to read CimInstance classname = {0}; namespace = {1}", 1, cimInstance.CimSystemProperties.ClassName, cimInstance.CimSystemProperties.Namespace); + this.NewCimInstanceOperation.GetCimInstance(cimInstance, this.ContextObject); + return false; + } + #endregion + + #region private members + + internal CimNewCimInstance NewCimInstanceOperation { get; } + + #endregion + } + + #endregion + + #region class CimSessionProxyNewCimInstance + + /// + /// + /// Support PassThru for set-ciminstance. + /// + /// + internal class CimSessionProxySetCimInstance : CimSessionProxy + { + #region constructors + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given object. + /// Then create wrapper object. + /// + /// object to clone. + /// PassThru, true means output the modified instance; otherwise does not output. + public CimSessionProxySetCimInstance(CimSessionProxy originalProxy, bool passThru) + : base(originalProxy) + { + this.passThru = passThru; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name. + /// Then create wrapper object. + /// + /// + /// + /// + public CimSessionProxySetCimInstance(string computerName, + CimInstance cimInstance, + bool passThru) + : base(computerName, cimInstance) + { + this.passThru = passThru; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Create by given computer name + /// and session options. + /// Then create wrapper object. + /// + /// + /// + public CimSessionProxySetCimInstance(CimSession session, bool passThru) + : base(session) + { + this.passThru = passThru; + } + #endregion + + #region pre action APIs + /// + /// Called before new action event. + /// + /// + protected override bool PreNewActionEvent(CmdletActionEventArgs args) + { + DebugHelper.WriteLogEx(); + + if ((!this.passThru) && (args.Action is CimWriteResultObject)) + { + // filter out any output object + return false; + } + + return true; + } + #endregion + + #region private members + + /// + /// Ture indicates need to output the modified result. + /// + private readonly bool passThru = false; + + #endregion + } + + #endregion +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs new file mode 100644 index 0000000000000000000000000000000000000000..91cf332bde9f6e9329510bfec6ac69b51a58a924 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -0,0 +1,291 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Containing all necessary information originated from + /// the parameters of + /// + internal class CimSetCimInstanceContext : XOperationContextBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + internal CimSetCimInstanceContext(string theNamespace, + IDictionary theProperty, + CimSessionProxy theProxy, + string theParameterSetName, + bool passThru) + { + this.proxy = theProxy; + this.Property = theProperty; + this.nameSpace = theNamespace; + this.ParameterSetName = theParameterSetName; + this.PassThru = passThru; + } + + /// + /// property value + /// + internal IDictionary Property { get; } + + /// + /// parameter set name + /// + internal string ParameterSetName { get; } + + /// + /// PassThru value + /// + internal bool PassThru { get; } + } + + /// + /// + /// Implements operations of set-ciminstance cmdlet. + /// + /// + internal sealed class CimSetCimInstance : CimGetInstance + { + /// + /// Initializes a new instance of the class. + /// + public CimSetCimInstance() + : base() + { + } + + /// + /// + /// Base on parametersetName to set ciminstances + /// + /// + /// object. + public void SetCimInstance(SetCimInstanceCommand cmdlet) + { + IEnumerable computerNames = ConstValue.GetComputerNames( + GetComputerName(cmdlet)); + List proxys = new(); + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimInstanceComputerSet: + foreach (string computerName in computerNames) + { + // create CimSessionProxySetCimInstance object internally + proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet, cmdlet.PassThru)); + } + + break; + case CimBaseCommand.CimInstanceSessionSet: + foreach (CimSession session in GetCimSession(cmdlet)) + { + // create CimSessionProxySetCimInstance object internally + proxys.Add(CreateSessionProxy(session, cmdlet, cmdlet.PassThru)); + } + + break; + default: + break; + } + + switch (cmdlet.ParameterSetName) + { + case CimBaseCommand.CimInstanceComputerSet: + case CimBaseCommand.CimInstanceSessionSet: + string nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace); + string target = cmdlet.CimInstance.ToString(); + foreach (CimSessionProxy proxy in proxys) + { + if (!cmdlet.ShouldProcess(target, action)) + { + return; + } + + Exception exception = null; + CimInstance instance = cmdlet.CimInstance; + // For CimInstance parameter sets, Property is an optional parameter + if (cmdlet.Property != null) + { + if (!SetProperty(cmdlet.Property, ref instance, ref exception)) + { + cmdlet.ThrowTerminatingError(exception, action); + return; + } + } + + proxy.ModifyInstanceAsync(nameSpace, instance); + } + + break; + case CimBaseCommand.QueryComputerSet: + case CimBaseCommand.QuerySessionSet: + GetCimInstanceInternal(cmdlet); + break; + default: + break; + } + } + + /// + /// + /// Set with properties specified in cmdlet + /// + /// + /// + public void SetCimInstance(CimInstance cimInstance, CimSetCimInstanceContext context, CmdletOperationBase cmdlet) + { + DebugHelper.WriteLog("CimSetCimInstance::SetCimInstance", 4); + + if (!cmdlet.ShouldProcess(cimInstance.ToString(), action)) + { + return; + } + + Exception exception = null; + if (!SetProperty(context.Property, ref cimInstance, ref exception)) + { + cmdlet.ThrowTerminatingError(exception, action); + return; + } + + CimSessionProxy proxy = CreateCimSessionProxy(context.Proxy, context.PassThru); + proxy.ModifyInstanceAsync(cimInstance.CimSystemProperties.Namespace, cimInstance); + } + + #region private members + + /// + /// + /// Set the properties value to be modified to the given + /// + /// + /// + /// + /// + /// + /// + private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, ref Exception exception) + { + DebugHelper.WriteLogEx(); + if (properties.Count == 0) + { + // simply ignore if empty properties was provided + return true; + } + + IDictionaryEnumerator enumerator = properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + object value = GetBaseObject(enumerator.Value); + string key = enumerator.Key.ToString(); + DebugHelper.WriteLog("Input property name '{0}' with value '{1}'", 1, key, value); + + try + { + CimProperty property = cimInstance.CimInstanceProperties[key]; + // modify existing property value if found + if (property != null) + { + if ((property.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly) + { + // can not modify ReadOnly property + exception = new CimException(string.Format(CultureInfo.CurrentUICulture, + CimCmdletStrings.CouldNotModifyReadonlyProperty, key, cimInstance)); + return false; + } + // allow modify the key property value as long as it is not readonly, + // then the modified ciminstance is stand for a different CimInstance + DebugHelper.WriteLog("Set property name '{0}' has old value '{1}'", 4, key, property.Value); + property.Value = value; + } + else // For dynamic instance, it is valid to add a new property + { + CimProperty newProperty; + if (value == null) + { + newProperty = CimProperty.Create( + key, + value, + CimType.String, + CimFlags.Property); + } + else + { + CimType referenceType = CimType.Unknown; + object referenceObject = GetReferenceOrReferenceArrayObject(value, ref referenceType); + if (referenceObject != null) + { + newProperty = CimProperty.Create( + key, + referenceObject, + referenceType, + CimFlags.Property); + } + else + { + newProperty = CimProperty.Create( + key, + value, + CimFlags.Property); + } + } + + try + { + cimInstance.CimInstanceProperties.Add(newProperty); + } + catch (CimException e) + { + if (e.NativeErrorCode == NativeErrorCode.Failed) + { + string errorMessage = string.Format(CultureInfo.CurrentUICulture, + CimCmdletStrings.UnableToAddPropertyToInstance, + newProperty.Name, + cimInstance); + exception = new CimException(errorMessage, e); + } + else + { + exception = e; + } + + return false; + } + + DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, key, value); + } + } + catch (Exception e) + { + DebugHelper.WriteLog("Exception {0}", 4, e); + exception = e; + return false; + } + } + + return true; + } + + #endregion + + #region const strings + /// + /// Action. + /// + private const string action = @"Set-CimInstance"; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs new file mode 100644 index 0000000000000000000000000000000000000000..f1ebe9116035bcece6c9fb02db549879c09a1a4c --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -0,0 +1,394 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using Microsoft.Management.Infrastructure.Options; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + #region class ErrorToErrorRecord + + /// + /// + /// Convert error or exception to + /// + /// + internal sealed class ErrorToErrorRecord + { + /// + /// + /// Convert ErrorRecord from exception object, + /// can be either or general . + /// + /// + /// + /// The context starting the operation, which generated the error. + /// The CimResultContext used to provide ErrorSource, etc. info. + /// + internal static ErrorRecord ErrorRecordFromAnyException( + InvocationContext context, + Exception inner, + CimResultContext cimResultContext) + { + Debug.Assert(inner != null, "Caller should verify inner != null"); + + if (inner is CimException cimException) + { + return CreateFromCimException(context, cimException, cimResultContext); + } + + if (inner is IContainsErrorRecord containsErrorRecord) + { + return InitializeErrorRecord(context, + exception: inner, + errorId: "CimCmdlet_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId, + errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category, + cimResultContext: cimResultContext); + } + else + { + return InitializeErrorRecord(context, + exception: inner, + errorId: "CimCmdlet_" + inner.GetType().Name, + errorCategory: ErrorCategory.NotSpecified, + cimResultContext: cimResultContext); + } + } + + #region Helper functions + /// + /// Create from object. + /// + /// + /// + /// The CimResultContext used to provide ErrorSource, etc. info. + /// + internal static ErrorRecord CreateFromCimException( + InvocationContext context, + CimException cimException, + CimResultContext cimResultContext) + { + Debug.Assert(cimException != null, "Caller should verify cimException != null"); + + return InitializeErrorRecord(context, cimException, cimResultContext); + } + + /// + /// Create from object. + /// + /// + /// + /// + /// + /// The CimResultContext used to provide ErrorSource, etc. info. + /// + internal static ErrorRecord InitializeErrorRecord( + InvocationContext context, + Exception exception, + string errorId, + ErrorCategory errorCategory, + CimResultContext cimResultContext) + { + return InitializeErrorRecordCore( + context, + exception: exception, + errorId: errorId, + errorCategory: errorCategory, + cimResultContext: cimResultContext); + } + + /// + /// Create from object. + /// + /// + /// + /// The CimResultContext used to provide ErrorSource, etc. info. + /// + internal static ErrorRecord InitializeErrorRecord( + InvocationContext context, + CimException cimException, + CimResultContext cimResultContext) + { + ErrorRecord errorRecord = InitializeErrorRecordCore( + context, + exception: cimException, + errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode, + errorCategory: ConvertCimExceptionToErrorCategory(cimException), + cimResultContext: cimResultContext); + + if (cimException.ErrorData != null) + { + errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; + } + + return errorRecord; + } + + /// + /// Create from object. + /// + /// + /// + /// + /// + /// The CimResultContext used to provide ErrorSource, etc. info. + /// + internal static ErrorRecord InitializeErrorRecordCore( + InvocationContext context, + Exception exception, + string errorId, + ErrorCategory errorCategory, + CimResultContext cimResultContext) + { + object theTargetObject = null; + if (cimResultContext != null) + { + theTargetObject = cimResultContext.ErrorSource; + } + + if (theTargetObject == null) + { + if (context != null) + { + if (context.TargetCimInstance != null) + { + theTargetObject = context.TargetCimInstance; + } + } + } + + ErrorRecord coreErrorRecord = new( + exception: exception, + errorId: errorId, + errorCategory: errorCategory, + targetObject: theTargetObject); + + if (context == null) + { + return coreErrorRecord; + } + + System.Management.Automation.Remoting.OriginInfo originInfo = new( + context.ComputerName, + Guid.Empty); + + ErrorRecord errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord( + coreErrorRecord, + originInfo); + + DebugHelper.WriteLogEx("Created RemotingErrorRecord.", 0); + return errorRecord; + } + + /// + /// Convert to . + /// + /// + /// + internal static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cimException) + { + ErrorCategory result = ErrorCategory.NotSpecified; + + if (cimException.ErrorData != null) + { + result = ConvertCimErrorToErrorCategory(cimException.ErrorData); + } + + if (result == ErrorCategory.NotSpecified) + { + result = ConvertCimNativeErrorCodeToErrorCategory(cimException.NativeErrorCode); + } + + return result; + } + + /// + /// Convert to . + /// + /// + /// + internal static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErrorCode nativeErrorCode) + { + switch (nativeErrorCode) + { + case NativeErrorCode.Failed: + return ErrorCategory.NotSpecified; + case NativeErrorCode.AccessDenied: + return ErrorCategory.PermissionDenied; + case NativeErrorCode.InvalidNamespace: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidParameter: + return ErrorCategory.InvalidArgument; + case NativeErrorCode.InvalidClass: + return ErrorCategory.MetadataError; + case NativeErrorCode.NotFound: + return ErrorCategory.ObjectNotFound; + case NativeErrorCode.NotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.ClassHasChildren: + return ErrorCategory.MetadataError; + case NativeErrorCode.ClassHasInstances: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidSuperClass: + return ErrorCategory.MetadataError; + case NativeErrorCode.AlreadyExists: + return ErrorCategory.ResourceExists; + case NativeErrorCode.NoSuchProperty: + return ErrorCategory.MetadataError; + case NativeErrorCode.TypeMismatch: + return ErrorCategory.InvalidType; + case NativeErrorCode.QueryLanguageNotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.InvalidQuery: + return ErrorCategory.InvalidArgument; + case NativeErrorCode.MethodNotAvailable: + return ErrorCategory.MetadataError; + case NativeErrorCode.MethodNotFound: + return ErrorCategory.MetadataError; + case NativeErrorCode.NamespaceNotEmpty: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidEnumerationContext: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidOperationTimeout: + return ErrorCategory.InvalidArgument; + case NativeErrorCode.PullHasBeenAbandoned: + return ErrorCategory.OperationStopped; + case NativeErrorCode.PullCannotBeAbandoned: + return ErrorCategory.CloseError; + case NativeErrorCode.FilteredEnumerationNotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.ContinuationOnErrorNotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.ServerLimitsExceeded: + return ErrorCategory.ResourceBusy; + case NativeErrorCode.ServerIsShuttingDown: + return ErrorCategory.ResourceUnavailable; + default: + return ErrorCategory.NotSpecified; + } + } + + /// + /// Convert to . + /// + /// + /// + internal static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError) + { + if (cimError == null) + { + return ErrorCategory.NotSpecified; + } + + CimProperty errorCategoryProperty = cimError.CimInstanceProperties[@"Error_Category"]; + if (errorCategoryProperty == null) + { + return ErrorCategory.NotSpecified; + } + + ErrorCategory errorCategoryValue; + if (!LanguagePrimitives.TryConvertTo(errorCategoryProperty.Value, CultureInfo.InvariantCulture, out errorCategoryValue)) + { + return ErrorCategory.NotSpecified; + } + + return errorCategoryValue; + } + + #endregion + } + + #endregion + + /// + /// + /// Write error to pipeline + /// + /// + internal sealed class CimWriteError : CimSyncAction + { + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + public CimWriteError(CimInstance error, InvocationContext context) + { + this.Error = error; + this.CimInvocationContext = context; + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + public CimWriteError(Exception exception, InvocationContext context, CimResultContext cimResultContext) + { + this.Exception = exception; + this.CimInvocationContext = context; + this.ResultContext = cimResultContext; + } + + /// + /// + /// Write error to pipeline + /// + /// + /// + public override void Execute(CmdletOperationBase cmdlet) + { + Debug.Assert(cmdlet != null, "Caller should verify that cmdlet != null"); + try + { + Exception errorException = (Error != null) ? new CimException(Error) : this.Exception; + + // PS engine takes care of handling error action + cmdlet.WriteError(ErrorToErrorRecord.ErrorRecordFromAnyException(this.CimInvocationContext, errorException, this.ResultContext)); + + // if user wants to continue, we will get here + this.responseType = CimResponseType.Yes; + } + catch + { + this.responseType = CimResponseType.NoToAll; + throw; + } + finally + { + // unblocking the waiting thread + this.OnComplete(); + } + } + + #region members + + /// + /// + /// Error instance + /// + /// + + internal CimInstance Error { get; } + + /// + /// + /// Exception object + /// + /// + internal Exception Exception { get; } + + internal InvocationContext CimInvocationContext { get; } + + internal CimResultContext ResultContext { get; } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..f4b244b97f9964c0595f6e97277009319485aac1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using Microsoft.Management.Infrastructure.Options; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Write message to message channel + /// + /// + internal sealed class CimWriteMessage : CimBaseAction + { + #region members + + /// + /// Channel id. + /// + #endregion + + #region Properties + + internal uint Channel { get; } + + internal string Message { get; } + + #endregion + + /// + /// Initializes a new instance of the class. + /// + public CimWriteMessage(uint channel, + string message) + { + this.Channel = channel; + this.Message = message; + } + + /// + /// + /// Write message to the target channel + /// + /// + /// + public override void Execute(CmdletOperationBase cmdlet) + { + ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); + + switch ((CimWriteMessageChannel)Channel) + { + case CimWriteMessageChannel.Verbose: + cmdlet.WriteVerbose(Message); + break; + case CimWriteMessageChannel.Warning: + cmdlet.WriteWarning(Message); + break; + case CimWriteMessageChannel.Debug: + cmdlet.WriteDebug(Message); + break; + default: + break; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs new file mode 100644 index 0000000000000000000000000000000000000000..b99407ccc812e6490b15094f293f2f6418380295 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Write progress record of given activity + /// + /// + internal sealed class CimWriteProgress : CimBaseAction + { + /// + /// Initializes a new instance of the class. + /// + /// + /// Activity identifier of the given activity + /// + /// + /// current operation description of the given activity + /// + /// + /// current status description of the given activity + /// + /// + /// percentage completed of the given activity + /// + /// + /// how many seconds remained for the given activity + /// + public CimWriteProgress( + string theActivity, + int theActivityID, + string theCurrentOperation, + string theStatusDescription, + uint thePercentageCompleted, + uint theSecondsRemaining) + { + this.Activity = theActivity; + this.ActivityID = theActivityID; + this.CurrentOperation = theCurrentOperation; + if (string.IsNullOrEmpty(theStatusDescription)) + { + this.StatusDescription = CimCmdletStrings.DefaultStatusDescription; + } + else + { + this.StatusDescription = theStatusDescription; + } + + this.PercentageCompleted = thePercentageCompleted; + this.SecondsRemaining = theSecondsRemaining; + } + + /// + /// + /// Write progress record to powershell + /// + /// + /// + public override void Execute(CmdletOperationBase cmdlet) + { + DebugHelper.WriteLog( + "...Activity {0}: id={1}, remain seconds ={2}, percentage completed = {3}", + 4, + this.Activity, + this.ActivityID, + this.SecondsRemaining, + this.PercentageCompleted); + + ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); + ProgressRecord record = new( + this.ActivityID, + this.Activity, + this.StatusDescription); + record.Activity = this.Activity; + record.ParentActivityId = 0; + record.SecondsRemaining = (int)this.SecondsRemaining; + record.PercentComplete = (int)this.PercentageCompleted; + cmdlet.WriteProgress(record); + } + + #region members + + /// + /// Gets the activity of the given activity. + /// + internal string Activity { get; } + + /// + /// Gets the activity identifier of the given activity. + /// + internal int ActivityID { get; } + + /// + /// Gets the current operation text of the given activity. + /// + internal string CurrentOperation { get; } + + /// + /// Gets the status description of the given activity. + /// + internal string StatusDescription { get; } + + /// + /// Gets the percentage completed of the given activity. + /// + internal uint PercentageCompleted { get; } + + /// + /// Gets the number of seconds remaining for the given activity. + /// + internal uint SecondsRemaining { get; } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs new file mode 100644 index 0000000000000000000000000000000000000000..a4dcdfaa5c4fce5ea7b3fe9663959cbdf43980dc --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Write result object to ps pipeline + /// + /// + internal sealed class CimWriteResultObject : CimBaseAction + { + /// + /// Initializes a new instance of the class. + /// + public CimWriteResultObject(object result, XOperationContextBase theContext) + { + this.Result = result; + this.Context = theContext; + } + + /// + /// + /// Write result object to ps pipeline + /// + /// + /// + public override void Execute(CmdletOperationBase cmdlet) + { + ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); + cmdlet.WriteObject(Result, this.Context); + } + + #region members + /// + /// Result object. + /// + internal object Result { get; } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs new file mode 100644 index 0000000000000000000000000000000000000000..bd1a275162271597f6ec69fe4b440756188431b9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -0,0 +1,403 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Wrapper of Cmdlet, forward the operation to Cmdlet directly. + /// This is for unit test purpose, unit test can derive from this class, + /// to hook up all of the cmdlet related operation and verify the correctness. + /// + /// + internal class CmdletOperationBase + { + /// + /// + /// Wrap the Cmdlet object. + /// + /// + private readonly Cmdlet cmdlet; + + /// + /// + /// Wrap the Cmdlet methods, for testing purpose. + /// Test binary can define a child class of CmdletOperationBase. + /// While Execute method of accept the + /// object of CmdletOperationBase as parameter. + /// + /// + #region CMDLET methods + + public virtual bool ShouldContinue(string query, string caption) + { + return cmdlet.ShouldContinue(query, caption); + } + + public virtual bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + return cmdlet.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + public virtual bool ShouldProcess(string target) + { + return cmdlet.ShouldProcess(target); + } + + public virtual bool ShouldProcess(string target, string action) + { + return cmdlet.ShouldProcess(target, action); + } + + public virtual bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + public virtual bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public virtual void ThrowTerminatingError(ErrorRecord errorRecord) + { + cmdlet.ThrowTerminatingError(errorRecord); + } + + public virtual void WriteCommandDetail(string text) + { + cmdlet.WriteCommandDetail(text); + } + + public virtual void WriteDebug(string text) + { + cmdlet.WriteDebug(text); + } + + public virtual void WriteError(ErrorRecord errorRecord) + { + cmdlet.WriteError(errorRecord); + } + + public virtual void WriteObject(object sendToPipeline, XOperationContextBase context) + { + cmdlet.WriteObject(sendToPipeline); + } + + public virtual void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context) + { + cmdlet.WriteObject(sendToPipeline, enumerateCollection); + } + + public virtual void WriteProgress(ProgressRecord progressRecord) + { + cmdlet.WriteProgress(progressRecord); + } + + public virtual void WriteVerbose(string text) + { + cmdlet.WriteVerbose(text); + } + + public virtual void WriteWarning(string text) + { + cmdlet.WriteWarning(text); + } + + /// + /// + /// Throw terminating error + /// + /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + internal void ThrowTerminatingError(Exception exception, string operation) + { + ErrorRecord errorRecord = new(exception, operation, ErrorCategory.InvalidOperation, this); + cmdlet.ThrowTerminatingError(errorRecord); + } + #endregion + + /// + /// Initializes a new instance of the class. + /// + public CmdletOperationBase(Cmdlet cmdlet) + { + ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); + this.cmdlet = cmdlet; + } + } + + #region Class CmdletOperationRemoveCimInstance + + /// + /// + /// Wrapper of Cmdlet, override WriteObject function call since + /// we need to remove . + /// + /// + internal class CmdletOperationRemoveCimInstance : CmdletOperationBase + { + /// + /// Initializes a new instance of the class. + /// + /// + public CmdletOperationRemoveCimInstance(Cmdlet cmdlet, + CimRemoveCimInstance cimRemoveCimInstance) + : base(cmdlet) + { + ValidationHelper.ValidateNoNullArgument(cimRemoveCimInstance, cimRemoveCimInstanceParameterName); + this.removeCimInstance = cimRemoveCimInstance; + } + + /// + /// + /// Object here need to be removed if it is CimInstance + /// + /// + /// + public override void WriteObject(object sendToPipeline, XOperationContextBase context) + { + if (sendToPipeline is CimInstance) + { + DebugHelper.WriteLog(">>>>CmdletOperationRemoveCimInstance::WriteObject", 4); + this.removeCimInstance.RemoveCimInstance(sendToPipeline as CimInstance, context, this); + } + else + { + base.WriteObject(sendToPipeline, context); + } + } + + public override void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context) + { + if (sendToPipeline is CimInstance) + { + this.WriteObject(sendToPipeline, context); + } + else + { + base.WriteObject(sendToPipeline, enumerateCollection, context); + } + } + + #region private methods + + private readonly CimRemoveCimInstance removeCimInstance; + + private const string cimRemoveCimInstanceParameterName = @"cimRemoveCimInstance"; + + #endregion + } + + #endregion + + #region Class CmdletOperationSetCimInstance + + /// + /// + /// Wrapper of Cmdlet, override WriteObject function call since + /// we need to set . + /// + /// + internal class CmdletOperationSetCimInstance : CmdletOperationBase + { + /// + /// Initializes a new instance of the class. + /// + /// + public CmdletOperationSetCimInstance(Cmdlet cmdlet, + CimSetCimInstance theCimSetCimInstance) + : base(cmdlet) + { + ValidationHelper.ValidateNoNullArgument(theCimSetCimInstance, theCimSetCimInstanceParameterName); + this.setCimInstance = theCimSetCimInstance; + } + + /// + /// + /// Object here need to be removed if it is CimInstance + /// + /// + /// + public override void WriteObject(object sendToPipeline, XOperationContextBase context) + { + DebugHelper.WriteLogEx(); + + if (sendToPipeline is CimInstance) + { + if (context is CimSetCimInstanceContext setContext) + { + if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) || + string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase)) + { + this.setCimInstance.SetCimInstance(sendToPipeline as CimInstance, setContext, this); + return; + } + else + { + DebugHelper.WriteLog("Write the cimInstance to pipeline since this CimInstance is returned by SetCimInstance.", 4); + } + } + else + { + DebugHelper.WriteLog("Assert. CimSetCimInstance::SetCimInstance has NULL CimSetCimInstanceContext", 4); + } + } + + base.WriteObject(sendToPipeline, context); + } + + public override void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context) + { + if (sendToPipeline is CimInstance) + { + this.WriteObject(sendToPipeline, context); + } + else + { + base.WriteObject(sendToPipeline, enumerateCollection, context); + } + } + + #region private methods + + private readonly CimSetCimInstance setCimInstance; + + private const string theCimSetCimInstanceParameterName = @"theCimSetCimInstance"; + + #endregion + } + #endregion + + #region Class CmdletOperationInvokeCimMethod + /// + /// + /// Wrapper of Cmdlet, override WriteObject function call since + /// we need to invoke cim method. + /// + /// + internal class CmdletOperationInvokeCimMethod : CmdletOperationBase + { + /// + /// Initializes a new instance of the class. + /// + /// + public CmdletOperationInvokeCimMethod(Cmdlet cmdlet, + CimInvokeCimMethod theCimInvokeCimMethod) + : base(cmdlet) + { + ValidationHelper.ValidateNoNullArgument(theCimInvokeCimMethod, theCimInvokeCimMethodParameterName); + this.cimInvokeCimMethod = theCimInvokeCimMethod; + } + + /// + /// + /// Object here need to be removed if it is CimInstance + /// + /// + /// + public override void WriteObject(object sendToPipeline, XOperationContextBase context) + { + DebugHelper.WriteLogEx(); + + if (sendToPipeline is CimInstance) + { + this.cimInvokeCimMethod.InvokeCimMethodOnCimInstance(sendToPipeline as CimInstance, context, this); + } + else + { + base.WriteObject(sendToPipeline, context); + } + } + + public override void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context) + { + if (sendToPipeline is CimInstance) + { + this.WriteObject(sendToPipeline, context); + } + else + { + base.WriteObject(sendToPipeline, enumerateCollection, context); + } + } + + #region private methods + + private readonly CimInvokeCimMethod cimInvokeCimMethod; + + private const string theCimInvokeCimMethodParameterName = @"theCimInvokeCimMethod"; + + #endregion + } + + #endregion + + #region Class CmdletOperationTestCimSession + + /// + /// + /// Wrapper of Cmdlet, override WriteObject function call since + /// we need to add cim session to global cache. + /// + /// + internal class CmdletOperationTestCimSession : CmdletOperationBase + { + /// + /// Initializes a new instance of the class. + /// + /// + public CmdletOperationTestCimSession(Cmdlet cmdlet, + CimNewSession theCimNewSession) + : base(cmdlet) + { + ValidationHelper.ValidateNoNullArgument(theCimNewSession, theCimNewSessionParameterName); + this.cimNewSession = theCimNewSession; + } + + /// + /// + /// Add session object to cache + /// + /// + /// + public override void WriteObject(object sendToPipeline, XOperationContextBase context) + { + DebugHelper.WriteLogEx(); + + if (sendToPipeline is CimSession) + { + DebugHelper.WriteLog("Call CimNewSession::AddSessionToCache", 1); + + this.cimNewSession.AddSessionToCache(sendToPipeline as CimSession, context, this); + } + else if (sendToPipeline is PSObject) + { + DebugHelper.WriteLog("Write PSObject to pipeline", 1); + base.WriteObject(sendToPipeline, context); + } + else + { + // NOTES: May need to output for warning message/verbose message + DebugHelper.WriteLog("Ignore other type object {0}", 1, sendToPipeline); + } + } + + #region private methods + + private readonly CimNewSession cimNewSession; + + private const string theCimNewSessionParameterName = @"theCimNewSession"; + + #endregion + } + + #endregion +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..6c4d0c94d2bfdd99e7fa035447d9b3ead8892dfc --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -0,0 +1,325 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// The Cmdlet retrieves instances connected to the given instance, which + /// is called the source instance, via a given association. In an + /// association each instance has a named role, and the same instance can + /// participate in an association in different roles. Hence, the Cmdlet + /// takes SourceRole and AssociatorRole parameters in addition to the + /// Association parameter. + /// + /// + [Alias("gcai")] + [Cmdlet(VerbsCommon.Get, + GetCimAssociatedInstanceCommand.Noun, + DefaultParameterSetName = CimBaseCommand.ComputerSetName, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227958")] + [OutputType(typeof(CimInstance))] + public class GetCimAssociatedInstanceCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public GetCimAssociatedInstanceCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + + /// + /// The following is the definition of the input parameter "Association". + /// Specifies the class name of the association to be traversed from the + /// SourceRole to AssociatorRole. + /// + [Parameter( + Position = 1, + ValueFromPipelineByPropertyName = true)] + public string Association { get; set; } + + /// + /// The following is the definition of the input parameter "ResultClassName". + /// Specifies the class name of the result class name, which associated with + /// the given instance. + /// + [Parameter] + public string ResultClassName { get; set; } + + /// + /// + /// The following is the definition of the input parameter "InputObject". + /// Provides the instance from which the association traversal is to begin. + /// + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true)] + [Alias(CimBaseCommand.AliasCimInstance)] + public CimInstance InputObject + { + get + { + return CimInstance; + } + + set + { + CimInstance = value; + base.SetParameter(value, nameCimInstance); + } + } + + /// + /// Property for internal usage purpose. + /// + internal CimInstance CimInstance { get; private set; } + + /// + /// The following is the definition of the input parameter "Namespace". + /// Identifies the Namespace in which the source class, indicated by ClassName, + /// is registered. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string Namespace { get; set; } + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Specifies the operation timeout after which the client operation should be + /// canceled. The default is the CimSession operation timeout. If this parameter + /// is specified, then this value takes precedence over the CimSession + /// OperationTimeout. + /// + [Alias(AliasOT)] + [Parameter(ValueFromPipelineByPropertyName = true)] + public uint OperationTimeoutSec { get; set; } + + /// + /// + /// The following is the definition of the input parameter "ResourceUri". + /// Define the Resource Uri for which the instances are retrieved. + /// + /// + [Parameter] + public Uri ResourceUri + { + get + { + return resourceUri; + } + + set + { + this.resourceUri = value; + base.SetParameter(value, nameResourceUri); + } + } + + private Uri resourceUri; + + /// + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specifies the name of the computer where the source instance is stored and + /// where the association traversal should begin. + /// + /// + /// This is an optional parameter and if it is not provided, the default value + /// will be "localhost". + /// + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ParameterSetName = ComputerSetName)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computerName; + } + + set + { + computerName = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computerName; + + /// + /// The following is the definition of the input parameter "CimSession". + /// Identifies the CimSession which is to be used to retrieve the instances. + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = SessionSetName)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.Management.Infrastructure.CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private Microsoft.Management.Infrastructure.CimSession[] cimSession; + + /// + /// + /// The following is the definition of the input parameter "KeyOnly". + /// Indicates that only key properties of the retrieved instances should be + /// returned to the client. + /// + /// + [Parameter] + public SwitchParameter KeyOnly { get; set; } + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + this.CmdletOperation = new CmdletOperationBase(this); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + CimGetAssociatedInstance operation = this.GetOperationAgent() ?? this.CreateOperationAgent(); + + operation.GetCimAssociatedInstance(this); + operation.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimGetAssociatedInstance operation = this.GetOperationAgent(); + operation?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all Get-CimAssociatedInstance operations. + /// + /// + private CimGetAssociatedInstance GetOperationAgent() + { + return this.AsyncOperation as CimGetAssociatedInstance; + } + + /// + /// + /// Create object, which is + /// used to delegate all Get-CimAssociatedInstance operations. + /// + /// + /// + private CimGetAssociatedInstance CreateOperationAgent() + { + this.AsyncOperation = new CimGetAssociatedInstance(); + return GetOperationAgent(); + } + + #endregion + + #region internal const strings + + /// + /// Noun of current cmdlet. + /// + internal const string Noun = @"CimAssociatedInstance"; + + #endregion + + #region private members + + #region const string of parameter names + internal const string nameCimInstance = "InputObject"; + internal const string nameComputerName = "ComputerName"; + internal const string nameCimSession = "CimSession"; + internal const string nameResourceUri = "ResourceUri"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false), + } + }, + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true), + } + }, + { + nameCimInstance, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, true), + new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true), + } + }, + { + nameResourceUri, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false), + new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, false), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.SessionSetName, new ParameterSetEntry(2, false) }, + { CimBaseCommand.ComputerSetName, new ParameterSetEntry(1, true) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..1bededc485f4bd02c1586c4a780146ad3c8cdff2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -0,0 +1,283 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Enables the user to enumerate the list of CIM Classes under a specific + /// Namespace. If no list of classes is given, the Cmdlet returns all + /// classes in the given namespace. + /// + /// + /// NOTES: The class instance contains the Namespace properties + /// Should the class remember what Session it came from? No. + /// + /// + [Alias("gcls")] + [Cmdlet(VerbsCommon.Get, GetCimClassCommand.Noun, DefaultParameterSetName = ComputerSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227959")] + [OutputType(typeof(CimClass))] + public class GetCimClassCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public GetCimClassCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + + /// + /// Gets or sets flag to retrieve a localized data for WMI class. + /// + [Parameter] + public SwitchParameter Amended { get; set; } + + /// + /// + /// The following is the definition of the input parameter "ClassName". + /// + /// + /// Wildcard expansion should be allowed. + /// + /// + [Parameter( + Position = 0, + ValueFromPipelineByPropertyName = true)] + public string ClassName { get; set; } + + /// + /// + /// The following is the definition of the input parameter "Namespace". + /// Specifies the Namespace under which to look for the specified class name. + /// If no class name is specified, the cmdlet should return all classes under + /// the specified Namespace. + /// + /// + /// Default namespace is root\cimv2 + /// + /// + [Parameter( + Position = 1, + ValueFromPipelineByPropertyName = true)] + public string Namespace { get; set; } + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Enables the user to specify the operation timeout in Seconds. This value + /// overwrites the value specified by the CimSession Operation timeout. + /// + [Alias(AliasOT)] + [Parameter(ValueFromPipelineByPropertyName = true)] + public uint OperationTimeoutSec { get; set; } + + /// + /// The following is the definition of the input parameter "Session". + /// Uses a CimSession context. + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = SessionSetName)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimSession; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Provides the name of the computer from which to retrieve the + /// + /// + /// If no ComputerName is specified the default value is "localhost" + /// + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = ComputerSetName)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computerName; + } + + set + { + computerName = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computerName; + + /// + /// + /// The following is the definition of the input parameter "MethodName", + /// Which may contains wildchar. + /// Then Filter the by given methodname + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string MethodName { get; set; } + + /// + /// + /// The following is the definition of the input parameter "PropertyName", + /// Which may contains wildchar. + /// Filter the by given property name. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string PropertyName { get; set; } + + /// + /// + /// The following is the definition of the input parameter "QualifierName", + /// Which may contains wildchar. + /// Filter the by given methodname + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string QualifierName { get; set; } + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + this.CmdletOperation = new CmdletOperationBase(this); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + CimGetCimClass cimGetCimClass = this.GetOperationAgent() ?? CreateOperationAgent(); + + cimGetCimClass.GetCimClass(this); + cimGetCimClass.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimGetCimClass cimGetCimClass = this.GetOperationAgent(); + cimGetCimClass?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all New-CimInstance operations. + /// + /// + private CimGetCimClass GetOperationAgent() + { + return this.AsyncOperation as CimGetCimClass; + } + + /// + /// + /// Create object, which is + /// used to delegate all Get-CimClass operations. + /// + /// + /// + private CimGetCimClass CreateOperationAgent() + { + CimGetCimClass cimGetCimClass = new(); + this.AsyncOperation = cimGetCimClass; + return cimGetCimClass; + } + + #endregion + + #region internal const strings + + /// + /// Noun of current cmdlet. + /// + internal const string Noun = @"CimClass"; + + #endregion + + #region private members + + #region const string of parameter names + internal const string nameCimSession = "CimSession"; + internal const string nameComputerName = "ComputerName"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true), + } + }, + + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.SessionSetName, new ParameterSetEntry(1) }, + { CimBaseCommand.ComputerSetName, new ParameterSetEntry(0, true) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..65eeae8e4508b1c152e0b113dbd0ac0d7f8d9629 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -0,0 +1,684 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Returns zero, one or more CIM (dynamic) instances with the properties + /// specified in the Property parameter, KeysOnly parameter or the Select clause + /// of the Query parameter. + /// + [Alias("gcim")] + [Cmdlet(VerbsCommon.Get, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227961")] + [OutputType(typeof(CimInstance))] + public class GetCimInstanceCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + public GetCimInstanceCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + + /// + /// + /// The following is the definition of the input parameter "CimSession". + /// Identifies the CimSession which is to be used to retrieve the instances. + /// + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimSession; + + /// + /// + /// The following is the definition of the input parameter "ClassName". + /// Define the class name for which the instances are retrieved. + /// + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + public string ClassName + { + get + { + return className; + } + + set + { + this.className = value; + base.SetParameter(value, nameClassName); + } + } + + private string className; + + /// + /// + /// The following is the definition of the input parameter "ResourceUri". + /// Define the Resource Uri for which the instances are retrieved. + /// + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public Uri ResourceUri + { + get + { + return resourceUri; + } + + set + { + this.resourceUri = value; + base.SetParameter(value, nameResourceUri); + } + } + + private Uri resourceUri; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Provides the name of the computer from which to retrieve the instances. The + /// ComputerName is used to create a temporary CimSession with default parameter + /// values, which is then used to retrieve the instances. + /// + /// + /// If no ComputerName is specified the default value is "localhost" + /// + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computerName; + } + + set + { + computerName = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computerName; + + /// + /// + /// The following is the definition of the input parameter "KeyOnly". + /// Indicates that only key properties of the retrieved instances should be + /// returned to the client. + /// + /// + [Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + public SwitchParameter KeyOnly + { + get + { + return keyOnly; + } + + set + { + keyOnly = value; + base.SetParameter(value, nameKeyOnly); + } + } + + private SwitchParameter keyOnly; + + /// + /// + /// The following is the definition of the input parameter "Namespace". + /// Identifies the Namespace in which the class, indicated by ClassName, is + /// registered. + /// + /// + /// Default namespace is 'root\cimv2' if this property is not specified. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public string Namespace + { + get + { + return nameSpace; + } + + set + { + nameSpace = value; + base.SetParameter(value, nameNamespace); + } + } + + private string nameSpace; + + /// + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Specifies the operation timeout after which the client operation should be + /// canceled. The default is the CimSession operation timeout. If this parameter + /// is specified, then this value takes precedence over the CimSession + /// OperationTimeout. + /// + /// + [Alias(AliasOT)] + [Parameter] + public uint OperationTimeoutSec { get; set; } + + /// + /// The following is the definition of the input parameter "InputObject". + /// Provides the that containing the [Key] properties, + /// based on the key properties to retrieve the . + /// + /// + /// User can call New-CimInstance to create the CimInstance with key only + /// properties, for example: + /// New-CimInstance -ClassName C -Namespace root\cimv2 + /// -Property @{CreationClassName="CIM_VirtualComputerSystem";Name="VM3358"} + /// -Keys {"CreationClassName", "Name"} -Local + /// + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Alias(CimBaseCommand.AliasCimInstance)] + public CimInstance InputObject + { + get + { + return CimInstance; + } + + set + { + CimInstance = value; + base.SetParameter(value, nameCimInstance); + } + } + + /// + /// Property for internal usage purpose. + /// + internal CimInstance CimInstance { get; private set; } + + /// + /// The following is the definition of the input parameter "Query". + /// Specifies the query string for what instances, and what properties of those + /// instances, should be retrieve. + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public string Query + { + get + { + return query; + } + + set + { + query = value; + base.SetParameter(value, nameQuery); + } + } + + private string query; + + /// + /// + /// The following is the definition of the input parameter "QueryDialect". + /// Specifies the dialect used by the query Engine that interprets the Query + /// string. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + + public string QueryDialect + { + get + { + return queryDialect; + } + + set + { + queryDialect = value; + base.SetParameter(value, nameQueryDialect); + } + } + + private string queryDialect; + + /// + /// + /// The following is the definition of the input parameter "Shallow". + /// If the switch is set to True, only instance of the class identified by + /// Namespace + ClassName will be returned. If the switch is not set, instances + /// of the above class and of all of its descendents will be returned (the + /// enumeration will cascade the class inheritance hierarchy). + /// + /// + [Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter(ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.QuerySessionSet)] + public SwitchParameter Shallow + { + get + { + return shallow; + } + + set + { + shallow = value; + base.SetParameter(value, nameShallow); + } + } + + private SwitchParameter shallow; + + /// + /// + /// The following is the definition of the input parameter "Filter". + /// Specifies the where clause of the query. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + public string Filter + { + get + { + return filter; + } + + set + { + filter = value; + base.SetParameter(value, nameFilter); + } + } + + private string filter; + + /// + /// + /// The following is the definition of the input parameter "Property". + /// Specifies the selected properties of result instances. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [Alias("SelectProperties")] + public string[] Property + { + get + { + return SelectProperties; + } + + set + { + SelectProperties = value; + base.SetParameter(value, nameSelectProperties); + } + } + /// + /// Property for internal usage. + /// + internal string[] SelectProperties { get; private set; } + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + this.CmdletOperation = new CmdletOperationBase(this); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + this.CheckArgument(); + CimGetInstance cimGetInstance = this.GetOperationAgent() ?? CreateOperationAgent(); + + cimGetInstance.GetCimInstance(this); + cimGetInstance.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimGetInstance cimGetInstance = this.GetOperationAgent(); + cimGetInstance?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all Get-CimInstance operations, such + /// as enumerate instances, get instance, query instance. + /// + /// + private CimGetInstance GetOperationAgent() + { + return this.AsyncOperation as CimGetInstance; + } + + /// + /// + /// Create object, which is + /// used to delegate all Get-CimInstance operations, such + /// as enumerate instances, get instance, query instance. + /// + /// + /// + private CimGetInstance CreateOperationAgent() + { + CimGetInstance cimGetInstance = new(); + this.AsyncOperation = cimGetInstance; + return cimGetInstance; + } + + /// + /// Check argument value. + /// + private void CheckArgument() + { + switch (this.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.ClassNameSessionSet: + // validate the classname & property + this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); + this.SelectProperties = ValidationHelper.ValidateArgumentIsValidName(nameSelectProperties, this.SelectProperties); + break; + default: + break; + } + } + #endregion + + #region private members + + #region const string of parameter names + internal const string nameCimInstance = "InputObject"; + internal const string nameCimSession = "CimSession"; + internal const string nameClassName = "ClassName"; + internal const string nameResourceUri = "ResourceUri"; + internal const string nameComputerName = "ComputerName"; + internal const string nameFilter = "Filter"; + internal const string nameKeyOnly = "KeyOnly"; + internal const string nameNamespace = "Namespace"; + internal const string nameOperationTimeoutSec = "OperationTimeoutSec"; + internal const string nameQuery = "Query"; + internal const string nameQueryDialect = "QueryDialect"; + internal const string nameSelectProperties = "Property"; + internal const string nameShallow = "Shallow"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + } + }, + { + nameResourceUri, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + } + }, + { + nameClassName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + } + }, + { + nameKeyOnly, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + } + }, + { + nameNamespace, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + } + }, + { + nameCimInstance, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + } + }, + { + nameQuery, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), + } + }, + { + nameQueryDialect, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + } + }, + { + nameShallow, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + } + }, + { + nameFilter, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + } + }, + { + nameSelectProperties, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1) }, + { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, + { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(1) }, + { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) }, + { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(2) } + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..3289b6c86c0c566c33710211814c71372500d26e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// The command returns zero, one or more CimSession objects that represent + /// connections with remote computers established from the current PS Session. + /// + [Alias("gcms")] + [Cmdlet(VerbsCommon.Get, "CimSession", DefaultParameterSetName = ComputerNameSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227966")] + [OutputType(typeof(CimSession))] + public sealed class GetCimSessionCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public GetCimSessionCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + + /// + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specifies one or more connections by providing their ComputerName(s). The + /// Cmdlet then gets CimSession(s) opened with those connections. This parameter + /// is an alternative to using CimSession(s) that also identifies the remote + /// computer(s). + /// + /// + /// This is the only optional parameter of the Cmdlet. If not provided, the + /// Cmdlet returns all CimSession(s) live/active in the runspace. + /// + /// + /// If an instance of CimSession is pipelined to Get-CimSession, the + /// ComputerName property of the instance is bound by name with this parameter. + /// + /// + [Alias(AliasCN, AliasServerName)] + [Parameter(Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = ComputerNameSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computername; + + /// + /// The following is the definition of the input parameter "Id". + /// Specifies one or more numeric Id(s) for which to get CimSession(s). + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = SessionIdSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public uint[] Id + { + get + { + return id; + } + + set + { + id = value; + base.SetParameter(value, nameId); + } + } + + private uint[] id; + + /// + /// The following is the definition of the input parameter "InstanceID". + /// Specifies one or Session Instance IDs. + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = InstanceIdSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Guid[] InstanceId + { + get + { + return instanceid; + } + + set + { + instanceid = value; + base.SetParameter(value, nameInstanceId); + } + } + + private Guid[] instanceid; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies one or more session Name(s) for which to get CimSession(s). The + /// argument may contain wildcard characters. + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = NameSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get + { + return name; + } + + set + { + name = value; + base.SetParameter(value, nameName); + } + } + + private string[] name; + + #endregion + + #region cmdlet processing methods + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + cimGetSession = new CimGetSession(); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + cimGetSession.GetCimSession(this); + } + + #endregion + + #region private members + /// + /// object used to search CimSession from cache. + /// + private CimGetSession cimGetSession; + + #region const string of parameter names + internal const string nameComputerName = "ComputerName"; + internal const string nameId = "Id"; + internal const string nameInstanceId = "InstanceId"; + internal const string nameName = "Name"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, false), + } + }, + { + nameId, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true), + } + }, + { + nameInstanceId, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true), + } + }, + { + nameName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.NameSet, true), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) }, + { CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) }, + { CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) }, + { CimBaseCommand.NameSet, new ParameterSetEntry(1) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..e3bc6f293b67d98f8849810d441cfeb510d3c5a3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -0,0 +1,582 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// This cmdlet enables the user to invoke a static method on a CIM class using + /// the arguments passed as a list of name value pair dictionary. + /// + [Alias("icim")] + [Cmdlet( + "Invoke", + "CimMethod", + SupportsShouldProcess = true, + DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227965")] + public class InvokeCimMethodCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public InvokeCimMethodCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + + /// + /// The following is the definition of the input parameter "ClassName". + /// Specifies the Class Name, on which to invoke static method. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Alias("Class")] + public string ClassName + { + get + { + return className; + } + + set + { + className = value; + base.SetParameter(value, nameClassName); + } + } + + private string className; + + /// + /// + /// The following is the definition of the input parameter "ResourceUri". + /// Define the Resource Uri for which the instances are retrieved. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + public Uri ResourceUri + { + get + { + return resourceUri; + } + + set + { + this.resourceUri = value; + base.SetParameter(value, nameResourceUri); + } + } + + private Uri resourceUri; + + /// + /// The following is the definition of the input parameter "CimClass". + /// Specifies the object, on which to invoke static method. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimClassComputerSet)] + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimClassSessionSet)] + public CimClass CimClass + { + get + { + return cimClass; + } + + set + { + cimClass = value; + base.SetParameter(value, nameCimClass); + } + } + + private CimClass cimClass; + + /// + /// The following is the definition of the input parameter "Query". + /// Specifies the object, on which to invoke static method. + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public string Query + { + get + { + return query; + } + + set + { + query = value; + base.SetParameter(value, nameQuery); + } + } + + private string query; + + /// + /// + /// The following is the definition of the input parameter "QueryDialect". + /// Specifies the dialect used by the query Engine that interprets the Query + /// string. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public string QueryDialect + { + get + { + return queryDialect; + } + + set + { + queryDialect = value; + base.SetParameter(value, nameQueryDialect); + } + } + + private string queryDialect; + + /// + /// The following is the definition of the input parameter "InputObject". + /// Takes a CimInstance object retrieved by a Get-CimInstance call. + /// Invoke the method against the given instance. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Alias(CimBaseCommand.AliasCimInstance)] + public CimInstance InputObject + { + get + { + return CimInstance; + } + + set + { + CimInstance = value; + base.SetParameter(value, nameCimInstance); + } + } + + /// + /// Property for internal usage purpose. + /// + internal CimInstance CimInstance { get; private set; } + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Provides the name of the computer from which to invoke the method. The + /// ComputerName is used to create a temporary CimSession with default parameter + /// values, which is then used to retrieve the instances. + /// + /// + /// If no ComputerName is specified the default value is "localhost" + /// + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimClassComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computerName; + } + + set + { + DebugHelper.WriteLogEx(); + computerName = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computerName; + + /// + /// + /// The following is the definition of the input parameter "CimSession". + /// Identifies the CimSession which is to be used to retrieve the instances. + /// + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimClassSessionSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimSession; + + /// + /// The following is the definition of the input parameter "Arguments". + /// Specifies the parameter arguments for the static method using a name value + /// pair. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public IDictionary Arguments { get; set; } + + /// + /// The following is the definition of the input parameter "MethodName". + /// Name of the Static Method to use. + /// + [Parameter(Mandatory = true, + Position = 2, + ValueFromPipelineByPropertyName = true)] + [Alias("Name")] + public string MethodName + { + get + { + return methodName; + } + + set + { + methodName = value; + base.SetParameter(value, nameMethodName); + } + } + + private string methodName; + + /// + /// The following is the definition of the input parameter "Namespace". + /// Specifies the NameSpace in which the class or instance lives under. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + public string Namespace + { + get + { + return nameSpace; + } + + set + { + nameSpace = value; + base.SetParameter(value, nameNamespace); + } + } + + private string nameSpace; + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Enables the user to specify the operation timeout in Seconds. This value + /// overwrites the value specified by the CimSession Operation timeout. + /// + [Alias(AliasOT)] + [Parameter] + public uint OperationTimeoutSec { get; set; } + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent() ?? CreateOperationAgent(); + + this.CmdletOperation = new CmdletOperationInvokeCimMethod(this, cimInvokeMethod); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + this.CheckArgument(); + CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); + cimInvokeMethod.InvokeCimMethod(this); + cimInvokeMethod.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); + cimInvokeMethod?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all Invoke-CimMethod operations. + /// + /// + private CimInvokeCimMethod GetOperationAgent() + { + return this.AsyncOperation as CimInvokeCimMethod; + } + + /// + /// + /// Create object, which is + /// used to delegate all Invoke-CimMethod operations. + /// + /// + /// + private CimInvokeCimMethod CreateOperationAgent() + { + CimInvokeCimMethod cimInvokeMethod = new(); + this.AsyncOperation = cimInvokeMethod; + return cimInvokeMethod; + } + + /// + /// Check argument value. + /// + private void CheckArgument() + { + switch (this.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.ClassNameSessionSet: + // validate the classname + this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); + break; + default: + break; + } + } + #endregion + + #region private members + + #region const string of parameter names + internal const string nameClassName = "ClassName"; + internal const string nameCimClass = "CimClass"; + internal const string nameQuery = "Query"; + internal const string nameResourceUri = "ResourceUri"; + internal const string nameQueryDialect = "QueryDialect"; + internal const string nameCimInstance = "InputObject"; + internal const string nameComputerName = "ComputerName"; + internal const string nameCimSession = "CimSession"; + internal const string nameArguments = "Arguments"; + internal const string nameMethodName = "MethodName"; + internal const string nameNamespace = "Namespace"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameClassName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + } + }, + { + nameCimClass, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), + } + }, + { + nameQuery, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + } + }, + { + nameQueryDialect, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + } + }, + { + nameCimInstance, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + } + }, + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + } + }, + { + nameMethodName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), + } + }, + { + nameNamespace, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + } + }, + { + nameResourceUri, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(2, true) }, + { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(3) }, + { CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(2) }, + { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(3) }, + { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) }, + { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) }, + { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(2) }, + { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(3) }, + { CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(2) }, + { CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(3) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj new file mode 100644 index 0000000000000000000000000000000000000000..582858a592ba0a8edda643311e7945e8eaa6ca4d --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj @@ -0,0 +1,13 @@ + + + + PowerShell's Microsoft.Management.Infrastructure.CimCmdlets project + $(NoWarn);CS1570;CS1572;CS1573;CS1574;CS1584;CS1587;CS1591 + Microsoft.Management.Infrastructure.CimCmdlets + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..5843f25a26b4745fe1a75be2b21783841f9abc45 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -0,0 +1,521 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// This Cmdlet creates an instance of a CIM class based on the class + /// definition, which is an instance factory + /// + /// + /// If -ClientOnly is not specified, New-CimInstance will create a new instance + /// on the server, otherwise just create client in-memory instance + /// + /// + [Alias("ncim")] + [Cmdlet(VerbsCommon.New, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227963")] + [OutputType(typeof(CimInstance))] + public class NewCimInstanceCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public NewCimInstanceCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + + /// + /// The following is the definition of the input parameter "ClassName". + /// Name of the Class to use to create Instance. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + public string ClassName + { + get + { + return className; + } + + set + { + className = value; + base.SetParameter(value, nameClassName); + } + } + + private string className; + + /// + /// + /// The following is the definition of the input parameter "ResourceUri". + /// Define the Resource Uri for which the instances are retrieved. + /// + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + public Uri ResourceUri + { + get + { + return resourceUri; + } + + set + { + this.resourceUri = value; + base.SetParameter(value, nameResourceUri); + } + } + + private Uri resourceUri; + + /// + /// + /// The following is the definition of the input parameter "Key". + /// Enables the user to specify list of key property name. + /// + /// + /// Example: -Key {"K1", "K2"} + /// + /// + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Key + { + get + { + return key; + } + + set + { + key = value; + base.SetParameter(value, nameKey); + } + } + + private string[] key; + + /// + /// The following is the definition of the input parameter "CimClass". + /// The CimClass is used to create Instance. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimClassSessionSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimClassComputerSet)] + public CimClass CimClass + { + get + { + return cimClass; + } + + set + { + cimClass = value; + base.SetParameter(value, nameCimClass); + } + } + + private CimClass cimClass; + + /// + /// + /// The following is the definition of the input parameter "Property". + /// Enables the user to specify instances with specific property values. + /// + /// + /// Example: -Property @{P1="Value1";P2="Value2"} + /// + /// + [Parameter( + Position = 1, + ValueFromPipelineByPropertyName = true)] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("Arguments")] + public IDictionary Property { get; set; } + + /// + /// The following is the definition of the input parameter "Namespace". + /// Namespace used to look for the classes under to store the instances. + /// Default namespace is 'root\cimv2' + /// + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + public string Namespace + { + get + { + return nameSpace; + } + + set + { + nameSpace = value; + base.SetParameter(value, nameNamespace); + } + } + + private string nameSpace; + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Operation Timeout of the cmdlet in seconds. Overrides the value in the Cim + /// Session. + /// + [Alias(AliasOT)] + [Parameter] + public uint OperationTimeoutSec { get; set; } + + /// + /// + /// The following is the definition of the input parameter "CimSession". + /// Identifies the CimSession which is to be used to create the instances. + /// + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimClassSessionSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimSession; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Provides the name of the computer from which to create the instances. + /// + /// + /// If no ComputerName is specified the default value is "localhost" + /// + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimClassComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computerName; + } + + set + { + computerName = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computerName; + + /// + /// + /// The following is the definition of the input parameter "ClientOnly". + /// Indicates to create a client only ciminstance object, NOT on the server. + /// + /// + [Alias("Local")] + [Parameter( + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter( + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimClassComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimClassSessionSet)] + public SwitchParameter ClientOnly + { + get + { + return clientOnly; + } + + set + { + clientOnly = value; + base.SetParameter(value, nameClientOnly); + } + } + + private SwitchParameter clientOnly; + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + this.CmdletOperation = new CmdletOperationBase(this); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + this.CheckArgument(); + if (this.ClientOnly) + { + string conflictParameterName = null; + if (this.ComputerName != null) + { + conflictParameterName = @"ComputerName"; + } + else if (this.CimSession != null) + { + conflictParameterName = @"CimSession"; + } + + if (conflictParameterName != null) + { + ThrowConflictParameterWasSet(@"New-CimInstance", conflictParameterName, @"ClientOnly"); + return; + } + } + + CimNewCimInstance cimNewCimInstance = this.GetOperationAgent() ?? CreateOperationAgent(); + + cimNewCimInstance.NewCimInstance(this); + cimNewCimInstance.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimNewCimInstance cimNewCimInstance = this.GetOperationAgent(); + cimNewCimInstance?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all New-CimInstance operations. + /// + /// + private CimNewCimInstance GetOperationAgent() + { + return this.AsyncOperation as CimNewCimInstance; + } + + /// + /// + /// Create object, which is + /// used to delegate all New-CimInstance operations. + /// + /// + /// + private CimNewCimInstance CreateOperationAgent() + { + CimNewCimInstance cimNewCimInstance = new(); + this.AsyncOperation = cimNewCimInstance; + return cimNewCimInstance; + } + + /// + /// Check argument value. + /// + private void CheckArgument() + { + switch (this.ParameterSetName) + { + case CimBaseCommand.ClassNameComputerSet: + case CimBaseCommand.ClassNameSessionSet: + // validate the classname + this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); + break; + default: + break; + } + } + #endregion + + #region private members + + #region const string of parameter names + internal const string nameClassName = "ClassName"; + internal const string nameResourceUri = "ResourceUri"; + internal const string nameKey = "Key"; + internal const string nameCimClass = "CimClass"; + internal const string nameProperty = "Property"; + internal const string nameNamespace = "Namespace"; + internal const string nameCimSession = "CimSession"; + internal const string nameComputerName = "ComputerName"; + internal const string nameClientOnly = "ClientOnly"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameClassName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), + } + }, + { + nameResourceUri, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), + } + }, + { + nameKey, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + } + }, + { + nameCimClass, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), + } + }, + { + nameNamespace, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), + } + }, + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false), + } + }, + { + nameClientOnly, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, + { CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(1) }, + { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b8e36cf82968cc066b29864cd2b443fae9e2b20 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using Microsoft.Management.Infrastructure.Options; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// This Cmdlet enables the IT Pro to create a CIM Session. CIM Session object + /// is a client-side representation of the connection between the client and the + /// server. + /// The CimSession object returned by the Cmdlet is used by all other CIM + /// cmdlets. + /// + [Alias("ncms")] + [Cmdlet(VerbsCommon.New, "CimSession", DefaultParameterSetName = CredentialParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227967")] + [OutputType(typeof(CimSession))] + public sealed class NewCimSessionCommand : CimBaseCommand + { + #region cmdlet parameters + + /// + /// The following is the definition of the input parameter "Authentication". + /// The following is the validation set for allowed authentication types. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CredentialParameterSet)] + public PasswordAuthenticationMechanism Authentication + { + get + { + return authentication; + } + + set + { + authentication = value; + authenticationSet = true; + } + } + + private PasswordAuthenticationMechanism authentication; + private bool authenticationSet = false; + + /// + /// The following is the definition of the input parameter "Credential". + /// Specifies a user account that has permission to perform this action. + /// The default is the current user. + /// + [Parameter(Position = 1, ParameterSetName = CredentialParameterSet)] + [Credential] + public PSCredential Credential { get; set; } + + /// + /// The following is the definition of the input parameter "CertificateThumbprint". + /// This is specificly for wsman protocol. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CertificateParameterSet)] + public string CertificateThumbprint { get; set; } + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specifies the computer on which the commands associated with this session + /// will run. The default value is LocalHost. + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + Position = 0, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName { get; set; } + + /// + /// + /// The following is the definition of the input parameter "Name". + /// Specifies a friendly name for the CIM Session connection. + /// + /// + /// If a name is not passed, then the session is given the name CimSession, + /// where is the next available session number. Example, CimSession1, + /// CimSession2, etc... + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string Name { get; set; } + + /// + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Specifies the operation timeout for all operations in session. Individual + /// operations can override this timeout. + /// + /// + /// The unit is Second. + /// + /// + [Alias(AliasOT)] + [Parameter(ValueFromPipelineByPropertyName = true)] + public uint OperationTimeoutSec + { + get + { + return operationTimeout; + } + + set + { + operationTimeout = value; + operationTimeoutSet = true; + } + } + + private uint operationTimeout; + internal bool operationTimeoutSet = false; + + /// + /// + /// The following is the definition of the input parameter "SkipTestConnection". + /// Specifies where test connection should be skipped + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public SwitchParameter SkipTestConnection { get; set; } + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port number to use, if different than the default port number. + /// This is specificly for wsman protocol. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public uint Port + { + get + { + return port; + } + + set + { + port = value; + portSet = true; + } + } + + private uint port; + private bool portSet = false; + + /// + /// + /// The following is the definition of the input parameter "SessionOption". + /// Specifies the SessionOption object that is passed to the Cmdlet as argument. + /// + /// + /// If the argument is not given, a default SessionOption will be created for + /// the session in .NET API layer. + /// + /// + /// If a object is passed, then + /// connection is made using DCOM. If a + /// object is passed, then connection is made using WsMan. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption { get; set; } + + #endregion + + #region cmdlet processing methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + cimNewSession = new CimNewSession(); + this.CmdletOperation = new CmdletOperationTestCimSession(this, this.cimNewSession); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + CimSessionOptions outputOptions; + CimCredential outputCredential; + BuildSessionOptions(out outputOptions, out outputCredential); + cimNewSession.NewCimSession(this, outputOptions, outputCredential); + cimNewSession.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + cimNewSession.ProcessRemainActions(this.CmdletOperation); + } + #endregion + + #region helper methods + + /// + /// Build a CimSessionOptions, used to create CimSession. + /// + /// Null means no prefer CimSessionOptions. + internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential) + { + DebugHelper.WriteLogEx(); + + CimSessionOptions options = null; + if (this.SessionOption != null) + { + // clone the sessionOption object + if (this.SessionOption is WSManSessionOptions) + { + options = new WSManSessionOptions(this.SessionOption as WSManSessionOptions); + } + else + { + options = new DComSessionOptions(this.SessionOption as DComSessionOptions); + } + } + + outputOptions = null; + outputCredential = null; + if (options != null) + { + if (options is DComSessionOptions dcomOptions) + { + bool conflict = false; + string parameterName = string.Empty; + if (this.CertificateThumbprint != null) + { + conflict = true; + parameterName = @"CertificateThumbprint"; + } + + if (portSet) + { + conflict = true; + parameterName = @"Port"; + } + + if (conflict) + { + ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions"); + return; + } + } + } + + if (portSet || (this.CertificateThumbprint != null)) + { + WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions; + if (portSet) + { + wsmanOptions.DestinationPort = this.Port; + portSet = false; + } + + if (this.CertificateThumbprint != null) + { + CimCredential credentials = new(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint); + wsmanOptions.AddDestinationCredentials(credentials); + } + + options = wsmanOptions; + } + + if (this.operationTimeoutSet) + { + if (options != null) + { + options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec); + } + } + + if (this.authenticationSet || (this.Credential != null)) + { + PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default; + if (this.authenticationSet) + { + this.authenticationSet = false; + } + + CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication"); + if (credentials == null) + { + return; + } + + DebugHelper.WriteLog("Credentials: {0}", 1, credentials); + outputCredential = credentials; + if (options != null) + { + DebugHelper.WriteLog("Add credentials to option: {0}", 1, options); + options.AddDestinationCredentials(credentials); + } + } + + DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions); + outputOptions = options; + } + + #endregion + + #region private members + + /// + /// + /// CimNewSession object + /// + /// + private CimNewSession cimNewSession; + + #endregion + + #region IDisposable + /// + /// Clean up resources. + /// + protected override void DisposeInternal() + { + base.DisposeInternal(); + + // Dispose managed resources. + this.cimNewSession?.Dispose(); + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..54956a9805a59143bb89d27f3211a0db08b55a0d --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -0,0 +1,861 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using Microsoft.Management.Infrastructure.Options; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Define Protocol type. + /// + public enum ProtocolType + { + Default, + + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + Dcom, + + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + Wsman + } + + /// + /// The Cmdlet allows the IT Pro to create a CimSessionOptions object that she/he + /// can subsequently use to create one or more CimSession connections. The + /// options object holds the CIM Session information that is less commonly set + /// and used by the IT Pro, and most commonly defaulted. + /// + /// The Cmdlet has two parameter sets, one for WMMan options and one for DCOM + /// options. Depending on the arguments the Cmdlet will return an instance of + /// DComSessionOptions or WSManSessionOptions, which derive from + /// CimSessionOptions. + /// + [Alias("ncso")] + [Cmdlet(VerbsCommon.New, "CimSessionOption", DefaultParameterSetName = ProtocolNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227969")] + [OutputType(typeof(CimSessionOptions))] + public sealed class NewCimSessionOptionCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public NewCimSessionOptionCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region cmdlet parameters + + /// + /// The following is the definition of the input parameter "NoEncryption". + /// Switch indicating if WSMan can use no encryption in the given CimSession (there are also global client and server WSMan settings - AllowUnencrypted). + /// + [Parameter(ParameterSetName = WSManParameterSet)] + public SwitchParameter NoEncryption + { + get + { + return noEncryption; + } + + set + { + noEncryption = value; + noEncryptionSet = true; + base.SetParameter(value, nameNoEncryption); + } + } + + private SwitchParameter noEncryption; + private bool noEncryptionSet = false; + + /// + /// The following is the definition of the input parameter "CertificateCACheck". + /// Switch indicating if Certificate Authority should be validated. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public SwitchParameter SkipCACheck + { + get + { + return skipCACheck; + } + + set + { + skipCACheck = value; + skipCACheckSet = true; + base.SetParameter(value, nameSkipCACheck); + } + } + + private SwitchParameter skipCACheck; + private bool skipCACheckSet = false; + + /// + /// The following is the definition of the input parameter "CertificateCNCheck". + /// Switch indicating if Certificate Name should be validated. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public SwitchParameter SkipCNCheck + { + get + { + return skipCNCheck; + } + + set + { + skipCNCheck = value; + skipCNCheckSet = true; + base.SetParameter(value, nameSkipCNCheck); + } + } + + private SwitchParameter skipCNCheck; + private bool skipCNCheckSet = false; + + /// + /// The following is the definition of the input parameter "CertRevocationCheck". + /// Switch indicating if certificate should be revoked. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public SwitchParameter SkipRevocationCheck + { + get + { + return skipRevocationCheck; + } + + set + { + skipRevocationCheck = value; + skipRevocationCheckSet = true; + base.SetParameter(value, nameSkipRevocationCheck); + } + } + + private SwitchParameter skipRevocationCheck; + private bool skipRevocationCheckSet = false; + + /// + /// The following is the definition of the input parameter "EncodePortInServicePrincipalName". + /// Switch indicating if to encode Port In Service Principal Name. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public SwitchParameter EncodePortInServicePrincipalName + { + get + { + return encodeportinserviceprincipalname; + } + + set + { + encodeportinserviceprincipalname = value; + encodeportinserviceprincipalnameSet = true; + base.SetParameter(value, nameEncodePortInServicePrincipalName); + } + } + + private SwitchParameter encodeportinserviceprincipalname; + private bool encodeportinserviceprincipalnameSet = false; + + /// + /// The following is the definition of the input parameter "Encoding". + /// Defined the message encoding. + /// The allowed encodings are { Default | Utf8 | Utf16 }. The default value + /// should be Utf8. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public PacketEncoding Encoding + { + get + { + return encoding; + } + + set + { + encoding = value; + encodingSet = true; + base.SetParameter(value, nameEncoding); + } + } + + private PacketEncoding encoding; + private bool encodingSet = false; + + /// + /// The following is the definition of the input parameter "HttpPrefix". + /// This is the HTTP URL on the server on which the WSMan service is listening. + /// In most cases it is /wsman, which is the default. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public Uri HttpPrefix + { + get + { + return httpprefix; + } + + set + { + httpprefix = value; + base.SetParameter(value, nameHttpPrefix); + } + } + + private Uri httpprefix; + + /// + /// The following is the definition of the input parameter "MaxEnvelopeSizeKB". + /// Sets the limit to the maximum size of the WSMan message envelope. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public uint MaxEnvelopeSizeKB + { + get + { + return maxenvelopesizekb; + } + + set + { + maxenvelopesizekb = value; + maxenvelopesizekbSet = true; + base.SetParameter(value, nameMaxEnvelopeSizeKB); + } + } + + private uint maxenvelopesizekb; + private bool maxenvelopesizekbSet = false; + + /// + /// The following is the definition of the input parameter "ProxyAuthentication". + /// Which proxy authentication types to use: Allowed set is: + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public PasswordAuthenticationMechanism ProxyAuthentication + { + get + { + return proxyAuthentication; + } + + set + { + proxyAuthentication = value; + proxyauthenticationSet = true; + base.SetParameter(value, nameProxyAuthentication); + } + } + + private PasswordAuthenticationMechanism proxyAuthentication; + private bool proxyauthenticationSet = false; + + /// + /// The following is the definition of the input parameter "ProxyCertificateThumbprint". + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public string ProxyCertificateThumbprint + { + get + { + return proxycertificatethumbprint; + } + + set + { + proxycertificatethumbprint = value; + base.SetParameter(value, nameProxyCertificateThumbprint); + } + } + + private string proxycertificatethumbprint; + + /// + /// The following is the definition of the input parameter "ProxyCredential". + /// Ps Credential used by the proxy server when required by the server. + /// + [Parameter(ParameterSetName = WSManParameterSet)] + [Credential] + public PSCredential ProxyCredential + { + get + { + return proxycredential; + } + + set + { + proxycredential = value; + base.SetParameter(value, nameProxyCredential); + } + } + + private PSCredential proxycredential; + + /// + /// The following is the definition of the input parameter "ProxyType". + /// Which proxy type to use: Valid set is: + /// { InternetExplorer | WinHttp | Auto | None } + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public ProxyType ProxyType + { + get + { + return proxytype; + } + + set + { + proxytype = value; + proxytypeSet = true; + base.SetParameter(value, nameProxyType); + } + } + + private ProxyType proxytype; + private bool proxytypeSet = false; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Switch indicating if Secure Sockets Layer connection should be used. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = WSManParameterSet)] + public SwitchParameter UseSsl + { + get + { + return usessl; + } + + set + { + usessl = value; + usesslSet = true; + base.SetParameter(value, nameUseSsl); + } + } + + private SwitchParameter usessl; + private bool usesslSet = false; + + /// + /// The following is the definition of the input parameter "Impersonation". + /// Used to select if, and if so what kind of, impersonation should be used. + /// Applies only to the DCOM channel. + /// + [Parameter(ParameterSetName = DcomParameterSet)] + public ImpersonationType Impersonation + { + get + { + return impersonation; + } + + set + { + impersonation = value; + impersonationSet = true; + base.SetParameter(value, nameImpersonation); + } + } + + private ImpersonationType impersonation; + private bool impersonationSet = false; + + /// + /// The following is the definition of the input parameter "PacketIntegrity". + /// Switch indicating if the package integrity in DCOM connections should be + /// checked/enforced. + /// + [Parameter(ParameterSetName = DcomParameterSet)] + public SwitchParameter PacketIntegrity + { + get + { + return packetintegrity; + } + + set + { + packetintegrity = value; + packetintegritySet = true; + base.SetParameter(value, namePacketIntegrity); + } + } + + private SwitchParameter packetintegrity; + private bool packetintegritySet = false; + + /// + /// The following is the definition of the input parameter "PacketPrivacy". + /// Switch indicating if packet privacy of the packets in DCOM communications + /// should be checked/enforced. + /// + [Parameter(ParameterSetName = DcomParameterSet)] + public SwitchParameter PacketPrivacy + { + get + { + return packetprivacy; + } + + set + { + packetprivacy = value; + packetprivacySet = true; + base.SetParameter(value, namePacketPrivacy); + } + } + + private SwitchParameter packetprivacy; + private bool packetprivacySet = false; + + /// + /// The following is the definition of the input parameter "Protocol". + /// Switch indicating if to encode Port In Service Principal Name. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = ProtocolNameParameterSet)] + public ProtocolType Protocol + { + get + { + return protocol; + } + + set + { + protocol = value; + base.SetParameter(value, nameProtocol); + } + } + + private ProtocolType protocol; + + /// + /// The following is the definition of the input parameter "UICulture". + /// Specifies the UI Culture to use. i.e. en-us, ar-sa. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public CultureInfo UICulture { get; set; } + + /// + /// The following is the definition of the input parameter "Culture". + /// Specifies the culture to use. i.e. en-us, ar-sa. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public CultureInfo Culture { get; set; } + + #endregion + + #region cmdlet processing methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + this.CmdletOperation = new CmdletOperationBase(this); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + CimSessionOptions options; + switch (this.ParameterSetName) + { + case WSManParameterSet: + { + options = CreateWSMANSessionOptions(); + } + + break; + case DcomParameterSet: + { + options = CreateDComSessionOptions(); + } + + break; + case ProtocolNameParameterSet: + switch (Protocol) + { + case ProtocolType.Dcom: + options = CreateDComSessionOptions(); + break; + case ProtocolType.Wsman: + default: + options = CreateWSMANSessionOptions(); + break; + } + + break; + default: + return; + } + + if (options != null) + { + if (this.Culture != null) + { + options.Culture = this.Culture; + } + + if (this.UICulture != null) + { + options.UICulture = this.UICulture; + } + + this.WriteObject(options); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + } + + #endregion + + #region helper functions + /// + /// Create DComSessionOptions. + /// + /// + internal DComSessionOptions CreateDComSessionOptions() + { + DComSessionOptions dcomoptions = new(); + if (this.impersonationSet) + { + dcomoptions.Impersonation = this.Impersonation; + this.impersonationSet = false; + } + else + { + dcomoptions.Impersonation = ImpersonationType.Impersonate; + } + + if (this.packetintegritySet) + { + dcomoptions.PacketIntegrity = this.packetintegrity; + this.packetintegritySet = false; + } + else + { + dcomoptions.PacketIntegrity = true; + } + + if (this.packetprivacySet) + { + dcomoptions.PacketPrivacy = this.PacketPrivacy; + this.packetprivacySet = false; + } + else + { + dcomoptions.PacketPrivacy = true; + } + + return dcomoptions; + } + + /// + /// Create WSMANSessionOptions. + /// + /// + internal WSManSessionOptions CreateWSMANSessionOptions() + { + WSManSessionOptions wsmanoptions = new(); + if (this.noEncryptionSet) + { + wsmanoptions.NoEncryption = true; + this.noEncryptionSet = false; + } + else + { + wsmanoptions.NoEncryption = false; + } + + if (this.skipCACheckSet) + { + wsmanoptions.CertCACheck = false; + this.skipCACheckSet = false; + } + else + { + wsmanoptions.CertCACheck = true; + } + + if (this.skipCNCheckSet) + { + wsmanoptions.CertCNCheck = false; + this.skipCNCheckSet = false; + } + else + { + wsmanoptions.CertCNCheck = true; + } + + if (this.skipRevocationCheckSet) + { + wsmanoptions.CertRevocationCheck = false; + this.skipRevocationCheckSet = false; + } + else + { + wsmanoptions.CertRevocationCheck = true; + } + + if (this.encodeportinserviceprincipalnameSet) + { + wsmanoptions.EncodePortInServicePrincipalName = this.EncodePortInServicePrincipalName; + this.encodeportinserviceprincipalnameSet = false; + } + else + { + wsmanoptions.EncodePortInServicePrincipalName = false; + } + + if (this.encodingSet) + { + wsmanoptions.PacketEncoding = this.Encoding; + } + else + { + wsmanoptions.PacketEncoding = PacketEncoding.Utf8; + } + + if (this.HttpPrefix != null) + { + wsmanoptions.HttpUrlPrefix = this.HttpPrefix; + } + + if (this.maxenvelopesizekbSet) + { + wsmanoptions.MaxEnvelopeSize = this.MaxEnvelopeSizeKB; + } + else + { + wsmanoptions.MaxEnvelopeSize = 0; + } + + if (!string.IsNullOrWhiteSpace(this.ProxyCertificateThumbprint)) + { + CimCredential credentials = new(CertificateAuthenticationMechanism.Default, this.ProxyCertificateThumbprint); + wsmanoptions.AddProxyCredentials(credentials); + } + + if (this.proxyauthenticationSet) + { + this.proxyauthenticationSet = false; + DebugHelper.WriteLogEx("create credential", 1); + CimCredential credentials = CreateCimCredentials(this.ProxyCredential, this.ProxyAuthentication, @"New-CimSessionOption", @"ProxyAuthentication"); + if (credentials != null) + { + try + { + DebugHelper.WriteLogEx("Add proxy credential", 1); + wsmanoptions.AddProxyCredentials(credentials); + } + catch (Exception ex) + { + DebugHelper.WriteLogEx(ex.ToString(), 1); + throw; + } + } + } + + if (this.proxytypeSet) + { + wsmanoptions.ProxyType = this.ProxyType; + this.proxytypeSet = false; + } + else + { + wsmanoptions.ProxyType = Options.ProxyType.WinHttp; + } + + if (this.usesslSet) + { + wsmanoptions.UseSsl = this.UseSsl; + this.usesslSet = false; + } + else + { + wsmanoptions.UseSsl = false; + } + + wsmanoptions.DestinationPort = 0; + return wsmanoptions; + } + #endregion + + #region private members + + #region const string of parameter names + internal const string nameNoEncryption = "NoEncryption"; + internal const string nameSkipCACheck = "SkipCACheck"; + internal const string nameSkipCNCheck = "SkipCNCheck"; + internal const string nameSkipRevocationCheck = "SkipRevocationCheck"; + internal const string nameEncodePortInServicePrincipalName = "EncodePortInServicePrincipalName"; + internal const string nameEncoding = "Encoding"; + internal const string nameHttpPrefix = "HttpPrefix"; + internal const string nameMaxEnvelopeSizeKB = "MaxEnvelopeSizeKB"; + internal const string nameProxyAuthentication = "ProxyAuthentication"; + internal const string nameProxyCertificateThumbprint = "ProxyCertificateThumbprint"; + internal const string nameProxyCredential = "ProxyCredential"; + internal const string nameProxyType = "ProxyType"; + internal const string nameUseSsl = "UseSsl"; + internal const string nameImpersonation = "Impersonation"; + internal const string namePacketIntegrity = "PacketIntegrity"; + internal const string namePacketPrivacy = "PacketPrivacy"; + internal const string nameProtocol = "Protocol"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameNoEncryption, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameSkipCACheck, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameSkipCNCheck, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + { + nameSkipRevocationCheck, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameEncodePortInServicePrincipalName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + { + nameEncoding, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameHttpPrefix, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + { + nameMaxEnvelopeSizeKB, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameProxyAuthentication, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + { + nameProxyCertificateThumbprint, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameProxyCredential, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + { + nameProxyType, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + + { + nameUseSsl, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false), + } + }, + { + nameImpersonation, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.DcomParameterSet, false), + } + }, + + { + namePacketIntegrity, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.DcomParameterSet, false), + } + }, + { + namePacketPrivacy, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.DcomParameterSet, false), + } + }, + + { + nameProtocol, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ProtocolNameParameterSet, true), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.ProtocolNameParameterSet, new ParameterSetEntry(1, true) }, + { CimBaseCommand.DcomParameterSet, new ParameterSetEntry(0) }, + { CimBaseCommand.WSManParameterSet, new ParameterSetEntry(0) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..b314691e41f6ce9d74d196e5ae4f7579442a85ba --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -0,0 +1,365 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; +using Microsoft.PowerShell.Commands; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Enables the user to subscribe to indications using Filter Expression or + /// Query Expression. + /// -SourceIdentifier is a name given to the subscription + /// The Cmdlet should return a PS EventSubscription object that can be used to + /// cancel the subscription + /// Should we have the second parameter set with a -Query? + /// + [Alias("rcie")] + [Cmdlet(VerbsLifecycle.Register, "CimIndicationEvent", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227960")] + public class RegisterCimIndicationCommand : ObjectEventRegistrationBase + { + #region parameters + + /// + /// + /// The following is the definition of the input parameter "Namespace". + /// Specifies the NameSpace under which to look for the specified class name. + /// + /// + /// Default value is root\cimv2 + /// + /// + [Parameter] + public string Namespace { get; set; } + + /// + /// The following is the definition of the input parameter "ClassName". + /// Specifies the Class Name to register the indication on. + /// + [Parameter( + Mandatory = true, + Position = 0, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + public string ClassName + { + get + { + return className; + } + + set + { + className = value; + this.SetParameter(value, nameClassName); + } + } + + private string className; + + /// + /// The following is the definition of the input parameter "Query". + /// The Query Expression to pass. + /// + [Parameter( + Mandatory = true, + Position = 0, + ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] + [Parameter( + Mandatory = true, + Position = 0, + ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] + public string Query + { + get + { + return query; + } + + set + { + query = value; + this.SetParameter(value, nameQuery); + } + } + + private string query; + + /// + /// + /// The following is the definition of the input parameter "QueryDialect". + /// Specifies the dialect used by the query Engine that interprets the Query + /// string. + /// + /// + [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] + public string QueryDialect + { + get + { + return queryDialect; + } + + set + { + queryDialect = value; + this.SetParameter(value, nameQueryDialect); + } + } + + private string queryDialect; + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Enables the user to specify the operation timeout in Seconds. This value + /// overwrites the value specified by the CimSession Operation timeout. + /// + [Alias(CimBaseCommand.AliasOT)] + [Parameter] + public uint OperationTimeoutSec { get; set; } + + /// + /// The following is the definition of the input parameter "Session". + /// Uses a CimSession context. + /// + [Parameter( + Mandatory = true, + ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] + [Parameter( + Mandatory = true, + ParameterSetName = CimBaseCommand.ClassNameSessionSet)] + public CimSession CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + this.SetParameter(value, nameCimSession); + } + } + + private CimSession cimSession; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specifies the computer on which the commands associated with this session + /// will run. The default value is LocalHost. + /// + [Alias(CimBaseCommand.AliasCN, CimBaseCommand.AliasServerName)] + [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] + [Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + this.SetParameter(value, nameComputerName); + } + } + + private string computername; + + #endregion + + /// + /// Returns the object that generates events to be monitored. + /// + protected override object GetSourceObject() + { + CimIndicationWatcher watcher = null; + string parameterSetName = null; + try + { + parameterSetName = this.parameterBinder.GetParameterSet(); + } + finally + { + this.parameterBinder.reset(); + } + + string tempQueryExpression = string.Empty; + switch (parameterSetName) + { + case CimBaseCommand.QueryExpressionSessionSet: + case CimBaseCommand.QueryExpressionComputerSet: + tempQueryExpression = this.Query; + break; + case CimBaseCommand.ClassNameSessionSet: + case CimBaseCommand.ClassNameComputerSet: + // validate the classname + this.CheckArgument(); + tempQueryExpression = string.Create(CultureInfo.CurrentCulture, $"Select * from {this.ClassName}"); + break; + } + + switch (parameterSetName) + { + case CimBaseCommand.QueryExpressionSessionSet: + case CimBaseCommand.ClassNameSessionSet: + { + watcher = new CimIndicationWatcher(this.CimSession, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); + } + + break; + case CimBaseCommand.QueryExpressionComputerSet: + case CimBaseCommand.ClassNameComputerSet: + { + watcher = new CimIndicationWatcher(this.ComputerName, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); + } + + break; + } + + watcher?.SetCmdlet(this); + + return watcher; + } + + /// + /// Returns the event name to be monitored on the input object. + /// + protected override string GetSourceObjectEventName() + { + return "CimIndicationArrived"; + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + DebugHelper.WriteLogEx(); + + base.EndProcessing(); + + // Register for the "Unsubscribed" event so that we can stop the + // Cimindication event watcher. + PSEventSubscriber newSubscriber = NewSubscriber; + if (newSubscriber != null) + { + DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4); + newSubscriber.Unsubscribed += newSubscriber_Unsubscribed; + } + } + + /// + /// + /// Handler to handle unsubscribe event + /// + /// + /// + /// + private static void newSubscriber_Unsubscribed( + object sender, PSEventUnsubscribedEventArgs e) + { + DebugHelper.WriteLogEx(); + + CimIndicationWatcher watcher = sender as CimIndicationWatcher; + watcher?.Stop(); + } + + #region private members + /// + /// Check argument value. + /// + private void CheckArgument() + { + this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); + } + + /// + /// Parameter binder used to resolve parameter set name. + /// + private readonly ParameterBinder parameterBinder = new( + parameters, parameterSets); + + /// + /// Set the parameter. + /// + /// + private void SetParameter(object value, string parameterName) + { + if (value == null) + { + return; + } + + this.parameterBinder.SetParameter(parameterName, true); + } + + #region const string of parameter names + internal const string nameClassName = "ClassName"; + internal const string nameQuery = "Query"; + internal const string nameQueryDialect = "QueryDialect"; + internal const string nameCimSession = "CimSession"; + internal const string nameComputerName = "ComputerName"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameClassName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), + } + }, + { + nameQuery, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, true), + } + }, + { + nameQueryDialect, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), + } + }, + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) }, + { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, + }; + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..5ac8d1293675f5bde94f2d8b77c93a916cc1fdd1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -0,0 +1,386 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// Enables the user to remove a CimInstance. + /// + [Alias("rcim")] + [Cmdlet( + VerbsCommon.Remove, + "CimInstance", + SupportsShouldProcess = true, + DefaultParameterSetName = CimBaseCommand.CimInstanceComputerSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227964")] + public class RemoveCimInstanceCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public RemoveCimInstanceCommand() + : base(parameters, parameterSets) + { + DebugHelper.WriteLogEx(); + } + + #endregion + + #region parameters + /// + /// The following is the definition of the input parameter "Session". + /// CIM session used to remove the CIM Instance. + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimSession; + + /// + /// + /// The following is the definition of the input parameter "ResourceUri". + /// Define the Resource Uri for which the instances are retrieved. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + public Uri ResourceUri + { + get + { + return resourceUri; + } + + set + { + this.resourceUri = value; + base.SetParameter(value, nameResourceUri); + } + } + + private Uri resourceUri; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computername; + + /// + /// The following is the definition of the input parameter "Namespace". + /// The Namespace used to look for the Class instances under. + /// + [Parameter( + Position = 1, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter( + Position = 1, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + public string Namespace + { + get + { + return nameSpace; + } + + set + { + nameSpace = value; + base.SetParameter(value, nameNamespace); + } + } + + private string nameSpace; + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Used to set the invocation operation time out. This value overrides the + /// CimSession operation timeout. + /// + [Alias(AliasOT)] + [Parameter] + public uint OperationTimeoutSec { get; set; } + + /// + /// The following is the definition of the input parameter "InputObject". + /// Used to get a CimInstance using Get-CimInstance | Remove-CimInstance. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Alias(CimBaseCommand.AliasCimInstance)] + public CimInstance InputObject + { + get + { + return CimInstance; + } + + set + { + CimInstance = value; + base.SetParameter(value, nameCimInstance); + } + } + + /// + /// Property for internal usage purpose. + /// + internal CimInstance CimInstance { get; private set; } + + /// + /// The following is the definition of the input parameter "Query". + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public string Query + { + get + { + return query; + } + + set + { + query = value; + base.SetParameter(value, nameQuery); + } + } + + private string query; + + /// + /// The following is the definition of the input parameter "QueryDialect". + /// Specifies the dialect used by the query Engine that interprets the Query + /// string. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + public string QueryDialect + { + get + { + return querydialect; + } + + set + { + querydialect = value; + base.SetParameter(value, nameQueryDialect); + } + } + + private string querydialect; + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent() ?? CreateOperationAgent(); + + this.CmdletOperation = new CmdletOperationRemoveCimInstance(this, cimRemoveInstance); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent(); + cimRemoveInstance.RemoveCimInstance(this); + cimRemoveInstance.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent(); + cimRemoveInstance?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all Remove-CimInstance operations. + /// + /// + private CimRemoveCimInstance GetOperationAgent() + { + return this.AsyncOperation as CimRemoveCimInstance; + } + + /// + /// + /// Create object, which is + /// used to delegate all Remove-CimInstance operations. + /// + /// + /// + private CimRemoveCimInstance CreateOperationAgent() + { + CimRemoveCimInstance cimRemoveInstance = new(); + this.AsyncOperation = cimRemoveInstance; + return cimRemoveInstance; + } + + #endregion + + #region private members + + #region const string of parameter names + internal const string nameCimSession = "CimSession"; + internal const string nameComputerName = "ComputerName"; + internal const string nameResourceUri = "ResourceUri"; + internal const string nameNamespace = "Namespace"; + internal const string nameCimInstance = "InputObject"; + internal const string nameQuery = "Query"; + internal const string nameQueryDialect = "QueryDialect"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + } + }, + { + nameNamespace, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + } + }, + { + nameCimInstance, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + } + }, + { + nameQuery, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + } + }, + { + nameQueryDialect, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + } + }, + { + nameResourceUri, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1, true) }, + { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(1) }, + { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(2) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..2f1a5ad026e26eaba1cd0ec405141f80df4b4b1c --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -0,0 +1,259 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +#endregion + +/****************************************************************************** + * warning 28750: Banned usage of lstrlen and its variants: lstrlenW is a + * banned API for improved error handling purposes. + *****************************************************************************/ +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// This Cmdlet allows the to remove, or terminate, one or more CimSession(s). + /// + [Alias("rcms")] + [Cmdlet(VerbsCommon.Remove, "CimSession", + SupportsShouldProcess = true, + DefaultParameterSetName = CimSessionSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227968")] + public sealed class RemoveCimSessionCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public RemoveCimSessionCommand() + : base(parameters, parameterSets) + { + } + + #endregion + + #region parameters + + /// + /// The following is the definition of the input parameter "CimSession". + /// Specifies one or more CimSession object to be removed from the local PS + /// session/runspace. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimSessionSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimsession; + } + + set + { + cimsession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimsession; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specified one or more computer names for which all CimSession(s) + /// (connections) should be removed (terminated). + /// This is the only optional parameter. If no value for this parameter is + /// provided, all CimSession(s) are terminated. + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = ComputerNameSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computername; + + /// + /// The following is the definition of the input parameter "Id". + /// Specifies the friendly Id(s) of the CimSession(s) that should be removed + /// (terminated). + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = SessionIdSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public uint[] Id + { + get + { + return id; + } + + set + { + id = value; + base.SetParameter(value, nameId); + } + } + + private uint[] id; + + /// + /// The following is the definition of the input parameter "InstanceId". + /// Specifies one or more automatically generated InstanceId(s) (GUIDs) of the + /// CimSession(s) that should be removed (terminated). + /// + [Parameter( + Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = InstanceIdSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Guid[] InstanceId + { + get + { + return instanceid; + } + + set + { + instanceid = value; + base.SetParameter(value, nameInstanceId); + } + } + + private Guid[] instanceid; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies one or more of friendly Names of the CimSession(s) that should be + /// removed (terminated). + /// + [Parameter( + Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = NameSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get + { + return name; + } + + set + { + name = value; + base.SetParameter(value, nameName); + } + } + + private string[] name; + + #endregion + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + this.cimRemoveSession = new CimRemoveSession(); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + this.cimRemoveSession.RemoveCimSession(this); + } + + #region private members + /// + /// object used to remove the session from + /// session cache. + /// + private CimRemoveSession cimRemoveSession; + + #region const string of parameter names + internal const string nameCimSession = "CimSession"; + internal const string nameComputerName = "ComputerName"; + internal const string nameId = "Id"; + internal const string nameInstanceId = "InstanceId"; + internal const string nameName = "Name"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimSessionSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, true), + } + }, + { + nameId, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true), + } + }, + { + nameInstanceId, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true), + } + }, + { + nameName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.NameSet, true), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.CimSessionSet, new ParameterSetEntry(1, true) }, + { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(1) }, + { CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) }, + { CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) }, + { CimBaseCommand.NameSet, new ParameterSetEntry(1) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..d190e5fafbae2b06cfd625ccaca8dcbdc603a81f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -0,0 +1,444 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +#endregion + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Enables the user to Set properties and keys on a specific + /// CimInstance must have values of all [KEY] properties. + /// + /// + [Alias("scim")] + [Cmdlet( + VerbsCommon.Set, + "CimInstance", + SupportsShouldProcess = true, + DefaultParameterSetName = CimBaseCommand.CimInstanceComputerSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227962")] + public class SetCimInstanceCommand : CimBaseCommand + { + #region constructor + + /// + /// Initializes a new instance of the class. + /// + public SetCimInstanceCommand() + : base(parameters, parameterSets) + { + } + + #endregion + + #region parameters + /// + /// The following is the definition of the input parameter "Session". + /// CIM session used to set the CIM Instance. + /// + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public CimSession[] CimSession + { + get + { + return cimSession; + } + + set + { + cimSession = value; + base.SetParameter(value, nameCimSession); + } + } + + private CimSession[] cimSession; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// + [Alias(AliasCN, AliasServerName)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + base.SetParameter(value, nameComputerName); + } + } + + private string[] computername; + + /// + /// + /// The following is the definition of the input parameter "ResourceUri". + /// Define the Resource Uri for which the instances are retrieved. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + public Uri ResourceUri + { + get + { + return resourceUri; + } + + set + { + this.resourceUri = value; + base.SetParameter(value, nameResourceUri); + } + } + + private Uri resourceUri; + + /// + /// The following is the definition of the input parameter "Namespace". + /// The Namespace used to look for the Class instances under. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + public string Namespace + { + get + { + return nameSpace; + } + + set + { + nameSpace = value; + base.SetParameter(value, nameNamespace); + } + } + + private string nameSpace; + + /// + /// The following is the definition of the input parameter "OperationTimeoutSec". + /// Used to set the invocation operation time out. This value overrides the + /// CimSession operation timeout. + /// + [Alias(AliasOT)] + [Parameter] + public uint OperationTimeoutSec { get; set; } + + /// + /// The following is the definition of the input parameter "InputObject". + /// Used to get a CimInstance using Get-CimInstance | Set-CimInstance. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Alias(CimBaseCommand.AliasCimInstance)] + public CimInstance InputObject + { + get + { + return CimInstance; + } + + set + { + CimInstance = value; + base.SetParameter(value, nameCimInstance); + } + } + + /// + /// Property for internal usage purpose. + /// + internal CimInstance CimInstance { get; private set; } + + /// + /// The following is the definition of the input parameter "Query". + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + public string Query + { + get + { + return query; + } + + set + { + query = value; + base.SetParameter(value, nameQuery); + } + } + + private string query; + + /// + /// The following is the definition of the input parameter "QueryDialect". + /// Specifies the dialect used by the query Engine that interprets the Query + /// string. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + public string QueryDialect + { + get + { + return querydialect; + } + + set + { + querydialect = value; + base.SetParameter(value, nameQueryDialect); + } + } + + private string querydialect; + + /// + /// + /// The following is the definition of the input parameter "Property", + /// defines the value to be changed. + /// + /// + /// The key properties will be ignored. Any invalid property will cause + /// termination of the cmdlet execution. + /// + /// + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QuerySessionSet)] + [Parameter(Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.QueryComputerSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("Arguments")] + public IDictionary Property + { + get + { + return property; + } + + set + { + property = value; + base.SetParameter(value, nameProperty); + } + } + + private IDictionary property; + + /// + /// + /// The following is the definition of the input parameter "PassThru", + /// indicate whether Set-CimInstance should output modified result instance or not. + /// + /// + /// True indicates output the result instance, otherwise output nothing as by default + /// behavior. + /// + /// + [Parameter] + [ValidateNotNull] + public SwitchParameter PassThru { get; set; } + + #endregion + + #region cmdlet methods + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + CimSetCimInstance cimSetCimInstance = this.GetOperationAgent() ?? CreateOperationAgent(); + + this.CmdletOperation = new CmdletOperationSetCimInstance(this, cimSetCimInstance); + this.AtBeginProcess = false; + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + base.CheckParameterSet(); + CimSetCimInstance cimSetCimInstance = this.GetOperationAgent(); + cimSetCimInstance.SetCimInstance(this); + cimSetCimInstance.ProcessActions(this.CmdletOperation); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + CimSetCimInstance cimSetCimInstance = this.GetOperationAgent(); + cimSetCimInstance?.ProcessRemainActions(this.CmdletOperation); + } + + #endregion + + #region helper methods + + /// + /// + /// Get object, which is + /// used to delegate all Set-CimInstance operations. + /// + /// + private CimSetCimInstance GetOperationAgent() + { + return this.AsyncOperation as CimSetCimInstance; + } + + /// + /// + /// Create object, which is + /// used to delegate all Set-CimInstance operations. + /// + /// + /// + private CimSetCimInstance CreateOperationAgent() + { + CimSetCimInstance cimSetCimInstance = new(); + this.AsyncOperation = cimSetCimInstance; + return cimSetCimInstance; + } + + #endregion + + #region private members + + #region const string of parameter names + internal const string nameCimSession = "CimSession"; + internal const string nameComputerName = "ComputerName"; + internal const string nameResourceUri = "ResourceUri"; + internal const string nameNamespace = "Namespace"; + internal const string nameCimInstance = "InputObject"; + internal const string nameQuery = "Query"; + internal const string nameQueryDialect = "QueryDialect"; + internal const string nameProperty = "Property"; + #endregion + + /// + /// Static parameter definition entries. + /// + private static readonly Dictionary> parameters = new() + { + { + nameCimSession, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + } + }, + { + nameComputerName, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + } + }, + { + nameNamespace, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + } + }, + { + nameCimInstance, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), + } + }, + { + nameQuery, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + } + }, + { + nameQueryDialect, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), + } + }, + { + nameProperty, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), + new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + } + }, + { + nameResourceUri, new HashSet { + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), + new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false), + } + }, + }; + + /// + /// Static parameter set entries. + /// + private static readonly Dictionary parameterSets = new() + { + { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) }, + { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) }, + { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, + { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1, true) }, + }; + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs new file mode 100644 index 0000000000000000000000000000000000000000..adcab2542311720cdb112a13377953e1d370d344 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -0,0 +1,435 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// #define LOGENABLE // uncomment this line to enable the log, +// create c:\temp\cim.log before invoking cimcmdlets + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Text.RegularExpressions; + +namespace Microsoft.Management.Infrastructure.CimCmdlets +{ + /// + /// + /// Global Non-localization strings + /// + /// + internal static class ConstValue + { + /// + /// + /// Default computername + /// + /// + internal static readonly string[] DefaultSessionName = { @"*" }; + + /// + /// + /// Empty computername, which will create DCOM session + /// + /// + internal static readonly string NullComputerName = null; + + /// + /// + /// Empty computername array, which will create DCOM session + /// + /// + internal static readonly string[] NullComputerNames = { NullComputerName }; + + /// + /// + /// localhost computername, which will create WSMAN session + /// + /// + internal static readonly string LocalhostComputerName = @"localhost"; + + /// + /// + /// Default namespace + /// + /// + internal static readonly string DefaultNameSpace = @"root\cimv2"; + + /// + /// + /// Default namespace + /// + /// + internal static readonly string DefaultQueryDialect = @"WQL"; + + /// + /// Name of the note property that controls if "PSComputerName" column is shown. + /// + internal static readonly string ShowComputerNameNoteProperty = "PSShowComputerName"; + + /// + /// + /// Whether given computername is either null or empty + /// + /// + /// + /// + internal static bool IsDefaultComputerName(string computerName) + { + return string.IsNullOrEmpty(computerName); + } + + /// + /// + /// Get computer names, if it is null then return DCOM one + /// + /// + /// + /// + internal static IEnumerable GetComputerNames(IEnumerable computerNames) + { + return computerNames ?? NullComputerNames; + } + + /// + /// Get computer name, if it is null then return default one. + /// + /// + /// + internal static string GetComputerName(string computerName) + { + return string.IsNullOrEmpty(computerName) ? NullComputerName : computerName; + } + + /// + /// + /// Get namespace, if it is null then return default one + /// + /// + /// + /// + internal static string GetNamespace(string nameSpace) + { + return nameSpace ?? DefaultNameSpace; + } + + /// + /// + /// Get queryDialect, if it is null then return default query Dialect + /// + /// + /// + /// + internal static string GetQueryDialectWithDefault(string queryDialect) + { + return queryDialect ?? DefaultQueryDialect; + } + } + + /// + /// + /// Debug helper class used to dump debug message to log file + /// + /// + internal static class DebugHelper + { + #region private members + + /// + /// Flag used to control generating log message into file. + /// + internal static bool GenerateLog { get; set; } = true; + + /// + /// Whether the log been initialized. + /// + private static bool logInitialized = false; + + internal static bool GenerateVerboseMessage { get; set; } = true; + + /// + /// Flag used to control generating message into powershell. + /// + internal static readonly string logFile = @"c:\temp\Cim.log"; + + /// + /// Indent space string. + /// + internal static readonly string space = @" "; + + /// + /// Indent space strings array. + /// + internal static readonly string[] spaces = { + string.Empty, + space, + space + space, + space + space + space, + space + space + space + space, + space + space + space + space + space, + }; + + /// + /// Lock the log file. + /// + internal static readonly object logLock = new(); + + #endregion + + #region internal strings + internal static readonly string runspaceStateChanged = "Runspace {0} state changed to {1}"; + internal static readonly string classDumpInfo = @"Class type is {0}"; + internal static readonly string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}"; + internal static readonly string defaultPropertyType = @"It is a default property, default value is {0}"; + internal static readonly string propertyValueSet = @"This property value is set by user {0}"; + internal static readonly string addParameterSetName = @"Add parameter set {0} name to cache"; + internal static readonly string removeParameterSetName = @"Remove parameter set {0} name from cache"; + internal static readonly string currentParameterSetNameCount = @"Cache have {0} parameter set names"; + internal static readonly string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}"; + internal static readonly string currentnonMandatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}"; + internal static readonly string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names"; + internal static readonly string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}"; + internal static readonly string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}"; + internal static readonly string startToResolveParameterSet = @"------Resolve ParameterSet Name"; + internal static readonly string reservedString = @"------"; + #endregion + + #region runtime methods + internal static string GetSourceCodeInformation(bool withFileName, int depth) + { + StackTrace trace = new(); + StackFrame frame = trace.GetFrame(depth); + + return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod().DeclaringType.Name}::{frame.GetMethod().Name} "); + } + #endregion + + /// + /// Write message to log file named @logFile. + /// + /// + internal static void WriteLog(string message) + { + WriteLog(message, 0); + } + + /// + /// Write blank line to log file named @logFile. + /// + /// + internal static void WriteEmptyLine() + { + WriteLog(string.Empty, 0); + } + + /// + /// Write message to log file named @logFile with args. + /// + /// + internal static void WriteLog(string message, int indent, params object[] args) + { + string outMessage = string.Empty; + FormatLogMessage(ref outMessage, message, args); + WriteLog(outMessage, indent); + } + + /// + /// Write message to log file w/o arguments. + /// + /// + /// + internal static void WriteLog(string message, int indent) + { + WriteLogInternal(message, indent, -1); + } + + /// + /// Write message to log file named @logFile with args. + /// + /// + internal static void WriteLogEx(string message, int indent, params object[] args) + { + string outMessage = string.Empty; + WriteLogInternal(string.Empty, 0, -1); + FormatLogMessage(ref outMessage, message, args); + WriteLogInternal(outMessage, indent, 3); + } + + /// + /// Write message to log file w/o arguments. + /// + /// + /// + internal static void WriteLogEx(string message, int indent) + { + WriteLogInternal(string.Empty, 0, -1); + WriteLogInternal(message, indent, 3); + } + + /// + /// Write message to log file w/o arguments. + /// + /// + /// + internal static void WriteLogEx() + { + WriteLogInternal(string.Empty, 0, -1); + WriteLogInternal(string.Empty, 0, 3); + } + + /// + /// Format the message. + /// + /// + /// + /// + [Conditional("LOGENABLE")] + private static void FormatLogMessage(ref string outMessage, string message, params object[] args) + { + outMessage = string.Format(CultureInfo.CurrentCulture, message, args); + } + + /// + /// Write message to log file named @logFile + /// with indent space ahead of the message. + /// + /// + /// + [Conditional("LOGENABLE")] + private static void WriteLogInternal(string message, int indent, int depth) + { + if (!logInitialized) + { + lock (logLock) + { + if (!logInitialized) + { + DebugHelper.GenerateLog = File.Exists(logFile); + logInitialized = true; + } + } + } + + if (GenerateLog) + { + if (indent < 0) + { + indent = 0; + } + + if (indent > 5) + { + indent = 5; + } + + string sourceInformation = string.Empty; + if (depth != -1) + { + sourceInformation = string.Format( + CultureInfo.InvariantCulture, + "Thread {0}#{1}:{2}:{3} {4}", + Environment.CurrentManagedThreadId, + DateTime.Now.Hour, + DateTime.Now.Minute, + DateTime.Now.Second, + GetSourceCodeInformation(true, depth)); + } + + lock (logLock) + { + using (FileStream fs = new(logFile, FileMode.OpenOrCreate)) + using (StreamWriter writer = new(fs)) + { + writer.WriteLineAsync(spaces[indent] + sourceInformation + @" " + message); + } + } + } + } + } + + /// + /// + /// Helper class used to validate given parameter + /// + /// + internal static class ValidationHelper + { + /// + /// Validate the argument is not null. + /// + /// + /// + public static void ValidateNoNullArgument(object obj, string argumentName) + { + ArgumentNullException.ThrowIfNull(obj, argumentName); + } + + /// + /// Validate the argument is not null and not whitespace. + /// + /// + /// + public static void ValidateNoNullorWhiteSpaceArgument(string obj, string argumentName) + { + if (string.IsNullOrWhiteSpace(obj)) + { + throw new ArgumentException(argumentName); + } + } + + /// + /// Validate that given classname/propertyname is a valid name compliance with DMTF standard. + /// Only for verifying ClassName and PropertyName argument. + /// + /// + /// + /// + /// Throw if the given value is not a valid name (class name or property name). + public static string ValidateArgumentIsValidName(string parameterName, string value) + { + DebugHelper.WriteLogEx(); + if (value != null) + { + string trimed = value.Trim(); + // The first character should be contained in set: [A-Za-z_] + // Inner characters should be contained in set: [A-Za-z0-9_] + Regex regex = new(@"^[a-zA-Z_][a-zA-Z0-9_]*\z"); + if (regex.IsMatch(trimed)) + { + DebugHelper.WriteLogEx("A valid name: {0}={1}", 0, parameterName, value); + return trimed; + } + } + + DebugHelper.WriteLogEx("An invalid name: {0}={1}", 0, parameterName, value); + throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidParameterValue, value, parameterName)); + } + + /// + /// Validate given arry argument contains all valid name (for -SelectProperties). + /// * is valid for this case. + /// + /// + /// + /// + /// Throw if the given value contains any invalid name (class name or property name). + public static string[] ValidateArgumentIsValidName(string parameterName, string[] value) + { + if (value != null) + { + foreach (string propertyName in value) + { + // * is wild char supported in select properties + if ((propertyName != null) && string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + ValidationHelper.ValidateArgumentIsValidName(parameterName, propertyName); + } + } + + return value; + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..d479d28b5bf31a1d048b1d3a447e296cbbda679c --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Operation '{0}' complete. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Create CimInstance + + + Delete CimInstance + + + Enumerate Associated CimInstances + + + Enumerate CimClasses + + + Enumerate CimInstances + + + Get CimClass + + + Get CimInstance + + + Invoke CimMethod + + + Modify CimInstance + + + Query CimInstances + + + Subscribe CimIndication + + + Perform operation '{0}' with following parameters, '{1}'. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Parameter '{0}' cannot be used with the parameter '{1}'. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Could not find CimSession with the given {0} = {1} + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Could not find the following properties from the given class {0}: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Could not modify readonly property '{0}' of object '{1}'. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Default status description. + N/A + + + Cannot perform operation because the wildcard path {0} did not resolve to a file. + {0} is a placeholder for a path + + + Authentication type '{0}' is invalid without credential. Only following authentication type are allowed without credential, '{1}', '{2}', '{3}', or '{4}'. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Can not find method '{0}' in class '{1}'. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Can not find Parameter '{0}' in method '{1}' of class '{2}'. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Invalid operation. Current cmdlet already have operation created. + N/A + + + Argument '{0}' contains characters that are not allowed in parameter '{1}'. Supply an argument that is valid and then try the command again. + {0} stand for argument value, {1} stand for parameter name. + + + Cannot perform operation because the path resolved to more than one file. This command cannot operate on multiple files. + + + Argument '{0}' can not be null. + N/A + + + CimSession proxy object already have operation in progress. + N/A + + + Cannot open file because the current provider ({0}) cannot open a file. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Unable to add property '{0}' to input object '{1}'. The class schema does not contain the property. + {0} stand for property name, {1} stand for cim instance path. + + + Unable to resolve the parameter set name. + N/A + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/CommonHelper.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/CommonHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..c9492c701d6b1f96ae5ccedbb01d1efd2c2c8307 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/CommonHelper.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Windows; + +// Specifies the location in which theme dictionaries are stored for types in an assembly. +[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] + +namespace Microsoft.Management.UI +{ + /// + /// Utilities in common in this assembly. + /// + internal static class CommonHelper + { + /// + /// Restore the values from the settings to the actual window position, size and state. + /// + /// The window we are setting position and size of. + /// The value for top from the user settings. + /// The value for left from the user settings. + /// The value for width from the user settings. + /// The value for height from the user settings. + /// The with used if is not valid. + /// The height used if is not valid. + /// True if the window is maximized in the user setting. + internal static void SetStartingPositionAndSize(Window target, double userSettingTop, double userSettingLeft, double userSettingWidth, double userSettingHeight, double defaultWidth, double defaultHeight, bool userSettingMaximized) + { + bool leftInvalid = userSettingLeft < System.Windows.SystemParameters.VirtualScreenLeft || + userSettingWidth > System.Windows.SystemParameters.VirtualScreenLeft + + System.Windows.SystemParameters.VirtualScreenWidth; + + bool topInvalid = userSettingTop < System.Windows.SystemParameters.VirtualScreenTop || + userSettingTop > System.Windows.SystemParameters.VirtualScreenTop + + System.Windows.SystemParameters.VirtualScreenHeight; + + bool widthInvalid = userSettingWidth < 0 || + userSettingWidth > System.Windows.SystemParameters.VirtualScreenWidth; + + bool heightInvalid = userSettingHeight < 0 || + userSettingHeight > System.Windows.SystemParameters.VirtualScreenHeight; + + if (leftInvalid || topInvalid) + { + target.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; + } + else + { + target.Left = userSettingLeft; + target.Top = userSettingTop; + } + + // If any saved coordinate is invalid, we set the window to the default position + if (widthInvalid || heightInvalid) + { + target.Width = defaultWidth; + target.Height = defaultHeight; + } + else + { + target.Width = userSettingWidth; + target.Height = userSettingHeight; + } + + if (userSettingMaximized) + { + target.WindowState = WindowState.Maximized; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..fdb81a6d4168fb65411a6b3b4902ff467a9de948 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -0,0 +1,994 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Text; +using System.Windows.Documents; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Builds a help paragraph for a cmdlet. + /// + internal class HelpParagraphBuilder : ParagraphBuilder + { + /// + /// Indentation size. + /// + internal const int IndentSize = 4; + + /// + /// new line separators. + /// + private static readonly string[] Separators = new[] { "\r\n", "\n" }; + + /// + /// Object with the cmdelt. + /// + private readonly PSObject psObj; + + /// + /// Initializes a new instance of the HelpParagraphBuilder class. + /// + /// Paragraph being built. + /// Object with help information. + internal HelpParagraphBuilder(Paragraph paragraph, PSObject psObj) + : base(paragraph) + { + this.psObj = psObj; + this.AddTextToParagraphBuilder(); + } + + /// + /// Enum for category of Help. + /// + private enum HelpCategory + { + Default, + DscResource, + Class + } + + /// + /// Gets the string value of a property or null if it could not be retrieved. + /// + /// Object with the property. + /// Property name. + /// The string value of a property or null if it could not be retrieved. + internal static string GetPropertyString(PSObject psObj, string propertyName) + { + Debug.Assert(psObj != null, "ensured by caller"); + object value = GetPropertyObject(psObj, propertyName); + + if (value == null) + { + return null; + } + + return value.ToString(); + } + + /// + /// Adds the help text to the paragraph. + /// + internal void AddTextToParagraphBuilder() + { + this.ResetAllText(); + + string strCategory = HelpParagraphBuilder.GetProperty(this.psObj, "Category").Value.ToString(); + + HelpCategory category = HelpCategory.Default; + + if (string.Equals(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase)) + { + category = HelpCategory.DscResource; + } + else if (string.Equals(strCategory, "Class", StringComparison.OrdinalIgnoreCase)) + { + category = HelpCategory.Class; + } + + if (HelpParagraphBuilder.GetProperty(this.psObj, "Syntax") == null) + { + if (category == HelpCategory.Default) + { + // if there is no syntax, this is not the standard help + // it might be an about page + this.AddText(this.psObj.ToString(), false); + return; + } + } + + switch (category) + { + case HelpCategory.Class: + this.AddDescription(HelpWindowSettings.Default.HelpSynopsysDisplayed, HelpWindowResources.SynopsisTitle, "Introduction"); + this.AddMembers(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.PropertiesTitle); + this.AddMembers(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.MethodsTitle); + break; + case HelpCategory.DscResource: + this.AddStringSection(HelpWindowSettings.Default.HelpSynopsysDisplayed, "Synopsis", HelpWindowResources.SynopsisTitle); + this.AddDescription(HelpWindowSettings.Default.HelpDescriptionDisplayed, HelpWindowResources.DescriptionTitle, "Description"); + this.AddParameters(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.PropertiesTitle, "Properties", HelpCategory.DscResource); + break; + default: + this.AddStringSection(HelpWindowSettings.Default.HelpSynopsysDisplayed, "Synopsis", HelpWindowResources.SynopsisTitle); + this.AddDescription(HelpWindowSettings.Default.HelpDescriptionDisplayed, HelpWindowResources.DescriptionTitle, "Description"); + this.AddParameters(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.ParametersTitle, "Parameters", HelpCategory.Default); + this.AddSyntax(HelpWindowSettings.Default.HelpSyntaxDisplayed, HelpWindowResources.SyntaxTitle); + break; + } + + this.AddInputOrOutputEntries(HelpWindowSettings.Default.HelpInputsDisplayed, HelpWindowResources.InputsTitle, "inputTypes", "inputType"); + this.AddInputOrOutputEntries(HelpWindowSettings.Default.HelpOutputsDisplayed, HelpWindowResources.OutputsTitle, "returnValues", "returnValue"); + this.AddNotes(HelpWindowSettings.Default.HelpNotesDisplayed, HelpWindowResources.NotesTitle); + this.AddExamples(HelpWindowSettings.Default.HelpExamplesDisplayed, HelpWindowResources.ExamplesTitle); + this.AddNavigationLink(HelpWindowSettings.Default.HelpRelatedLinksDisplayed, HelpWindowResources.RelatedLinksTitle); + this.AddStringSection(HelpWindowSettings.Default.HelpRemarksDisplayed, "Remarks", HelpWindowResources.RemarksTitle); + } + + /// + /// Gets the object property or null if it could not be retrieved. + /// + /// Object with the property. + /// Property name. + /// The object property or null if it could not be retrieved. + private static PSPropertyInfo GetProperty(PSObject psObj, string propertyName) + { + Debug.Assert(psObj != null, "ensured by caller"); + return psObj.Properties[propertyName]; + } + + /// + /// Gets a PSObject and then a value from it or null if the value could not be retrieved. + /// + /// PSObject that contains another PSObject as a property. + /// Property name that contains the PSObject. + /// Property name in the inner PSObject. + /// The string from the inner psObject property or null if it could not be retrieved. + private static string GetInnerPSObjectPropertyString(PSObject psObj, string psObjectName, string propertyName) + { + Debug.Assert(psObj != null, "ensured by caller"); + PSObject innerPsObj = GetPropertyObject(psObj, psObjectName) as PSObject; + + if (innerPsObj == null) + { + return null; + } + + object value = GetPropertyObject(innerPsObj, propertyName); + + if (value == null) + { + return null; + } + + return value.ToString(); + } + + /// + /// Gets the value of a property or null if the value could not be retrieved. + /// + /// Object with the property. + /// Property name. + /// The value of a property or null if the value could not be retrieved. + private static object GetPropertyObject(PSObject psObj, string propertyName) + { + Debug.Assert(psObj != null, "ensured by caller"); + PSPropertyInfo property = HelpParagraphBuilder.GetProperty(psObj, propertyName); + if (property == null) + { + return null; + } + + object value = null; + try + { + value = property.Value; + } + catch (ExtendedTypeSystemException) + { + // ignore this exception + } + + return value; + } + + /// + /// Gets the text from a property of type PSObject[] where the first object has a text property. + /// + /// Objhect to get text from. + /// Property with PSObject[] containing text. + /// The text from a property of type PSObject[] where the first object has a text property. + private static string GetTextFromArray(PSObject psObj, string propertyText) + { + PSObject[] introductionObjects = HelpParagraphBuilder.GetPropertyObject(psObj, propertyText) as PSObject[]; + if (introductionObjects != null && introductionObjects.Length > 0) + { + return GetPropertyString(introductionObjects[0], "text"); + } + + return null; + } + + /// + /// Returns the largest size of a group of strings. + /// + /// Strings to evaluate the largest size from. + /// The largest size of a group of strings. + private static int LargestSize(params string[] strs) + { + int returnValue = 0; + + foreach (string str in strs) + { + if (str != null && str.Length > returnValue) + { + returnValue = str.Length; + } + } + + return returnValue; + } + + /// + /// Splits the string adding indentation before each line. + /// + /// String to add indentation to. + /// The string indented. + private static string AddIndent(string str) + { + return HelpParagraphBuilder.AddIndent(str, 1); + } + + /// + /// Splits the string adding indentation before each line. + /// + /// String to add indentation to. + /// Number of indentations. + /// The string indented. + private static string AddIndent(string str, int numberOfIdents) + { + StringBuilder indent = new StringBuilder(); + indent.Append(' ', numberOfIdents * HelpParagraphBuilder.IndentSize); + return HelpParagraphBuilder.AddIndent(str, indent.ToString()); + } + + /// + /// Splits the string adding indentation before each line. + /// + /// String to add indentation to. + /// Indentation string. + /// The string indented. + private static string AddIndent(string str, string indentString) + { + if (str == null) + { + return string.Empty; + } + + string[] lines = str.Split(Separators, StringSplitOptions.None); + + StringBuilder returnValue = new StringBuilder(); + foreach (string line in lines) + { + // Indentation is not localized + returnValue.Append($"{indentString}{line}\r\n"); + } + + if (returnValue.Length > 2) + { + // remove the last \r\n + returnValue.Remove(returnValue.Length - 2, 2); + } + + return returnValue.ToString(); + } + + /// + /// Get the object array value of a property. + /// + /// Object containing the property. + /// Property with the array value. + /// The object array value of a property. + private static object[] GetPropertyObjectArray(PSObject obj, string propertyName) + { + object innerObject; + if ((innerObject = HelpParagraphBuilder.GetPropertyObject(obj, propertyName)) == null) + { + return null; + } + + if (innerObject is PSObject) + { + return new[] { innerObject }; + } + + object[] innerObjectArray = innerObject as object[]; + return innerObjectArray; + } + + /// + /// Adds a section that contains only a string. + /// + /// True if it should add the segment. + /// Name of the section to add. + /// Title of the section. + private void AddStringSection(bool setting, string sectionName, string sectionTitle) + { + string propertyValue; + if (!setting || (propertyValue = HelpParagraphBuilder.GetPropertyString(this.psObj, sectionName)) == null) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + this.AddText(HelpParagraphBuilder.AddIndent(propertyValue), false); + this.AddText("\r\n\r\n", false); + } + + /// + /// Adds the help syntax segment. + /// + /// True if it should add the segment. + /// Title of the section. + private void AddSyntax(bool setting, string sectionTitle) + { + PSObject syntaxObject; + if (!setting || (syntaxObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "Syntax") as PSObject) == null) + { + return; + } + + object[] syntaxItemsObj = HelpParagraphBuilder.GetPropertyObjectArray(syntaxObject, "syntaxItem"); + if (syntaxItemsObj == null || syntaxItemsObj.Length == 0) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (object syntaxItemObj in syntaxItemsObj) + { + PSObject syntaxItem = syntaxItemObj as PSObject; + if (syntaxItem == null) + { + continue; + } + + string commandName = GetPropertyString(syntaxItem, "name"); + + object[] parameterObjs = HelpParagraphBuilder.GetPropertyObjectArray(syntaxItem, "parameter"); + if (commandName == null || parameterObjs == null || parameterObjs.Length == 0) + { + continue; + } + + string commandStart = string.Create(CultureInfo.CurrentCulture, $"{commandName} "); + this.AddText(HelpParagraphBuilder.AddIndent(commandStart), false); + + foreach (object parameterObj in parameterObjs) + { + PSObject parameter = parameterObj as PSObject; + if (parameter == null) + { + continue; + } + + string parameterValue = GetPropertyString(parameter, "parameterValue"); + string position = GetPropertyString(parameter, "position"); + string required = GetPropertyString(parameter, "required"); + string parameterName = GetPropertyString(parameter, "name"); + if (position == null || required == null || parameterName == null) + { + continue; + } + + string parameterType = parameterValue == null ? string.Empty : string.Create(CultureInfo.CurrentCulture, $"<{parameterValue}>"); + + string parameterOptionalOpenBrace, parameterOptionalCloseBrace; + + if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase)) + { + parameterOptionalOpenBrace = string.Empty; + parameterOptionalCloseBrace = string.Empty; + } + else + { + parameterOptionalOpenBrace = "["; + parameterOptionalCloseBrace = "]"; + } + + string parameterNameOptionalOpenBrace, parameterNameOptionalCloseBrace; + + if (string.Equals(position, "named", StringComparison.OrdinalIgnoreCase)) + { + parameterNameOptionalOpenBrace = parameterNameOptionalCloseBrace = string.Empty; + } + else + { + parameterNameOptionalOpenBrace = "["; + parameterNameOptionalCloseBrace = "]"; + } + + string paramterPrefix = string.Format( + CultureInfo.CurrentCulture, + "{0}{1}-", + parameterOptionalOpenBrace, + parameterNameOptionalOpenBrace); + + this.AddText(paramterPrefix, false); + this.AddText(parameterName, true); + + string paramterSuffix = string.Format( + CultureInfo.CurrentCulture, + "{0} {1}{2} ", + parameterNameOptionalCloseBrace, + parameterType, + parameterOptionalCloseBrace); + this.AddText(paramterSuffix, false); + } + + string commonParametersText = string.Format( + CultureInfo.CurrentCulture, + "[<{0}>]\r\n\r\n", + HelpWindowResources.CommonParameters); + + this.AddText(commonParametersText, false); + } + + this.AddText("\r\n", false); + } + + /// + /// Adds the help description segment. + /// + /// True if it should add the segment. + /// Title of the section. + /// PropertyName that has description. + private void AddDescription(bool setting, string sectionTitle, string propertyName) + { + PSObject[] descriptionObjects; + if (!setting || + (descriptionObjects = HelpParagraphBuilder.GetPropertyObject(this.psObj, propertyName) as PSObject[]) == null || + descriptionObjects.Length == 0) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (PSObject description in descriptionObjects) + { + string descriptionText = GetPropertyString(description, "text"); + this.AddText(HelpParagraphBuilder.AddIndent(descriptionText), false); + this.AddText("\r\n", false); + } + + this.AddText("\r\n\r\n", false); + } + + /// + /// Adds the help examples segment. + /// + /// True if it should add the segment. + /// Title of the section. + private void AddExamples(bool setting, string sectionTitle) + { + if (!setting) + { + return; + } + + PSObject exampleRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "Examples") as PSObject; + if (exampleRootObject == null) + { + return; + } + + object[] exampleObjects = HelpParagraphBuilder.GetPropertyObjectArray(exampleRootObject, "example"); + if (exampleObjects == null || exampleObjects.Length == 0) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (object exampleObj in exampleObjects) + { + PSObject example = exampleObj as PSObject; + if (example == null) + { + continue; + } + + string introductionText = null; + introductionText = GetTextFromArray(example, "introduction"); + + string codeText = GetPropertyString(example, "code"); + string title = GetPropertyString(example, "title"); + + if (codeText == null) + { + continue; + } + + if (title != null) + { + this.AddText(HelpParagraphBuilder.AddIndent(title), false); + this.AddText("\r\n", false); + } + + string codeLine = string.Format( + CultureInfo.CurrentCulture, + "{0}{1}\r\n\r\n", + introductionText, + codeText); + + this.AddText(HelpParagraphBuilder.AddIndent(codeLine), false); + + PSObject[] remarks = HelpParagraphBuilder.GetPropertyObject(example, "remarks") as PSObject[]; + if (remarks == null) + { + continue; + } + + foreach (PSObject remark in remarks) + { + string remarkText = GetPropertyString(remark, "text"); + if (remarkText == null) + { + continue; + } + + this.AddText(remarkText, false); + this.AddText("\r\n", false); + } + } + + this.AddText("\r\n\r\n", false); + } + + private void AddMembers(bool setting, string sectionTitle) + { + if (!setting || string.IsNullOrEmpty(sectionTitle)) + { + return; + } + + PSObject memberRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "Members") as PSObject; + if (memberRootObject == null) + { + return; + } + + object[] memberObjects = HelpParagraphBuilder.GetPropertyObjectArray(memberRootObject, "member"); + + if (memberObjects == null) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (object memberObj in memberObjects) + { + string description = null; + string memberText = null; + + PSObject member = memberObj as PSObject; + if (member == null) + { + continue; + } + + string name = GetPropertyString(member, "title"); + string type = GetPropertyString(member, "type"); + string propertyType = null; + + if (string.Equals("field", type, StringComparison.OrdinalIgnoreCase)) + { + PSObject fieldData = HelpParagraphBuilder.GetPropertyObject(member, "fieldData") as PSObject; + + if (fieldData != null) + { + PSObject propertyTypeObject = HelpParagraphBuilder.GetPropertyObject(fieldData, "type") as PSObject; + if (propertyTypeObject != null) + { + propertyType = GetPropertyString(propertyTypeObject, "name"); + description = GetPropertyString(propertyTypeObject, "description"); + } + + memberText = string.Create(CultureInfo.CurrentCulture, $" [{propertyType}] {name}\r\n"); + } + } + else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase)) + { + FormatMethodData(member, name, out memberText, out description); + } + + if (!string.IsNullOrEmpty(memberText)) + { + this.AddText(HelpParagraphBuilder.AddIndent(string.Empty), false); + this.AddText(memberText, true); + + if (description != null) + { + this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false); + this.AddText("\r\n", false); + } + + this.AddText("\r\n", false); + } + } + } + + private static void FormatMethodData(PSObject member, string name, out string memberText, out string description) + { + memberText = null; + description = null; + + if (member == null || string.IsNullOrEmpty(name)) + { + return; + } + + string returnType = null; + StringBuilder parameterText = new StringBuilder(); + + // Get method return type + PSObject returnTypeObject = HelpParagraphBuilder.GetPropertyObject(member, "returnValue") as PSObject; + if (returnTypeObject != null) + { + PSObject returnTypeData = HelpParagraphBuilder.GetPropertyObject(returnTypeObject, "type") as PSObject; + if (returnTypeData != null) + { + returnType = GetPropertyString(returnTypeData, "name"); + } + } + + // Get method description. + PSObject[] methodDescriptions = HelpParagraphBuilder.GetPropertyObject(member, "introduction") as PSObject[]; + if (methodDescriptions != null) + { + foreach (var methodDescription in methodDescriptions) + { + description = GetPropertyString(methodDescription, "Text"); + + // If we get an text we do not need to iterate more. + if (!string.IsNullOrEmpty(description)) + { + break; + } + } + } + + // Get method parameters. + PSObject parametersObject = HelpParagraphBuilder.GetPropertyObject(member, "parameters") as PSObject; + if (parametersObject != null) + { + PSObject[] paramObject = HelpParagraphBuilder.GetPropertyObject(parametersObject, "parameter") as PSObject[]; + + if (paramObject != null) + { + foreach (var param in paramObject) + { + string parameterName = GetPropertyString(param, "name"); + string parameterType = null; + + PSObject parameterTypeData = HelpParagraphBuilder.GetPropertyObject(param, "type") as PSObject; + + if (parameterTypeData != null) + { + parameterType = GetPropertyString(parameterTypeData, "name"); + + // If there is no type for the parameter, we expect it is System.Object + if (string.IsNullOrEmpty(parameterType)) + { + parameterType = "object"; + } + } + + string paramString = string.Create(CultureInfo.CurrentCulture, $"[{parameterType}] ${parameterName},"); + + parameterText.Append(paramString); + } + + if (string.Equals(parameterText[parameterText.Length - 1].ToString(), ",", StringComparison.OrdinalIgnoreCase)) + { + parameterText = parameterText.Remove(parameterText.Length - 1, 1); + } + } + } + + memberText = string.Create(CultureInfo.CurrentCulture, $" [{returnType}] {name}({parameterText})\r\n"); + } + + /// + /// Adds the help parameters segment. + /// + /// True if it should add the segment. + /// Title of the section. + /// Name of the property which has properties. + /// Category of help. + private void AddParameters(bool setting, string sectionTitle, string paramPropertyName, HelpCategory helpCategory) + { + if (!setting) + { + return; + } + + PSObject parameterRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, paramPropertyName) as PSObject; + if (parameterRootObject == null) + { + return; + } + + object[] parameterObjects = null; + + // Root object for Class has members not parameters. + if (helpCategory != HelpCategory.Class) + { + parameterObjects = HelpParagraphBuilder.GetPropertyObjectArray(parameterRootObject, "parameter"); + } + + if (parameterObjects == null || parameterObjects.Length == 0) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (object parameterObj in parameterObjects) + { + PSObject parameter = parameterObj as PSObject; + if (parameter == null) + { + continue; + } + + string parameterValue = GetPropertyString(parameter, "parameterValue"); + string name = GetPropertyString(parameter, "name"); + string description = GetTextFromArray(parameter, "description"); + string required = GetPropertyString(parameter, "required"); + string position = GetPropertyString(parameter, "position"); + string pipelineinput = GetPropertyString(parameter, "pipelineInput"); + string defaultValue = GetPropertyString(parameter, "defaultValue"); + string acceptWildcard = GetPropertyString(parameter, "globbing"); + + if (string.IsNullOrEmpty(name)) + { + continue; + } + + if (helpCategory == HelpCategory.DscResource) + { + this.AddText(HelpParagraphBuilder.AddIndent(string.Empty), false); + } + else + { + this.AddText(HelpParagraphBuilder.AddIndent("-"), false); + } + + this.AddText(name, true); + string parameterText = string.Format( + CultureInfo.CurrentCulture, + " <{0}>\r\n", + parameterValue); + + this.AddText(parameterText, false); + + if (description != null) + { + this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false); + this.AddText("\r\n", false); + } + + this.AddText("\r\n", false); + + int largestSize = HelpParagraphBuilder.LargestSize( + HelpWindowResources.ParameterRequired, + HelpWindowResources.ParameterPosition, + HelpWindowResources.ParameterDefaultValue, + HelpWindowResources.ParameterPipelineInput, + HelpWindowResources.ParameterAcceptWildcard); + + // justification of parameter values is not localized + string formatString = string.Format( + CultureInfo.CurrentCulture, + "{{0,-{0}}}{{1}}", + largestSize + 2); + + string tableLine; + + tableLine = string.Format( + CultureInfo.CurrentCulture, + formatString, + HelpWindowResources.ParameterRequired, + required); + this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false); + this.AddText("\r\n", false); + + // these are not applicable for Dsc Resource help + if (helpCategory != HelpCategory.DscResource) + { + tableLine = string.Format( + CultureInfo.CurrentCulture, + formatString, + HelpWindowResources.ParameterPosition, + position); + this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false); + this.AddText("\r\n", false); + + tableLine = string.Format( + CultureInfo.CurrentCulture, + formatString, + HelpWindowResources.ParameterDefaultValue, + defaultValue); + this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false); + this.AddText("\r\n", false); + + tableLine = string.Format( + CultureInfo.CurrentCulture, + formatString, + HelpWindowResources.ParameterPipelineInput, + pipelineinput); + this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false); + this.AddText("\r\n", false); + + tableLine = string.Format( + CultureInfo.CurrentCulture, + formatString, + HelpWindowResources.ParameterAcceptWildcard, + acceptWildcard); + this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false); + } + + this.AddText("\r\n\r\n", false); + } + + this.AddText("\r\n\r\n", false); + } + + /// + /// Adds the help navigation links segment. + /// + /// True if it should add the segment. + /// Title of the section. + private void AddNavigationLink(bool setting, string sectionTitle) + { + if (!setting) + { + return; + } + + PSObject linkRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "RelatedLinks") as PSObject; + if (linkRootObject == null) + { + return; + } + + PSObject[] linkObjects; + + if ((linkObjects = HelpParagraphBuilder.GetPropertyObject(linkRootObject, "navigationLink") as PSObject[]) == null || + linkObjects.Length == 0) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (PSObject linkObject in linkObjects) + { + string text = GetPropertyString(linkObject, "linkText"); + string uri = GetPropertyString(linkObject, "uri"); + + string linkLine = string.IsNullOrEmpty(uri) ? text : string.Format( + CultureInfo.CurrentCulture, + HelpWindowResources.LinkTextFormat, + text, + uri); + + this.AddText(HelpParagraphBuilder.AddIndent(linkLine), false); + this.AddText("\r\n", false); + } + + this.AddText("\r\n\r\n", false); + } + + /// + /// Adds the help input or output segment. + /// + /// True if it should add the segment. + /// Title of the section. + /// Property with the outter object. + /// Property with the inner object. + private void AddInputOrOutputEntries(bool setting, string sectionTitle, string inputOrOutputProperty, string inputOrOutputInnerProperty) + { + if (!setting) + { + return; + } + + PSObject rootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, inputOrOutputProperty) as PSObject; + if (rootObject == null) + { + return; + } + + object[] inputOrOutputObjs; + inputOrOutputObjs = HelpParagraphBuilder.GetPropertyObjectArray(rootObject, inputOrOutputInnerProperty); + + if (inputOrOutputObjs == null || inputOrOutputObjs.Length == 0) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + + foreach (object inputOrOutputObj in inputOrOutputObjs) + { + PSObject inputOrOutput = inputOrOutputObj as PSObject; + if (inputOrOutput == null) + { + continue; + } + + string type = HelpParagraphBuilder.GetInnerPSObjectPropertyString(inputOrOutput, "type", "name"); + string description = GetTextFromArray(inputOrOutput, "description"); + + this.AddText(HelpParagraphBuilder.AddIndent(type), false); + this.AddText("\r\n", false); + if (description != null) + { + this.AddText(HelpParagraphBuilder.AddIndent(description), false); + this.AddText("\r\n", false); + } + } + + this.AddText("\r\n", false); + } + + /// + /// Adds the help notes segment. + /// + /// True if it should add the segment. + /// Title of the section. + private void AddNotes(bool setting, string sectionTitle) + { + if (!setting) + { + return; + } + + PSObject rootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "alertSet") as PSObject; + if (rootObject == null) + { + return; + } + + string note = GetTextFromArray(rootObject, "alert"); + + if (note == null) + { + return; + } + + this.AddText(sectionTitle, true); + this.AddText("\r\n", false); + this.AddText(HelpParagraphBuilder.AddIndent(note), false); + this.AddText("\r\n\r\n", false); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs new file mode 100644 index 0000000000000000000000000000000000000000..7ab8681fef42fe23ba8c77251373839d0608004f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs @@ -0,0 +1,283 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Windows.Documents; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// ViewModel for the Help Dialog used to: + /// build the help document + /// search the help document + /// offer text for labels. + /// + internal class HelpViewModel : INotifyPropertyChanged + { + /// + /// The builder for the help FlowDocument Paragraph used in a RichEditText control. + /// + private readonly HelpParagraphBuilder helpBuilder; + + /// + /// Searcher for selecting current matches in paragraph text. + /// + private readonly ParagraphSearcher searcher; + + /// + /// Title of the help window. + /// + private readonly string helpTitle; + + /// + /// the zoom bound to the zoom slider value. + /// + private double zoom = 100; + + /// + /// Text to be found. This is bound to the find TextBox. + /// + private string findText; + + /// + /// text for the number of matches found. + /// + private string matchesLabel; + + /// + /// Initializes a new instance of the HelpViewModel class. + /// + /// Object containing help. + /// Paragraph in which help text is built/searched. + internal HelpViewModel(PSObject psObj, Paragraph documentParagraph) + { + Debug.Assert(psObj != null, "ensured by caller"); + Debug.Assert(documentParagraph != null, "ensured by caller"); + + this.helpBuilder = new HelpParagraphBuilder(documentParagraph, psObj); + this.helpBuilder.BuildParagraph(); + this.searcher = new ParagraphSearcher(); + this.helpBuilder.PropertyChanged += this.HelpBuilder_PropertyChanged; + this.helpTitle = string.Format( + CultureInfo.CurrentCulture, + HelpWindowResources.HelpTitleFormat, + HelpParagraphBuilder.GetPropertyString(psObj, "name")); + } + + #region INotifyPropertyChanged Members + /// + /// Used to notify of property changes. + /// + public event PropertyChangedEventHandler PropertyChanged; + #endregion + + /// + /// Gets or sets the Zoom bound to the zoom slider value. + /// + public double Zoom + { + get + { + return this.zoom; + } + + set + { + this.zoom = value; + this.OnNotifyPropertyChanged("Zoom"); + this.OnNotifyPropertyChanged("ZoomLabel"); + this.OnNotifyPropertyChanged("ZoomLevel"); + } + } + + /// + /// Gets the value bound to the RichTextEdit zoom, which is calculated based on the zoom. + /// + public double ZoomLevel + { + get + { + return this.zoom / 100.0; + } + } + + /// + /// Gets the label to be displayed for the zoom. + /// + public string ZoomLabel + { + get + { + return string.Format(CultureInfo.CurrentCulture, HelpWindowResources.ZoomLabelTextFormat, this.zoom); + } + } + + /// + /// Gets or sets the text to be found. + /// + public string FindText + { + get + { + return this.findText; + } + + set + { + this.findText = value; + this.Search(); + this.SetMatchesLabel(); + } + } + + /// + /// Gets the title of the window. + /// + public string HelpTitle + { + get + { + return this.helpTitle; + } + } + + /// + /// Gets or sets the label for current matches. + /// + public string MatchesLabel + { + get + { + return this.matchesLabel; + } + + set + { + this.matchesLabel = value; + this.OnNotifyPropertyChanged("MatchesLabel"); + } + } + + /// + /// Gets a value indicating whether there are matches to go to. + /// + public bool CanGoToNextOrPrevious + { + get + { + return this.HelpBuilder.HighlightCount != 0; + } + } + + /// + /// Gets the searcher for selecting current matches in paragraph text. + /// + internal ParagraphSearcher Searcher + { + get { return this.searcher; } + } + + /// + /// Gets the paragraph builder used to write help content. + /// + internal HelpParagraphBuilder HelpBuilder + { + get { return this.helpBuilder; } + } + + /// + /// Highlights all matches to this.findText + /// Called when findText changes or whenever the search has to be refreshed + /// + internal void Search() + { + this.HelpBuilder.HighlightAllInstancesOf(this.findText, HelpWindowSettings.Default.HelpSearchMatchCase, HelpWindowSettings.Default.HelpSearchWholeWord); + this.searcher.ResetSearch(); + } + + /// + /// Increases Zoom if not above maximum. + /// + internal void ZoomIn() + { + if (this.Zoom + HelpWindow.ZoomInterval <= HelpWindow.MaximumZoom) + { + this.Zoom += HelpWindow.ZoomInterval; + } + } + + /// + /// Decreases Zoom if not below minimum. + /// + internal void ZoomOut() + { + if (this.Zoom - HelpWindow.ZoomInterval >= HelpWindow.MinimumZoom) + { + this.Zoom -= HelpWindow.ZoomInterval; + } + } + + /// + /// Called to update the matches label. + /// + /// Event sender. + /// Event arguments. + private void HelpBuilder_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == "HighlightCount") + { + this.SetMatchesLabel(); + this.OnNotifyPropertyChanged("CanGoToNextOrPrevious"); + } + } + + /// + /// Sets the current matches label. + /// + private void SetMatchesLabel() + { + if (this.findText == null || this.findText.Trim().Length == 0) + { + this.MatchesLabel = string.Empty; + } + else + { + if (this.HelpBuilder.HighlightCount == 0) + { + this.MatchesLabel = HelpWindowResources.NoMatches; + } + else + { + if (this.HelpBuilder.HighlightCount == 1) + { + this.MatchesLabel = HelpWindowResources.OneMatch; + } + else + { + this.MatchesLabel = string.Format( + CultureInfo.CurrentCulture, + HelpWindowResources.SomeMatchesFormat, + this.HelpBuilder.HighlightCount); + } + } + } + } + + /// + /// Called internally to notify when a property changed. + /// + /// Property name. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml new file mode 100644 index 0000000000000000000000000000000000000000..2b2a8fe60b151910b4b87ae8ed2d1f78906697b0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..6793806503ac9d83f26e4baf537dc4da67bba798 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs @@ -0,0 +1,318 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Globalization; +using System.Management.Automation; +using System.Windows; +using System.Windows.Documents; +using System.Windows.Input; + +using Microsoft.Management.UI.Internal; + +namespace Microsoft.Management.UI +{ + /// + /// A window displaying help content and allowing search. + /// + public partial class HelpWindow : Window + { + /// + /// Minimum zoom in the slider. + /// + public static double MinimumZoom + { + get + { + return 20; + } + } + + /// + /// Maximum zoom in the slider. + /// + public static double MaximumZoom + { + get + { + return 300; + } + } + + /// + /// Zoom interval. + /// + public static double ZoomInterval + { + get + { + return 10; + } + } + + /// + /// The ViewModel for the dialog. + /// + private readonly HelpViewModel viewModel; + + /// + /// Initializes a new instance of the HelpWindow class. + /// + /// The object with help information. + public HelpWindow(PSObject helpObject) + { + InitializeComponent(); + this.viewModel = new HelpViewModel(helpObject, this.DocumentParagraph); + CommonHelper.SetStartingPositionAndSize( + this, + HelpWindowSettings.Default.HelpWindowTop, + HelpWindowSettings.Default.HelpWindowLeft, + HelpWindowSettings.Default.HelpWindowWidth, + HelpWindowSettings.Default.HelpWindowHeight, + double.Parse((string)HelpWindowSettings.Default.Properties["HelpWindowWidth"].DefaultValue, CultureInfo.InvariantCulture.NumberFormat), + double.Parse((string)HelpWindowSettings.Default.Properties["HelpWindowHeight"].DefaultValue, CultureInfo.InvariantCulture.NumberFormat), + HelpWindowSettings.Default.HelpWindowMaximized); + + this.ReadZoomUserSetting(); + + this.viewModel.PropertyChanged += this.ViewModel_PropertyChanged; + this.DataContext = this.viewModel; + + this.Loaded += this.HelpDialog_Loaded; + this.Closed += this.HelpDialog_Closed; + } + + /// + /// Handles the mouse wheel to zoom in/out. + /// + /// Event arguments. + protected override void OnPreviewMouseWheel(MouseWheelEventArgs e) + { + if (Keyboard.Modifiers != ModifierKeys.Control) + { + return; + } + + if (e.Delta > 0) + { + this.viewModel.ZoomIn(); + e.Handled = true; + } + else + { + this.viewModel.ZoomOut(); + e.Handled = true; + } + } + + /// + /// Handles key down to fix the Page/Douwn going to end of help issue + /// And to implement some additional shortcuts like Ctrl+F and ZoomIn/ZoomOut. + /// + /// Event arguments. + protected override void OnPreviewKeyDown(KeyEventArgs e) + { + if (Keyboard.Modifiers == ModifierKeys.None) + { + if (e.Key == Key.PageUp) + { + this.Scroll.PageUp(); + e.Handled = true; + return; + } + + if (e.Key == Key.PageDown) + { + this.Scroll.PageDown(); + e.Handled = true; + return; + } + } + + if (Keyboard.Modifiers == ModifierKeys.Control) + { + this.HandleZoomInAndZoomOut(e); + if (e.Handled) + { + return; + } + + if (e.Key == Key.F) + { + this.Find.Focus(); + e.Handled = true; + return; + } + } + + if (Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift)) + { + this.HandleZoomInAndZoomOut(e); + } + } + + /// + /// Reads the zoom part of the user settings. + /// + private void ReadZoomUserSetting() + { + if (HelpWindowSettings.Default.HelpZoom < HelpWindow.MinimumZoom || HelpWindowSettings.Default.HelpZoom > HelpWindow.MaximumZoom) + { + HelpWindowSettings.Default.HelpZoom = 100; + } + + this.viewModel.Zoom = HelpWindowSettings.Default.HelpZoom; + } + + /// + /// Handles Zoom in and Zoom out keys. + /// + /// Event arguments. + private void HandleZoomInAndZoomOut(KeyEventArgs e) + { + if (e.Key == Key.OemPlus || e.Key == Key.Add) + { + this.viewModel.ZoomIn(); + e.Handled = true; + } + + if (e.Key == Key.OemMinus || e.Key == Key.Subtract) + { + this.viewModel.ZoomOut(); + e.Handled = true; + } + } + + /// + /// Listens to changes in the zoom in order to update the user settings. + /// + /// Event sender. + /// Event arguments. + private void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == "Zoom") + { + HelpWindowSettings.Default.HelpZoom = this.viewModel.Zoom; + } + } + + /// + /// Saves the user settings. + /// + /// Event sender. + /// Event arguments. + private void HelpDialog_Closed(object sender, System.EventArgs e) + { + HelpWindowSettings.Default.Save(); + } + + /// + /// Updates the user setting with window state. + /// + /// Event sender. + /// Event arguments. + private void HelpDialog_StateChanged(object sender, System.EventArgs e) + { + HelpWindowSettings.Default.HelpWindowMaximized = this.WindowState == WindowState.Maximized; + } + + /// + /// Sets the positions from user settings and start monitoring position changes. + /// + /// Event sender. + /// Event arguments. + private void HelpDialog_Loaded(object sender, RoutedEventArgs e) + { + this.StateChanged += this.HelpDialog_StateChanged; + this.LocationChanged += this.HelpDialog_LocationChanged; + this.SizeChanged += this.HelpDialog_SizeChanged; + } + + /// + /// Saves size changes in user settings. + /// + /// Event sender. + /// Event arguments. + private void HelpDialog_SizeChanged(object sender, SizeChangedEventArgs e) + { + HelpWindowSettings.Default.HelpWindowWidth = this.Width; + HelpWindowSettings.Default.HelpWindowHeight = this.Height; + } + + /// + /// Saves position changes in user settings. + /// + /// Event sender. + /// Event arguments. + private void HelpDialog_LocationChanged(object sender, System.EventArgs e) + { + HelpWindowSettings.Default.HelpWindowTop = this.Top; + HelpWindowSettings.Default.HelpWindowLeft = this.Left; + } + + /// + /// Called when the settings button is clicked. + /// + /// Event sender. + /// Event arguments. + private void Settings_Click(object sender, RoutedEventArgs e) + { + SettingsDialog settings = new SettingsDialog(); + settings.Owner = this; + + settings.ShowDialog(); + + if (settings.DialogResult == true) + { + this.viewModel.HelpBuilder.AddTextToParagraphBuilder(); + this.viewModel.Search(); + } + } + + /// + /// Called when the Previous button is clicked. + /// + /// Event sender. + /// Event arguments. + private void PreviousMatch_Click(object sender, RoutedEventArgs e) + { + this.MoveToNextMatch(false); + } + + /// + /// Called when the Next button is clicked. + /// + /// Event sender. + /// Event arguments. + private void NextMatch_Click(object sender, RoutedEventArgs e) + { + this.MoveToNextMatch(true); + } + + /// + /// Moves to the previous or next match. + /// + /// True for forward false for backwards. + private void MoveToNextMatch(bool forward) + { + TextPointer caretPosition = this.HelpText.CaretPosition; + Run nextRun = this.viewModel.Searcher.MoveAndHighlightNextNextMatch(forward, caretPosition); + this.MoveToRun(nextRun); + } + + /// + /// Moves to the caret and brings the view to the . + /// + /// Run to move to. + private void MoveToRun(Run run) + { + if (run == null) + { + return; + } + + run.BringIntoView(); + this.HelpText.CaretPosition = run.ElementEnd; + this.HelpText.Focus(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..937429ebf0967dbe4025474a67b2d3282a652e50 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.16598 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +// namespace Microsoft.Management.UI.Internal { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class HelpWindowSettings : global::System.Configuration.ApplicationSettingsBase { + + private static HelpWindowSettings defaultInstance = ((HelpWindowSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new HelpWindowSettings()))); + + public static HelpWindowSettings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpRemarksDisplayed + { + get + { + return ((bool)(this["HelpRemarksDisplayed"])); + } + set + { + this["HelpRemarksDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpSyntaxDisplayed { + get { + return ((bool)(this["HelpSyntaxDisplayed"])); + } + set { + this["HelpSyntaxDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpExamplesDisplayed { + get { + return ((bool)(this["HelpExamplesDisplayed"])); + } + set { + this["HelpExamplesDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpSynopsysDisplayed { + get { + return ((bool)(this["HelpSynopsysDisplayed"])); + } + set { + this["HelpSynopsysDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpDescriptionDisplayed { + get { + return ((bool)(this["HelpDescriptionDisplayed"])); + } + set { + this["HelpDescriptionDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpParametersDisplayed { + get { + return ((bool)(this["HelpParametersDisplayed"])); + } + set { + this["HelpParametersDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpInputsDisplayed { + get { + return ((bool)(this["HelpInputsDisplayed"])); + } + set { + this["HelpInputsDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpOutputsDisplayed { + get { + return ((bool)(this["HelpOutputsDisplayed"])); + } + set { + this["HelpOutputsDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpNotesDisplayed { + get { + return ((bool)(this["HelpNotesDisplayed"])); + } + set { + this["HelpNotesDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HelpRelatedLinksDisplayed { + get { + return ((bool)(this["HelpRelatedLinksDisplayed"])); + } + set { + this["HelpRelatedLinksDisplayed"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool HelpSearchMatchCase { + get { + return ((bool)(this["HelpSearchMatchCase"])); + } + set { + this["HelpSearchMatchCase"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool HelpSearchWholeWord { + get { + return ((bool)(this["HelpSearchWholeWord"])); + } + set { + this["HelpSearchWholeWord"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("400")] + public double HelpWindowHeight { + get { + return ((double)(this["HelpWindowHeight"])); + } + set { + this["HelpWindowHeight"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("600")] + public double HelpWindowWidth { + get { + return ((double)(this["HelpWindowWidth"])); + } + set { + this["HelpWindowWidth"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double HelpWindowTop { + get { + return ((double)(this["HelpWindowTop"])); + } + set { + this["HelpWindowTop"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double HelpWindowLeft { + get { + return ((double)(this["HelpWindowLeft"])); + } + set { + this["HelpWindowLeft"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool HelpWindowMaximized { + get { + return ((bool)(this["HelpWindowMaximized"])); + } + set { + this["HelpWindowMaximized"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("100")] + public double HelpZoom { + get { + return ((double)(this["HelpZoom"])); + } + set { + this["HelpZoom"] = value; + } + } + } +//} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.settings b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.settings new file mode 100644 index 0000000000000000000000000000000000000000..2631ff7c38a0e4a79051e5342ad6d566ce926ccd --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.settings @@ -0,0 +1,60 @@ + + + + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + False + + + False + + + -1 + + + -1 + + + False + + + 100 + + + 500 + + + 700 + + + True + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..77b1b5c966f9f18574ff4152830d26d5ce3770a6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -0,0 +1,357 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; +using System.Windows.Documents; +using System.Windows.Media; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Builds a paragraph based on Text + Bold + Highlight information. + /// Bold are the segments of the text that should be bold, and Highlight are + /// the segments of the text that should be highlighted (like search results). + /// + internal class ParagraphBuilder : INotifyPropertyChanged + { + /// + /// The text spans that should be bold. + /// + private readonly List boldSpans; + + /// + /// The text spans that should be highlighted. + /// + private readonly List highlightedSpans; + + /// + /// The text displayed. + /// + private readonly StringBuilder textBuilder; + + /// + /// Paragraph built in BuildParagraph. + /// + private readonly Paragraph paragraph; + + /// + /// Initializes a new instance of the ParagraphBuilder class. + /// + /// Paragraph we will be adding lines to in BuildParagraph. + internal ParagraphBuilder(Paragraph paragraph) + { + ArgumentNullException.ThrowIfNull(paragraph); + + this.paragraph = paragraph; + this.boldSpans = new List(); + this.highlightedSpans = new List(); + this.textBuilder = new StringBuilder(); + } + + #region INotifyPropertyChanged Members + /// + /// Used to notify of property changes. + /// + public event PropertyChangedEventHandler PropertyChanged; + #endregion + + /// + /// Gets the number of highlights. + /// + internal int HighlightCount + { + get { return this.highlightedSpans.Count; } + } + + /// + /// Gets the paragraph built in BuildParagraph. + /// + internal Paragraph Paragraph + { + get { return this.paragraph; } + } + + /// + /// Called after all the AddText calls have been made to build the paragraph + /// based on the current text. + /// This method goes over 3 collections simultaneously: + /// 1) characters in this.textBuilder + /// 2) spans in this.boldSpans + /// 3) spans in this.highlightedSpans + /// And adds the minimal number of Inlines to the paragraph so that all + /// characters that should be bold and/or highlighted are. + /// + internal void BuildParagraph() + { + this.paragraph.Inlines.Clear(); + + int currentBoldIndex = 0; + TextSpan? currentBoldSpan = this.boldSpans.Count == 0 ? (TextSpan?)null : this.boldSpans[0]; + int currentHighlightedIndex = 0; + TextSpan? currentHighlightedSpan = this.highlightedSpans.Count == 0 ? (TextSpan?)null : this.highlightedSpans[0]; + + bool currentBold = false; + bool currentHighlighted = false; + + StringBuilder sequence = new StringBuilder(); + int i = 0; + foreach (char c in this.textBuilder.ToString()) + { + bool newBold = false; + bool newHighlighted = false; + + ParagraphBuilder.MoveSpanToPosition(ref currentBoldIndex, ref currentBoldSpan, i, this.boldSpans); + newBold = currentBoldSpan == null ? false : currentBoldSpan.Value.Contains(i); + + ParagraphBuilder.MoveSpanToPosition(ref currentHighlightedIndex, ref currentHighlightedSpan, i, this.highlightedSpans); + newHighlighted = currentHighlightedSpan == null ? false : currentHighlightedSpan.Value.Contains(i); + + if (newBold != currentBold || newHighlighted != currentHighlighted) + { + ParagraphBuilder.AddInline(this.paragraph, currentBold, currentHighlighted, sequence); + } + + sequence.Append(c); + + currentHighlighted = newHighlighted; + currentBold = newBold; + i++; + } + + ParagraphBuilder.AddInline(this.paragraph, currentBold, currentHighlighted, sequence); + } + + /// + /// Highlights all occurrences of . + /// This is called after all calls to AddText have been made. + /// + /// Search string. + /// True if search should be case sensitive. + /// True if we should search whole word only. + internal void HighlightAllInstancesOf(string search, bool caseSensitive, bool wholeWord) + { + this.highlightedSpans.Clear(); + + if (search == null || search.Trim().Length == 0) + { + this.BuildParagraph(); + this.OnNotifyPropertyChanged("HighlightCount"); + return; + } + + string text = this.textBuilder.ToString(); + StringComparison comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + int start = 0; + int match; + while ((match = text.IndexOf(search, start, comparison)) != -1) + { + // false loop + do + { + if (wholeWord) + { + if (match > 0 && char.IsLetterOrDigit(text[match - 1])) + { + break; + } + + if ((match + search.Length <= text.Length - 1) && char.IsLetterOrDigit(text[match + search.Length])) + { + break; + } + } + + this.AddHighlight(match, search.Length); + } + while (false); + + start = match + search.Length; + } + + this.BuildParagraph(); + this.OnNotifyPropertyChanged("HighlightCount"); + } + + /// + /// Adds text to the paragraph later build with BuildParagraph. + /// + /// Text to be added. + /// True if the text should be bold. + internal void AddText(string str, bool bold) + { + ArgumentNullException.ThrowIfNull(str); + + if (str.Length == 0) + { + return; + } + + if (bold) + { + this.boldSpans.Add(new TextSpan(this.textBuilder.Length, str.Length)); + } + + this.textBuilder.Append(str); + } + + /// + /// Called before a derived class starts adding text + /// to reset the current content. + /// + internal void ResetAllText() + { + this.boldSpans.Clear(); + this.highlightedSpans.Clear(); + this.textBuilder.Clear(); + } + + /// + /// Adds an inline to based on the remaining parameters. + /// + /// Paragraph to add Inline to. + /// True if text should be added in bold. + /// True if the text should be added with highlight. + /// The text to add and clear. + private static void AddInline(Paragraph currentParagraph, bool currentBold, bool currentHighlighted, StringBuilder sequence) + { + if (sequence.Length == 0) + { + return; + } + + Run run = new Run(sequence.ToString()); + if (currentHighlighted) + { + run.Background = ParagraphSearcher.HighlightBrush; + } + + Inline inline = currentBold ? (Inline)new Bold(run) : run; + currentParagraph.Inlines.Add(inline); + sequence.Clear(); + } + + /// + /// This is an auxiliar method in BuildParagraph to move the current bold or highlighted spans + /// according to the + /// The current bold and highlighted span should be ending ahead of the current position. + /// Moves and to the + /// proper span in according to the + /// This is an auxiliar method in BuildParagraph. + /// + /// Current index within . + /// Current span within . + /// Character position. This comes from a position within this.textBuilder. + /// The collection of spans. This is either this.boldSpans or this.highlightedSpans. + private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? currentSpan, int caracterPosition, List allSpans) + { + if (currentSpan == null || caracterPosition <= currentSpan.Value.End) + { + return; + } + + for (int newBoldIndex = currentSpanIndex + 1; newBoldIndex < allSpans.Count; newBoldIndex++) + { + TextSpan newBoldSpan = allSpans[newBoldIndex]; + if (caracterPosition <= newBoldSpan.End) + { + currentSpanIndex = newBoldIndex; + currentSpan = newBoldSpan; + return; + } + } + + // there is no span ending ahead of current position, so + // we set the current span to null to prevent unnecessary comparisons against the currentSpan + currentSpan = null; + } + + /// + /// Adds one individual text highlight + /// This is called after all calls to AddText have been made. + /// + /// Highlight start. + /// Highlight length. + private void AddHighlight(int start, int length) + { + ArgumentOutOfRangeException.ThrowIfNegative(start); + ArgumentOutOfRangeException.ThrowIfGreaterThan(start + length, this.textBuilder.Length, nameof(length)); + + this.highlightedSpans.Add(new TextSpan(start, length)); + } + + /// + /// Called internally to notify when a property changed. + /// + /// Property name. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + + /// + /// A text span used to mark bold and highlighted segments. + /// + internal struct TextSpan + { + /// + /// Index of the first character in the span. + /// + private readonly int start; + + /// + /// Index of the last character in the span. + /// + private readonly int end; + + /// + /// Initializes a new instance of the TextSpan struct. + /// + /// Index of the first character in the span. + /// Index of the last character in the span. + internal TextSpan(int start, int length) + { + ArgumentOutOfRangeException.ThrowIfNegative(start); + ArgumentOutOfRangeException.ThrowIfLessThan(length, 1); + + this.start = start; + this.end = start + length - 1; + } + + /// + /// Gets the index of the first character in the span. + /// + internal int Start + { + get { return this.start; } + } + + /// + /// Gets the index of the first character in the span. + /// + internal int End + { + get + { + return this.end; + } + } + + /// + /// Returns true if the is between start and end (inclusive). + /// + /// Position to verify if is in the span. + /// True if the is between start and end (inclusive). + internal bool Contains(int position) + { + return (position >= this.start) && (position <= this.end); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs new file mode 100644 index 0000000000000000000000000000000000000000..c8b9907751dc4d1044dfa5bfb71001c5e36ac4d1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -0,0 +1,241 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics; +using System.Windows.Documents; +using System.Windows.Media; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Moves through search highlights built in a ParagraphBuilder + /// changing the color of the current highlight. + /// + internal class ParagraphSearcher + { + /// + /// Highlight for all matches except the current. + /// + internal static readonly Brush HighlightBrush = Brushes.Yellow; + + /// + /// Highlight for the current match. + /// + private static readonly Brush CurrentHighlightBrush = Brushes.Cyan; + + /// + /// Current match being highlighted in search. + /// + private Run currentHighlightedMatch; + + /// + /// Initializes a new instance of the ParagraphSearcher class. + /// + internal ParagraphSearcher() + { + } + + /// + /// Move to the next highlight starting at the . + /// + /// True for next false for previous. + /// Caret position. + /// The next highlight starting at the . + internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPosition) + { + Debug.Assert(caretPosition != null, "a caret position is always valid"); + Debug.Assert(caretPosition.Parent != null && caretPosition.Parent is Run, "a caret Parent is always a valid Run"); + Run caretRun = (Run)caretPosition.Parent; + + Run currentRun; + + if (this.currentHighlightedMatch != null) + { + // restore the curent highlighted background to plain highlighted + this.currentHighlightedMatch.Background = ParagraphSearcher.HighlightBrush; + } + + // If the caret is in the end of a highlight we move to the adjacent run + // It has to be in the end because if there is a match at the beginning of the file + // and the caret has not been touched (so it is in the beginning of the file too) + // we want to highlight this first match. + // Considering the caller always set the caret to the end of the highlight + // The condition below works well for successive searchs + // We also need to move to the adjacent run if the caret is at the first run and we + // are moving backwards so that a search backwards when the first run is highlighted + // and the caret is at the beginning will wrap to the end + if ((!forward && IsFirstRun(caretRun)) || + ((caretPosition.GetOffsetToPosition(caretRun.ContentEnd) == 0) && ParagraphSearcher.Ishighlighted(caretRun))) + { + currentRun = ParagraphSearcher.GetNextRun(caretRun, forward); + } + else + { + currentRun = caretRun; + } + + currentRun = ParagraphSearcher.GetNextMatch(currentRun, forward); + + if (currentRun == null) + { + // if we could not find a next highlight wraparound + currentRun = ParagraphSearcher.GetFirstOrLastRun(caretRun, forward); + currentRun = ParagraphSearcher.GetNextMatch(currentRun, forward); + } + + this.currentHighlightedMatch = currentRun; + if (this.currentHighlightedMatch != null) + { + // restore the curent highlighted background to current highlighted + this.currentHighlightedMatch.Background = ParagraphSearcher.CurrentHighlightBrush; + } + + return currentRun; + } + + /// + /// Resets the search for fresh calls to MoveAndHighlightNextNextMatch. + /// + internal void ResetSearch() + { + this.currentHighlightedMatch = null; + } + + /// + /// Returns true if is highlighted. + /// + /// Run to check if is highlighted. + /// True if is highlighted. + private static bool Ishighlighted(Run run) + { + if (run == null) + { + return false; + } + + SolidColorBrush background = run.Background as SolidColorBrush; + if (background != null && background == ParagraphSearcher.HighlightBrush) + { + return true; + } + + return false; + } + + /// + /// Get the next or previous run according to . + /// + /// The current run. + /// True for next false for previous. + /// The next or previous run according to . + private static Run GetNextRun(Run currentRun, bool forward) + { + Bold parentBold = currentRun.Parent as Bold; + + Inline nextInline; + + if (forward) + { + nextInline = parentBold != null ? ((Inline)parentBold).NextInline : currentRun.NextInline; + } + else + { + nextInline = parentBold != null ? ((Inline)parentBold).PreviousInline : currentRun.PreviousInline; + } + + return GetRun(nextInline); + } + + /// + /// Gets the run of an inline. Inlines in a ParagrahBuilder are either a Run or a Bold + /// which contains a Run. + /// + /// Inline to get the run from. + /// The run of the inline. + private static Run GetRun(Inline inline) + { + Bold inlineBold = inline as Bold; + if (inlineBold != null) + { + return (Run)inlineBold.Inlines.FirstInline; + } + + return (Run)inline; + } + + /// + /// Gets the next highlighted run starting and including + /// according to the direction specified in . + /// + /// The current run. + /// True for next false for previous. + /// + /// the next highlighted run starting and including + /// according to the direction specified in . + /// + private static Run GetNextMatch(Run currentRun, bool forward) + { + while (currentRun != null) + { + if (ParagraphSearcher.Ishighlighted(currentRun)) + { + return currentRun; + } + + currentRun = ParagraphSearcher.GetNextRun(currentRun, forward); + } + + return currentRun; + } + + /// + /// Gets the run's paragraph. + /// + /// Run to get the paragraph from. + /// The run's paragraph. + private static Paragraph GetParagraph(Run run) + { + Bold parentBold = run.Parent as Bold; + Paragraph parentParagraph = (parentBold != null ? parentBold.Parent : run.Parent) as Paragraph; + Debug.Assert(parentParagraph != null, "the documents we are saerching are built with ParagraphBuilder, which builds the document like this"); + return parentParagraph; + } + + /// + /// Returns true if the run is the first run of the paragraph. + /// + /// Run to check. + /// True if the run is the first run of the paragraph. + private static bool IsFirstRun(Run run) + { + Paragraph paragraph = GetParagraph(run); + Run firstRun = ParagraphSearcher.GetRun(paragraph.Inlines.FirstInline); + return run == firstRun; + } + + /// + /// Gets the first or lasr run in the paragraph containing . + /// + /// Run containing the caret. + /// True for first false for last. + /// The first or last run in the paragraph containing . + private static Run GetFirstOrLastRun(Run caretRun, bool forward) + { + Debug.Assert(caretRun != null, "a caret run is always valid"); + + Paragraph paragraph = GetParagraph(caretRun); + + Inline firstOrLastInline; + if (forward) + { + firstOrLastInline = paragraph.Inlines.FirstInline; + } + else + { + firstOrLastInline = paragraph.Inlines.LastInline; + } + + return GetRun(firstOrLastInline); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml new file mode 100644 index 0000000000000000000000000000000000000000..d99c86c2a6ad09aa9b3197a080954b9494df6338 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..5d499d47f71e30d454c8b1d58e541c14216f3596 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Management.UI +{ + using System.Windows; + using Microsoft.Management.UI.Internal; + + /// + /// Dialog with settings for the help dialog. + /// + public partial class SettingsDialog : Window + { + /// + /// Initializes a new instance of the SettingsDialog class. + /// + public SettingsDialog() + { + InitializeComponent(); + this.Description.IsChecked = HelpWindowSettings.Default.HelpDescriptionDisplayed; + this.Examples.IsChecked = HelpWindowSettings.Default.HelpExamplesDisplayed; + this.Inputs.IsChecked = HelpWindowSettings.Default.HelpInputsDisplayed; + this.Notes.IsChecked = HelpWindowSettings.Default.HelpNotesDisplayed; + this.Outputs.IsChecked = HelpWindowSettings.Default.HelpOutputsDisplayed; + this.Parameters.IsChecked = HelpWindowSettings.Default.HelpParametersDisplayed; + this.RelatedLinks.IsChecked = HelpWindowSettings.Default.HelpRelatedLinksDisplayed; + this.Remarks.IsChecked = HelpWindowSettings.Default.HelpRemarksDisplayed; + this.Synopsys.IsChecked = HelpWindowSettings.Default.HelpSynopsysDisplayed; + this.Syntax.IsChecked = HelpWindowSettings.Default.HelpSyntaxDisplayed; + this.CaseSensitive.IsChecked = HelpWindowSettings.Default.HelpSearchMatchCase; + this.WholeWord.IsChecked = HelpWindowSettings.Default.HelpSearchWholeWord; + } + + /// + /// Called when the OK button has been clicked. + /// + /// Event sender. + /// Event arguments. + private void OK_Click(object sender, RoutedEventArgs e) + { + HelpWindowSettings.Default.HelpDescriptionDisplayed = this.Description.IsChecked == true; + HelpWindowSettings.Default.HelpExamplesDisplayed = this.Examples.IsChecked == true; + HelpWindowSettings.Default.HelpInputsDisplayed = this.Inputs.IsChecked == true; + HelpWindowSettings.Default.HelpOutputsDisplayed = this.Outputs.IsChecked == true; + HelpWindowSettings.Default.HelpNotesDisplayed = this.Notes.IsChecked == true; + HelpWindowSettings.Default.HelpParametersDisplayed = this.Parameters.IsChecked == true; + HelpWindowSettings.Default.HelpRelatedLinksDisplayed = this.RelatedLinks.IsChecked == true; + HelpWindowSettings.Default.HelpRemarksDisplayed = this.Remarks.IsChecked == true; + HelpWindowSettings.Default.HelpSynopsysDisplayed = this.Synopsys.IsChecked == true; + HelpWindowSettings.Default.HelpSyntaxDisplayed = this.Syntax.IsChecked == true; + HelpWindowSettings.Default.HelpSearchMatchCase = this.CaseSensitive.IsChecked == true; + HelpWindowSettings.Default.HelpSearchWholeWord = this.WholeWord.IsChecked == true; + HelpWindowSettings.Default.Save(); + this.DialogResult = true; + this.Close(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs new file mode 100644 index 0000000000000000000000000000000000000000..40f3e9e15a9a1c06202030a89a5c7ec6cc42482c --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Windows; +using System.Windows.Automation.Peers; +using System.Windows.Controls; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Provides a control that is always visible in the automation tree. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + [Description("Provides a System.Windows.Controls.Button control that is always visible in the automation tree.")] + public class AutomationButton : Button + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + public AutomationButton() + { + // This constructor intentionally left blank + } + + #endregion + + #region Overides + + /// + /// Returns the implementations for this control. + /// + /// The implementations for this control. + protected override AutomationPeer OnCreateAutomationPeer() + { + return new AutomationButtonAutomationPeer(this); + } + + #endregion + } + + /// + /// Provides an automation peer for AutomationButton. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + internal class AutomationButtonAutomationPeer : ButtonAutomationPeer + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The owner of the automation peer. + public AutomationButtonAutomationPeer(Button owner) + : base(owner) + { + // This constructor intentionally left blank + } + + #endregion + + #region Overrides + + /// + /// Gets a value that indicates whether the element is understood by the user as interactive or as contributing to the logical structure of the control in the GUI. Called by IsControlElement(). + /// + /// This method always returns false. + protected override bool IsControlElementCore() + { + return this.Owner.Visibility != Visibility.Hidden; + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs new file mode 100644 index 0000000000000000000000000000000000000000..1c0690a43c98cda80b0fe141e707d544c6e94e22 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Windows.Automation.Peers; +using System.Windows.Controls; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Provides a control that is always visible in the automation tree. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + [Description("Provides a System.Windows.Controls.Image control that is always visible in the automation tree.")] + public class AutomationImage : Image + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + public AutomationImage() + { + // This constructor intentionally left blank + } + + #endregion + + #region Overides + + /// + /// Returns the implementations for this control. + /// + /// The implementations for this control. + protected override AutomationPeer OnCreateAutomationPeer() + { + return new AutomationImageAutomationPeer(this); + } + + #endregion + } + + /// + /// Provides an automation peer for AutomationImage. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + internal class AutomationImageAutomationPeer : ImageAutomationPeer + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The owner of the automation peer. + public AutomationImageAutomationPeer(Image owner) + : base(owner) + { + // This constructor intentionally left blank + } + + #endregion + + #region Overrides + + /// + /// Gets a value that indicates whether the element is understood by the user as interactive or as contributing to the logical structure of the control in the GUI. Called by IsControlElement(). + /// + /// This method always returns false. + protected override bool IsControlElementCore() + { + return false; + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs new file mode 100644 index 0000000000000000000000000000000000000000..50db1bb78c171af9a656f451ed8b80bef08362bd --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Windows.Automation.Peers; +using System.Windows.Controls; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Provides a control that is always visible in the automation tree. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + [Description("Provides a System.Windows.Controls.TextBlock control that is always visible in the automation tree.")] + public class AutomationTextBlock : TextBlock + { + #region Structors + + /// + /// Initializes a new instance of the class. + /// + public AutomationTextBlock() + { + // This constructor intentionally left blank + } + + #endregion + + #region Overides + + /// + /// Returns the implementations for this control. + /// + /// The implementations for this control. + protected override AutomationPeer OnCreateAutomationPeer() + { + return new AutomationTextBlockAutomationPeer(this); + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs new file mode 100644 index 0000000000000000000000000000000000000000..6de73299abbaecba4eb62dd5feedf18c6d06a6f9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Windows.Automation.Peers; +using System.Windows.Controls; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Provides an automation peer for AutomationTextBlock. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + internal class AutomationTextBlockAutomationPeer : TextBlockAutomationPeer + { + #region Structors + + /// + /// Initializes a new instance of the class. + /// + /// The owner of the automation peer. + public AutomationTextBlockAutomationPeer(TextBlock owner) + : base(owner) + { + // This constructor intentionally left blank + } + + #endregion + + #region Overrides + + /// + /// Gets a value that indicates whether the element is understood by the user as interactive or as contributing to the logical structure of the control in the GUI. Called by IsControlElement(). + /// + /// This method always returns true. + protected override bool IsControlElementCore() + { + return true; + } + + /// + /// Gets the class name. + /// + /// The class name. + protected override string GetClassNameCore() + { + return this.Owner.GetType().Name; + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs new file mode 100644 index 0000000000000000000000000000000000000000..92d50d5d00738ab3a64d70ea58ef24b9e1490d1d --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Management.UI.Internal +{ + /// + /// A class which returns the same boxed bool values. + /// + internal static class BooleanBoxes + { + private static object trueBox = true; + private static object falseBox = false; + + internal static object TrueBox + { + get + { + return trueBox; + } + } + + internal static object FalseBox + { + get + { + return falseBox; + } + } + + internal static object Box(bool value) + { + if (value) + { + return TrueBox; + } + else + { + return FalseBox; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..c9c8606f899ade47c5427a25bd4269cddb2e4a2e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Security; +using System.Text; +using System.Windows; +using System.Windows.Input; + +namespace Microsoft.Management.UI.Internal +{ + internal static class CommandHelper + { + internal static void ExecuteCommand(ICommand command, object parameter, IInputElement target) + { + RoutedCommand command2 = command as RoutedCommand; + if (command2 != null) + { + if (command2.CanExecute(parameter, target)) + { + command2.Execute(parameter, target); + } + } + else if (command.CanExecute(parameter)) + { + command.Execute(parameter); + } + } + + internal static bool CanExecuteCommand(ICommand command, object parameter, IInputElement target) + { + if (command == null) + { + return false; + } + + RoutedCommand command2 = command as RoutedCommand; + + if (command2 != null) + { + return command2.CanExecute(parameter, target); + } + else + { + return command.CanExecute(parameter); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs new file mode 100644 index 0000000000000000000000000000000000000000..6b0db6d5f95e9dd3865f3cdce194624026f7eaf5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// The CustomTypeComparer is responsible for holding custom comparers + /// for different types, which are in turn used to perform comparison + /// operations instead of the default IComparable comparison. + /// with a custom comparer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public static class CustomTypeComparer + { + private static Dictionary comparers = new Dictionary(); + + /// + /// The static constructor. + /// + static CustomTypeComparer() + { + comparers.Add(typeof(DateTime), new DateTimeApproximationComparer()); + } + + /// + /// Compares two objects and returns a value indicating + /// whether one is less than, equal to, or greater than the other. + /// + /// + /// The first object to compare. + /// + /// + /// The second object to compare. + /// + /// + /// A type implementing IComparable. + /// + /// + /// If value1 is less than value2, then a value less than zero is returned. + /// If value1 equals value2, than zero is returned. + /// If value1 is greater than value2, then a value greater than zero is returned. + /// + public static int Compare(T value1, T value2) where T : IComparable + { + IComparer comparer; + if (TryGetCustomComparer(out comparer) == false) + { + return value1.CompareTo(value2); + } + + return comparer.Compare(value1, value2); + } + + private static bool TryGetCustomComparer(out IComparer comparer) where T : IComparable + { + comparer = null; + + object uncastComparer = null; + if (comparers.TryGetValue(typeof(T), out uncastComparer) == false) + { + return false; + } + + Debug.Assert(uncastComparer is IComparer, "must be IComparer"); + comparer = (IComparer)uncastComparer; + + return true; + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs new file mode 100644 index 0000000000000000000000000000000000000000..f75555b1da450b1e468bd59f41bf278486eddd03 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Windows; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Routed event args which provide the ability to attach an + /// arbitrary piece of data. + /// + /// There are no restrictions on type T. + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class DataRoutedEventArgs : RoutedEventArgs + { + private T data; + + /// + /// Constructs a new instance of the DataRoutedEventArgs class. + /// + /// The data payload to be stored. + /// The routed event. + public DataRoutedEventArgs(T data, RoutedEvent routedEvent) + { + this.data = data; + this.RoutedEvent = routedEvent; + } + + /// + /// Gets a value containing the data being stored. + /// + public T Data + { + get { return this.data; } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs new file mode 100644 index 0000000000000000000000000000000000000000..affbe8ca4ab687c2884ba32ea7f322a84cfeb473 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// The DateTimeApproximationComparer is responsible for comparing two + /// DateTime objects at a level of precision determined by + /// the first object. The comparison either compares at the + /// date level or the date and time (down to Seconds precision). + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class DateTimeApproximationComparer : IComparer + { + /// + /// Compares two objects and returns a value indicating + /// whether one is less than, equal to, or greater than the other. + /// + /// + /// The first object to compare. + /// + /// + /// The second object to compare. + /// + /// + /// If value1 is less than value2, then a value less than zero is returned. + /// If value1 equals value2, than zero is returned. + /// If value1 is greater than value2, then a value greater than zero is returned. + /// + public int Compare(DateTime value1, DateTime value2) + { + DateTime roundedX; + DateTime roundedY; + GetRoundedValues(value1, value2, out roundedX, out roundedY); + + return roundedX.CompareTo(roundedY); + } + + private static void GetRoundedValues(DateTime value1, DateTime value2, out DateTime roundedValue1, out DateTime roundedValue2) + { + roundedValue1 = value1; + roundedValue2 = value2; + + bool hasTimeComponent = HasTimeComponent(value1); + + int hour = hasTimeComponent ? value1.Hour : value2.Hour; + int minute = hasTimeComponent ? value1.Minute : value2.Minute; + int second = hasTimeComponent ? value1.Second : value2.Second; + + roundedValue1 = new DateTime(value1.Year, value1.Month, value1.Day, hour, minute, second); + roundedValue2 = new DateTime(value2.Year, value2.Month, value2.Day, value2.Hour, value2.Minute, value2.Second); + } + + private static bool HasTimeComponent(DateTime value) + { + bool hasNoTimeComponent = value.Hour == 0 + && value.Minute == 0 + && value.Second == 0 + && value.Millisecond == 0; + + return !hasNoTimeComponent; + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs new file mode 100644 index 0000000000000000000000000000000000000000..3a2768b17b013aa5564ff3e1953eef39225b3180 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs @@ -0,0 +1,273 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region StyleCop Suppression - generated code +using System; +using System.ComponentModel; +using System.Windows; +using System.Windows.Input; + +namespace Microsoft.Management.UI.Internal +{ + + /// + /// A popup which child controls can signal to be dismissed. + /// + /// + /// If a control wants to dismiss the popup then they should execute the DismissPopupCommand on a target in the popup window. + /// + [Localizability(LocalizationCategory.None)] + partial class DismissiblePopup + { + // + // DismissPopup routed command + // + /// + /// A command which child controls can use to tell the popup to close. + /// + public static readonly RoutedCommand DismissPopupCommand = new RoutedCommand("DismissPopup",typeof(DismissiblePopup)); + + static private void DismissPopupCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) + { + DismissiblePopup obj = (DismissiblePopup) sender; + obj.OnDismissPopupExecuted( e ); + } + + /// + /// Called when DismissPopup executes. + /// + /// + /// A command which child controls can use to tell the popup to close. + /// + protected virtual void OnDismissPopupExecuted(ExecutedRoutedEventArgs e) + { + OnDismissPopupExecutedImplementation(e); + } + + partial void OnDismissPopupExecutedImplementation(ExecutedRoutedEventArgs e); + + // + // CloseOnEscape dependency property + // + /// + /// Identifies the CloseOnEscape dependency property. + /// + public static readonly DependencyProperty CloseOnEscapeProperty = DependencyProperty.Register( "CloseOnEscape", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.TrueBox, CloseOnEscapeProperty_PropertyChanged) ); + + /// + /// Gets or sets a value indicating whether the popup closes when ESC is pressed. + /// + [Bindable(true)] + [Category("Common Properties")] + [Description("Gets or sets a value indicating whether the popup closes when ESC is pressed.")] + [Localizability(LocalizationCategory.None)] + public bool CloseOnEscape + { + get + { + return (bool) GetValue(CloseOnEscapeProperty); + } + set + { + SetValue(CloseOnEscapeProperty,BooleanBoxes.Box(value)); + } + } + + static private void CloseOnEscapeProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) + { + DismissiblePopup obj = (DismissiblePopup) o; + obj.OnCloseOnEscapeChanged( new PropertyChangedEventArgs((bool)e.OldValue, (bool)e.NewValue) ); + } + + /// + /// Occurs when CloseOnEscape property changes. + /// + public event EventHandler> CloseOnEscapeChanged; + + /// + /// Called when CloseOnEscape property changes. + /// + protected virtual void OnCloseOnEscapeChanged(PropertyChangedEventArgs e) + { + OnCloseOnEscapeChangedImplementation(e); + RaisePropertyChangedEvent(CloseOnEscapeChanged, e); + } + + partial void OnCloseOnEscapeChangedImplementation(PropertyChangedEventArgs e); + + // + // FocusChildOnOpen dependency property + // + /// + /// Identifies the FocusChildOnOpen dependency property. + /// + public static readonly DependencyProperty FocusChildOnOpenProperty = DependencyProperty.Register( "FocusChildOnOpen", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.TrueBox, FocusChildOnOpenProperty_PropertyChanged) ); + + /// + /// Gets or sets a value indicating whether focus should be set on the child when the popup opens. + /// + [Bindable(true)] + [Category("Common Properties")] + [Description("Gets or sets a value indicating whether focus should be set on the child when the popup opens.")] + [Localizability(LocalizationCategory.None)] + public bool FocusChildOnOpen + { + get + { + return (bool) GetValue(FocusChildOnOpenProperty); + } + set + { + SetValue(FocusChildOnOpenProperty,BooleanBoxes.Box(value)); + } + } + + static private void FocusChildOnOpenProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) + { + DismissiblePopup obj = (DismissiblePopup) o; + obj.OnFocusChildOnOpenChanged( new PropertyChangedEventArgs((bool)e.OldValue, (bool)e.NewValue) ); + } + + /// + /// Occurs when FocusChildOnOpen property changes. + /// + public event EventHandler> FocusChildOnOpenChanged; + + /// + /// Called when FocusChildOnOpen property changes. + /// + protected virtual void OnFocusChildOnOpenChanged(PropertyChangedEventArgs e) + { + OnFocusChildOnOpenChangedImplementation(e); + RaisePropertyChangedEvent(FocusChildOnOpenChanged, e); + } + + partial void OnFocusChildOnOpenChangedImplementation(PropertyChangedEventArgs e); + + // + // SetFocusOnClose dependency property + // + /// + /// Identifies the SetFocusOnClose dependency property. + /// + public static readonly DependencyProperty SetFocusOnCloseProperty = DependencyProperty.Register( "SetFocusOnClose", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.FalseBox, SetFocusOnCloseProperty_PropertyChanged) ); + + /// + /// Indicates whether the focus returns to either a defined by the FocusOnCloseTarget dependency property UIElement or PlacementTarget or not. + /// + [Bindable(true)] + [Category("Common Properties")] + [Description("Indicates whether the focus returns to either a defined by the FocusOnCloseTarget dependency property UIElement or PlacementTarget or not.")] + [Localizability(LocalizationCategory.None)] + public bool SetFocusOnClose + { + get + { + return (bool) GetValue(SetFocusOnCloseProperty); + } + set + { + SetValue(SetFocusOnCloseProperty,BooleanBoxes.Box(value)); + } + } + + static private void SetFocusOnCloseProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) + { + DismissiblePopup obj = (DismissiblePopup) o; + obj.OnSetFocusOnCloseChanged( new PropertyChangedEventArgs((bool)e.OldValue, (bool)e.NewValue) ); + } + + /// + /// Occurs when SetFocusOnClose property changes. + /// + public event EventHandler> SetFocusOnCloseChanged; + + /// + /// Called when SetFocusOnClose property changes. + /// + protected virtual void OnSetFocusOnCloseChanged(PropertyChangedEventArgs e) + { + OnSetFocusOnCloseChangedImplementation(e); + RaisePropertyChangedEvent(SetFocusOnCloseChanged, e); + } + + partial void OnSetFocusOnCloseChangedImplementation(PropertyChangedEventArgs e); + + // + // SetFocusOnCloseElement dependency property + // + /// + /// Identifies the SetFocusOnCloseElement dependency property. + /// + public static readonly DependencyProperty SetFocusOnCloseElementProperty = DependencyProperty.Register( "SetFocusOnCloseElement", typeof(UIElement), typeof(DismissiblePopup), new PropertyMetadata( null, SetFocusOnCloseElementProperty_PropertyChanged) ); + + /// + /// If the SetFocusOnClose property is set True and this property is set to a valid UIElement, focus returns to this UIElement after the DismissiblePopup is closed. + /// + [Bindable(true)] + [Category("Common Properties")] + [Description("If the SetFocusOnClose property is set True and this property is set to a valid UIElement, focus returns to this UIElement after the DismissiblePopup is closed.")] + [Localizability(LocalizationCategory.None)] + public UIElement SetFocusOnCloseElement + { + get + { + return (UIElement) GetValue(SetFocusOnCloseElementProperty); + } + set + { + SetValue(SetFocusOnCloseElementProperty,value); + } + } + + static private void SetFocusOnCloseElementProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) + { + DismissiblePopup obj = (DismissiblePopup) o; + obj.OnSetFocusOnCloseElementChanged( new PropertyChangedEventArgs((UIElement)e.OldValue, (UIElement)e.NewValue) ); + } + + /// + /// Occurs when SetFocusOnCloseElement property changes. + /// + public event EventHandler> SetFocusOnCloseElementChanged; + + /// + /// Called when SetFocusOnCloseElement property changes. + /// + protected virtual void OnSetFocusOnCloseElementChanged(PropertyChangedEventArgs e) + { + OnSetFocusOnCloseElementChangedImplementation(e); + RaisePropertyChangedEvent(SetFocusOnCloseElementChanged, e); + } + + partial void OnSetFocusOnCloseElementChangedImplementation(PropertyChangedEventArgs e); + + /// + /// Called when a property changes. + /// + private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) + { + if (eh != null) + { + eh(this,e); + } + } + + // + // Static constructor + // + + /// + /// Called when the type is initialized. + /// + static DismissiblePopup() + { + CommandManager.RegisterClassCommandBinding( typeof(DismissiblePopup), new CommandBinding( DismissiblePopup.DismissPopupCommand, DismissPopupCommand_CommandExecuted )); + StaticConstructorImplementation(); + } + + static partial void StaticConstructorImplementation(); + + } +} +#endregion diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs new file mode 100644 index 0000000000000000000000000000000000000000..582be1c7ecdfe88913ea892bd680988eafd3e079 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Partial class implementation for DismissiblePopup control. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public partial class DismissiblePopup : Popup + { + /// + /// Constructs an instance of DismissablePopup. + /// + public DismissiblePopup() : base() + { + // nothing + } + + private delegate void FocusChildDelegate(); + + /// + /// Responds to the condition in which the value of the IsOpen property changes from false to true. + /// + /// The event arguments. + protected override void OnOpened(EventArgs e) + { + base.OnOpened(e); + + if (this.FocusChildOnOpen) + { + this.Dispatcher.BeginInvoke( + System.Windows.Threading.DispatcherPriority.Loaded, + new FocusChildDelegate(this.FocusChild)); + } + + this.SetupAutomationIdBinding(); + } + + /// + /// Responds when the value of the IsOpen property changes from to true to false. + /// + /// The event arguments. + protected override void OnClosed(EventArgs e) + { + base.OnClosed(e); + + if (this.SetFocusOnClose) + { + // Find a control to set focus on. + if (this.SetFocusOnCloseElement != null) + { + // The focus target is set explicitly. + this.SetFocus(this.SetFocusOnCloseElement); + } + else if (this.PlacementTarget != null) + { + // Use PlacementTarget as a first chance option. + this.SetFocus(this.PlacementTarget); + } + else + { + // Use parent UIObject when neither FocusOnCloseTarget nor PlacementTarget is set. + UIElement parent = this.Parent as UIElement; + if (parent != null) + { + this.SetFocus(parent); + } + } + } + } + + private void SetFocus(UIElement element) + { + if (element.Focusable) + { + element.Focus(); + } + else + { + element.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); + } + } + + private void SetupAutomationIdBinding() + { + var popupRoot = this.FindPopupRoot(); + + var binding = new Binding(); + binding.Source = this; + binding.Path = new PropertyPath(AutomationProperties.AutomationIdProperty); + popupRoot.SetBinding(AutomationProperties.AutomationIdProperty, binding); + } + + private FrameworkElement FindPopupRoot() + { + DependencyObject element = this.Child; + + while (element.GetType().Name.Equals("PopupRoot", StringComparison.Ordinal) == false) + { + element = VisualTreeHelper.GetParent(element); + } + + Debug.Assert(element != null, "element not null"); + + return (FrameworkElement)element; + } + + /// + /// Provides class handling for the KeyDown routed event that occurs when the user presses a key while this control has focus. + /// + /// The event data. + protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) + { + //// + // Close the popup if ESC is pressed + //// + if (e.Key == System.Windows.Input.Key.Escape && this.CloseOnEscape) + { + this.IsOpen = false; + } + else + { + base.OnKeyDown(e); + } + } + + partial void OnDismissPopupExecutedImplementation(ExecutedRoutedEventArgs e) + { + this.IsOpen = false; + } + + private void FocusChild() + { + if (this.Child != null) + { + this.Child.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs new file mode 100644 index 0000000000000000000000000000000000000000..0f269df5b75da59624c46969530826c8d89b6d44 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Windows; +using System.Windows.Automation.Peers; +using System.Windows.Controls; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Provides a base automation peer for FrameworkElement controls. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class ExtendedFrameworkElementAutomationPeer : FrameworkElementAutomationPeer + { + #region Fields + + /// + /// Gets or sets the control type of the element that is associated with this automation peer. + /// + private AutomationControlType controlType = AutomationControlType.Custom; + + /// + /// Gets or sets a value that indicates whether the control should show in the logical tree. + /// + private bool isControlElement = true; + + #endregion + + #region Structors + + /// + /// Initializes a new instance of the class. + /// + /// The owner of the automation peer. + public ExtendedFrameworkElementAutomationPeer(FrameworkElement owner) + : base(owner) + { + // This constructor intentionally left blank + } + + /// + /// Initializes a new instance of the class. + /// + /// The owner of the automation peer. + /// The control type of the element that is associated with the automation peer. + public ExtendedFrameworkElementAutomationPeer(FrameworkElement owner, AutomationControlType controlType) + : this(owner) + { + this.controlType = controlType; + } + + /// + /// Initializes a new instance of the class. + /// + /// The owner of the automation peer. + /// The control type of the element that is associated with the automation peer. + /// Whether the element should show in the logical tree. + public ExtendedFrameworkElementAutomationPeer(FrameworkElement owner, AutomationControlType controlType, bool isControlElement) + : this(owner, controlType) + { + this.isControlElement = isControlElement; + } + + #endregion + + #region Overrides + + /// + /// Gets the class name. + /// + /// The class name. + protected override string GetClassNameCore() + { + return this.Owner.GetType().Name; + } + + /// + /// Gets the control type of the element that is associated with the automation peer. + /// + /// Returns the control type of the element that is associated with the automation peer. + protected override AutomationControlType GetAutomationControlTypeCore() + { + return this.controlType; + } + + /// + /// Gets a value that indicates whether the element is understood by the user as interactive or as contributing to the logical structure of the control in the GUI. Called by IsControlElement(). + /// + /// This method always returns true. + protected override bool IsControlElementCore() + { + return this.isControlElement; + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs new file mode 100644 index 0000000000000000000000000000000000000000..a87266dd69603aeb78b75a57fe26a2feb621b9dd --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Windows; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// An interface designed to provide updates about an asynchronous operation. + /// If the UI is data bound to the properties in this interface then INotifyPropertyChanged should + /// be implemented by the type implementing IAsyncProgress so the UI can get notification of the properties + /// being changed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public interface IAsyncProgress + { + /// + /// Gets a value indicating whether the async operation is currently running. + /// + bool OperationInProgress + { + get; + } + + /// + /// Gets a the error for the async operation. This field is only valid if + /// OperationInProgress is false. null indicates there was no error. + /// + Exception OperationError + { + get; + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs new file mode 100644 index 0000000000000000000000000000000000000000..e1539e76707c7bdd7ee7838cf87cd1a08dc63c90 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Defines an interface for a factory that creates + /// StateDescriptors. + /// + /// The type T used by the StateDescriptor. + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public interface IStateDescriptorFactory + { + /// + /// Creates a new StateDescriptor based upon custom + /// logic. + /// + /// A new StateDescriptor. + StateDescriptor Create(); + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..27c45ef288b534f5ca5b362b5e9952c1b9e4d5fb --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; +using System.Windows; +using System.Windows.Data; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Takes a value and returns the largest value which is a integral amount of the second value. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class IntegralConverter : IMultiValueConverter + { + /// + /// Takes a value and returns the largest value which is a integral amount of the second value. + /// + /// + /// The first value is the source. The second is the factor. + /// + /// The parameter is not used. + /// The padding to subtract from the first value. + /// The parameter is not used. + /// + /// The integral value. + /// + public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + ArgumentNullException.ThrowIfNull(values); + + if (values.Length != 2) + { + throw new ArgumentException("Two values expected", "values"); + } + + if (values[0] == DependencyProperty.UnsetValue || + values[1] == DependencyProperty.UnsetValue) + { + return DependencyProperty.UnsetValue; + } + + var source = (double)values[0]; + var factor = (double)values[1]; + + double padding = 0; + + if (parameter != null) + { + padding = double.Parse((string)parameter, CultureInfo.InvariantCulture); + } + + var newSource = source - padding; + + if (newSource < factor) + { + return source; + } + + var remainder = newSource % factor; + var result = newSource - remainder; + + return result; + } + + /// + /// This method is not used. + /// + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..efefb08bae92b73bbfd7f8c4d0da54985e14ce59 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Windows.Data; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Takes a bool value and returns the inverse. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class InverseBooleanConverter : IValueConverter + { + /// + /// Converts a boolean value to be it's inverse. + /// + /// The source value. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The inverted boolean value. + public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + ArgumentNullException.ThrowIfNull(value); + + var boolValue = (bool)value; + + return !boolValue; + } + + /// + /// This method is not used. + /// + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..dbd806a64d67fff057f6a97aacfd6bbda6737b42 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Windows; +using System.Windows.Data; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Takes two objects and determines whether they are equal. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class IsEqualConverter : IMultiValueConverter + { + /// + /// Takes two items and determines whether they are equal. + /// + /// + /// Two objects of any type. + /// + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// + /// True if-and-only-if the two objects are equal per Object.Equals(). + /// Null is equal only to null. + /// + public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + ArgumentNullException.ThrowIfNull(values); + + if (values.Length != 2) + { + throw new ArgumentException("Two values expected", "values"); + } + + object item1 = values[0]; + object item2 = values[1]; + + if (item1 == null) + { + return item2 == null; + } + + if (item2 == null) + { + return false; + } + + bool equal = item1.Equals(item2); + return equal; + } + + /// + /// This method is not used. + /// + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..265e0266c5319fc01c49152112a059b26c8ff9a5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Windows.Data; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// The IsNotNullConverter is responsible for converting a value into + /// a boolean indicting whether the value is not null. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] + public class IsNotNullConverter : IValueConverter + { + #region IValueConverter Members + + /// + /// Determines if value is not null. + /// + /// The object to check. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// Returns true if value is not null, false otherwise. + public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + return value != null; + } + + /// + /// This method is not used. + /// + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + /// The parameter is not used. + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotSupportedException(); + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs new file mode 100644 index 0000000000000000000000000000000000000000..386b33996c1e5f3463b0baf93ed5cc9661ab0501 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Windows; +using System.Windows.Input; + +namespace Microsoft.Management.UI.Internal +{ + internal enum LogicalDirection + { + None, + Left, + Right + } + + internal static class KeyboardHelp + { + /// + /// Gets the logical direction for a key, taking into account RTL settings. + /// + /// The element to get FlowDirection from. + /// The key pressed. + /// The logical direction. + public static LogicalDirection GetLogicalDirection(DependencyObject element, Key key) + { + Debug.Assert(element != null, "element not null"); + + bool rightToLeft = IsElementRightToLeft(element); + + switch (key) + { + case Key.Right: + if (rightToLeft) + { + return LogicalDirection.Left; + } + else + { + return LogicalDirection.Right; + } + + case Key.Left: + if (rightToLeft) + { + return LogicalDirection.Right; + } + else + { + return LogicalDirection.Left; + } + + default: + return LogicalDirection.None; + } + } + + /// + /// Gets the focus direction for a key, taking into account RTL settings. + /// + /// The element to get FlowDirection from. + /// The key pressed. + /// The focus direction. + public static FocusNavigationDirection GetNavigationDirection(DependencyObject element, Key key) + { + Debug.Assert(element != null, "element not null"); + Debug.Assert(IsFlowDirectionKey(key)); + + bool rightToLeft = IsElementRightToLeft(element); + + switch (key) + { + case Key.Right: + if (rightToLeft) + { + return FocusNavigationDirection.Left; + } + else + { + return FocusNavigationDirection.Right; + } + + case Key.Left: + if (rightToLeft) + { + return FocusNavigationDirection.Right; + } + else + { + return FocusNavigationDirection.Left; + } + + case Key.Down: + return FocusNavigationDirection.Down; + case Key.Up: + return FocusNavigationDirection.Up; + default: + Debug.Fail("Non-direction key specified"); + return FocusNavigationDirection.First; + } + } + + /// + /// Determines if the control key is pressed. + /// + /// True if a control is pressed. + public static bool IsControlPressed() + { + if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) + { + return true; + } + else + { + return false; + } + } + + /// + /// Determines if the key is a navigation key. + /// + /// The key pressed. + /// True if the key is a navigation key. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + private static bool IsFlowDirectionKey(Key key) + { + switch (key) + { + case Key.Right: + case Key.Left: + case Key.Down: + case Key.Up: + return true; + default: + return false; + } + } + + private static bool IsElementRightToLeft(DependencyObject element) + { + FlowDirection flowDirection = FrameworkElement.GetFlowDirection(element); + bool rightToLeft = flowDirection == FlowDirection.RightToLeft; + return rightToLeft; + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs new file mode 100644 index 0000000000000000000000000000000000000000..799cd260e1292d7fd3b00a4b994e85194c938fca --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +// +// +// This code was generated by a tool. DO NOT EDIT +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// + +#region StyleCop Suppression - generated code +using System; +using System.Collections; +using System.ComponentModel; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; + +namespace Microsoft.Management.UI.Internal +{ + + /// + /// This control presents a dropdown listbox with associated organizing actions that can be performed on it. + /// + /// + /// + /// + /// If a custom template is provided for this control, then the template MUST provide the following template parts: + /// + /// PART_Picker - A required template part which must be of type PickerBase. This control provides basic functionality for Picker-like controls. + /// + /// + [TemplatePart(Name="PART_Picker", Type=typeof(PickerBase))] + [Localizability(LocalizationCategory.None)] + partial class ListOrganizer + { + // + // Fields + // + private PickerBase picker; + + // + // ItemDeleted RoutedEvent + // + /// + /// Identifies the ItemDeleted RoutedEvent. + /// + public static readonly RoutedEvent ItemDeletedEvent = EventManager.RegisterRoutedEvent("ItemDeleted",RoutingStrategy.Bubble,typeof(EventHandler>),typeof(ListOrganizer)); + + /// + /// Occurs when an item is deleted from the list. + /// + public event EventHandler> ItemDeleted + { + add + { + AddHandler(ItemDeletedEvent,value); + } + remove + { + RemoveHandler(ItemDeletedEvent,value); + } + } + + // + // ItemSelected RoutedEvent + // + /// + /// Identifies the ItemSelected RoutedEvent. + /// + public static readonly RoutedEvent ItemSelectedEvent = EventManager.RegisterRoutedEvent("ItemSelected",RoutingStrategy.Bubble,typeof(EventHandler>),typeof(ListOrganizer)); + + /// + /// Occurs when an item is selected in the list. + /// + public event EventHandler> ItemSelected + { + add + { + AddHandler(ItemSelectedEvent,value); + } + remove + { + RemoveHandler(ItemSelectedEvent,value); + } + } + + // + // DeleteItem routed command + // + /// + /// Informs the ListOrganizer that it should delete the item passed. + /// + public static readonly RoutedCommand DeleteItemCommand = new RoutedCommand("DeleteItem",typeof(ListOrganizer)); + + static private void DeleteItemCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) + { + ListOrganizer obj = (ListOrganizer) sender; + obj.OnDeleteItemExecuted( e ); + } + + /// + /// Called when DeleteItem executes. + /// + /// + /// Informs the ListOrganizer that it should delete the item passed. + /// + protected virtual void OnDeleteItemExecuted(ExecutedRoutedEventArgs e) + { + OnDeleteItemExecutedImplementation(e); + } + + partial void OnDeleteItemExecutedImplementation(ExecutedRoutedEventArgs e); + + // + // SelectItem routed command + // + /// + /// Informs the ListOrganizer that it should select the item passed. + /// + public static readonly RoutedCommand SelectItemCommand = new RoutedCommand("SelectItem",typeof(ListOrganizer)); + + static private void SelectItemCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) + { + ListOrganizer obj = (ListOrganizer) sender; + obj.OnSelectItemExecuted( e ); + } + + /// + /// Called when SelectItem executes. + /// + /// + /// Informs the ListOrganizer that it should select the item passed. + /// + protected virtual void OnSelectItemExecuted(ExecutedRoutedEventArgs e) + { + OnSelectItemExecutedImplementation(e); + } + + partial void OnSelectItemExecutedImplementation(ExecutedRoutedEventArgs e); + + // + // DropDownButtonTemplate dependency property + // + /// + /// Identifies the DropDownButtonTemplate dependency property. + /// + public static readonly DependencyProperty DropDownButtonTemplateProperty = DependencyProperty.Register( "DropDownButtonTemplate", typeof(ControlTemplate), typeof(ListOrganizer), new PropertyMetadata( null, DropDownButtonTemplateProperty_PropertyChanged) ); + + /// + /// Gets or sets a value that controls the visual tree of the DropDown button. + /// + [Bindable(true)] + [Category("Common Properties")] + [Description("Gets or sets a value that controls the visual tree of the DropDown button.")] + [Localizability(LocalizationCategory.None)] + public ControlTemplate DropDownButtonTemplate + { + get + { + return (ControlTemplate) GetValue(DropDownButtonTemplateProperty); + } + set + { + SetValue(DropDownButtonTemplateProperty,value); + } + } + + static private void DropDownButtonTemplateProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) + { + ListOrganizer obj = (ListOrganizer) o; + obj.OnDropDownButtonTemplateChanged( new PropertyChangedEventArgs((ControlTemplate)e.OldValue, (ControlTemplate)e.NewValue) ); + } + + /// + /// Occurs when DropDownButtonTemplate property changes. + /// + public event EventHandler> DropDownButtonTemplateChanged; + + /// + /// Called when DropDownButtonTemplate property changes. + /// + protected virtual void OnDropDownButtonTemplateChanged(PropertyChangedEventArgs e) + { + OnDropDownButtonTemplateChangedImplementation(e); + RaisePropertyChangedEvent(DropDownButtonTemplateChanged, e); + } + + partial void OnDropDownButtonTemplateChangedImplementation(PropertyChangedEventArgs e); + + // + // DropDownStyle dependency property + // + /// + /// Identifies the DropDownStyle dependency property. + /// + public static readonly DependencyProperty DropDownStyleProperty = DependencyProperty.Register( "DropDownStyle", typeof(Style), typeof(ListOrganizer), new PropertyMetadata( null, DropDownStyleProperty_PropertyChanged) ); + + /// + /// Gets or sets the style of the drop-down. + /// + [Bindable(true)] + [Category("Common Properties")] + [Description("Gets or sets the style of the drop-down.")] + [Localizability(LocalizationCategory.None)] + public Style DropDownStyle + { + get + { + return (Style) GetValue(DropDownStyleProperty); + } + set + { + SetValue(DropDownStyleProperty,value); + } + } + + static private void DropDownStyleProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) + { + ListOrganizer obj = (ListOrganizer) o; + obj.OnDropDownStyleChanged( new PropertyChangedEventArgs + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..5d360017c16d5bd2f8fdedc37a42bc17c0a3810e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Windows; +using System.Windows.Controls; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for AllModulesControl.xaml. + /// + public partial class AllModulesControl : UserControl + { + #region Construction and Destructor + + /// + /// Initializes a new instance of the AllModulesControl class. + /// + public AllModulesControl() + { + InitializeComponent(); + + this.Loaded += (obj, args) => + { + this.ModulesCombo.Focus(); + }; + } + + #endregion + /// + /// Gets current control of the ShowModuleControl. + /// + internal ShowModuleControl CurrentShowModuleControl + { + get { return this.ShowModuleControl; } + } + + private void RefreshButton_Click(object sender, System.Windows.RoutedEventArgs e) + { + AllModulesViewModel viewModel = this.DataContext as AllModulesViewModel; + if (viewModel == null) + { + return; + } + + viewModel.OnRefresh(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml new file mode 100644 index 0000000000000000000000000000000000000000..f7e77ed944ddc072894553e760e883a3026a90c7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..0837bb567e48c2f2283853f42aaa1265a95feeac --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Windows; +using System.Windows.Controls; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for CmdletControl.xaml. + /// + public partial class CmdletControl : UserControl + { + /// + /// Field used for the CurrentCommandViewModel parameter. + /// + private CommandViewModel currentCommandViewModel; + + #region Construction and Destructor + /// + /// Initializes a new instance of the CmdletControl class. + /// + public CmdletControl() + { + InitializeComponent(); + this.NotImportedControl.ImportModuleButton.Click += ImportModuleButton_Click; + this.ParameterSetTabControl.DataContextChanged += new DependencyPropertyChangedEventHandler(this.ParameterSetTabControl_DataContextChanged); + this.KeyDown += this.CmdletControl_KeyDown; + this.helpButton.innerButton.Click += this.HelpButton_Click; + } + #endregion + + #region Properties + /// + /// Gets the owner of the ViewModel. + /// + private CommandViewModel CurrentCommandViewModel + { + get { return this.currentCommandViewModel; } + } + #endregion + + #region Private Events + + /// + /// DataContextChanged event. + /// + /// Event sender. + /// Event args. + private void ParameterSetTabControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) + { + if (this.DataContext == null) + { + return; + } + + CommandViewModel viewModel = (CommandViewModel)this.DataContext; + this.currentCommandViewModel = viewModel; + + if (viewModel.ParameterSets.Count == 0) + { + return; + } + + this.ParameterSetTabControl.SelectedItem = viewModel.ParameterSets[0]; + } + + /// + /// Key down event for user press F1 button. + /// + /// Event sender. + /// Event args. + private void CmdletControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) + { + if (e.Key == System.Windows.Input.Key.F1) + { + this.CurrentCommandViewModel.OpenHelpWindow(); + } + } + + /// + /// Help button event. + /// + /// Event sender. + /// Event args. + private void HelpButton_Click(object sender, RoutedEventArgs e) + { + this.CurrentCommandViewModel.OpenHelpWindow(); + } + + /// + /// Import Module Button event. + /// + /// Event sender. + /// Event args. + private void ImportModuleButton_Click(object sender, RoutedEventArgs e) + { + this.CurrentCommandViewModel.OnImportModule(); + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml new file mode 100644 index 0000000000000000000000000000000000000000..024b287e80aa4b03a53798f04c72cbe8af563203 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..05247f46ff0a879ab1b9749cd006ee159e8d11ef --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Windows.Automation; +using System.Windows.Automation.Peers; +using System.Windows.Controls; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Button with images to represent enabled and disabled states. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Required by XAML")] + public partial class ImageButton : ImageButtonBase + { + /// + /// Initializes a new instance of the ImageButton class. + /// + public ImageButton() + { + InitializeComponent(); + this.Loaded += this.ImageButton_Loaded; + } + + /// + /// Copies the automation id and name from the parent control to the inner button. + /// + /// Event sender. + /// Event arguments. + private void ImageButton_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + object thisAutomationId = this.GetValue(AutomationProperties.AutomationIdProperty); + if (thisAutomationId != null) + { + this.innerButton.SetValue(AutomationProperties.AutomationIdProperty, thisAutomationId); + } + + object thisAutomationName = this.GetValue(AutomationProperties.NameProperty); + if (thisAutomationName != null) + { + this.innerButton.SetValue(AutomationProperties.NameProperty, thisAutomationName); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..76ab5cf3c28aa34c03f46808aa2ff247eaea8c34 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Implements the ImageButtonBase base class to the ImageButton and ImageToggleButton. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Required by XAML")] + public class ImageButtonBase : Grid + { + /// + /// Command associated with this button. + /// + public static readonly DependencyProperty CommandProperty = + DependencyProperty.Register("Command", typeof(RoutedUICommand), typeof(ImageButton)); + + /// + /// Image to be used for the enabled state. + /// + public static readonly DependencyProperty EnabledImageSourceProperty = + DependencyProperty.Register("EnabledImageSource", typeof(ImageSource), typeof(ImageButton)); + + /// + /// Image to be used for the disabled state. + /// + public static readonly DependencyProperty DisabledImageSourceProperty = + DependencyProperty.Register("DisabledImageSource", typeof(ImageSource), typeof(ImageButton)); + + /// + /// Gets or sets the image to be used for the enabled state. + /// + public ImageSource EnabledImageSource + { + get { return (ImageSource)GetValue(ImageButton.EnabledImageSourceProperty); } + set { SetValue(ImageButton.EnabledImageSourceProperty, value); } + } + + /// + /// Gets or sets the image to be used for the disabled state. + /// + public ImageSource DisabledImageSource + { + get { return (ImageSource)GetValue(ImageButton.DisabledImageSourceProperty); } + set { SetValue(ImageButton.DisabledImageSourceProperty, value); } + } + + /// + /// Gets or sets the command associated with this button. + /// + public RoutedUICommand Command + { + get { return (RoutedUICommand)GetValue(ImageButton.CommandProperty); } + set { SetValue(ImageButton.CommandProperty, value); } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml new file mode 100644 index 0000000000000000000000000000000000000000..f89e474a2de32a667e1c1ca2e795eaa66dfd091f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..bec10afc6b774d0a8c92795c571337077adad1cb --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Windows.Controls; +using System.Windows.Data; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Converts a an ImageButtonBase to its corresponding ToolTip. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed for XAML")] + public class ImageButtonToolTipConverter : IValueConverter + { + // This class is meant to be used like this in XAML: + // + // ... + // + // + // + // ... + // + #region IValueConverter Members + + /// + /// Converts a an ImageButtonBase to its corresponding ToolTip by checking if it has a tooltip property + /// or a command with tooltip text + /// + /// The ImageButtonBase we are trying to Convert. + /// is not used. + /// is not used. + /// is not used. + /// The resulting object obtained from retrieving the property value in (or property values if contains dots) out of . . + public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + ImageButtonBase imageButtonBase = value as ImageButtonBase; + if (imageButtonBase == null) + { + return null; + } + + object toolTipObj = imageButtonBase.GetValue(Button.ToolTipProperty); + if (toolTipObj != null) + { + return toolTipObj.ToString(); + } + + if (imageButtonBase.Command != null && !string.IsNullOrEmpty(imageButtonBase.Command.Text)) + { + return imageButtonBase.Command.Text.Replace("_", string.Empty); + } + + return null; + } + + /// + /// This method is not supported. + /// + /// is not used. + /// is not used. + /// is not used. + /// is not used. + /// No value is returned. + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotSupportedException(); + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml new file mode 100644 index 0000000000000000000000000000000000000000..c472721ac85f6e810083cfe3918c6d339417363e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..adc1e1a642164a1772a3e4bf7255abed0d4ab519 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Windows; +using System.Windows.Automation; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Toggle button with images to represent enabled and disabled states. + /// + [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Required by XAML")] + public partial class ImageToggleButton : ImageButtonBase + { + /// + /// Value indicating the button is checked. + /// + public static readonly DependencyProperty IsCheckedProperty = + DependencyProperty.Register("IsChecked", typeof(bool), typeof(ImageToggleButton)); + + /// + /// Initializes a new instance of the ImageToggleButton class. + /// + public ImageToggleButton() + { + InitializeComponent(); + this.Loaded += this.ImageButton_Loaded; + } + + /// + /// Gets or sets a value indicating whether the button is checked. + /// + public bool IsChecked + { + get { return (bool)GetValue(ImageToggleButton.IsCheckedProperty); } + set { SetValue(ImageToggleButton.IsCheckedProperty, value); } + } + + /// + /// Copies the automation id and name from the parent control to the inner button. + /// + /// Event sender. + /// Event arguments. + private void ImageButton_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + object thisAutomationId = this.GetValue(AutomationProperties.AutomationIdProperty); + if (thisAutomationId != null) + { + this.toggleInnerButton.SetValue(AutomationProperties.AutomationIdProperty, thisAutomationId); + } + + object thisAutomationName = this.GetValue(AutomationProperties.NameProperty); + if (thisAutomationName != null) + { + this.toggleInnerButton.SetValue(AutomationProperties.NameProperty, thisAutomationName); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml new file mode 100644 index 0000000000000000000000000000000000000000..557741edf0de03d9173396e8025344ba35558368 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..f57d5dfda51225b9e4157a1002784f6c3860b92e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Globalization; +using System.Management.Automation; +using System.Text; +using System.Windows; +using System.Windows.Controls; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for MultipleSelectionControl.xaml. + /// + public partial class MultipleSelectionControl : UserControl + { + /// + /// Initializes a new instance of the MultipleSelectionControl class. + /// + public MultipleSelectionControl() + { + InitializeComponent(); + } + + /// + /// Show more items in new dialog. + /// + /// Event sender. + /// Event arguments. + private void ButtonBrowse_Click(object sender, RoutedEventArgs e) + { + MultipleSelectionDialog multipleSelectionDialog = new MultipleSelectionDialog(); + multipleSelectionDialog.Title = this.multipleValueButton.ToolTip.ToString(); + multipleSelectionDialog.listboxParameter.ItemsSource = comboxParameter.ItemsSource; + multipleSelectionDialog.ShowDialog(); + + if (multipleSelectionDialog.DialogResult != true) + { + return; + } + + StringBuilder newComboText = new StringBuilder(); + + foreach (object selectedItem in multipleSelectionDialog.listboxParameter.SelectedItems) + { + newComboText.Append(CultureInfo.InvariantCulture, $"{selectedItem},"); + } + + if (newComboText.Length > 1) + { + newComboText.Remove(newComboText.Length - 1, 1); + } + + comboxParameter.Text = newComboText.ToString(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml new file mode 100644 index 0000000000000000000000000000000000000000..cb0a9198b80cc56c05ef65e20d96d9f31609a2b8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..6577400423634cba4b7bc431c354d8389cca81d2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Windows.Controls; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for NotImportedCmdletControl.xaml. + /// + public partial class NotImportedCmdletControl : UserControl + { + #region Construction and Destructor + + /// + /// Initializes a new instance of the NotImportedCmdletControl class. + /// + public NotImportedCmdletControl() + { + InitializeComponent(); + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml new file mode 100644 index 0000000000000000000000000000000000000000..c59f519d663bdf11337dea8b9721ca7507be33e8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml @@ -0,0 +1,22 @@ + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..6efef65eec6b601d0b33c7b8b9858bc3a6e236c9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -0,0 +1,403 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Data; + +using Microsoft.Management.UI.Internal; +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for ParameterSetControl.xaml. + /// + public partial class ParameterSetControl : UserControl + { + /// + /// First focusable element in the generated UI. + /// + private UIElement firstFocusableElement; + + /// + /// Field used for the CurrentParameterSetViewModel parameter. + /// + private ParameterSetViewModel currentParameterSetViewModel; + + #region Construction and Destructor + /// + /// Initializes a new instance of the ParameterSetControl class. + /// + public ParameterSetControl() + { + InitializeComponent(); + this.DataContextChanged += new DependencyPropertyChangedEventHandler(this.ParameterSetControl_DataContextChanged); + } + #endregion + + #region Public Methods + + /// + /// Focuses the first focusable element in this control. + /// + public void FocusFirstElement() + { + if (this.firstFocusableElement != null) + { + this.firstFocusableElement.Focus(); + } + } + + #endregion + + #region Private Property + /// + /// Gets current ParameterSetViewModel. + /// + private ParameterSetViewModel CurrentParameterSetViewModel + { + get { return this.currentParameterSetViewModel; } + } + + #endregion + + /// + /// Creates a CheckBox for switch parameters. + /// + /// DataContext object. + /// Row number. + /// a CheckBox for switch parameters. + private static CheckBox CreateCheckBox(ParameterViewModel parameterViewModel, int rowNumber) + { + CheckBox checkBox = new CheckBox(); + + checkBox.SetBinding(Label.ContentProperty, new Binding("NameCheckLabel")); + checkBox.DataContext = parameterViewModel; + checkBox.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; + checkBox.SetValue(Grid.ColumnProperty, 0); + checkBox.SetValue(Grid.ColumnSpanProperty, 2); + checkBox.SetValue(Grid.RowProperty, rowNumber); + checkBox.IsThreeState = false; + checkBox.Margin = new Thickness(8, rowNumber == 0 ? 7 : 5, 0, 5); + checkBox.SetBinding(CheckBox.ToolTipProperty, new Binding("ToolTip")); + checkBox.SetBinding(AutomationProperties.HelpTextProperty, new Binding("ToolTip")); + Binding valueBinding = new Binding("Value"); + checkBox.SetBinding(CheckBox.IsCheckedProperty, valueBinding); + + //// Add AutomationProperties.AutomationId for Ui Automation test. + checkBox.SetValue( + System.Windows.Automation.AutomationProperties.AutomationIdProperty, + string.Create(CultureInfo.CurrentCulture, $"chk{parameterViewModel.Name}")); + + checkBox.SetValue( + System.Windows.Automation.AutomationProperties.NameProperty, + parameterViewModel.Name); + + return checkBox; + } + + /// + /// Creates a ComboBox control for input type field. + /// + /// DataContext object. + /// Row number. + /// Control data source. + /// Return a ComboBox control. + private static ComboBox CreateComboBoxControl(ParameterViewModel parameterViewModel, int rowNumber, IEnumerable itemsSource) + { + ComboBox comboBox = new ComboBox(); + + comboBox.DataContext = parameterViewModel; + comboBox.SetValue(Grid.ColumnProperty, 1); + comboBox.SetValue(Grid.RowProperty, rowNumber); + comboBox.Margin = new Thickness(2); + comboBox.SetBinding(TextBox.ToolTipProperty, new Binding("ToolTip")); + comboBox.ItemsSource = itemsSource; + + Binding selectedItemBinding = new Binding("Value"); + comboBox.SetBinding(ComboBox.SelectedItemProperty, selectedItemBinding); + + string automationId = string.Create(CultureInfo.CurrentCulture, $"combox{parameterViewModel.Name}"); + + //// Add AutomationProperties.AutomationId for Ui Automation test. + comboBox.SetValue( + System.Windows.Automation.AutomationProperties.AutomationIdProperty, + automationId); + + comboBox.SetValue( + System.Windows.Automation.AutomationProperties.NameProperty, + parameterViewModel.Name); + + return comboBox; + } + + /// + /// Creates a MultiSelectCombo control for input type field. + /// + /// DataContext object. + /// Row number. + /// Control data source. + /// Return a MultiSelectCombo control. + private static MultipleSelectionControl CreateMultiSelectComboControl(ParameterViewModel parameterViewModel, int rowNumber, IEnumerable itemsSource) + { + MultipleSelectionControl multiControls = new MultipleSelectionControl(); + + multiControls.DataContext = parameterViewModel; + multiControls.SetValue(Grid.ColumnProperty, 1); + multiControls.SetValue(Grid.RowProperty, rowNumber); + multiControls.Margin = new Thickness(2); + multiControls.comboxParameter.ItemsSource = itemsSource; + multiControls.SetBinding(TextBox.ToolTipProperty, new Binding("ToolTip")); + + Binding valueBinding = new Binding("Value"); + valueBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; + multiControls.comboxParameter.SetBinding(ComboBox.TextProperty, valueBinding); + + // Add AutomationProperties.AutomationId for Ui Automation test. + multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Create(CultureInfo.CurrentCulture, $"combox{parameterViewModel.Name}")); + + multiControls.comboxParameter.SetValue( + System.Windows.Automation.AutomationProperties.NameProperty, + parameterViewModel.Name); + + string buttonToolTipAndName = string.Format( + CultureInfo.CurrentUICulture, + ShowCommandResources.SelectMultipleValuesForParameterFormat, + parameterViewModel.Name); + + multiControls.multipleValueButton.SetValue(Button.ToolTipProperty, buttonToolTipAndName); + multiControls.multipleValueButton.SetValue( + System.Windows.Automation.AutomationProperties.NameProperty, + buttonToolTipAndName); + + return multiControls; + } + + /// + /// Creates a TextBox control for input type field. + /// + /// DataContext object. + /// Row number. + /// Return a TextBox control. + private static TextBox CreateTextBoxControl(ParameterViewModel parameterViewModel, int rowNumber) + { + TextBox textBox = new TextBox(); + + textBox.DataContext = parameterViewModel; + textBox.SetValue(Grid.ColumnProperty, 1); + textBox.SetValue(Grid.RowProperty, rowNumber); + textBox.Margin = new Thickness(2); + textBox.SetBinding(TextBox.ToolTipProperty, new Binding("ToolTip")); + + Binding valueBinding = new Binding("Value"); + valueBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; + textBox.SetBinding(TextBox.TextProperty, valueBinding); + + //// Add AutomationProperties.AutomationId for UI Automation test. + textBox.SetValue( + System.Windows.Automation.AutomationProperties.AutomationIdProperty, + string.Create(CultureInfo.CurrentCulture, $"txt{parameterViewModel.Name}")); + + textBox.SetValue( + System.Windows.Automation.AutomationProperties.NameProperty, + parameterViewModel.Name); + + ShowCommandParameterType parameterType = parameterViewModel.Parameter.ParameterType; + + if (parameterType.IsArray) + { + parameterType = parameterType.ElementType; + } + + if (parameterType.IsScriptBlock || parameterType.ImplementsDictionary) + { + textBox.AcceptsReturn = true; + textBox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; + textBox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; + textBox.Loaded += ParameterSetControl.MultiLineTextBox_Loaded; + } + + return textBox; + } + + /// + /// Called for a newly created multiline text box to increase its height and. + /// + /// Event sender. + /// Event arguments. + private static void MultiLineTextBox_Loaded(object sender, RoutedEventArgs e) + { + TextBox senderTextBox = (TextBox)sender; + senderTextBox.Loaded -= ParameterSetControl.MultiLineTextBox_Loaded; + + // This will set the height to about 3 lines since the total height of the + // TextBox is a bit greater than a line's height + senderTextBox.Height = senderTextBox.ActualHeight * 2; + } + + #region Event Methods + + /// + /// When user switch ParameterSet.It will trigger this event. + /// This event method will renew generate all controls for current ParameterSet. + /// + /// Event sender. + /// Event args. + private void ParameterSetControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) + { + this.firstFocusableElement = null; + this.MainGrid.Children.Clear(); + this.MainGrid.RowDefinitions.Clear(); + + ParameterSetViewModel viewModel = e.NewValue as ParameterSetViewModel; + if (viewModel == null) + { + return; + } + + this.currentParameterSetViewModel = viewModel; + + for (int rowNumber = 0; rowNumber < viewModel.Parameters.Count; rowNumber++) + { + ParameterViewModel parameter = viewModel.Parameters[rowNumber]; + this.MainGrid.RowDefinitions.Add(this.CreateNewRow()); + + if (parameter.Parameter.ParameterType.IsSwitch) + { + this.AddControlToMainGrid(ParameterSetControl.CreateCheckBox(parameter, rowNumber)); + } + else + { + this.CreateAndAddLabel(parameter, rowNumber); + Control control = null; + if (parameter.Parameter.HasParameterSet) + { + // For ValidateSet parameter + ArrayList itemsSource = new ArrayList(); + itemsSource.Add(string.Empty); + + for (int i = 0; i < parameter.Parameter.ValidParamSetValues.Count; i++) + { + itemsSource.Add(parameter.Parameter.ValidParamSetValues[i]); + } + + control = ParameterSetControl.CreateComboBoxControl(parameter, rowNumber, itemsSource); + } + else if (parameter.Parameter.ParameterType.IsEnum) + { + if (parameter.Parameter.ParameterType.HasFlagAttribute) + { + ArrayList itemsSource = new ArrayList(); + itemsSource.Add(string.Empty); + itemsSource.AddRange(parameter.Parameter.ParameterType.EnumValues); + control = ParameterSetControl.CreateComboBoxControl(parameter, rowNumber, itemsSource); + } + else + { + control = ParameterSetControl.CreateMultiSelectComboControl(parameter, rowNumber, parameter.Parameter.ParameterType.EnumValues); + } + } + else if (parameter.Parameter.ParameterType.IsBoolean) + { + control = ParameterSetControl.CreateComboBoxControl(parameter, rowNumber, new string[] { string.Empty, "$True", "$False" }); + } + else + { + // For input parameter + control = ParameterSetControl.CreateTextBoxControl(parameter, rowNumber); + } + + if (control != null) + { + this.AddControlToMainGrid(control); + } + } + } + } + + /// + /// When user trigger click on anyone CheckBox. Get value from sender. + /// + /// Event sender. + /// Event args. + private void CheckBox_Click(object sender, RoutedEventArgs e) + { + CheckBox senderCheck = (CheckBox)sender; + ((ParameterViewModel)senderCheck.DataContext).Value = senderCheck.IsChecked.ToString(); + } + + #endregion + + #region Private Method + + /// + /// Creates a RowDefinition for MainGrid. + /// + /// Return a RowDefinition object. + private RowDefinition CreateNewRow() + { + RowDefinition row = new RowDefinition(); + row.Height = GridLength.Auto; + return row; + } + + /// + /// Adds a control to MainGrid;. + /// + /// Will adding UIControl. + private void AddControlToMainGrid(UIElement uiControl) + { + if (this.firstFocusableElement == null && uiControl is not Label) + { + this.firstFocusableElement = uiControl; + } + + this.MainGrid.Children.Add(uiControl); + } + + /// + /// Creates a Label control and add it to MainGrid. + /// + /// DataContext object. + /// Row number. + private void CreateAndAddLabel(ParameterViewModel parameterViewModel, int rowNumber) + { + Label label = this.CreateLabel(parameterViewModel, rowNumber); + this.AddControlToMainGrid(label); + } + + /// + /// Creates a Label control for input type field. + /// + /// DataContext object. + /// Row number. + /// Return a Label control. + private Label CreateLabel(ParameterViewModel parameterViewModel, int rowNumber) + { + Label label = new Label(); + + label.SetBinding(Label.ContentProperty, new Binding("NameTextLabel")); + label.DataContext = parameterViewModel; + label.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; + label.SetValue(Grid.ColumnProperty, 0); + label.SetValue(Grid.RowProperty, rowNumber); + label.Margin = new Thickness(2); + label.SetBinding(Label.ToolTipProperty, new Binding("ToolTip")); + + //// Add AutomationProperties.AutomationId for Ui Automation test. + label.SetValue( + System.Windows.Automation.AutomationProperties.AutomationIdProperty, + string.Create(CultureInfo.CurrentCulture, $"lbl{parameterViewModel.Name}")); + + return label; + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml new file mode 100644 index 0000000000000000000000000000000000000000..e03c7859ed05eb3867a2e741eaf172d6324b5ca7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..4bdaa32fd9f856d3f37766f9707c094860f8ce6d --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Control taht shows cmdlets in a module and details for a selected cmdlet. + /// + public partial class ShowModuleControl : UserControl + { + /// + /// Field used for the Owner parameter. + /// + private Window owner; + + /// + /// Initializes a new instance of the ShowModuleControl class. + /// + public ShowModuleControl() + { + InitializeComponent(); + + // See comment in method summary to understand why this event is handled + this.CommandList.PreviewMouseMove += this.CommandList_PreviewMouseMove; + + // See comment in method summary to understand why this event is handled + this.CommandList.SelectionChanged += this.CommandList_SelectionChanged; + } + + /// + /// Gets or sets the owner of the container. + /// + public Window Owner + { + get { return this.owner; } + set { this.owner = value; } + } + + #region Events Handlers + /// + /// WPF has an interesting feature in list selection where if you hold the mouse button down, + /// it will select the item under it, but if you keep the mouse button down and move the mouse + /// (if the list supported drag and drop, the mouse action would be the same as dragging) it + /// will select other list items. + /// If the first selection change causes details for the item to be displayed and resizes the list, + /// the selection can skip to another list item that happens to be over as the list got resized. + /// In summary, resizing the list on selection can cause a selection bug. If the user selects an + /// item in the end of the list the next item downwards can be selected. + /// The WPF drag-and-select feature is not a standard win32 list behavior, and we can do without it + /// since it causes this problem. + /// WPF sets up this behavior by using a mouse capture. We undo the behavior in the handler below + /// which removes the behavior. + /// + /// Event sender. + /// Event arguments. + private void CommandList_PreviewMouseMove(object sender, MouseEventArgs e) + { + if (this.CommandList.IsMouseCaptured) + { + this.CommandList.ReleaseMouseCapture(); + } + } + + /// + /// Ensures the selected item is scrolled into view and that the list is focused. + /// An item could be out of the view if the selection was changed in the object model + /// + /// Event sender. + /// Event arguments. + private void CommandList_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (this.CommandList.SelectedItem == null) + { + return; + } + + this.CommandList.ScrollIntoView(this.CommandList.SelectedItem); + } + #endregion Events Handlers + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..18194cec8fbd99799631ef242d625f048503848c --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.16808 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Management.UI.Internal.ShowCommand { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class ShowCommandSettings : global::System.Configuration.ApplicationSettingsBase { + + private static ShowCommandSettings defaultInstance = ((ShowCommandSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ShowCommandSettings()))); + + public static ShowCommandSettings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowOneCommandTop { + get { + return ((double)(this["ShowOneCommandTop"])); + } + set { + this["ShowOneCommandTop"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowOneCommandLeft { + get { + return ((double)(this["ShowOneCommandLeft"])); + } + set { + this["ShowOneCommandLeft"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowOneCommandWidth { + get { + return ((double)(this["ShowOneCommandWidth"])); + } + set { + this["ShowOneCommandWidth"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowOneCommandHeight { + get { + return ((double)(this["ShowOneCommandHeight"])); + } + set { + this["ShowOneCommandHeight"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowCommandsTop { + get { + return ((double)(this["ShowCommandsTop"])); + } + set { + this["ShowCommandsTop"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowCommandsLeft { + get { + return ((double)(this["ShowCommandsLeft"])); + } + set { + this["ShowCommandsLeft"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowCommandsWidth { + get { + return ((double)(this["ShowCommandsWidth"])); + } + set { + this["ShowCommandsWidth"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("-1")] + public double ShowCommandsHeight { + get { + return ((double)(this["ShowCommandsHeight"])); + } + set { + this["ShowCommandsHeight"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool ShowCommandsWindowMaximized { + get { + return ((bool)(this["ShowCommandsWindowMaximized"])); + } + set { + this["ShowCommandsWindowMaximized"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool ShowOneCommandWindowMaximized { + get { + return ((bool)(this["ShowOneCommandWindowMaximized"])); + } + set { + this["ShowOneCommandWindowMaximized"] = value; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.settings b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.settings new file mode 100644 index 0000000000000000000000000000000000000000..53a4da1a5d76cfea14caf520929b8bf206b30204 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.settings @@ -0,0 +1,36 @@ + + + + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + False + + + False + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs new file mode 100644 index 0000000000000000000000000000000000000000..04fc95e42235e1258d31dd87085ab477201bedbc --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -0,0 +1,658 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Management.Automation; +using System.Windows; + +using Microsoft.Management.UI.Internal; +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Contains all Commands, Parameters, ParameterSet and Common Parameter. + /// + public class AllModulesViewModel : INotifyPropertyChanged + { + #region Private Fields + /// + /// Flag indicating a wait message is being displayed. + /// + private bool waitMessageDisplayed; + + /// + /// True if this ViewModel is not supposed to show common parameters. + /// + private bool noCommonParameter; + + /// + /// the filterName of command. + /// + private string commandNameFilter; + + /// + /// Field used for the Modules property. + /// + private List modules; + + /// + /// true if a command can be run. + /// + private bool canRun; + + /// + /// true if a command can be copied. + /// + private bool canCopy; + + /// + /// the selected module being displayed in the GUI. + /// + private ModuleViewModel selectedModule; + + /// + /// the visibility of the refresh button. + /// + private Visibility refreshVisibility = Visibility.Collapsed; + + /// + /// Provides an extra viewModel object that allows callers to control certain aspects of the GUI. + /// + private object extraViewModel; + + /// + /// private property for ZoomLevel. + /// + private double zoomLevel = 1.0; + #endregion + + #region Construction and Destructor + /// + /// Initializes a new instance of the AllModulesViewModel class. + /// + /// The loaded modules. + /// Commands to show. + public AllModulesViewModel(Dictionary importedModules, IEnumerable commands) + { + ArgumentNullException.ThrowIfNull(commands); + + if (!commands.GetEnumerator().MoveNext()) + { + throw new ArgumentNullException("commands"); + } + + this.Initialization(importedModules, commands, true); + } + + /// + /// Initializes a new instance of the AllModulesViewModel class. + /// + /// The loaded modules. + /// All PowerShell commands. + /// True not to show common parameters. + public AllModulesViewModel(Dictionary importedModules, IEnumerable commands, bool noCommonParameter) + { + ArgumentNullException.ThrowIfNull(commands); + + this.Initialization(importedModules, commands, noCommonParameter); + } + + #endregion + + #region INotifyPropertyChanged Members + /// + /// PropertyChanged Event. + /// + public event PropertyChangedEventHandler PropertyChanged; + #endregion + + /// + /// Indicates the selected command in the selected module needs to display the help for a command. + /// + public event EventHandler SelectedCommandInSelectedModuleNeedsHelp; + + /// + /// Indicates the selected command in the selected module needs to import a module for a command. + /// + public event EventHandler SelectedCommandInSelectedModuleNeedsImportModule; + + /// + /// Indicates the selected command in the selected module should be run. + /// + public event EventHandler RunSelectedCommandInSelectedModule; + + /// + /// Indicates we want to refresh the viewModel. + /// + public event EventHandler Refresh; + + #region Public Properties + + /// + /// Get or Sets Zoom level. + /// + public double ZoomLevel + { + get + { + return this.zoomLevel; + } + + set + { + if (value > 0) + { + this.zoomLevel = value / 100.0; + this.OnNotifyPropertyChanged("ZoomLevel"); + } + } + } + + /// + /// Gets the tooltip for the refresh button. + /// + public static string RefreshTooltip + { + get { return string.Format(CultureInfo.CurrentUICulture, ShowCommandResources.RefreshShowCommandTooltipFormat, "import-module"); } + } + + /// + /// Gets or sets the visibility of the refresh button. + /// + public Visibility RefreshVisibility + { + get + { + return this.refreshVisibility; + } + + set + { + if (this.refreshVisibility == value) + { + return; + } + + this.refreshVisibility = value; + this.OnNotifyPropertyChanged("RefreshVisibility"); + } + } + + /// + /// Gets a value indicating whether common parameters are displayed. + /// + public bool NoCommonParameter + { + get { return this.noCommonParameter; } + } + + /// + /// Gets or sets the filterName of command. + /// + public string CommandNameFilter + { + get + { + return this.commandNameFilter; + } + + set + { + if (this.CommandNameFilter == value) + { + return; + } + + this.commandNameFilter = value; + if (this.selectedModule != null) + { + this.selectedModule.RefreshFilteredCommands(this.CommandNameFilter); + this.selectedModule.SelectedCommand = null; + } + + this.OnNotifyPropertyChanged("CommandNameFilter"); + } + } + + /// + /// Gets or sets the selected module being displayed in the GUI. + /// + public ModuleViewModel SelectedModule + { + get + { + return this.selectedModule; + } + + set + { + if (this.selectedModule == value) + { + return; + } + + if (this.selectedModule != null) + { + this.selectedModule.SelectedCommandNeedsImportModule -= this.SelectedModule_SelectedCommandNeedsImportModule; + this.selectedModule.SelectedCommandNeedsHelp -= this.SelectedModule_SelectedCommandNeedsHelp; + this.selectedModule.RunSelectedCommand -= this.SelectedModule_RunSelectedCommand; + this.selectedModule.PropertyChanged -= this.SelectedModule_PropertyChanged; + } + + this.selectedModule = value; + this.SetCanRun(); + this.SetCanCopy(); + + if (this.selectedModule != null) + { + this.selectedModule.RefreshFilteredCommands(this.CommandNameFilter); + this.selectedModule.SelectedCommandNeedsImportModule += this.SelectedModule_SelectedCommandNeedsImportModule; + this.selectedModule.SelectedCommandNeedsHelp += this.SelectedModule_SelectedCommandNeedsHelp; + this.selectedModule.RunSelectedCommand += this.SelectedModule_RunSelectedCommand; + this.selectedModule.PropertyChanged += this.SelectedModule_PropertyChanged; + this.selectedModule.SelectedCommand = null; + } + + this.OnNotifyPropertyChanged("SelectedModule"); + } + } + + /// + /// Gets a value indicating whether we can run a command. + /// + public bool CanRun + { + get + { + return this.canRun; + } + } + + /// + /// Gets a value indicating whether we can copy a command. + /// + public bool CanCopy + { + get + { + return this.canCopy; + } + } + + /// + /// Gets the Modules parameter. + /// + public List Modules + { + get { return this.modules; } + } + + /// + /// Gets the visibility of the wait message. + /// + public Visibility WaitMessageVisibility + { + get + { + return this.waitMessageDisplayed ? Visibility.Visible : Visibility.Hidden; + } + } + + /// + /// Gets the visibility of the main grid. + /// + public Visibility MainGridVisibility + { + get + { + return this.waitMessageDisplayed ? Visibility.Hidden : Visibility.Visible; + } + } + + /// + /// Gets a value indicating whether the main grid is displayed. + /// + public bool MainGridDisplayed + { + get + { + return !this.waitMessageDisplayed; + } + } + + /// + /// Gets or sets a value indicating whether the wait message is displayed. + /// + public bool WaitMessageDisplayed + { + get + { + return this.waitMessageDisplayed; + } + + set + { + if (this.waitMessageDisplayed == value) + { + return; + } + + this.waitMessageDisplayed = value; + this.SetCanCopy(); + this.SetCanRun(); + this.OnNotifyPropertyChanged("WaitMessageDisplayed"); + this.OnNotifyPropertyChanged("WaitMessageVisibility"); + this.OnNotifyPropertyChanged("MainGridDisplayed"); + this.OnNotifyPropertyChanged("MainGridVisibility"); + } + } + + /// + /// Gets or sets an extra viewModel object that allows callers to control certain aspects of the GUI. + /// + public object ExtraViewModel + { + get + { + return this.extraViewModel; + } + + set + { + if (this.extraViewModel == value) + { + return; + } + + this.extraViewModel = value; + this.OnNotifyPropertyChanged("ExtraViewModel"); + } + } + #endregion + + /// + /// Returns the selected script. + /// + /// The selected script. + public string GetScript() + { + if (this.SelectedModule == null) + { + return null; + } + + if (this.SelectedModule.SelectedCommand == null) + { + return null; + } + + return this.SelectedModule.SelectedCommand.GetScript(); + } + + /// + /// Triggers Refresh. + /// + internal void OnRefresh() + { + EventHandler handler = this.Refresh; + if (handler != null) + { + handler(this, new EventArgs()); + } + } + + #region Private Methods + /// + /// If current modules name is ALL, then return true. + /// + /// The modules name. + /// Return true is the module name is ALLModulesViewModel. + private static bool IsAll(string name) + { + return name.Equals(ShowCommandResources.All, StringComparison.Ordinal); + } + + /// + /// Monitors property changes in the selected module to call: + /// SetCanRun for IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues + /// SetCanCopy for SetCanCopy + /// + /// Event sender. + /// Event arguments. + private void SelectedModule_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == "IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues") + { + this.SetCanRun(); + } + else if (e.PropertyName == "IsThereASelectedCommand") + { + this.SetCanCopy(); + } + } + + /// + /// Called to set this.CanRun when: + /// The SelectedModule changes, since there will be no selected command in the new module, and CanRun should be false + /// WaitMessageDisplayedMessage changes since this being true will cause this.MainGridDisplayed to be false and CanRun should be false + /// IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues changes in the selected module + /// + private void SetCanRun() + { + bool newValue = this.selectedModule != null && this.MainGridDisplayed && + this.selectedModule.IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues; + + if (this.canRun == newValue) + { + return; + } + + this.canRun = newValue; + this.OnNotifyPropertyChanged("CanRun"); + } + + /// + /// Called to set this.CanCopy when: + /// The SelectedModule changes, since there will be no selected command in the new module, and CanCopy should be false + /// WaitMessageDisplayedMessage changes since this being true will cause this.MainGridDisplayed to be false and CanCopy should be false + /// IsThereASelectedCommand changes in the selected module + /// + private void SetCanCopy() + { + bool newValue = this.selectedModule != null && this.MainGridDisplayed && this.selectedModule.IsThereASelectedCommand; + + if (this.canCopy == newValue) + { + return; + } + + this.canCopy = newValue; + this.OnNotifyPropertyChanged("CanCopy"); + } + + /// + /// Initialize AllModulesViewModel. + /// + /// All loaded modules. + /// List of commands in all modules. + /// Whether showing common parameter. + private void Initialization(Dictionary importedModules, IEnumerable commands, bool noCommonParameterInModel) + { + if (commands == null) + { + return; + } + + Dictionary rawModuleViewModels = new Dictionary(); + + this.noCommonParameter = noCommonParameterInModel; + + // separates commands in their Modules + foreach (ShowCommandCommandInfo command in commands) + { + ModuleViewModel moduleViewModel; + if (!rawModuleViewModels.TryGetValue(command.ModuleName, out moduleViewModel)) + { + moduleViewModel = new ModuleViewModel(command.ModuleName, importedModules); + rawModuleViewModels.Add(command.ModuleName, moduleViewModel); + } + + CommandViewModel commandViewModel; + + try + { + commandViewModel = CommandViewModel.GetCommandViewModel(moduleViewModel, command, noCommonParameterInModel); + } + catch (RuntimeException) + { + continue; + } + + moduleViewModel.Commands.Add(commandViewModel); + moduleViewModel.SetAllModules(this); + } + + // populates this.modules + this.modules = new List(); + + // if there is just one module then use only it + if (rawModuleViewModels.Values.Count == 1) + { + this.modules.Add(rawModuleViewModels.Values.First()); + this.modules[0].SortCommands(false); + this.SelectedModule = this.modules[0]; + return; + } + + // If there are more modules, create an additional module to aggregate all commands + ModuleViewModel allCommandsModule = new ModuleViewModel(ShowCommandResources.All, null); + this.modules.Add(allCommandsModule); + allCommandsModule.SetAllModules(this); + + if (rawModuleViewModels.Values.Count > 0) + { + foreach (ModuleViewModel module in rawModuleViewModels.Values) + { + module.SortCommands(false); + this.modules.Add(module); + + allCommandsModule.Commands.AddRange(module.Commands); + } + } + + allCommandsModule.SortCommands(true); + + this.modules.Sort(this.Compare); + this.SelectedModule = this.modules.Count == 0 ? null : this.modules[0]; + } + + /// + /// Compare two ModuleViewModel target and source. + /// + /// The source ModuleViewModel. + /// The target ModuleViewModel. + /// Compare result. + private int Compare(ModuleViewModel source, ModuleViewModel target) + { + if (AllModulesViewModel.IsAll(source.Name) && !AllModulesViewModel.IsAll(target.Name)) + { + return -1; + } + + if (!AllModulesViewModel.IsAll(source.Name) && AllModulesViewModel.IsAll(target.Name)) + { + return 1; + } + + return string.Compare(source.Name, target.Name, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Called when the SelectedCommandNeedsHelp event is triggered in the Selected Module. + /// + /// Event sender. + /// Event arguments. + private void SelectedModule_SelectedCommandNeedsHelp(object sender, HelpNeededEventArgs e) + { + this.OnSelectedCommandInSelectedModuleNeedsHelp(e); + } + + /// + /// Called when the SelectedCommandNeedsImportModule event is triggered in the Selected Module. + /// + /// Event sender. + /// Event arguments. + private void SelectedModule_SelectedCommandNeedsImportModule(object sender, ImportModuleEventArgs e) + { + this.OnSelectedCommandInSelectedModuleNeedsImportModule(e); + } + + /// + /// Triggers SelectedCommandInSelectedModuleNeedsHelp. + /// + /// Event arguments. + private void OnSelectedCommandInSelectedModuleNeedsHelp(HelpNeededEventArgs e) + { + EventHandler handler = this.SelectedCommandInSelectedModuleNeedsHelp; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Triggers SelectedCommandInSelectedModuleNeedsImportModule. + /// + /// Event arguments. + private void OnSelectedCommandInSelectedModuleNeedsImportModule(ImportModuleEventArgs e) + { + EventHandler handler = this.SelectedCommandInSelectedModuleNeedsImportModule; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Called when the RunSelectedCommand is triggered in the selected module. + /// + /// Event sender. + /// Event arguments. + private void SelectedModule_RunSelectedCommand(object sender, CommandEventArgs e) + { + this.OnRunSelectedCommandInSelectedModule(e); + } + + /// + /// Triggers RunSelectedCommandInSelectedModule. + /// + /// Event arguments. + private void OnRunSelectedCommandInSelectedModule(CommandEventArgs e) + { + EventHandler handler = this.RunSelectedCommandInSelectedModule; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// If property changed will be notify. + /// + /// The changed property. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs new file mode 100644 index 0000000000000000000000000000000000000000..857d466c80f3c6e8325166a4d2e12ddb5a13f656 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Arguments for the event triggered when something happens at the cmdlet level. + /// + public class CommandEventArgs : EventArgs + { + /// + /// the command targeted by the event. + /// + private CommandViewModel command; + + /// + /// Initializes a new instance of the CommandEventArgs class. + /// + /// The command targeted by the event. + public CommandEventArgs(CommandViewModel command) + { + this.command = command; + } + + /// + /// Gets the command targeted by the event. + /// + public CommandViewModel Command + { + get { return this.command; } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs new file mode 100644 index 0000000000000000000000000000000000000000..cfa2798963c0d8c0c2cbee597350e3bb0d5021c0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -0,0 +1,645 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Windows; + +using Microsoft.Management.UI; +using Microsoft.Management.UI.Internal; +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +using SMAI = System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Contains information about a cmdlet's Shard ParameterSet, + /// ParameterSets, Parameters, Common Parameters and error message. + /// + public class CommandViewModel : INotifyPropertyChanged + { + #region Private Fields + /// + /// The name of the AllParameterSets. + /// + private const string SharedParameterSetName = "__AllParameterSets"; + + /// + /// Grid length constant. + /// + private static readonly GridLength star = new GridLength(1, GridUnitType.Star); + + /// + /// The module containing this cmdlet in the gui. + /// + private ModuleViewModel parentModule; + + /// + /// The name of the default ParameterSet. + /// + private string defaultParameterSetName; + + /// + /// Field used for the AreCommonParametersExpanded parameter. + /// + private bool areCommonParametersExpanded; + + /// + /// Field used for the SelectedParameterSet parameter. + /// + private ParameterSetViewModel selectedParameterSet; + + /// + /// Field used for the ParameterSets parameter. + /// + private List parameterSets = new List(); + + /// + /// Field used for the ParameterSetTabControlVisibility parameter. + /// + private bool noCommonParameters; + + /// + /// Field used for the CommonParameters parameter. + /// + private ParameterSetViewModel comonParameters; + + /// + /// The ShowCommandCommandInfo this model is based on. + /// + private ShowCommandCommandInfo commandInfo; + + /// + /// value indicating whether the selected parameter set has all mandatory parameters valid. + /// + private bool selectedParameterSetAllMandatoryParametersHaveValues; + + /// + /// value indicating whether the command name should be qualified by the module in GetScript. + /// + private bool moduleQualifyCommandName; + + /// + /// The height for common parameters that will depend on CommonParameterVisibility. + /// + private GridLength commonParametersHeight; + #endregion + + /// + /// Prevents a default instance of the CommandViewModel class from being created. + /// + private CommandViewModel() + { + } + + #region INotifyPropertyChanged Members + + /// + /// PropertyChanged Event. + /// + public event PropertyChangedEventHandler PropertyChanged; + + #endregion + + /// + /// Indicates the command needs to display the help for a command. + /// + public event EventHandler HelpNeeded; + + /// + /// Indicates a module needs to be imported. + /// + public event EventHandler ImportModule; + + #region Public Properties + /// + /// Gets or sets a value indicating whether the command name should be qualified by the module in GetScript. + /// + public bool ModuleQualifyCommandName + { + get { return this.moduleQualifyCommandName; } + set { this.moduleQualifyCommandName = value; } + } + + /// + /// Gets or sets a value indicating whether the common parameters are expanded. + /// + public bool AreCommonParametersExpanded + { + get + { + return this.areCommonParametersExpanded; + } + + set + { + if (this.areCommonParametersExpanded == value) + { + return; + } + + this.areCommonParametersExpanded = value; + this.OnNotifyPropertyChanged("AreCommonParametersExpanded"); + this.SetCommonParametersHeight(); + } + } + + /// + /// Gets or sets the SelectedParameterSet parameter. + /// + public ParameterSetViewModel SelectedParameterSet + { + get + { + return this.selectedParameterSet; + } + + set + { + if (this.selectedParameterSet != value) + { + if (this.selectedParameterSet != null) + { + this.selectedParameterSet.PropertyChanged -= this.SelectedParameterSet_PropertyChanged; + } + + this.selectedParameterSet = value; + if (this.selectedParameterSet != null) + { + this.selectedParameterSet.PropertyChanged += this.SelectedParameterSet_PropertyChanged; + this.SelectedParameterSetAllMandatoryParametersHaveValues = this.SelectedParameterSet.AllMandatoryParametersHaveValues; + } + else + { + this.SelectedParameterSetAllMandatoryParametersHaveValues = true; + } + + this.OnNotifyPropertyChanged("SelectedParameterSet"); + } + } + } + + /// + /// Gets or sets a value indicating whether the selected parameter set has all mandatory parameters valid. + /// If there is no selected parameter set this value is true + /// + public bool SelectedParameterSetAllMandatoryParametersHaveValues + { + get + { + return this.selectedParameterSetAllMandatoryParametersHaveValues; + } + + set + { + if (this.selectedParameterSetAllMandatoryParametersHaveValues == value) + { + return; + } + + this.selectedParameterSetAllMandatoryParametersHaveValues = value; + this.OnNotifyPropertyChanged("SelectedParameterSetAllMandatoryParametersHaveValues"); + } + } + + /// + /// Gets the ParameterSets parameter. + /// + public List ParameterSets + { + get { return this.parameterSets; } + } + + /// + /// Gets the visibility for the tab control displaying several ParameterSetControl. This is displayed when there are more than 1 parameter sets. + /// + public Visibility ParameterSetTabControlVisibility + { + get { return (this.ParameterSets.Count > 1) && this.IsImported ? Visibility.Visible : Visibility.Collapsed; } + } + + /// + /// Gets the visibility for the single ParameterSetControl displayed when there is only 1 parameter set. + /// + public Visibility SingleParameterSetControlVisibility + { + get { return (this.ParameterSets.Count == 1) ? Visibility.Visible : Visibility.Collapsed; } + } + + /// + /// Gets the CommonParameters parameter. + /// + public ParameterSetViewModel CommonParameters + { + get { return this.comonParameters; } + } + + /// + /// Gets the CommonParameterVisibility parameter. + /// + public Visibility CommonParameterVisibility + { + get { return this.noCommonParameters || (this.CommonParameters.Parameters.Count == 0) ? Visibility.Collapsed : Visibility.Visible; } + } + + /// + /// Gets or sets the height for common parameters that will depend on CommonParameterVisibility. + /// + public GridLength CommonParametersHeight + { + get + { + return this.commonParametersHeight; + } + + set + { + if (this.commonParametersHeight == value) + { + return; + } + + this.commonParametersHeight = value; + this.OnNotifyPropertyChanged("CommonParametersHeight"); + } + } + + /// + /// Gets the visibility for the control displayed when the module is not imported. + /// + public Visibility NotImportedVisibility + { + get + { + return this.IsImported ? Visibility.Collapsed : Visibility.Visible; + } + } + + /// + /// Gets the visibility for the control displayed when there are no parameters. + /// + public Visibility NoParameterVisibility + { + get + { + bool hasNoParameters = this.ParameterSets.Count == 0 || (this.ParameterSets.Count == 1 && this.ParameterSets[0].Parameters.Count == 0); + return this.IsImported && hasNoParameters ? Visibility.Visible : Visibility.Collapsed; + } + } + + /// + /// Gets a value indicating whether the cmdlet comes from a module which is imported. + /// + public bool IsImported + { + get + { + return this.commandInfo.Module == null || this.ParentModule.IsModuleImported; + } + } + + /// + /// Gets the Name parameter. + /// + public string Name + { + get + { + if (this.commandInfo != null) + { + return this.commandInfo.Name; + } + + return string.Empty; + } + } + + /// + /// Gets the module path if it is not null or empty, or the name otherwise. + /// + public string ModuleName + { + get + { + if (this.commandInfo != null && this.commandInfo.ModuleName != null) + { + return this.commandInfo.ModuleName; + } + + return string.Empty; + } + } + + /// + /// Gets the module containing this cmdlet in the GUI. + /// + public ModuleViewModel ParentModule + { + get + { + return this.parentModule; + } + } + + /// + /// Gets Tooltip string for the cmdlet. + /// + public string ToolTip + { + get + { + return string.Format( + CultureInfo.CurrentCulture, + ShowCommandResources.CmdletTooltipFormat, + this.Name, + this.ParentModule.DisplayName, + this.IsImported ? ShowCommandResources.Imported : ShowCommandResources.NotImported); + } + } + + /// + /// Gets the message to be displayed when the cmdlet belongs to a module that is not imported. + /// + public string ImportModuleMessage + { + get + { + return string.Format( + CultureInfo.CurrentCulture, + ShowCommandResources.NotImportedFormat, + this.ModuleName, + this.Name, + ShowCommandResources.ImportModuleButtonText); + } + } + + /// + /// Gets the title for the cmdlet details. + /// + public string DetailsTitle + { + get + { + if (this.IsImported) + { + return string.Format( + CultureInfo.CurrentCulture, + ShowCommandResources.DetailsParameterTitleFormat, + this.Name); + } + else + { + return string.Format( + CultureInfo.CurrentCulture, + ShowCommandResources.NameLabelFormat, + this.Name); + } + } + } + #endregion + + /// + /// Gets a Grid length constant. + /// + internal static GridLength Star + { + get { return CommandViewModel.star; } + } + + /// + /// Gets the builded PowerShell script. + /// + /// Return script as string. + public string GetScript() + { + StringBuilder builder = new StringBuilder(); + + string commandName = this.commandInfo.CommandType == CommandTypes.ExternalScript ? this.commandInfo.Definition : this.Name; + + if (this.ModuleQualifyCommandName && !string.IsNullOrEmpty(this.ModuleName)) + { + commandName = this.ModuleName + "\\" + commandName; + } + + if (commandName.Contains(' ')) + { + builder.Append($"& \"{commandName}\""); + } + else + { + builder.Append(commandName); + } + + builder.Append(' '); + + if (this.SelectedParameterSet != null) + { + builder.Append(this.SelectedParameterSet.GetScript()); + builder.Append(' '); + } + + if (this.CommonParameters != null) + { + builder.Append(this.CommonParameters.GetScript()); + } + + string script = builder.ToString(); + + return script.Trim(); + } + + /// + /// Showing help information for current active cmdlet. + /// + public void OpenHelpWindow() + { + this.OnHelpNeeded(); + } + + /// + /// Determines whether current command name and a specified ParameterSetName have same name. + /// + /// The name of ShareParameterSet. + /// Return true is ShareParameterSet. Else return false. + internal static bool IsSharedParameterSetName(string name) + { + return name.Equals(CommandViewModel.SharedParameterSetName, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Creates a new CommandViewModel out the . + /// + /// Module to which the CommandViewModel will belong to. + /// Will showing command. + /// True to ommit displaying common parameter. + /// If commandInfo is null + /// + /// If could not create the CommandViewModel. For instance the ShowCommandCommandInfo corresponding to + /// the following function will throw a RuntimeException when the ShowCommandCommandInfo Parameters + /// are retrieved: + /// function CrashMe ([I.Am.A.Type.That.Does.Not.Exist]$name) {} + /// + /// The CommandViewModel corresponding to commandInfo. + internal static CommandViewModel GetCommandViewModel(ModuleViewModel module, ShowCommandCommandInfo commandInfo, bool noCommonParameters) + { + ArgumentNullException.ThrowIfNull(commandInfo); + + CommandViewModel returnValue = new CommandViewModel(); + returnValue.commandInfo = commandInfo; + returnValue.noCommonParameters = noCommonParameters; + returnValue.parentModule = module; + + Dictionary commonParametersTable = new Dictionary(); + + foreach (ShowCommandParameterSetInfo parameterSetInfo in commandInfo.ParameterSets) + { + if (parameterSetInfo.IsDefault) + { + returnValue.defaultParameterSetName = parameterSetInfo.Name; + } + + List parametersForParameterSet = new List(); + foreach (ShowCommandParameterInfo parameterInfo in parameterSetInfo.Parameters) + { + bool isCommon = Cmdlet.CommonParameters.Contains(parameterInfo.Name); + + if (isCommon) + { + if (!commonParametersTable.ContainsKey(parameterInfo.Name)) + { + commonParametersTable.Add(parameterInfo.Name, new ParameterViewModel(parameterInfo, parameterSetInfo.Name)); + } + + continue; + } + + parametersForParameterSet.Add(new ParameterViewModel(parameterInfo, parameterSetInfo.Name)); + } + + if (parametersForParameterSet.Count != 0) + { + returnValue.ParameterSets.Add(new ParameterSetViewModel(parameterSetInfo.Name, parametersForParameterSet)); + } + } + + List commonParametersList = commonParametersTable.Values.ToList(); + returnValue.comonParameters = new ParameterSetViewModel(string.Empty, commonParametersList); + + returnValue.parameterSets.Sort(returnValue.Compare); + + if (returnValue.parameterSets.Count > 0) + { + // Setting SelectedParameterSet will also set SelectedParameterSetAllMandatoryParametersHaveValues + returnValue.SelectedParameterSet = returnValue.ParameterSets[0]; + } + else + { + returnValue.SelectedParameterSetAllMandatoryParametersHaveValues = true; + } + + returnValue.SetCommonParametersHeight(); + + return returnValue; + } + + /// + /// Called to trigger the event fired when help is needed for the command. + /// + internal void OnHelpNeeded() + { + EventHandler handler = this.HelpNeeded; + if (handler != null) + { + handler(this, new HelpNeededEventArgs(this.Name)); + } + } + + /// + /// Called to trigger the event fired when a module needs to be imported. + /// + internal void OnImportModule() + { + EventHandler handler = this.ImportModule; + if (handler != null) + { + handler(this, new EventArgs()); + } + } + + #region Private Methods + /// + /// Called to set the height for common parameters initially or when the AreCommonParametersExpanded changes. + /// + private void SetCommonParametersHeight() + { + this.CommonParametersHeight = this.AreCommonParametersExpanded ? CommandViewModel.Star : GridLength.Auto; + } + + /// + /// Compares source and target by being the default parameter set and then by name. + /// + /// Source paremeterset. + /// Target parameterset. + /// 0 if they are the same, -1 if source is smaller, 1 if source is larger. + private int Compare(ParameterSetViewModel source, ParameterSetViewModel target) + { + if (this.defaultParameterSetName != null) + { + if (source.Name.Equals(this.defaultParameterSetName) && target.Name.Equals(this.defaultParameterSetName)) + { + return 0; + } + + if (source.Name.Equals(this.defaultParameterSetName, StringComparison.Ordinal)) + { + return -1; + } + + if (target.Name.Equals(this.defaultParameterSetName, StringComparison.Ordinal)) + { + return 1; + } + } + + return string.CompareOrdinal(source.Name, target.Name); + } + + /// + /// If property changed will be notify. + /// + /// The changed property. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + + /// + /// Called when the PropertyChanged event is triggered on the SelectedParameterSet. + /// + /// Event sender. + /// Event arguments. + private void SelectedParameterSet_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (!e.PropertyName.Equals("AllMandatoryParametersHaveValues")) + { + return; + } + + this.SelectedParameterSetAllMandatoryParametersHaveValues = this.SelectedParameterSet.AllMandatoryParametersHaveValues; + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs new file mode 100644 index 0000000000000000000000000000000000000000..3d4c42a6cbeaa30fbdc2ff9535a5920d55c8d8c9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Arguments for the event triggered when it is necessary to display help for a command. + /// + public class HelpNeededEventArgs : EventArgs + { + /// + /// the name for the command needing help. + /// + private string commandName; + + /// + /// Initializes a new instance of the HelpNeededEventArgs class. + /// + /// The name for the command needing help. + public HelpNeededEventArgs(string commandName) + { + this.commandName = commandName; + } + + /// + /// Gets the name for the command needing help. + /// + public string CommandName + { + get { return this.commandName; } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs new file mode 100644 index 0000000000000000000000000000000000000000..3d7a7ccf3f0ddf00381a4edf7bd67f037d263e59 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Arguments for the event triggered when it is necessary to display help for a command. + /// + public class ImportModuleEventArgs : EventArgs + { + /// + /// the name for the command belonging to the module to be imported. + /// + private string commandName; + + /// + /// the module path or name for the module we want to import. + /// + private string parentModuleName; + + /// + /// the name of the module that is selected, which can be different from parentModuleName + /// if "All" is selected + /// + private string selectedModuleName; + + /// + /// Initializes a new instance of the ImportModuleEventArgs class. + /// + /// The name for the command needing help. + /// The name of the module containing the command. + /// + /// the name of the module that is selected, which can be different from parentModuleName + /// if "All" is selected + /// + public ImportModuleEventArgs(string commandName, string parentModuleName, string selectedModuleName) + { + this.commandName = commandName; + this.parentModuleName = parentModuleName; + this.selectedModuleName = selectedModuleName; + } + + /// + /// Gets the name for the command belonging to the module to be imported. + /// + public string CommandName + { + get { return this.commandName; } + } + + /// + /// Gets the module path or name for the module we want to import. + /// + public string ParentModuleName + { + get { return this.parentModuleName; } + } + + /// + /// Gets the name of the module that is selected, which can be different from parentModuleName + /// if "All" is selected + /// + public string SelectedModuleName + { + get { return this.selectedModuleName; } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs new file mode 100644 index 0000000000000000000000000000000000000000..950dbe93758a9e849c92498fc356033b9372249e --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -0,0 +1,528 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Management.Automation; +using System.Windows; + +using Microsoft.Management.UI.Internal; +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// ModuleViewModel Contains information about a PowerShell module. + /// + public class ModuleViewModel : INotifyPropertyChanged + { + /// + /// True if the module is imported. + /// + private bool isModuleImported; + + /// + /// Field used for the Name parameter. + /// + private string name; + + /// + /// Filter commands property of this module. + /// + private ObservableCollection filteredCommands; + + /// + /// The selected command property of this module. + /// + private CommandViewModel selectedCommand; + + /// + /// Field used for the Commands parameter. + /// + private List commands; + + /// + /// value indicating whether there is a selected command which belongs to an imported module, + /// with no parameter sets or with a selected parameter set where all mandatory parameters have values + /// + private bool isThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues; + + /// + /// value indicating whether there is a selected command. + /// + private bool isThereASelectedCommand; + + /// + /// The AllModulesViewModel containing this, if any. + /// + private AllModulesViewModel allModules; + + #region Construction and Destructor + /// + /// Initializes a new instance of the ModuleViewModel class. + /// + /// Module name. + /// All loaded modules. + public ModuleViewModel(string name, Dictionary importedModules) + { + ArgumentNullException.ThrowIfNull(name); + + this.name = name; + this.commands = new List(); + this.filteredCommands = new ObservableCollection(); + + // This check looks to see if the given module name shows up in + // the set of modules that are known to be imported in the current + // session. In remote PowerShell sessions, the core cmdlet module + // Microsoft.PowerShell.Core doesn't appear as being imported despite + // always being loaded by default. To make sure we don't incorrectly + // mark this module as not imported, check for it by name. + this.isModuleImported = + importedModules == null ? true : name.Length == 0 || + importedModules.ContainsKey(name) || + string.Equals("Microsoft.PowerShell.Core", name, StringComparison.OrdinalIgnoreCase); + } + #endregion + + #region INotifyPropertyChanged Members + + /// + /// PropertyChanged Event. + /// + public event PropertyChangedEventHandler PropertyChanged; + #endregion + + /// + /// Indicates the selected command in needs to display the help for a command. + /// + public event EventHandler SelectedCommandNeedsHelp; + + /// + /// Indicates the selected command needs to import a module. + /// + public event EventHandler SelectedCommandNeedsImportModule; + + /// + /// Indicates the selected command should be run. + /// + public event EventHandler RunSelectedCommand; + + #region Public Property + /// + /// Gets the name property of this ModuleView. + /// + public string Name + { + get { return this.name; } + } + + /// + /// Gets the GUI friendly module name. + /// + public string DisplayName + { + get + { + if (!string.IsNullOrEmpty(this.name)) + { + return this.name; + } + + return ShowCommandResources.NoModuleName; + } + } + + /// + /// Gets CommandControl is visibility or not. + /// + public Visibility CommandControlVisibility + { + get { return this.selectedCommand == null ? Visibility.Collapsed : Visibility.Visible; } + } + + /// + /// Gets CommandControl Height. + /// + public GridLength CommandRowHeight + { + get { return this.selectedCommand == null ? GridLength.Auto : CommandViewModel.Star; } + } + + /// + /// Gets the commands under in this module. + /// + public List Commands + { + get { return this.commands; } + } + + /// + /// Gets the filter commands of this module. + /// + public ObservableCollection FilteredCommands + { + get { return this.filteredCommands; } + } + + /// + /// Gets or sets the selected commands of this module. + /// + public CommandViewModel SelectedCommand + { + get + { + return this.selectedCommand; + } + + set + { + if (value == this.selectedCommand) + { + return; + } + + if (this.selectedCommand != null) + { + this.selectedCommand.PropertyChanged -= this.SelectedCommand_PropertyChanged; + this.selectedCommand.HelpNeeded -= this.SelectedCommand_HelpNeeded; + this.selectedCommand.ImportModule -= this.SelectedCommand_ImportModule; + } + + this.selectedCommand = value; + + this.SetIsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues(); + + if (this.selectedCommand != null) + { + this.selectedCommand.PropertyChanged += this.SelectedCommand_PropertyChanged; + this.selectedCommand.HelpNeeded += this.SelectedCommand_HelpNeeded; + this.selectedCommand.ImportModule += this.SelectedCommand_ImportModule; + this.IsThereASelectedCommand = true; + } + else + { + this.IsThereASelectedCommand = false; + } + + this.OnNotifyPropertyChanged("SelectedCommand"); + this.OnNotifyPropertyChanged("CommandControlVisibility"); + this.OnNotifyPropertyChanged("CommandRowHeight"); + } + } + + /// + /// Gets or sets a value indicating whether there is a selected command. + /// + public bool IsThereASelectedCommand + { + get + { + return this.isThereASelectedCommand; + } + + set + { + if (value == this.isThereASelectedCommand) + { + return; + } + + this.isThereASelectedCommand = value; + this.OnNotifyPropertyChanged("IsThereASelectedCommand"); + } + } + + /// + /// Gets or sets a value indicating whether there is a selected command which belongs + /// to an imported module, with no parameter sets or with a selected parameter set + /// where all mandatory parameters have values + /// + public bool IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues + { + get + { + return this.isThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues; + } + + set + { + if (value == this.isThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues) + { + return; + } + + this.isThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues = value; + + this.OnNotifyPropertyChanged("IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues"); + } + } + + /// + /// Gets the AllModulesViewModel containing this, if any. + /// + public AllModulesViewModel AllModules + { + get + { + return this.allModules; + } + } + #endregion + + /// + /// Gets a value indicating whether the module is imported. + /// + internal bool IsModuleImported + { + get + { + return this.isModuleImported; + } + } + + /// + /// Sets the AllModulesViewModel containing this. + /// + /// The AllModulesViewModel containing this. + internal void SetAllModules(AllModulesViewModel parentAllModules) + { + this.allModules = parentAllModules; + } + + /// + /// Sorts commands and optionally sets ModuleQualifyCommandName. + /// + /// True to mark repeated commands with a flag that will produce a module qualified name in GetScript. + internal void SortCommands(bool markRepeatedCmdlets) + { + this.commands.Sort(this.Compare); + + if (!markRepeatedCmdlets || this.commands.Count == 0) + { + return; + } + + CommandViewModel reference = this.commands[0]; + for (int i = 1; i < this.commands.Count; i++) + { + CommandViewModel command = this.commands[i]; + if (reference.Name.Equals(command.Name, StringComparison.OrdinalIgnoreCase)) + { + reference.ModuleQualifyCommandName = true; + command.ModuleQualifyCommandName = true; + } + else + { + reference = command; + } + } + } + + /// + /// According commandNameFilter to filter command,and added the filter commands into filteredCommands property. + /// + /// Current filter. + internal void RefreshFilteredCommands(string filter) + { + this.filteredCommands.Clear(); + if (string.IsNullOrEmpty(filter)) + { + foreach (CommandViewModel command in this.Commands) + { + this.filteredCommands.Add(command); + } + + return; + } + + WildcardPattern filterPattern = null; + if (WildcardPattern.ContainsWildcardCharacters(filter)) + { + filterPattern = new WildcardPattern(filter, WildcardOptions.IgnoreCase); + } + + foreach (CommandViewModel command in this.Commands) + { + if (ModuleViewModel.Matches(filterPattern, command.Name, filter)) + { + this.filteredCommands.Add(command); + continue; + } + + if (filterPattern != null) + { + continue; + } + + string[] textSplit = filter.Split(' '); + if (textSplit.Length != 2) + { + continue; + } + + if (ModuleViewModel.Matches(filterPattern, command.Name, textSplit[0] + "-" + textSplit[1])) + { + this.filteredCommands.Add(command); + } + } + } + + /// + /// Called in response to a GUI event that requires the command to be run. + /// + internal void OnRunSelectedCommand() + { + EventHandler handler = this.RunSelectedCommand; + if (handler != null) + { + handler(this, new CommandEventArgs(this.SelectedCommand)); + } + } + + /// + /// Triggers the SelectedCommandNeedsHelp event. + /// + /// Event arguments. + internal void OnSelectedCommandNeedsHelp(HelpNeededEventArgs e) + { + EventHandler handler = this.SelectedCommandNeedsHelp; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Triggers the SelectedCommandNeedsImportModule event. + /// + internal void OnSelectedCommandNeedsImportModule() + { + EventHandler handler = this.SelectedCommandNeedsImportModule; + if (handler != null) + { + handler(this, new ImportModuleEventArgs(this.SelectedCommand.Name, this.SelectedCommand.ModuleName, this.Name)); + } + } + #region Private Method + + /// + /// Uses pattern matching if pattern is not null or calls MatchesEvenIfInPlural otherwise. + /// + /// Pattern corresponding to filter. + /// Command name string. + /// Filter string. + /// True if coparisonText matches str or pattern. + private static bool Matches(WildcardPattern filterPattern, string commandName, string filter) + { + if (filterPattern != null) + { + return filterPattern.IsMatch(commandName); + } + + return ModuleViewModel.MatchesEvenIfInPlural(commandName, filter); + } + + /// + /// Returns true if filter matches commandName, even when filter is in the plural. + /// + /// Command name string. + /// Filter string. + /// Return match result. + private static bool MatchesEvenIfInPlural(string commandName, string filter) + { + if (commandName.Contains(filter, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (filter.Length > 5 && filter.EndsWith("es", StringComparison.OrdinalIgnoreCase)) + { + ReadOnlySpan filterSpan = filter.AsSpan(0, filter.Length - 2); + return commandName.AsSpan().Contains(filterSpan, StringComparison.OrdinalIgnoreCase); + } + + if (filter.Length > 4 && filter.EndsWith("s", StringComparison.OrdinalIgnoreCase)) + { + ReadOnlySpan filterSpan = filter.AsSpan(0, filter.Length - 1); + return commandName.AsSpan().Contains(filterSpan, StringComparison.OrdinalIgnoreCase); + } + + return false; + } + + /// + /// Handles the HelpNeeded event in the selected command and triggers the SelectedCommandNeedsHelp event. + /// + /// HelpNeeded event sender. + /// HelpNeeded event argument. + private void SelectedCommand_HelpNeeded(object sender, HelpNeededEventArgs e) + { + this.OnSelectedCommandNeedsHelp(e); + } + + /// + /// Handles the ImportModule event in the selected command and triggers the SelectedCommandNeedsImportModule event. + /// + /// HelpNeeded event sender. + /// HelpNeeded event argument. + private void SelectedCommand_ImportModule(object sender, EventArgs e) + { + this.OnSelectedCommandNeedsImportModule(); + } + + /// + /// Called when the SelectedCommand property changes to update IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues. + /// + /// Event sender. + /// Event arguments. + private void SelectedCommand_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (!e.PropertyName.Equals("SelectedParameterSetAllMandatoryParametersHaveValues")) + { + return; + } + + this.SetIsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues(); + } + + /// + /// Called to set IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues when + /// SelectedParameterSetAllMandatoryParametersHaveValues changes in the SelectedCommand or + /// when the SelectedCommand changes + /// + private void SetIsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues() + { + this.IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues = + this.selectedCommand != null && + this.selectedCommand.IsImported && + this.selectedCommand.SelectedParameterSetAllMandatoryParametersHaveValues; + } + + /// + /// Compare source commandmodule is equal like target commandmodule. + /// + /// Source commandmodule. + /// Target commandmodule. + /// Return compare result. + private int Compare(CommandViewModel source, CommandViewModel target) + { + return string.Compare(source.Name, target.Name, StringComparison.OrdinalIgnoreCase); + } + #endregion + + /// + /// If property changed will be notify. + /// + /// The changed property. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs new file mode 100644 index 0000000000000000000000000000000000000000..b4f42dd78a2736a04f2d2d131645f7ce25855442 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -0,0 +1,388 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Language; +using System.Text; + +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Contains information about a single ParameterSet inside a cmdlet. + /// + public class ParameterSetViewModel : INotifyPropertyChanged + { + /// + /// Field used for the Name parameter. + /// + private string name; + + /// + /// value indicating all mandatory parameters have values. + /// + private bool allMandatoryParametersHaveValues; + + /// + /// Field used for the Parameters parameter. + /// + private List parameters; + + #region Construction and Destructor + + /// + /// Initializes a new instance of the ParameterSetViewModel class. + /// + /// The name of the parameterSet. + /// The array parameters of the parameterSet. + [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "this type is internal, made public only for WPF Binding")] + public ParameterSetViewModel( + string name, + List parameters) + { + ArgumentNullException.ThrowIfNull(name); + + ArgumentNullException.ThrowIfNull(parameters); + + parameters.Sort(Compare); + + this.name = name; + this.parameters = parameters; + foreach (ParameterViewModel parameter in this.parameters) + { + if (!parameter.IsMandatory) + { + continue; + } + + parameter.PropertyChanged += this.MandatoryParameter_PropertyChanged; + } + + this.EvaluateAllMandatoryParametersHaveValues(); + } + #endregion + + #region INotifyPropertyChanged Members + + /// + /// PropertyChanged Event. + /// + public event PropertyChangedEventHandler PropertyChanged; + + #endregion + + #region Public Property + /// + /// Gets the ParameterSet Name. + /// + public string Name + { + get { return this.name; } + } + + /// + /// Gets the Parameters of this parameterset. + /// + public List Parameters + { + get { return this.parameters; } + } + + /// + /// Gets or sets a value indicating whether all mandatory parameters have values. + /// + public bool AllMandatoryParametersHaveValues + { + get + { + return this.allMandatoryParametersHaveValues; + } + + set + { + if (this.allMandatoryParametersHaveValues != value) + { + this.allMandatoryParametersHaveValues = value; + this.OnNotifyPropertyChanged("AllMandatoryParametersHaveValues"); + } + } + } + #endregion + + #region Public Method + /// + /// Creates script according parameters of this parameterset. + /// + /// Return script of this parameterset parameters. + public string GetScript() + { + if (this.Parameters == null || this.Parameters.Count == 0) + { + return string.Empty; + } + + StringBuilder builder = new StringBuilder(); + foreach (ParameterViewModel parameter in this.Parameters) + { + if (parameter.Value == null) + { + continue; + } + + if (parameter.Parameter.ParameterType.IsSwitch) + { + if (((bool?)parameter.Value) == true) + { + builder.Append($"-{parameter.Name} "); + } + + continue; + } + + string parameterValueString = parameter.Value.ToString(); + + if (parameterValueString.Length == 0) + { + continue; + } + + ShowCommandParameterType parameterType = parameter.Parameter.ParameterType; + + if (parameterType.IsEnum || parameterType.IsString || (parameterType.IsArray && parameterType.ElementType.IsString)) + { + parameterValueString = ParameterSetViewModel.GetDelimitedParameter(parameterValueString, "\"", "\""); + } + else if (parameterType.IsScriptBlock) + { + parameterValueString = ParameterSetViewModel.GetDelimitedParameter(parameterValueString, "{", "}"); + } + else + { + parameterValueString = ParameterSetViewModel.GetDelimitedParameter(parameterValueString, "(", ")"); + } + + builder.Append($"-{parameter.Name} {parameterValueString} "); + } + + return builder.ToString().Trim(); + } + + /// + /// Gets the individual parameter count of this parameterset. + /// + /// Return individual parameter count of this parameterset. + public int GetIndividualParameterCount() + { + if (this.Parameters == null || this.Parameters.Count == 0) + { + return 0; + } + + int i = 0; + + foreach (ParameterViewModel p in this.Parameters) + { + if (p.IsInSharedParameterSet) + { + return i; + } + + i++; + } + + return i; + } + + #endregion + + #region Internal Method + + /// + /// Compare source parametermodel is equal like target parametermodel. + /// + /// The source of parametermodel. + /// The target of parametermodel. + /// Return compare result. + internal static int Compare(ParameterViewModel source, ParameterViewModel target) + { + if (source.Parameter.IsMandatory && !target.Parameter.IsMandatory) + { + return -1; + } + + if (!source.Parameter.IsMandatory && target.Parameter.IsMandatory) + { + return 1; + } + + return string.Compare(source.Parameter.Name, target.Parameter.Name); + } + + #endregion + + /// + /// Gets the delimited parameter if it needs delimitation and is not delimited. + /// + /// Value needing delimitation. + /// Open delimitation. + /// Close delimitation. + /// The delimited parameter if it needs delimitation and is not delimited. + private static string GetDelimitedParameter(string parameterValue, string openDelimiter, string closeDelimiter) + { + string parameterValueTrimmed = parameterValue.Trim(); + + if (parameterValueTrimmed.Length == 0) + { + return openDelimiter + parameterValue + closeDelimiter; + } + + char delimitationChar = ParameterSetViewModel.ParameterNeedsDelimitation(parameterValueTrimmed, openDelimiter.Length == 1 && openDelimiter[0] == '{'); + switch (delimitationChar) + { + case '1': + return openDelimiter + parameterValue + closeDelimiter; + case '\'': + return '\'' + parameterValue + '\''; + case '\"': + return '\"' + parameterValue + '\"'; + default: + return parameterValueTrimmed; + } + } + + /// + /// Returns '0' if the does not need delimitation, '1' if it does, and a quote character if it needs to be delimited with a quote. + /// + /// Parameter value to check. + /// True if the parameter value should be a scriptblock. + /// '0' if the parameter does not need delimitation, '1' if it needs, '\'' if it needs to be delimited with single quote and '\"' if it needs to be delimited with double quotes. + private static char ParameterNeedsDelimitation(string parameterValue, bool requireScriptblock) + { + Token[] tokens; + ParseError[] errors; + ScriptBlockAst values = Parser.ParseInput("commandName -parameterName " + parameterValue, out tokens, out errors); + + if (values == null || values.EndBlock == null || values.EndBlock.Statements.Count == 0) + { + return '1'; + } + + PipelineAst pipeline = values.EndBlock.Statements[0] as PipelineAst; + if (pipeline == null || pipeline.PipelineElements.Count == 0) + { + return '1'; + } + + CommandAst commandAst = pipeline.PipelineElements[0] as CommandAst; + + if (commandAst == null || commandAst.CommandElements.Count == 0) + { + return '1'; + } + + // 3 is for CommandName, Parameter and its value + if (commandAst.CommandElements.Count != 3) + { + return '1'; + } + + if (requireScriptblock) + { + ScriptBlockExpressionAst scriptAst = commandAst.CommandElements[2] as ScriptBlockExpressionAst; + return scriptAst == null ? '1' : '0'; + } + + StringConstantExpressionAst stringValue = commandAst.CommandElements[2] as StringConstantExpressionAst; + if (stringValue != null) + { + if (errors.Length == 0) + { + return '0'; + } + + char stringTerminationChar; + + if (stringValue.StringConstantType == StringConstantType.BareWord) + { + stringTerminationChar = parameterValue[0]; + } + else if (stringValue.StringConstantType == StringConstantType.DoubleQuoted || stringValue.StringConstantType == StringConstantType.DoubleQuotedHereString) + { + stringTerminationChar = '\"'; + } + else + { + stringTerminationChar = '\''; + } + + char oppositeTerminationChar = stringTerminationChar == '\"' ? '\'' : '\"'; + + // If the string is not terminated, it should be delimited by the opposite string termination character + return oppositeTerminationChar; + } + + if (errors.Length != 0) + { + return '1'; + } + + return '0'; + } + + /// + /// Called to evaluate the value of AllMandatoryParametersHaveValues. + /// + private void EvaluateAllMandatoryParametersHaveValues() + { + bool newCanRun = true; + foreach (ParameterViewModel parameter in this.parameters) + { + if (!parameter.IsMandatory) + { + continue; + } + + if (!parameter.HasValue) + { + newCanRun = false; + break; + } + } + + this.AllMandatoryParametersHaveValues = newCanRun; + } + + /// + /// If property changed will be notify. + /// + /// The changed property. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + + /// + /// Used to track changes to parameter values in order to verify the enabled state of buttons. + /// + /// Event arguments. + /// Event sender. + private void MandatoryParameter_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (!e.PropertyName.Equals("Value", StringComparison.Ordinal)) + { + return; + } + + this.EvaluateAllMandatoryParametersHaveValues(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs new file mode 100644 index 0000000000000000000000000000000000000000..93227df87a115898bcf630c87e887e2ac7cca6f7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -0,0 +1,272 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.ComponentModel; +using System.Globalization; +using System.Management.Automation; +using System.Text; + +using Microsoft.Management.UI.Internal; +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Contains information about a single parameter inside a parameter set. + /// If a parameter with the same name belongs to two (or more) parameter sets, + /// there will be two (or more) ParameterViewModel objects for the parameters, + /// each one inside its own ParameterSetViewModel. + /// + public class ParameterViewModel : INotifyPropertyChanged + { + /// + /// ParameterMetadata contains information that is the same throughout parameter sets + /// like Name and Type. + /// Note: It also happens to contain a list of all ParameterSetMetadata for the parametersets + /// in this cmdlet, but this information is not used in this class since if a parameter is + /// in multiple parametersets, there will be a ParameterViewModel for each time the parameter + /// appears in a parameterset. + /// + private ShowCommandParameterInfo parameter; + + /// + /// value entered in the GUI for the parameter. + /// + private object parameterValue; + + /// + /// Name of the parameter set this parameter is in. + /// + private string parameterSetName; + + #region Construction and Destructor + /// + /// Initializes a new instance of the ParameterViewModel class. + /// + /// The parameter information for this parameter. + /// The name of the parameter set this parameter is in. + public ParameterViewModel(ShowCommandParameterInfo parameter, string parameterSetName) + { + ArgumentNullException.ThrowIfNull(parameter); + + ArgumentNullException.ThrowIfNull(parameterSetName); + + this.parameter = parameter; + this.parameterSetName = parameterSetName; + + if (this.parameter.ParameterType.IsSwitch) + { + this.parameterValue = false; + } + else + { + this.parameterValue = string.Empty; + } + } + #endregion + + #region INotifyPropertyChanged Members + + /// + /// PropertyChanged Event. + /// + public event PropertyChangedEventHandler PropertyChanged; + + #endregion + + #region Properties + /// + /// Gets the ParameterMetadata that contains information that is the same throughout parameter sets + /// like Name and Type. + /// + public ShowCommandParameterInfo Parameter + { + get { return this.parameter; } + } + + /// + /// Gets or sets the value for this parameter from the GUI. + /// + public object Value + { + get + { + return this.parameterValue; + } + + set + { + if (this.parameterValue != value) + { + this.parameterValue = value; + this.OnNotifyPropertyChanged("Value"); + } + } + } + + /// + /// Gets the parameter name. + /// + public string Name + { + get { return this.Parameter.Name; } + } + + /// + /// Gets the name of the parameter set this parameter is in. + /// + public string ParameterSetName + { + get { return this.parameterSetName; } + } + + /// + /// Gets a value indicating whether this parameter is in the shared parameterset. + /// + public bool IsInSharedParameterSet + { + get { return CommandViewModel.IsSharedParameterSetName(this.parameterSetName); } + } + + /// + /// Gets Name with an extra suffix to indicate if the parameter is mandatory to serve. + /// + public string NameTextLabel + { + get + { + return this.Parameter.IsMandatory ? + string.Format( + CultureInfo.CurrentUICulture, + ShowCommandResources.MandatoryNameLabelFormat, + this.Name, + ShowCommandResources.MandatoryLabelSegment) : + string.Format( + CultureInfo.CurrentUICulture, + ShowCommandResources.NameLabelFormat, + this.Name); + } + } + + /// + /// Gets Label in the case this parameter is used in a combo box. + /// + public string NameCheckLabel + { + get + { + string returnValue = this.Parameter.Name; + if (this.Parameter.IsMandatory) + { + returnValue = string.Create(CultureInfo.CurrentUICulture, $"{returnValue}{ShowCommandResources.MandatoryLabelSegment}"); + } + + return returnValue; + } + } + + /// + /// Gets Tooltip string for the parameter. + /// + public string ToolTip + { + get + { + return ParameterViewModel.EvaluateTooltip( + this.Parameter.ParameterType.FullName, + this.Parameter.Position, + this.Parameter.IsMandatory, + this.IsInSharedParameterSet, + this.Parameter.ValueFromPipeline); + } + } + + /// + /// Gets a value indicating whether the parameter is mandatory. + /// + public bool IsMandatory + { + get { return this.Parameter.IsMandatory; } + } + + /// + /// Gets a value indicating whether the parameter has a value. + /// + public bool HasValue + { + get + { + if (this.Value == null) + { + return false; + } + + if (this.Parameter.ParameterType.IsSwitch) + { + return ((bool?)this.Value) == true; + } + + return this.Value.ToString().Length != 0; + } + } + #endregion + + /// + /// Evaluates the tooltip based on the parameters. + /// + /// Parameter type name. + /// Parameter position. + /// True if the parameter is mandatory. + /// True if the parameter is shared by parameter sets. + /// True if the parameter takes value from the pipeline. + /// the tooltip based on the parameters. + internal static string EvaluateTooltip(string typeName, int position, bool mandatory, bool shared, bool valueFromPipeline) + { + StringBuilder returnValue = new StringBuilder(string.Format( + CultureInfo.CurrentCulture, + ShowCommandResources.TypeFormat, + typeName)); + string newlineFormatString = Environment.NewLine + "{0}"; + + if (position >= 0) + { + string positionFormat = string.Format( + CultureInfo.CurrentCulture, + ShowCommandResources.PositionFormat, + position); + + returnValue.AppendFormat(CultureInfo.InvariantCulture, newlineFormatString, positionFormat); + } + + string optionalOrMandatory = mandatory ? ShowCommandResources.Mandatory : ShowCommandResources.Optional; + + returnValue.AppendFormat(CultureInfo.InvariantCulture, newlineFormatString, optionalOrMandatory); + + if (shared) + { + returnValue.AppendFormat(CultureInfo.InvariantCulture, newlineFormatString, ShowCommandResources.CommonToAllParameterSets); + } + + if (valueFromPipeline) + { + returnValue.AppendFormat(CultureInfo.InvariantCulture, newlineFormatString, ShowCommandResources.CanReceiveValueFromPipeline); + } + + return returnValue.ToString(); + } + + /// + /// If property changed will be notify. + /// + /// The changed property. + private void OnNotifyPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = this.PropertyChanged; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml new file mode 100644 index 0000000000000000000000000000000000000000..185c5513ddb257fbf2cfee042be8712eda8c938a --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..8097952ffab6cb654e184cb72a6963260fd505b3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Windows; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for MultipleSelectionDialog.xaml. + /// + public partial class MultipleSelectionDialog : Window + { + /// + /// Initializes a new instance of the MultipleSelectionDialog class. + /// + public MultipleSelectionDialog() + { + this.InitializeComponent(); + } + + /// + /// OK Click event function. + /// + /// Event sender. + /// Event arguments. + private void ButtonOK_Click(object sender, RoutedEventArgs e) + { + this.DialogResult = true; + this.Close(); + } + + /// + /// Cancel Click event function. + /// + /// Event sender. + /// Event arguments. + private void ButtonCancel_Click(object sender, RoutedEventArgs e) + { + this.DialogResult = false; + this.Close(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml new file mode 100644 index 0000000000000000000000000000000000000000..7a88bb3699b46e089cf9aac3542fa92de0cd4a39 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..b644264376ba5c38e397084a2e77753a1d52797f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Windows; +using System.Windows.Input; + +using Microsoft.Management.UI.Internal; +using Microsoft.Management.UI.Internal.ShowCommand; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for CmdletGUI.xaml. + /// + public partial class ShowAllModulesWindow : Window + { + /// + /// private constants for ZoomLevel. + /// + private double zoomLevel = 1.0; + + /// + /// Zoom Increments. + /// + private const double ZOOM_INCREMENT = 0.2; + + /// + /// Max ZoomLevel. + /// + private const double ZOOM_MAX = 3.0; + + /// + /// Min ZoomLevel. + /// + private const double ZOOM_MIN = 0.5; + + #region Construction and Destructor + + /// + /// Initializes a new instance of the ShowAllModulesWindow class. + /// + public ShowAllModulesWindow() + { + this.InitializeComponent(); + + if (this.AllModulesControl != null && this.AllModulesControl.ShowModuleControl != null) + { + this.AllModulesControl.ShowModuleControl.Owner = this; + } + + this.SizeChanged += this.ShowAllModulesWindow_SizeChanged; + this.LocationChanged += this.ShowAllModulesWindow_LocationChanged; + this.StateChanged += this.ShowAllModulesWindow_StateChanged; + this.Loaded += this.ShowAllModulesWindow_Loaded; + + RoutedCommand plusSettings = new RoutedCommand(); + KeyGestureConverter keyGestureConverter = new KeyGestureConverter(); + + try + { + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn1Shortcut)); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn2Shortcut)); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn3Shortcut)); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn4Shortcut)); + CommandBindings.Add(new CommandBinding(plusSettings, ZoomEventHandlerPlus)); + } + catch (NotSupportedException) + { + // localized has a problematic string - going to default + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Add")); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Plus")); + CommandBindings.Add(new CommandBinding(plusSettings, ZoomEventHandlerPlus)); + } + + RoutedCommand minusSettings = new RoutedCommand(); + try + { + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut1Shortcut)); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut2Shortcut)); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut3Shortcut)); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut4Shortcut)); + + CommandBindings.Add(new CommandBinding(minusSettings, ZoomEventHandlerMinus)); + } + catch (NotSupportedException) + { + // localized has a problematic string - going to default + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Subtract")); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Minus")); + CommandBindings.Add(new CommandBinding(minusSettings, ZoomEventHandlerMinus)); + } + } + + /// + /// Saves the user settings. + /// + /// Event arguments. + protected override void OnClosed(System.EventArgs e) + { + ShowCommandSettings.Default.Save(); + base.OnClosed(e); + } + + /// + /// Sets the focus on the CommandName control. + /// + /// Event sender. + /// Event arguments. + private void ShowAllModulesWindow_Loaded(object sender, RoutedEventArgs e) + { + this.AllModulesControl.CommandName.Focus(); + } + + /// + /// Saves size changes in user settings. + /// + /// Event sender. + /// Event arguments. + private void ShowAllModulesWindow_SizeChanged(object sender, SizeChangedEventArgs e) + { + ShowCommandSettings.Default.ShowCommandsWidth = this.Width; + ShowCommandSettings.Default.ShowCommandsHeight = this.Height; + } + + /// + /// Saves position changes in user settings. + /// + /// Event sender. + /// Event arguments. + private void ShowAllModulesWindow_LocationChanged(object sender, System.EventArgs e) + { + ShowCommandSettings.Default.ShowCommandsTop = this.Top; + ShowCommandSettings.Default.ShowCommandsLeft = this.Left; + } + + /// + /// Updates the user setting with window state. + /// + /// Event sender. + /// Event arguments. + private void ShowAllModulesWindow_StateChanged(object sender, System.EventArgs e) + { + ShowCommandSettings.Default.ShowCommandsWindowMaximized = this.WindowState == WindowState.Maximized; + } + + /// + /// Implements ZoomIn. + /// + /// . + /// . + private void ZoomEventHandlerPlus(object sender, ExecutedRoutedEventArgs e) + { + AllModulesViewModel viewModel = this.DataContext as AllModulesViewModel; + if (viewModel == null) + { + return; + } + + if (this.zoomLevel == 0) + { + this.zoomLevel = 1; + } + + if (this.zoomLevel < ZOOM_MAX) + { + // ViewModel applies ZoomLevel after dividing it by 100, So multiply it by 100 and then later reset to normal by dividing for next zoom + this.zoomLevel = (this.zoomLevel + ZOOM_INCREMENT) * 100; + viewModel.ZoomLevel = this.zoomLevel; + this.zoomLevel /= 100; + } + } + + /// + /// Implements ZoomOut. + /// + /// . + /// . + private void ZoomEventHandlerMinus(object sender, ExecutedRoutedEventArgs e) + { + AllModulesViewModel viewModel = this.DataContext as AllModulesViewModel; + if (viewModel == null) + { + return; + } + + if (this.zoomLevel >= ZOOM_MIN) + { + // ViewModel applies ZoomLevel after dividing it by 100, So multiply it by 100 and then later reset to normal by dividing it for next zoom + this.zoomLevel = (this.zoomLevel - ZOOM_INCREMENT) * 100; + viewModel.ZoomLevel = this.zoomLevel; + this.zoomLevel /= 100; + } + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml new file mode 100644 index 0000000000000000000000000000000000000000..6617070be4e56f9d095b62a4b2e397b29b086e01 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..c03a42ed8645e638d13af0e48ec069f0565bb4ee --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Windows; + +using Microsoft.Management.UI.Internal.ShowCommand; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Interaction logic for CmdletGUI.xaml. + /// + public partial class ShowCommandWindow : Window + { + #region Construction and Destructor + + /// + /// Initializes a new instance of the ShowCommandWindow class. + /// + public ShowCommandWindow() + { + this.InitializeComponent(); + this.SizeChanged += this.ShowCommandWindow_SizeChanged; + this.LocationChanged += this.ShowCommandWindow_LocationChanged; + this.StateChanged += this.ShowCommandWindow_StateChanged; + } + + /// + /// Saves the user settings. + /// + /// Event arguments. + protected override void OnClosed(System.EventArgs e) + { + ShowCommandSettings.Default.Save(); + base.OnClosed(e); + } + + /// + /// Saves size changes in user settings. + /// + /// Event sender. + /// Event arguments. + private void ShowCommandWindow_SizeChanged(object sender, SizeChangedEventArgs e) + { + ShowCommandSettings.Default.ShowOneCommandWidth = this.Width; + ShowCommandSettings.Default.ShowOneCommandHeight = this.Height; + } + + /// + /// Saves position changes in user settings. + /// + /// Event sender. + /// Event arguments. + private void ShowCommandWindow_LocationChanged(object sender, System.EventArgs e) + { + ShowCommandSettings.Default.ShowOneCommandTop = this.Top; + ShowCommandSettings.Default.ShowOneCommandLeft = this.Left; + } + + /// + /// Updates the user setting with window state. + /// + /// Event sender. + /// Event arguments. + private void ShowCommandWindow_StateChanged(object sender, System.EventArgs e) + { + ShowCommandSettings.Default.ShowOneCommandWindowMaximized = this.WindowState == WindowState.Maximized; + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/app.config b/PowerShell-master/src/Microsoft.Management.UI.Internal/app.config new file mode 100644 index 0000000000000000000000000000000000000000..a2f13686380862b77f9a49c5a300c3890395f0c3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/app.config @@ -0,0 +1,99 @@ + + + + +
+
+ + + + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + -1 + + + False + + + False + + + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + False + + + False + + + -1 + + + -1 + + + False + + + 100 + + + 500 + + + 700 + + + True + + + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..e0b036a93d0215e57c17a2360d4224a2655a6a2a --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Threading; +using System.Windows; + +using Microsoft.Management.UI; +using Microsoft.PowerShell.Commands.ShowCommandInternal; + +namespace Microsoft.PowerShell.Commands.Internal +{ + /// + /// Implements the WPF window part of the ShowWindow option of get-help. + /// + internal static class HelpWindowHelper + { + /// + /// Shows the help window. + /// + /// Object with help information. + /// Cmdlet calling this method. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from methods called using reflection")] + private static void ShowHelpWindow(PSObject helpObj, PSCmdlet cmdlet) + { + Window ownerWindow = ShowCommandHelper.GetHostWindow(cmdlet); + if (ownerWindow != null) + { + ownerWindow.Dispatcher.Invoke( + new SendOrPostCallback( + (_) => + { + HelpWindow helpWindow = new HelpWindow(helpObj); + helpWindow.Owner = ownerWindow; + helpWindow.Show(); + + helpWindow.Closed += new EventHandler((sender, e) => ownerWindow.Focus()); + }), + string.Empty); + return; + } + + Thread guiThread = new Thread( + (ThreadStart)delegate + { + HelpWindow helpWindow = new HelpWindow(helpObj); + helpWindow.ShowDialog(); + }); + guiThread.SetApartmentState(ApartmentState.STA); + guiThread.Start(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs new file mode 100644 index 0000000000000000000000000000000000000000..81621624992f6b7372c486380c187a173645e768 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs @@ -0,0 +1,607 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Threading; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; + +namespace Microsoft.Management.UI.Internal +{ + /// + /// OutGridViewWindow definition for PowerShell command out-gridview. + /// + internal class OutGridViewWindow + { + #region private Fields + + /// + /// Zoom Increments. + /// + private const double ZOOM_INCREMENT = 0.2; + + /// + /// Max ZoomLevel. + /// + private const double ZOOM_MAX = 3.0; + + /// + /// Min ZoomLevel. + /// + private const double ZOOM_MIN = 0.5; + + /// + /// Window for gridView. + /// + private Window gridViewWindow; + + /// + /// Local ManagementList. + /// + private ManagementList managementList; + + /// + /// A collection of PSObjects to be data bound to the local Management List. + /// + private ObservableCollection listItems; + + /// + /// Event used for the thread gridViewWindows signaling main thread after Windows loaded. + /// + private AutoResetEvent gridViewWindowLoaded; + + /// Is used to store any Management list calls exceptions. + private Exception exception = null; + + /// + /// Is used to block thread of the pipeline. + /// + private AutoResetEvent closedEvent; + + /// + /// OK Button's content. + /// + private static readonly string OKButtonContent = XamlLocalizableResources.OutGridView_Button_OK; + + /// + /// Cancel Button's content. + /// + private static readonly string CancelButtonContent = XamlLocalizableResources.OutGridView_Button_Cancel; + + /// + /// Used to store selected items in the ok processing. + /// + private List selectedItems; + + /// + /// The GUI thread of Out-GridView. + /// + private Thread guiThread; + + /// + /// private constants for ZoomLevel. + /// + private double zoomLevel = 1.0; + + #endregion private Fields + + #region internal Constructors + + /// + /// Constructor for OutGridView. + /// + internal OutGridViewWindow() + { + // Initialize the data source collection. + this.listItems = new ObservableCollection(); + } + + #endregion internal Constructors + + #region private delegates + /// + /// ThreadDelegate definition. + /// + /// Start GridView Window delegate. + private delegate void ThreadDelegate(object arg); + + #endregion private delegates + + #region Private method that are intended to be called by the Out-GridView cmdlet. + + /// + /// Start a new thread as STA for gridView Window. + /// + /// Commands of the PowerShell. + /// Selection mode of the list. + /// ClosedEvent. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")] + private void StartWindow(string invocation, string outputModeOptions, AutoResetEvent closedEvent) + { + this.closedEvent = closedEvent; + this.gridViewWindowLoaded = new AutoResetEvent(false); + + ParameterizedThreadStart threadStart = new ParameterizedThreadStart( + new ThreadDelegate(delegate + { + try + { + this.gridViewWindow = new Window(); + this.managementList = CreateManagementList(outputModeOptions); + this.gridViewWindow.Loaded += this.GridViewWindowLoaded; + this.gridViewWindow.Content = CreateMainGrid(outputModeOptions); + this.gridViewWindow.Title = invocation; + this.gridViewWindow.Closed += this.GridViewWindowClosed; + + RoutedCommand plusSettings = new RoutedCommand(); + KeyGestureConverter keyGestureConverter = new KeyGestureConverter(); + + try + { + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn1Shortcut)); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn2Shortcut)); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn3Shortcut)); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomIn4Shortcut)); + this.gridViewWindow.CommandBindings.Add(new CommandBinding(plusSettings, ZoomEventHandlerPlus)); + } + catch (NotSupportedException) + { + // localized has a problematic string - going to default + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Add")); + plusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Plus")); + this.gridViewWindow.CommandBindings.Add(new CommandBinding(plusSettings, ZoomEventHandlerPlus)); + } + + RoutedCommand minusSettings = new RoutedCommand(); + try + { + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut1Shortcut)); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut2Shortcut)); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut3Shortcut)); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString(UICultureResources.ZoomOut4Shortcut)); + + this.gridViewWindow.CommandBindings.Add(new CommandBinding(minusSettings, ZoomEventHandlerMinus)); + } + catch (NotSupportedException) + { + // localized has a problematic string - going to default + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Subtract")); + minusSettings.InputGestures.Add((KeyGesture)keyGestureConverter.ConvertFromString("Ctrl+Minus")); + this.gridViewWindow.CommandBindings.Add(new CommandBinding(minusSettings, ZoomEventHandlerMinus)); + } + + this.gridViewWindow.ShowDialog(); + } + catch (Exception e) + { + // Store the exception in a local variable that will be checked later. + if (e.InnerException != null) + { + this.exception = e.InnerException; + } + else + { + this.exception = e; + } + } + })); + + guiThread = new Thread(threadStart); + guiThread.SetApartmentState(ApartmentState.STA); + + guiThread.Start(); + } + + /// + /// Implements ZoomIn. + /// + /// . + /// . + private void ZoomEventHandlerPlus(object sender, ExecutedRoutedEventArgs e) + { + if (this.zoomLevel == 0) + { + this.zoomLevel = 1; + } + + if (this.zoomLevel < ZOOM_MAX) + { + this.zoomLevel += ZOOM_INCREMENT; + Grid g = this.gridViewWindow.Content as Grid; + + if (g != null) + { + g.LayoutTransform = new ScaleTransform(this.zoomLevel, this.zoomLevel, 0, 0); + } + } + } + + /// + /// Implements ZoomOut. + /// + /// . + /// . + private void ZoomEventHandlerMinus(object sender, ExecutedRoutedEventArgs e) + { + if (this.zoomLevel >= ZOOM_MIN) + { + this.zoomLevel -= ZOOM_INCREMENT; + Grid g = this.gridViewWindow.Content as Grid; + if (g != null) + { + g.LayoutTransform = new ScaleTransform(this.zoomLevel, this.zoomLevel, 0, 0); + } + } + } + + /// + /// Creates a new ManagementList. + /// + /// Output mode of the out-gridview. + /// A new ManagementList. + private ManagementList CreateManagementList(string outputMode) + { + ManagementList newList = new ManagementList(); + + newList.ViewSaverUserActionState = UserActionState.Hidden; + newList.ViewManagerUserActionState = UserActionState.Hidden; + newList.List.VerticalAlignment = VerticalAlignment.Stretch; + newList.List.SetValue(Grid.RowProperty, 0); + newList.List.SelectionMode = (outputMode == "Single") ? SelectionMode.Single : SelectionMode.Extended; + + return newList; + } + + /// + /// Creates a new main grid for window. + /// + /// Output mode of the out-gridview. + /// A new mainGrid. + private Grid CreateMainGrid(string outputMode) + { + Grid mainGrid = new Grid(); + mainGrid.RowDefinitions.Add(new RowDefinition()); + mainGrid.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star); + mainGrid.Children.Add(managementList); + + if (outputMode == "None") + { + return mainGrid; + } + + // OK and Cancel button should only be displayed if OutputMode is not None. + mainGrid.RowDefinitions.Add(new RowDefinition()); + mainGrid.RowDefinitions[1].Height = GridLength.Auto; + mainGrid.Children.Add(CreateButtonGrid()); + + return mainGrid; + } + + /// + /// Creates a OK button. + /// + /// A new buttonGrid. + private Grid CreateButtonGrid() + { + Grid buttonGrid = new Grid(); + + //// This will allow OK and Cancel to have the same width + buttonGrid.SetValue(Grid.IsSharedSizeScopeProperty, true); + buttonGrid.ColumnDefinitions.Add(new ColumnDefinition()); + buttonGrid.ColumnDefinitions.Add(new ColumnDefinition()); + buttonGrid.ColumnDefinitions[0].Width = GridLength.Auto; + buttonGrid.ColumnDefinitions[0].SharedSizeGroup = "okCancel"; + buttonGrid.ColumnDefinitions[1].Width = GridLength.Auto; + buttonGrid.ColumnDefinitions[1].SharedSizeGroup = "okCancel"; + buttonGrid.HorizontalAlignment = HorizontalAlignment.Right; + buttonGrid.SetValue(Grid.RowProperty, 1); + + //// This will add OK and Cancel button to buttonGrid. + buttonGrid.Children.Add(CreateOKButton()); + buttonGrid.Children.Add(CreateCancelButton()); + + return buttonGrid; + } + + /// + /// Creates a OK button. + /// + /// A new OK button. + private Button CreateOKButton() + { + Button ok = new Button(); + ok.Content = OKButtonContent; + ok.Margin = new Thickness(5); + ok.Padding = new Thickness(2); + ok.SetValue(Grid.ColumnProperty, 0); + ok.IsDefault = true; + ok.SetValue(AutomationProperties.AutomationIdProperty, "OGVOK"); + ok.Click += OK_Click; + return ok; + } + + /// + /// Creates a Cancel button. + /// + /// A new Cancel button. + private Button CreateCancelButton() + { + Button cancel = new Button(); + cancel.Content = CancelButtonContent; + cancel.Margin = new Thickness(5); + cancel.Padding = new Thickness(2); + cancel.SetValue(Grid.ColumnProperty, 1); + cancel.IsCancel = true; + cancel.SetValue(AutomationProperties.AutomationIdProperty, "OGVCancel"); + cancel.Click += Cancel_Click; + return cancel; + } + + /// + /// Store the selected items for use in EndProcessing. + /// + /// Event sender. + /// Event arguments. + private void OK_Click(object sender, RoutedEventArgs e) + { + if (this.managementList.List.SelectedItems.Count != 0) + { + this.selectedItems = new List(); + foreach (PSObject obj in this.managementList.List.SelectedItems) + { + this.selectedItems.Add(obj); + } + } + + this.gridViewWindow.Close(); + } + + /// + /// Closes the window. + /// + /// Event sender. + /// Event arguments. + private void Cancel_Click(object sender, RoutedEventArgs e) + { + this.gridViewWindow.Close(); + } + + /// + /// Gets selected items from List. + /// + /// Selected items of the list. + private List SelectedItems() + { + return this.selectedItems; + } + + /// + /// Closes the window. + /// + public void CloseWindow() + { + this.gridViewWindow.Dispatcher.Invoke(new ThreadStart(delegate { this.gridViewWindow.Close(); })); + } + + /// + /// Add column definitions to the underlying management list. + /// + /// An array of property names to add. + /// An array of display names to add. + /// An array of types to add. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")] + private void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) + { + // Wait for the gridViewWindow thread to signal that loading of Window is done + if (this.gridViewWindowLoaded != null) + { + this.gridViewWindowLoaded.WaitOne(); + this.gridViewWindowLoaded = null; + } + + this.managementList.Dispatcher.Invoke( + System.Windows.Threading.DispatcherPriority.Normal, + new Action( + () => + { + // Pick the length of the shortest incoming arrays. Normally all incoming arrays should be of the same length. + int length = propertyNames.Length; + if (length > displayNames.Length) + { + length = displayNames.Length; + } + + if (length > types.Length) + { + length = types.Length; + } + + try + { + // Clear all columns in case the view is changed. + this.managementList.List.Columns.Clear(); + + // Clear column filter rules. + this.managementList.AddFilterRulePicker.ColumnFilterRules.Clear(); + + // Add columns with provided names and Types. + for (int i = 0; i < propertyNames.Length; ++i) + { + DataTemplate dataTemplate; + bool haveTemplate = this.managementList.FilterRulePanel.TryGetContentTemplate(types[i], out dataTemplate); + InnerListColumn column = null; + + if (haveTemplate) + { + column = new InnerListColumn(new UIPropertyGroupDescription(propertyNames[i], displayNames[i], types[i])); + } + else + { + column = new InnerListColumn(new UIPropertyGroupDescription(propertyNames[i], displayNames[i], typeof(string))); + } + + this.managementList.AddColumn(column); + } + + this.managementList.List.SetColumnHeaderActions(); + + if (this.managementList.List.ItemsSource == null) + { + // Setting ItemsSource implicitly regenerates all columns. + this.managementList.List.ItemsSource = this.listItems; + } + + // Set focus on ListView + this.managementList.List.SelectedIndex = 0; + this.managementList.List.Focus(); + } + catch (Exception e) + { + // Store the exception in a local variable that will be checked later. + if (e.InnerException != null) + { + this.exception = e.InnerException; + } + else + { + this.exception = e; + } + } + })); + } + + /// + /// Add an item to ObservableCollection. + /// + /// PSObject of comlet data. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")] + private void AddItem(PSObject value) + { + if (this.GetWindowClosedStatus()) + { + return; + } + + this.managementList.Dispatcher.BeginInvoke( + System.Windows.Threading.DispatcherPriority.Normal, + new Action( + () => + { + try + { + // Remove any potential ANSI decoration + foreach (var property in value.Properties) + { + if (property.Value is string str) + { + StringDecorated decoratedString = new StringDecorated(str); + property.Value = decoratedString.ToString(OutputRendering.PlainText); + } + } + + this.listItems.Add(value); + } + catch (Exception e) + { + // Store the exception in a local variable that will be checked later. + if (e.InnerException != null) + { + this.exception = e.InnerException; + } + else + { + this.exception = e; + } + } + })); + } + + /// + /// Returns the state of GridView Window. + /// + /// The status of GridView Window close or not. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")] + private bool GetWindowClosedStatus() + { + if (this.closedEvent == null) + { + return false; + } + + return this.closedEvent.WaitOne(0); + } + + /// + /// Returns any exception that has been thrown by previous method calls. + /// + /// The thrown and caught exception. It returns null if no exceptions were thrown by any previous method calls. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The method is called using reflection.")] + private Exception GetLastException() + { + Exception local = this.exception; + + if (local != null) + { + // Clear the caught exception. + this.exception = null; + return local; + } + + return this.exception; + } + + #endregion Private method that are intended to be called by the Out-GridView cmdlet. + + #region Private methods + + /// + /// GridView Window is closing callback process. + /// + /// The sender object. + /// Event Args. + private void GridViewWindowClosed(object sender, EventArgs e) + { + if (this.closedEvent != null && !this.closedEvent.SafeWaitHandle.IsClosed) + { + try + { + this.closedEvent.Set(); + } + catch (ObjectDisposedException) + { + // we tried to avoid this exception with "&& !this.closedEvent.SafeWaitHandle.IsClosed" + // but since this runs in a different thread the if condition could be evaluated and after that + // the handle disposed + } + } + } + + /// + /// Set loaded as true when this method invoked. + /// + /// The sender object. + /// RoutedEvent Args. + private void GridViewWindowLoaded(object sender, RoutedEventArgs e) + { + // signal the main thread + this.gridViewWindowLoaded.Set(); + + // Make gridview window as active window + this.gridViewWindow.Activate(); + + // Set up AutomationId and Name + AutomationProperties.SetName(this.gridViewWindow, GraphicalHostResources.OutGridViewWindowObjectName); + AutomationProperties.SetAutomationId(this.gridViewWindow, "OutGridViewWindow"); + } + + #endregion Private methods + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs b/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..10690b65dc7d08bc5408f0d47d22f217debdd1ae --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs @@ -0,0 +1,1267 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Reflection; +using System.Threading; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Threading; + +using Microsoft.Management.UI; +using Microsoft.Management.UI.Internal; +using Microsoft.Management.UI.Internal.ShowCommand; +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands.ShowCommandInternal +{ + /// + /// Implements the WPF window part of the show-command cmdlet. + /// + internal class ShowCommandHelper : IDisposable + { + #region fields + + internal const string CommandTypeSegment = " -CommandType Cmdlet, Function, Script, ExternalScript"; + + /// + /// Method that will return the dialog from ShowAllModulesWindow or ShowCommandWindow. + /// This is necessary because the PlainInvokeAndShowDialog thread starter cannot receive parameters + /// + private DispatcherOperationCallback methodThatReturnsDialog; + + /// + /// Event set when the window is closed. + /// + private AutoResetEvent windowClosed = new AutoResetEvent(false); + + /// + /// Event set when help is needed. + /// + private AutoResetEvent helpNeeded = new AutoResetEvent(false); + + /// + /// Event set when it is necessary to import a module. + /// + private AutoResetEvent importModuleNeeded = new AutoResetEvent(false); + + /// + /// Event set when the window is loaded. + /// + private AutoResetEvent windowLoaded = new AutoResetEvent(false); + + /// + /// String with the command that needs help set when helpNeeded is set. + /// + private string commandNeedingHelp; + + /// + /// String with the command name that needs to import a module. + /// + private string commandNeedingImportModule; + + /// + /// String with the module name that needs to be imported. + /// + private string parentModuleNeedingImportModule; + + /// + /// String with the selected module at the time a module needs to be imported. + /// + private string selectedModuleNeedingImportModule; + + /// + /// Keeps the window for the implementation of CloseWindow. + /// + private Window window; + + /// + /// host window, if any. + /// + private Window hostWindow; + + /// + /// ViewModel when showing all modules. + /// + private AllModulesViewModel allModulesViewModel; + + /// + /// ViewModel when showing a single command. + /// + private CommandViewModel commandViewModel; + + /// + /// true when the window is closed with cancel. + /// + private bool dialogCanceled = true; + #endregion fields + + #region GetSerializedCommand script + + private const string ScriptGetSerializedCommand = @" +Function PSGetSerializedShowCommandInfo +{ + Function GetParameterType + { + param ( + [Type] $parameterType) + + $returnParameterType = new-object PSObject + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""FullName"" -Value $parameterType.FullName + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""IsEnum"" -Value $parameterType.IsEnum + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""IsArray"" -Value $parameterType.IsArray + + if ($parameterType.IsEnum) + { + $enumValues = [System.Enum]::GetValues($parameterType) + } + else + { + $enumValues = [string[]] @() + } + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""EnumValues"" -Value $enumValues + + if ($parameterType.IsArray) + { + $hasFlagAttribute = ($parameterType.GetCustomAttributes([System.FlagsAttribute], $true).Length -gt 0) + + # Recurse into array elements. + $elementType = GetParameterType($parameterType.GetElementType()) + } + else + { + $hasFlagAttribute = $false + $elementType = $null + } + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""HasFlagAttribute"" -Value $hasFlagAttribute + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""ElementType"" -Value $elementType + + + if (!($parameterType.IsEnum) -and !($parameterType.IsArray)) + { + $implementsDictionary = [System.Collections.IDictionary].IsAssignableFrom($parameterType) + } + else + { + $implementsDictionary = $false + } + $returnParameterType | Add-Member -MemberType NoteProperty -Name ""ImplementsDictionary"" -Value $implementsDictionary + + return $returnParameterType + } + + Function GetParameterInfo + { + param ( + $parameters) + + [PSObject[]] $parameterInfos = @() + + foreach ($parameter in $parameters) + { + $parameterInfo = new-object PSObject + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $parameter.Name + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""IsMandatory"" -Value $parameter.IsMandatory + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""ValueFromPipeline"" -Value $parameter.ValueFromPipeline + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""Position"" -Value $parameter.Position + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""ParameterType"" -Value (GetParameterType($parameter.ParameterType)) + + $hasParameterSet = $false + [string[]] $validValues = @() + if ($PSVersionTable.PSVersion.Major -gt 2) + { + $validateSetAttributes = $parameter.Attributes | Where { + [ValidateSet].IsAssignableFrom($_.GetType()) + } + if (($validateSetAttributes -ne $null) -and ($validateSetAttributes.Count -gt 0)) + { + $hasParameterSet = $true + $validValues = $validateSetAttributes[0].ValidValues + } + } + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""HasParameterSet"" -Value $hasParameterSet + $parameterInfo | Add-Member -MemberType NoteProperty -Name ""ValidParamSetValues"" -Value $validValues + + $parameterInfos += $parameterInfo + } + + return (,$parameterInfos) + } + + Function GetParameterSets + { + param ( + [System.Management.Automation.CommandInfo] $cmdInfo + ) + + $parameterSets = $null + try + { + $parameterSets = $cmdInfo.ParameterSets + } + catch [System.InvalidOperationException] { } + catch [System.Management.Automation.PSNotSupportedException] { } + catch [System.Management.Automation.PSNotImplementedException] { } + + if (($parameterSets -eq $null) -or ($parameterSets.Count -eq 0)) + { + return (,@()) + } + + [PSObject[]] $returnParameterSets = @() + + foreach ($parameterSet in $parameterSets) + { + $parameterSetInfo = new-object PSObject + $parameterSetInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $parameterSet.Name + $parameterSetInfo | Add-Member -MemberType NoteProperty -Name ""IsDefault"" -Value $parameterSet.IsDefault + $parameterSetInfo | Add-Member -MemberType NoteProperty -Name ""Parameters"" -Value (GetParameterInfo($parameterSet.Parameters)) + + $returnParameterSets += $parameterSetInfo + } + + return (,$returnParameterSets) + } + + Function GetModuleInfo + { + param ( + [System.Management.Automation.CommandInfo] $cmdInfo + ) + + if ($cmdInfo.ModuleName -ne $null) + { + $moduleName = $cmdInfo.ModuleName + } + else + { + $moduleName = """" + } + + $moduleInfo = new-object PSObject + $moduleInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $moduleName + + return $moduleInfo + } + + Function ConvertToShowCommandInfo + { + param ( + [System.Management.Automation.CommandInfo] $cmdInfo + ) + + $showCommandInfo = new-object PSObject + $showCommandInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $cmdInfo.Name + $showCommandInfo | Add-Member -MemberType NoteProperty -Name ""ModuleName"" -Value $cmdInfo.ModuleName + $showCommandInfo | Add-Member -MemberType NoteProperty -Name ""Module"" -Value (GetModuleInfo($cmdInfo)) + $showCommandInfo | Add-Member -MemberType NoteProperty -Name ""CommandType"" -Value $cmdInfo.CommandType + $showCommandInfo | Add-Member -MemberType NoteProperty -Name ""Definition"" -Value $cmdInfo.Definition + $showCommandInfo | Add-Member -MemberType NoteProperty -Name ""ParameterSets"" -Value (GetParameterSets($cmdInfo)) + + return $showCommandInfo + } + + $commandList = @(""Cmdlet"", ""Function"", ""Script"", ""ExternalScript"") + if ($PSVersionTable.PSVersion.Major -gt 2) + { + $commandList += ""Workflow"" + } + + foreach ($command in @(Get-Command -CommandType $commandList)) + { + Write-Output (ConvertToShowCommandInfo($command)) + } +}"; + + #endregion + + #region constructor and destructor + /// + /// Prevents a default instance of the ShowCommandHelper class from being created. + /// + private ShowCommandHelper() + { + } + + /// + /// Finalizes an instance of the class. + /// + ~ShowCommandHelper() + { + this.Dispose(false); + } + #endregion constructor and destructor + + #region properties called using reflection + /// + /// Gets the Screen Width. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private static double ScreenWidth + { + get + { + return System.Windows.SystemParameters.PrimaryScreenWidth; + } + } + + /// + /// Gets the Screen Height. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private static double ScreenHeight + { + get + { + return System.Windows.SystemParameters.PrimaryScreenHeight; + } + } + + /// + /// Gets the event set when the show-command window is closed. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private AutoResetEvent WindowClosed + { + get + { + return this.windowClosed; + } + } + + /// + /// Gets the event set when help is needed for a command. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private AutoResetEvent HelpNeeded + { + get + { + return this.helpNeeded; + } + } + + /// + /// Gets the event set when it is necessary to import a module. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private AutoResetEvent ImportModuleNeeded + { + get + { + return this.importModuleNeeded; + } + } + + /// + /// Gets the event set when the window is loaded. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private AutoResetEvent WindowLoaded + { + get + { + return this.windowLoaded; + } + } + + /// + /// Gets the command needing help when HelpNeeded is set. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private string CommandNeedingHelp + { + get + { + return this.commandNeedingHelp; + } + } + + /// + /// Gets the module we want to import. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private string ParentModuleNeedingImportModule + { + get + { + return this.parentModuleNeedingImportModule; + } + } + + /// + /// Gets a value indicating whether there is a host window. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private bool HasHostWindow + { + get + { + return this.hostWindow != null; + } + } + #endregion properties called using reflection + + #region public Dispose + /// + /// Dispose method in IDisposeable. + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + #endregion public Dispose + + #region internal static methods called using reflection from show-command + /// + /// Sets the text in the clipboard. + /// + /// Text to set the clipboard to. + internal static void SetClipboardText(string text) + { + try + { + Clipboard.SetText(text); + } + catch (System.Runtime.InteropServices.COMException) + { + // This is the recommended way to set clipboard text + System.Threading.Thread.Sleep(0); + try + { + Clipboard.SetText(text); + } + catch (System.Runtime.InteropServices.COMException) + { + } + } + } + + /// + /// Gets the command to be run to get commands and imported modules. + /// + /// Boolean flag determining whether Show-Command is queried in the local or remote runspace scenario. + /// Boolean flag to indicate that it is the second attempt to query Show-Command data. + /// The command to be run to get commands and imported modules. + internal static string GetShowAllModulesCommand(bool isRemoteRunspace = false, bool isFirstChance = true) + { + string scriptBase; + + if (isRemoteRunspace) + { + if (isFirstChance) + { + // Return command to run. + scriptBase = "@(Get-Command " + ShowCommandHelper.CommandTypeSegment + @" -ShowCommandInfo)"; + } + else + { + // Return script to run. + scriptBase = GetSerializedCommandScript(); + } + } + else + { + scriptBase = "@(Get-Command " + ShowCommandHelper.CommandTypeSegment + ")"; + } + + scriptBase += ShowCommandHelper.GetGetModuleSuffix(); + return scriptBase; + } + + /// + /// Retrieves the script for Get-SerializedCommand from local machine. + /// + /// String representation of the script for Get-SerializedCommand. + private static string GetSerializedCommandScript() + { + return string.Format( + CultureInfo.InvariantCulture, + "@({0};{1};{2})", + ScriptGetSerializedCommand, + @"PSGetSerializedShowCommandInfo", + @"Remove-Item -Path 'function:\PSGetSerializedShowCommandInfo' -Force"); + } + + /// + /// Gets the command to be run in order to show help for a command. + /// + /// Command we want to get help from. + /// The command to be run in order to show help for a command. + internal static string GetHelpCommand(string command) + { + return "Get-Help " + ShowCommandHelper.SingleQuote(command); + } + + /// + /// Constructs a dictionary of imported modules based on the module names. + /// + /// The imported modules. + /// a dictionary of imported modules based on the module names. + internal static Dictionary GetImportedModulesDictionary(object[] moduleObjects) + { + Dictionary returnValue = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (PSObject rawModule in moduleObjects) + { + ShowCommandModuleInfo wrappedModule = null; + PSModuleInfo module = rawModule.BaseObject as PSModuleInfo; + if (module != null) + { + wrappedModule = new ShowCommandModuleInfo(module); + } + else + { + wrappedModule = new ShowCommandModuleInfo(rawModule); + } + + // It is probably an issue somewhere else that a module would show up twice in the list, but we want to avoid + // throwing an exception regarding that in returnValue.Add + if (!returnValue.ContainsKey(wrappedModule.Name)) + { + returnValue.Add(wrappedModule.Name, wrappedModule); + } + } + + return returnValue; + } + + /// + /// Constructs a list of commands out of . + /// + /// The results of a get-command command. + /// a list of commands out of . + internal static List GetCommandList(object[] commandObjects) + { + List returnValue = new List(); + foreach (PSObject rawCommand in commandObjects) + { + CommandInfo command = rawCommand.BaseObject as CommandInfo; + if (command != null) + { + returnValue.Add(new ShowCommandCommandInfo(command)); + } + else + { + PSObject obj = rawCommand as PSObject; + if (obj != null) + { + returnValue.Add(new ShowCommandCommandInfo(obj)); + } + } + } + + return returnValue; + } + + /// + /// Constructs an array of objects out of . + /// + /// The result of a get-command command. + /// An array of objects out of . + internal static object[] ObjectArrayFromObjectCollection(object commandObjects) + { + object[] objectArray = commandObjects as object[] ?? ((System.Collections.ArrayList)commandObjects).ToArray(); + + return objectArray; + } + + /// + /// Called after a module in is imported to refresh the view model. + /// Gets a new AllModulesViewModel populated with and . + /// The is used to cleanup event listening in the old view model and to copy NoCommonParameters. + /// The new ViewModel will have the command selected according to , + /// and . + /// + /// The viewModel before the module was imported. + /// The list of imported modules. + /// The list of commands. + /// The name of the module that was selected in . + /// The name of the module that was imported. + /// The name of the command that was selected in . + /// The new ViewModel based on and . + internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewModel oldViewModel, Dictionary importedModules, IEnumerable commands, string selectedModuleNeedingImportModule, string parentModuleNeedingImportModule, string commandNeedingImportModule) + { + string oldFilter = null; + + if (oldViewModel.SelectedModule != null) + { + // this will allow the old view model to stop listening for events before we + // replace it with a new view model + oldViewModel.SelectedModule.SelectedCommand = null; + oldViewModel.SelectedModule = null; + oldFilter = oldViewModel.CommandNameFilter; + } + + AllModulesViewModel returnValue = new AllModulesViewModel(importedModules, commands, oldViewModel.NoCommonParameter); + if (!string.IsNullOrEmpty(oldFilter)) + { + returnValue.CommandNameFilter = oldFilter; + } + + if (selectedModuleNeedingImportModule == null || parentModuleNeedingImportModule == null) + { + return returnValue; + } + + ModuleViewModel moduleToSelect = returnValue.Modules.Find( + new Predicate((module) => + { + return module.Name.Equals(selectedModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase) ? true : false; + })); + + if (moduleToSelect == null) + { + return returnValue; + } + + returnValue.SelectedModule = moduleToSelect; + + CommandViewModel commandToSelect = moduleToSelect.Commands.Find( + new Predicate((command) => + { + return command.ModuleName.Equals(parentModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase) && + command.Name.Equals(commandNeedingImportModule, StringComparison.OrdinalIgnoreCase) ? true : false; + })); + + if (commandToSelect == null) + { + return returnValue; + } + + moduleToSelect.SelectedCommand = commandToSelect; + return returnValue; + } + + /// + /// Gets an error message to be displayed when failed to import a module. + /// + /// Command belonging to the module to import. + /// Module to import. + /// Error importing the module. + /// An error message to be displayed when failed to import a module. + internal static string GetImportModuleFailedMessage(string command, string module, string error) + { + return string.Format( + CultureInfo.CurrentUICulture, + ShowCommandResources.ImportModuleFailedFormat, + command, + module, + error); + } + + /// + /// Single quotes . + /// + /// String to quote. + /// single quoted. + internal static string SingleQuote(string str) + { + if (str == null) + { + str = string.Empty; + } + + return "\'" + System.Management.Automation.Language.CodeGeneration.EscapeSingleQuotedStringContent(str) + "\'"; + } + #endregion internal static methods called using reflection from show-command + + #region internal static methods used internally in this assembly + /// + /// Gets the host window, if it is present or null if it is not. + /// + /// Cmdlet calling this method. + /// The host window, if it is present or null if it is not. + internal static Window GetHostWindow(PSCmdlet cmdlet) + { + // The value of 'PrivateData' property may be null for the default host or a custom host. + PSPropertyInfo windowProperty = cmdlet.Host.PrivateData?.Properties["Window"]; + if (windowProperty == null) + { + return null; + } + + try + { + return windowProperty.Value as Window; + } + catch (ExtendedTypeSystemException) + { + return null; + } + } + #endregion internal static methods used internally in this assembly + + #region static private methods used only on this file + + /// + /// Gets a property value using reflection. + /// + /// Type containing the property. + /// Object containing the property (null for a static property). + /// Name of property to get. + /// Flags passed to reflection. + /// + /// Property value or null if it was not able to retrieve it. This method is not suitable to return a property value that might be null. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from a method called using reflection")] + private static object GetPropertyValue(Type type, object obj, string propertyName, BindingFlags bindingFlags) + { + PropertyInfo property = type.GetProperty(propertyName, bindingFlags); + if (property == null) + { + return null; + } + + try + { + return property.GetValue(obj, Array.Empty()); + } + catch (ArgumentException) + { + return null; + } + catch (TargetException) + { + return null; + } + catch (TargetParameterCountException) + { + return null; + } + catch (MethodAccessException) + { + return null; + } + catch (TargetInvocationException) + { + return null; + } + } + + /// + /// Sets a property value using reflection. + /// + /// Type containing the property. + /// Object containing the property (null for a static property). + /// Name of property to set. + /// Value to set the property with. + /// Flags passed to reflection. + /// True if it was able to set. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from a method called using reflection")] + private static bool SetPropertyValue(Type type, object obj, string propertyName, object value, BindingFlags bindingFlags) + { + PropertyInfo property = type.GetProperty(propertyName, bindingFlags); + if (property == null) + { + return false; + } + + try + { + property.SetValue(obj, value, Array.Empty()); + } + catch (ArgumentException) + { + return false; + } + catch (TargetException) + { + return false; + } + catch (TargetParameterCountException) + { + return false; + } + catch (MethodAccessException) + { + return false; + } + catch (TargetInvocationException) + { + return false; + } + + return true; + } + + /// + /// Gets the suffix that adds imported modules to a command. + /// + /// The suffix that adds imported modules to a command. + private static string GetGetModuleSuffix() + { + return ",@(get-module)"; + } + + #endregion static private methods used only on this file + + #region private methods called using reflection from show-command + /// + /// Gets the command to be run when calling show-command for a particular command. + /// + /// The particular command we are running show-command on. + /// True if we want to include aliases and retrieve modules. + /// The command to be run when calling show-command for a particular command. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private static string GetShowCommandCommand(string commandName, bool includeAliasAndModules) + { + string quotedCommandName = ShowCommandHelper.SingleQuote(commandName); + return "@(get-command " + quotedCommandName + " " + ShowCommandHelper.CommandTypeSegment + + (includeAliasAndModules ? ",Alias" : string.Empty) + ")" + + (includeAliasAndModules ? ShowCommandHelper.GetGetModuleSuffix() : string.Empty); + } + + /// + /// Gets a CommandViewModel of a CommandInfo. + /// + /// Command we want to get a CommandViewModel of. + /// True if we do not want common parameters. + /// The loaded modules. + /// True to qualify command with module name in GetScript. + /// A CommandViewModel of a CommandInfo. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private static object GetCommandViewModel(ShowCommandCommandInfo command, bool noCommonParameter, Dictionary importedModules, bool moduleQualify) + { + CommandViewModel returnValue = CommandViewModel.GetCommandViewModel(new ModuleViewModel(command.ModuleName, importedModules), command, noCommonParameter); + returnValue.ModuleQualifyCommandName = moduleQualify; + return returnValue; + } + + /// + /// Dispatches a message to the window for it to activate. + /// + /// Window to be activated. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from ActivateWindow() which is called using reflection")] + private static void ActivateWindow(Window window) + { + window.Dispatcher.Invoke( + new SendOrPostCallback( + (_) => window.Activate()), + string.Empty); + } + + /// + /// Shows the window listing cmdlets. + /// + /// Cmdlet calling this method. + /// All loaded modules. + /// Commands to be listed. + /// True if we should not show common parameters. + /// Window width. + /// Window height. + /// True if the GUI should mention ok instead of run. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private void ShowAllModulesWindow(PSCmdlet cmdlet, Dictionary importedModules, IEnumerable commands, bool noCommonParameter, double windowWidth, double windowHeight, bool passThrough) + { + this.methodThatReturnsDialog = new DispatcherOperationCallback((object ignored) => + { + ShowAllModulesWindow allModulesWindow = new ShowAllModulesWindow(); + this.allModulesViewModel = new AllModulesViewModel(importedModules, commands, noCommonParameter); + + this.SetupButtonEvents(allModulesWindow.Run, allModulesWindow.Copy, allModulesWindow.Cancel, passThrough); + this.SetupWindow(allModulesWindow); + this.SetupViewModel(); + CommonHelper.SetStartingPositionAndSize( + allModulesWindow, + ShowCommandSettings.Default.ShowCommandsTop, + ShowCommandSettings.Default.ShowCommandsLeft, + windowWidth != 0.0 && windowWidth > allModulesWindow.MinWidth ? windowWidth : ShowCommandSettings.Default.ShowCommandsWidth, + windowHeight != 0.0 && windowHeight > allModulesWindow.MinHeight ? windowHeight : ShowCommandSettings.Default.ShowCommandsHeight, + allModulesWindow.Width, + allModulesWindow.Height, + ShowCommandSettings.Default.ShowCommandsWindowMaximized); + + return allModulesWindow; + }); + + this.CallShowDialog(cmdlet); + } + + /// + /// Calls ShowsDialog on methodThatReturnsDialog either in a separate thread or dispatched + /// to the hostWindow thread if there is a hostWindow + /// + /// Cmdlet used to retrieve the host window. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from a method called using reflection")] + private void CallShowDialog(PSCmdlet cmdlet) + { + this.hostWindow = ShowCommandHelper.GetHostWindow(cmdlet); + if (this.hostWindow == null) + { + Thread guiThread = new Thread(new ThreadStart(this.PlainInvokeAndShowDialog)); + guiThread.SetApartmentState(ApartmentState.STA); + guiThread.Start(); + return; + } + + this.hostWindow.Dispatcher.Invoke( + new SendOrPostCallback( + (_) => + { + Window childWindow = (Window)this.methodThatReturnsDialog.Invoke(null); + childWindow.Owner = this.hostWindow; + childWindow.Show(); + }), + string.Empty); + } + + /// + /// Called from CallMethodThatShowsDialog as the thtead start when there is no host window. + /// + private void PlainInvokeAndShowDialog() + { + ((Window)this.methodThatReturnsDialog.Invoke(null)).ShowDialog(); + } + + /// + /// Shows the window for the cmdlet. + /// + /// Cmdlet calling this method. + /// Command to show in the window. + /// Window width. + /// Window height. + /// True if the GUI should mention ok instead of run. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private void ShowCommandWindow(PSCmdlet cmdlet, object commandViewModelObj, double windowWidth, double windowHeight, bool passThrough) + { + this.methodThatReturnsDialog = new DispatcherOperationCallback((object ignored) => + { + this.commandViewModel = (CommandViewModel)commandViewModelObj; + ShowCommandWindow showCommandWindow = new ShowCommandWindow(); + + this.commandViewModel.HelpNeeded += this.CommandNeedsHelp; + showCommandWindow.DataContext = this.commandViewModel; + + this.SetupButtonEvents(showCommandWindow.Run, showCommandWindow.Copy, showCommandWindow.Cancel, passThrough); + this.SetupWindow(showCommandWindow); + + CommonHelper.SetStartingPositionAndSize( + showCommandWindow, + ShowCommandSettings.Default.ShowOneCommandTop, + ShowCommandSettings.Default.ShowOneCommandLeft, + windowWidth != 0.0 && windowWidth > showCommandWindow.MinWidth ? windowWidth : ShowCommandSettings.Default.ShowOneCommandWidth, + windowHeight != 0.0 && windowHeight > showCommandWindow.MinHeight ? windowHeight : ShowCommandSettings.Default.ShowOneCommandHeight, + showCommandWindow.Width, + showCommandWindow.Height, + ShowCommandSettings.Default.ShowOneCommandWindowMaximized); + + return showCommandWindow; + }); + + this.CallShowDialog(cmdlet); + } + + /// + /// Called when the module importation is done. + /// + /// All modules currently imported. + /// Commands to be displayed. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private void ImportModuleDone(Dictionary importedModules, IEnumerable commands) + { + this.allModulesViewModel.WaitMessageDisplayed = false; + if (this.window != null) + { + this.window.Dispatcher.Invoke( + new SendOrPostCallback( + delegate(object ignored) + { + this.allModulesViewModel = ShowCommandHelper.GetNewAllModulesViewModel( + this.allModulesViewModel, + importedModules, + commands, + this.selectedModuleNeedingImportModule, + this.parentModuleNeedingImportModule, + this.commandNeedingImportModule); + this.SetupViewModel(); + }), + string.Empty); + } + } + + /// + /// Called when the module importation has failed. + /// + /// Reason why the module importation failed. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private void ImportModuleFailed(Exception reason) + { + this.allModulesViewModel.WaitMessageDisplayed = false; + if (this.window != null) + { + this.window.Dispatcher.Invoke( + new SendOrPostCallback( + (_) => + { + string message = ShowCommandHelper.GetImportModuleFailedMessage( + this.commandNeedingImportModule, + this.parentModuleNeedingImportModule, + reason.Message); + MessageBox.Show(this.window, message, ShowCommandResources.ShowCommandError, MessageBoxButton.OK, MessageBoxImage.Error); + }), + string.Empty); + } + } + + /// + /// Called when the results or get-help are ready in order to display the help window for a command. + /// + /// Results of a get-help call. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private void DisplayHelp(Collection getHelpResults) + { + if (this.window != null && getHelpResults != null && getHelpResults.Count > 0) + { + this.window.Dispatcher.Invoke( + new SendOrPostCallback( + delegate(object ignored) + { + HelpWindow help = new HelpWindow(getHelpResults[0]); + help.Owner = this.window; + help.Show(); + }), + string.Empty); + } + } + + /// + /// Activates this.window. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private void ActivateWindow() + { + if (this.window != null) + { + ShowCommandHelper.ActivateWindow(this.window); + } + } + + /// + /// Returns the script to execute if dialog has not been canceled. + /// + /// The script to execute if dialog has not been canceled. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] + private string GetScript() + { + if (this.dialogCanceled) + { + return null; + } + + return this.InternalGetScript(); + } + #endregion private methods called using reflection from show-command + + #region instance private methods used only on this file + /// + /// Sets up window settings common between the two flavors of show-command. + /// + /// The window being displayed. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from ShowAllModulesWindow and ShowCommandWindow which are called with reflection")] + private void SetupWindow(Window commandWindow) + { + this.window = commandWindow; + this.window.Closed += this.Window_Closed; + this.window.Loaded += this.Window_Loaded; + } + + /// + /// Handles the SelectedCommandInSelectedModuleNeedsImportModule event. + /// + /// Event sender. + /// Event arguments. + private void CommandNeedsImportModule(object sender, ImportModuleEventArgs e) + { + this.commandNeedingImportModule = e.CommandName; + this.parentModuleNeedingImportModule = e.ParentModuleName; + this.selectedModuleNeedingImportModule = e.SelectedModuleName; + this.allModulesViewModel.WaitMessageDisplayed = true; + this.ImportModuleNeeded.Set(); + } + + /// + /// Handles the SelectedCommandInSelectedModuleNeedsHelp event. + /// + /// Event sender. + /// Event arguments. + private void CommandNeedsHelp(object sender, HelpNeededEventArgs e) + { + this.commandNeedingHelp = e.CommandName; + this.HelpNeeded.Set(); + } + + /// + /// Called when the window is closed to set this.dialogCanceled. + /// + /// Event sender. + /// Event arguments. + private void Window_Closed(object sender, EventArgs e) + { + if (this.hostWindow != null) + { + this.hostWindow.Focus(); + } + + this.window = null; + this.windowClosed.Set(); + } + + /// + /// Called when the window is loaded to set this.Window_Loaded. + /// + /// Event sender. + /// Event arguments. + private void Window_Loaded(object sender, RoutedEventArgs e) + { + this.window.Loaded -= this.Window_Loaded; + this.windowLoaded.Set(); + } + + /// + /// Sets up event listening on the buttons. + /// + /// Button to run command. + /// Button to copy command code. + /// Button to close window. + /// True to change the text of Run to OK. + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from methods called using reflection")] + private void SetupButtonEvents(Button run, Button copy, Button cancel, bool passThrough) + { + if (passThrough) + { + run.Content = ShowCommandResources.ActionButtons_Button_Ok; + } + + run.Click += this.Buttons_RunClick; + copy.Click += this.Buttons_CopyClick; + cancel.Click += this.Buttons_CancelClick; + } + + /// + /// Sets up event listening for a new viewModel. + /// + private void SetupViewModel() + { + this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsHelp += this.CommandNeedsHelp; + this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsImportModule += this.CommandNeedsImportModule; + this.window.DataContext = this.allModulesViewModel; + } + + /// + /// Copies the script into the clipboard. + /// + /// Event sender. + /// Event arguments. + private void Buttons_CopyClick(object sender, RoutedEventArgs e) + { + string script = this.InternalGetScript(); + if (script == null) + { + return; + } + + this.window.Dispatcher.Invoke(new ThreadStart(delegate { ShowCommandHelper.SetClipboardText(script); })); + } + + /// + /// Sets a successful dialog result and then closes the window. + /// + /// Event sender. + /// Event arguments. + private void Buttons_RunClick(object sender, RoutedEventArgs e) + { + this.dialogCanceled = false; + this.CloseWindow(); + } + + /// + /// Closes the window. + /// + /// Event sender. + /// Event arguments. + private void Buttons_CancelClick(object sender, RoutedEventArgs e) + { + this.CloseWindow(); + } + + /// + /// Closes the window. + /// + private void CloseWindow() + { + if (this.window == null) + { + return; + } + + this.window.Dispatcher.Invoke(new ThreadStart(delegate + { + // This can happen if ISE is closed while show-command is up + if (this.window != null) + { + this.window.Close(); + } + })); + } + + /// + /// Showing a MessageBox when user type a invalidate command name. + /// + /// Error message. + private void ShowErrorString(string errorString) + { + if (errorString != null && errorString.Trim().Length > 0) + { + MessageBox.Show( + string.Format( + CultureInfo.CurrentUICulture, + ShowCommandResources.EndProcessingErrorMessage, + errorString), + "Show-Command", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + } + + /// + /// Returns the script to execute. + /// + /// The script to execute. + private string InternalGetScript() + { + if (this.allModulesViewModel != null) + { + return this.allModulesViewModel.GetScript(); + } + + if (this.commandViewModel == null) + { + return null; + } + + return this.commandViewModel.GetScript(); + } + + /// + /// Implements IDisposable logic. + /// + /// True if being called from Dispose. + private void Dispose(bool isDisposing) + { + if (isDisposing) + { + this.windowClosed.Dispose(); + this.helpNeeded.Dispose(); + this.windowLoaded.Dispose(); + this.importModuleNeeded.Dispose(); + } + } + #endregion instance private methods used only on this file + } +} diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Add16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Add16.png new file mode 100644 index 0000000000000000000000000000000000000000..d8e35e17068e662faec5efd839d705f81e14977c Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Add16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/CloseTile16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/CloseTile16.png new file mode 100644 index 0000000000000000000000000000000000000000..402faaaeb84f82c6d28c509532942491a125b4e6 Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/CloseTile16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Delete16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Delete16.png new file mode 100644 index 0000000000000000000000000000000000000000..6262686a39d56706638f3b984d4e02737b7bdc8a Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Delete16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Error16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Error16.png new file mode 100644 index 0000000000000000000000000000000000000000..d3f0d561f0fbf0ffc46f3d5acad6fdf31ed645d3 Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Error16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Help.ico b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Help.ico new file mode 100644 index 0000000000000000000000000000000000000000..f6b92d0b8c2d0f174335c827cab18f74064b260d Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Help.ico differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Rename16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Rename16.png new file mode 100644 index 0000000000000000000000000000000000000000..6e56ab34219a89e18e1dc7a3043257321c742a09 Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Rename16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Save16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Save16.png new file mode 100644 index 0000000000000000000000000000000000000000..d1a016c7d5de41518cfd400978266258d9f7c894 Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/Save16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SortAdornerAscending.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SortAdornerAscending.png new file mode 100644 index 0000000000000000000000000000000000000000..b9bab9b01e6895c862447a9caa81698f2da7a30b Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SortAdornerAscending.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SortAdornerDescending.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SortAdornerDescending.png new file mode 100644 index 0000000000000000000000000000000000000000..d13962672698f3bfb51bafcc7d0151f2e568faf3 Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SortAdornerDescending.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SpyGlass10.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SpyGlass10.png new file mode 100644 index 0000000000000000000000000000000000000000..ff3ebf3236ae531364931455cc4bc459961e72fb Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SpyGlass10.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SpyGlass16.png b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SpyGlass16.png new file mode 100644 index 0000000000000000000000000000000000000000..b7aa28c70aa697195d5c06445f64fe2a1dba84dc Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/SpyGlass16.png differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/down.ico b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/down.ico new file mode 100644 index 0000000000000000000000000000000000000000..98e0339426ab72e852e66ba335bc519ac0d33b11 Binary files /dev/null and b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/Graphics/down.ico differ diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..0a86d51a82eeb5870f0e6cc106e697803b085a38 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + OutGridViewWindow Object + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..3bcab7bfb8a1a1e2789a3d01a01ea2d4cb04405a --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cancel + + + Match Case + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Description + + + Examples + + + _Find: + + + Help Sections + + + {0} Help + + + Inputs + + + {0} {1} + + + Methods + + + _Next + + + No matches found + + + Notes + + + OK + + + 1 match + + + Outputs + + + Accept wildcard characters? + + + Default value + + + Accept pipeline input? + + + Position? + + + Required? + + + Parameters + + + _Previous + + + Properties + + + RelatedLinks + + + Remarks + + + Search Options + + + Settings + + + {0} matches + + + Synopsis + + + Syntax + + + Help for {0} + {0} is the name of a cmdlet + + + Whole Word + + + {0}% + + + Zoom + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..62924692a43f9c8cf3df6085c8a91023fde78dd4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0} cannot be modified directly, use {1} instead. + + + Columns + + + {0:G} + The format string that is used by the InnerList in the case where a DateTime type is used. The {0} will be the column value. + + + {0} + The format string that is used by the InnerList in the default case. The {0} will be the column value. + + + {0:N} + The format string that is used by the InnerList in the case where a floating point number is used. The {0} will be the column value. + + + {0:N0} + The format string that is used by the InnerList in the case where a whole number type is used. The {0} will be the column value. + + + {0} does not support adding to the Items collection, use {1} instead. + + + If View is set to a {0}, it should have the type {1}. + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..5853a0a3c01effbf02513f477bd4ca3da012ab0f --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx @@ -0,0 +1,239 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cancel + + + Co_py + + + _Run + + + All + + + Modules: + + + ? + + + Help + + + Common Parameters + + + Errors + + + Parameters for "{0}": + + + Name: {0} +Module: {1} ({2}) + + + The following errors occurred running the command: +{0} + + + * + Used in MandatoryNameLabelFormat to designate a mandatory parameter with a * + + + {0}:{1} + This is a label for a control, hence the colon. {0} is a parameter name, {1} is MandatoryLabelSegment or an empty string + + + {0}: + This is a label for a control, hence the colon. {0} is a parameter name + + + Name: + + + OK + + + ... + + + Command Name + + + Modules + + + <No module name> + + + Select multiple values for "{0}" + + + Can receive value from pipeline + + + Common to all parameter sets + + + Mandatory + + + Optional + + + Position: {0} + + + Type: {0} + + + Imported + + + Not Imported + + + Show Details + + + Failed to import the module required by command "{0}". Module name: "{1}". Error message: "{2}". + + + To import the "{0}" module and its cmdlets, including "{1}", click {2}. + + + Show Command - Error + + + Please Wait... + + + Refresh + + + There are no parameters. + + + Click after using "{0}" to see the new commands + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..7f5730b3f8667bec56d47b08a4d4fc772a88f977 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Select Columns... + + + (none) + The group title for items within a column whose value is empty/null. + + + Value should be of Type {0}. + This text represents the error which will be shown when the entered type does not match the type we are expecting. {0} is the expected type. + + + The current selection is empty. + The error validation string to present to the user when they have selected a value out of bounds. + + + contains + A filter rule that indicates a field must contain the specified value. + + + does not contain + A filter rule that indicates a field must not contain the specified value. + + + does not equal + A filter rule that indicates a field must not equal the specified value. + + + equals + A filter rule that indicates a field must equal the specified value. + + + is greater than or equal to + A filter rule that indicates a field must be greater than or equal to the specified value. + + + is between + A filter rule that indicates a field must be between the specified values. + + + is empty + A filter rule that indicates a field must be empty. + + + is not empty + A filter rule that indicates a field must not be empty. + + + is less than or equal to + A filter rule that indicates a field must be less than or equal to the specified value. + + + ends with + A filter rule that indicates a field must end with the specified value. + + + starts with + A filter rule that indicates a field must start with the specified value. + + + Back + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Forward + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + The value must be a valid date in the following format: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + The value must be a valid number. + + + Search + The default background text of the search box. + + + LeftToRight + This value will be loaded at runtime to define the flow direction of WPF application. This value should be set to "RightToLeft" for mirrored language and "LeftToRight" for others. + + + + An ellipsis character. + + + Ctrl+Add + + + Ctrl+Shift+Add + + + Ctrl+Plus + + + Ctrl+Shift+Plus + + + Ctrl+Subtract + + + Ctrl+Shift+Subtract + + + Ctrl+Minus + + + Ctrl+Shift+Minus + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..caff99962fd9b3d178371dda865486277b3b3332 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx @@ -0,0 +1,414 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Available Columns + + + Add + + + Remove + + + Selected Columns + + + Back + Localizable AutomationName for control that is used by accessibility screen readers. + + + Forward + Localizable AutomationName for control that is used by accessibility screen readers. + + + Find in this column + Background text shown in the search box. + + + Expand + + + Name + + + New Query + + + Tasks + This is the title string for the Task Pane. + + + Tasks + AutomationProperties.Name of a SeparatedList. + + + Indeterminate Progress Icon + + + Add criteria + + + Overwrite the existing query or type a different name to save a new query. Each query consists of criteria, sorting, and column customizations. + + + Ok + + + Cancel + + + Click to save a search query + + + Available columns + + + >> + The contents of a button which indicates that items will move from the left column to right column + + + << + The contents of a button which indicates that items will move from the right column to left column + + + Move up + + + Move down + + + OK + + + Cancel + + + Select columns + + + Move selected column to list of visible columns + + + Move selected column to list of hidden columns + + + This column may not be removed. + + + The list must always display at least one column. + + + Selected columns + + + Find in this column + + + Expand + + + Click to clear all filter criteria. + + + Click to add search criteria. + + + Click to expand search criteria. + + + There are currently no saved queries. + + + Queries + + + Delete + + + Rename + + + {0} rule + The text representation of a rule in the filter panel, displayed to accessibility clients. {0} will be the name of the rule. + + + Add + + + Cancel + + + Add Filter Criteria + + + Value + The name for text input fields + + + <Empty> + + + Rules + The name of the panel which contains the filter rules + + + Delete + + + Query + + + Queries + + + Search + + + ({0} of {1}) + The text displayed in the management list title when the list has a filter applied. {0} will be the number of items shown in the list. {1} will be the total number of items in the list before filtering. + + + Searching... + The text displayed in the management list title when the list is processing a filter. + + + ({0}) + The text displayed in the management list title when the list does not have a filter applied. {0} will be the number of items shown in the list. + + + Filter + Localizable AutomationName for control that is used by accessibility screen readers. + + + Filter + + + Shortcut Rules + The name used to indicate custom filter rules which are specific to a particular application. + + + Columns Rules + The name used to indicate filter rules that are based upon the properties of the items in the list. + + + Sort Glyph + + + Sort Glyph + + + Collapse + + + Collapse + + + Sorted ascending + The text used for the accessible ItemStatus property when a column is sorted ascending. + + + Sorted descending + The text used for the accessible ItemStatus property when a column is sorted descending. + + + Collapse + + + Expand + + + Search + + + Cancel + + + Clear All + + + Clear All + + + Clear Search Text + + + Tasks + + + Search + The accessible name of the Search button in the filter panel. + + + Cancel + The accessible name of the Stop Search button in the filter panel. + + + Expand or Collapse Filter Panel + The accessible name of the button that expands/collapses the filter panel. + + + Filter + The background text of the list's search box when filtering is immediate. + + + Click to display saved search queries. + + + Filter applied. + + + and + The first header operator indicates that it is the first item in the list of filter rules. The AND value is used to indicate that it is and'ed with the above SearchBox. + + + and + The header operator indicates that it is the first item in a group of filter rules which are the same. The AND value is used to indicate that it is and'ed with the other groups in the panel. + + + or + The Item operator indicates that it is NOT the first item in a group of filter rules which are the same. The OR value is used to indicate that it is or'ed with the other items in the same group. + + + No matches found. + The text displayed in the ManagementList when the filter has been applied but matching items were found. + + + Collapse + + + Expand + + + Show Children + + + Show Children + + + {0}: {1} + The format string used for the ManagementList title when query has been applied. For example, "Users: My Fancy Query" + + + Cancel + + + OK + + diff --git a/PowerShell-master/src/Microsoft.Management.UI.Internal/themes/generic.xaml b/PowerShell-master/src/Microsoft.Management.UI.Internal/themes/generic.xaml new file mode 100644 index 0000000000000000000000000000000000000000..36d2354e1afcec2dc683b1de3668e03466628ee7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.Management.UI.Internal/themes/generic.xaml @@ -0,0 +1,2790 @@ + + + + + M 0,0 L 4,3.5 L 0,7 Z + + M7.3391155,8.3084572 L7.3391708,16.109179 10.974259,12.431834 z + + + + + + + + + + + + + + + + + + M0.83647823,8.3277649 L5.9975096,11.519699 11.198949,8.3030383 + + M205.63696,8.9046901 L201.73368,12.456607 205.68294,16.093484 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs new file mode 100644 index 0000000000000000000000000000000000000000..dfe046ec8ca7c7e2b9607b5c2e2d4ae1883edb63 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.InteropServices; +using System.Text; + +namespace Microsoft.PowerShell.Commands.Diagnostics.Common +{ + internal static class CommonUtilities + { + private const string LibraryLoadDllName = "api-ms-win-core-libraryloader-l1-2-0.dll"; + private const string LocalizationDllName = "api-ms-win-core-localization-l1-2-1.dll"; + + private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; + private const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; + private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; + private const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; + + [DllImport(LocalizationDllName, SetLastError = true, CharSet = CharSet.Unicode)] + private static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, + uint dwMessageId, uint dwLanguageId, + [MarshalAs(UnmanagedType.LPWStr)] + StringBuilder lpBuffer, + uint nSize, IntPtr Arguments); + + [DllImport(LibraryLoadDllName, SetLastError = true, CharSet = CharSet.Unicode)] + private static extern IntPtr LoadLibraryEx( + [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, + IntPtr hFile, + uint dwFlags + ); + + [DllImport(LibraryLoadDllName)] + private static extern bool FreeLibrary(IntPtr hModule); + + [DllImport(LocalizationDllName, EntryPoint = "GetUserDefaultLangID", CallingConvention = CallingConvention.Winapi, SetLastError = true)] + private static extern ushort GetUserDefaultLangID(); + + public static uint FormatMessageFromModule(uint lastError, string moduleName, out string msg) + { + Debug.Assert(!string.IsNullOrEmpty(moduleName)); + + uint formatError = 0; + msg = string.Empty; + + IntPtr moduleHandle = LoadLibraryEx(moduleName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); + if (moduleHandle == IntPtr.Zero) + { + return (uint)Marshal.GetLastWin32Error(); + } + + try + { + uint LANGID = (uint)GetUserDefaultLangID(); + uint langError = (uint)Marshal.GetLastWin32Error(); + if (langError != 0) + { + LANGID = 0; // neutral + } + + StringBuilder outStringBuilder = new(1024); + uint nChars = FormatMessage( + dwFlags: FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE, + lpSource: moduleHandle, + dwMessageId: lastError, + dwLanguageId: LANGID, + lpBuffer: outStringBuilder, + nSize: (uint)outStringBuilder.Capacity, + Arguments: IntPtr.Zero); + + if (nChars == 0) + { + formatError = (uint)Marshal.GetLastWin32Error(); + } + else + { + msg = outStringBuilder.ToString(); + if (msg.EndsWith(Environment.NewLine, StringComparison.Ordinal)) + { + msg = msg.Substring(0, msg.Length - 2); + } + } + } + finally + { + FreeLibrary(moduleHandle); + } + return formatError; + } + + public static ResourceManager GetResourceManager() + { + return new ResourceManager("Microsoft.PowerShell.Commands.Diagnostics.resources.GetEventResources", typeof(CommonUtilities).GetTypeInfo().Assembly); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..2b11b6d3b03c4de15777e0b427f3b523b28a44ca --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Diagnostics; + +namespace Microsoft.PowerShell.Commands.GetCounter +{ + public class CounterFileInfo + { + internal CounterFileInfo(DateTime oldestRecord, + DateTime newestRecord, + UInt32 sampleCount) + { + _oldestRecord = oldestRecord; + _newestRecord = newestRecord; + _sampleCount = sampleCount; + } + + internal CounterFileInfo() { } + + public DateTime OldestRecord + { + get + { + return _oldestRecord; + } + } + + private DateTime _oldestRecord = DateTime.MinValue; + + public DateTime NewestRecord + { + get + { + return _newestRecord; + } + } + + private DateTime _newestRecord = DateTime.MaxValue; + + public UInt32 SampleCount + { + get + { + return _sampleCount; + } + } + + private UInt32 _sampleCount = 0; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs new file mode 100644 index 0000000000000000000000000000000000000000..9089216a485ec93d6b05543eb79689cbed503628 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Resources; + +namespace Microsoft.PowerShell.Commands.GetCounter +{ + public class PerformanceCounterSample + { + internal PerformanceCounterSample() + { + } + + internal PerformanceCounterSample(string path, + string instanceName, + double cookedValue, + UInt64 rawValue, + UInt64 secondValue, + uint multiCount, + PerformanceCounterType counterType, + UInt32 defaultScale, + UInt64 timeBase, + DateTime timeStamp, + UInt64 timeStamp100nSec, + UInt32 status) + { + Path = path; + InstanceName = instanceName; + CookedValue = cookedValue; + RawValue = rawValue; + SecondValue = secondValue; + MultipleCount = multiCount; + CounterType = counterType; + DefaultScale = defaultScale; + TimeBase = timeBase; + Timestamp = timeStamp; + Timestamp100NSec = timeStamp100nSec; + Status = status; + } + + public string Path { get; set; } = string.Empty; + + public string InstanceName { get; set; } = string.Empty; + + public double CookedValue { get; set; } + + public UInt64 RawValue { get; set; } + + public UInt64 SecondValue { get; set; } + + public uint MultipleCount { get; set; } + + public PerformanceCounterType CounterType { get; set; } + + public DateTime Timestamp { get; set; } = DateTime.MinValue; + + public UInt64 Timestamp100NSec { get; set; } + + public UInt32 Status { get; set; } + + public UInt32 DefaultScale { get; set; } + + public UInt64 TimeBase { get; set; } + } + + public class PerformanceCounterSampleSet + { + internal PerformanceCounterSampleSet() + { + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + } + + internal PerformanceCounterSampleSet(DateTime timeStamp, + PerformanceCounterSample[] counterSamples, + bool firstSet) : this() + { + Timestamp = timeStamp; + CounterSamples = counterSamples; + } + + public DateTime Timestamp { get; set; } = DateTime.MinValue; + + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample.CounterSamples", + Justification = "A string[] is required here because that is the type Powershell supports")] + public PerformanceCounterSample[] CounterSamples { get; set; } + + private readonly ResourceManager _resourceMgr = null; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs new file mode 100644 index 0000000000000000000000000000000000000000..dfc175b604cc4cbd5a60889a8a31f2d5f6fd462b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics; + +namespace Microsoft.PowerShell.Commands.GetCounter +{ + public class CounterSet + { + internal CounterSet(string setName, + string machineName, + PerformanceCounterCategoryType categoryType, + string setHelp, + ref Dictionary counterInstanceMapping) + { + CounterSetName = setName; + if (machineName == null || machineName.Length == 0) + { + machineName = "."; + } + else + { + MachineName = machineName; + if (!MachineName.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) + { + MachineName = @"\\" + MachineName; + } + } + + CounterSetType = categoryType; + Description = setHelp; + CounterInstanceMapping = counterInstanceMapping; + } + + public string CounterSetName { get; } = string.Empty; + + public string MachineName { get; } = "."; + + public PerformanceCounterCategoryType CounterSetType { get; } + + public string Description { get; } = string.Empty; + + internal Dictionary CounterInstanceMapping { get; } + + public StringCollection Paths + { + get + { + StringCollection retColl = new(); + foreach (string counterName in this.CounterInstanceMapping.Keys) + { + string path; + if (CounterInstanceMapping[counterName].Length != 0) + { + path = (MachineName == ".") ? + ("\\" + CounterSetName + "(*)\\" + counterName) : + (MachineName + "\\" + CounterSetName + "(*)\\" + counterName); + } + else + { + path = (MachineName == ".") ? + ("\\" + CounterSetName + "\\" + counterName) : + (MachineName + "\\" + CounterSetName + "\\" + counterName); + } + + retColl.Add(path); + } + + return retColl; + } + } + + public StringCollection PathsWithInstances + { + get + { + StringCollection retColl = new(); + foreach (string counterName in CounterInstanceMapping.Keys) + { + foreach (string instanceName in CounterInstanceMapping[counterName]) + { + string path = (MachineName == ".") ? + ("\\" + CounterSetName + "(" + instanceName + ")\\" + counterName) : + (MachineName + "\\" + CounterSetName + "(" + instanceName + ")\\" + counterName); + retColl.Add(path); + } + } + + return retColl; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..9385e55909fb9c088664de1deb6dc7b865891b4e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs @@ -0,0 +1,383 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Net; +using System.Reflection; +using System.Resources; +using System.Security; +using System.Security.Principal; +using System.Text; +using System.Threading; +using System.Xml; + +using Microsoft.PowerShell.Commands.Diagnostics.Common; +using Microsoft.PowerShell.Commands.GetCounter; +using Microsoft.Powershell.Commands.GetCounter.PdhNative; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class that implements the Get-Counter cmdlet. + /// + [Cmdlet(VerbsData.Export, "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138337")] + public sealed class ExportCounterCommand : PSCmdlet + { + // + // Path parameter + // + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources")] + [Alias("PSPath")] + + public string Path + { + get { return _path; } + + set { _path = value; } + } + + private string _path; + private string _resolvedPath; + + // + // Format parameter. + // Valid strings are "blg", "csv", "tsv" (case-insensitive). + // + [Parameter( + Mandatory = false, + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateNotNull] + [ValidateSet("blg", "csv", "tsv")] + public string FileFormat + { + get { return _format; } + + set { _format = value; } + } + + private string _format = "blg"; + + // + // MaxSize parameter + // Maximum output file size, in megabytes. + // + [Parameter( + HelpMessageBaseName = "GetEventResources")] + public UInt32 MaxSize + { + get { return _maxSize; } + + set { _maxSize = value; } + } + + private UInt32 _maxSize = 0; + + // + // InputObject parameter + // + [Parameter( + Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources")] + + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.ExportCounterCommand.InputObject", + Justification = "A PerformanceCounterSampleSet[] is required here because Powershell supports arrays natively.")] + public PerformanceCounterSampleSet[] InputObject + { + get { return _counterSampleSets; } + + set { _counterSampleSets = value; } + } + + private PerformanceCounterSampleSet[] _counterSampleSets = new PerformanceCounterSampleSet[0]; + + // + // Force switch + // + [Parameter( + HelpMessageBaseName = "GetEventResources")] + public SwitchParameter Force + { + get { return _force; } + + set { _force = value; } + } + + private SwitchParameter _force; + + // + // Circular switch + // + [Parameter( + HelpMessageBaseName = "GetEventResources")] + public SwitchParameter Circular + { + get { return _circular; } + + set { _circular = value; } + } + + private SwitchParameter _circular; + + private ResourceManager _resourceMgr = null; + + private PdhHelper _pdhHelper = null; + + private bool _stopping = false; + + private bool _queryInitialized = false; + + private PdhLogFileType _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; + + // + // BeginProcessing() is invoked once per pipeline + // + protected override void BeginProcessing() + { + +#if CORECLR + if (Platform.IsIoT) + { + // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. + throw new PlatformNotSupportedException(); + } + + // PowerShell 7 requires at least Windows 7, + // so no version test is needed + _pdhHelper = new PdhHelper(false); +#else + // + // Determine the OS version: this cmdlet requires Windows 7 + // because it uses new Pdh functionality. + // + Version osVersion = System.Environment.OSVersion.Version; + if (osVersion.Major < 6 || + (osVersion.Major == 6 && osVersion.Minor < 1)) + { + string msg = _resourceMgr.GetString("ExportCtrWin7Required"); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null)); + } + + _pdhHelper = new PdhHelper(osVersion.Major < 6); +#endif + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + + // + // Set output format (log file type) + // + SetOutputFormat(); + + if (Circular.IsPresent && _maxSize == 0) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterCircularNoMaxSize")); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterCircularNoMaxSize", ErrorCategory.InvalidResult, null)); + } + + uint res = _pdhHelper.ConnectToDataSource(); + if (res != 0) + { + ReportPdhError(res, true); + } + + res = _pdhHelper.OpenQuery(); + if (res != 0) + { + ReportPdhError(res, true); + } + } + + // + // EndProcessing() is invoked once per pipeline + // + protected override void EndProcessing() + { + _pdhHelper.Dispose(); + } + + /// + /// Handle Control-C + /// + protected override void StopProcessing() + { + _stopping = true; + _pdhHelper.Dispose(); + } + + // + // ProcessRecord() override. + // This is the main entry point for the cmdlet. + // When counter data comes from the pipeline, this gets invoked for each pipelined object. + // When it's passed in as an argument, ProcessRecord() is called once for the entire _counterSampleSets array. + // + protected override void ProcessRecord() + { + Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] != null); + + ResolvePath(); + + uint res = 0; + + if (!_queryInitialized) + { + if (_format.ToLowerInvariant().Equals("blg")) + { + res = _pdhHelper.AddRelogCounters(_counterSampleSets[0]); + } + else + { + res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[0]); + } + + if (res != 0) + { + ReportPdhError(res, true); + } + + res = _pdhHelper.OpenLogForWriting(_resolvedPath, _outputFormat, Force.IsPresent, _maxSize * 1024 * 1024, Circular.IsPresent, null); + if (res == PdhResults.PDH_FILE_ALREADY_EXISTS) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterFileExists"), _resolvedPath); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterFileExists", ErrorCategory.InvalidResult, null)); + } + else if (res == PdhResults.PDH_LOG_FILE_CREATE_ERROR) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileCreateFailed"), _resolvedPath); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "FileCreateFailed", ErrorCategory.InvalidResult, null)); + } + else if (res == PdhResults.PDH_LOG_FILE_OPEN_ERROR) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileOpenFailed"), _resolvedPath); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "FileOpenFailed", ErrorCategory.InvalidResult, null)); + } + else if (res != 0) + { + ReportPdhError(res, true); + } + + _queryInitialized = true; + } + + foreach (PerformanceCounterSampleSet set in _counterSampleSets) + { + _pdhHelper.ResetRelogValues(); + + foreach (PerformanceCounterSample sample in set.CounterSamples) + { + bool bUnknownKey = false; + res = _pdhHelper.SetCounterValue(sample, out bUnknownKey); + if (bUnknownKey) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterExportSampleNotInInitialSet"), sample.Path, _resolvedPath); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterExportSampleNotInInitialSet", ErrorCategory.InvalidResult, null)); + } + else if (res != 0) + { + ReportPdhError(res, true); + } + } + + res = _pdhHelper.WriteRelogSample(set.Timestamp); + if (res != 0) + { + ReportPdhError(res, true); + } + + if (_stopping) + { + break; + } + } + } + + // Determines Log File Type based on FileFormat parameter + // + private void SetOutputFormat() + { + switch (_format.ToLowerInvariant()) + { + case "csv": + _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV; + break; + case "tsv": + _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV; + break; + default: // By default file format is blg + _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; + break; + } + } + + private void ResolvePath() + { + try + { + Collection result = null; + result = SessionState.Path.GetResolvedPSPathFromPSPath(_path); + if (result.Count > 1) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ExportDestPathAmbiguous"), _path); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "ExportDestPathAmbiguous", ErrorCategory.InvalidArgument, null)); + } + + foreach (PathInfo currentPath in result) + { + _resolvedPath = currentPath.ProviderPath; + } + } + catch (ItemNotFoundException pathNotFound) + { + // + // This is an expected condition - we will be creating a new file + // + _resolvedPath = pathNotFound.ItemName; + } + } + + private void ReportPdhError(uint res, bool bTerminate) + { + string msg; + uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); + if (formatRes != 0) + { + msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); + } + + Exception exc = new Exception(msg); + if (bTerminate) + { + ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + else + { + WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..0122ad1941ff8dd64f015577a93d10a47b5b32bb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -0,0 +1,632 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Resources; +using System.Threading; +using Microsoft.Powershell.Commands.GetCounter.PdhNative; +using Microsoft.PowerShell.Commands.Diagnostics.Common; +using Microsoft.PowerShell.Commands.GetCounter; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class that implements the Get-Counter cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109647")] + public sealed class GetCounterCommand : PSCmdlet + { + // + // ListSet parameter + // + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "ListSetSet", + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ListSet { get; set; } = { "*" }; + + // + // Counter parameter + // + [Parameter( + Position = 0, + ParameterSetName = "GetCounterSet", + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] Counter + { + get + { + return _counter; + } + + set + { + _counter = value; + _defaultCounters = false; + } + } + + private string[] _counter = {@"\network interface(*)\bytes total/sec", + @"\processor(_total)\% processor time", + @"\memory\% committed bytes in use", + @"\memory\cache faults/sec", + @"\physicaldisk(_total)\% disk time", + @"\physicaldisk(_total)\current disk queue length"}; + + private bool _defaultCounters = true; + + private readonly List _accumulatedCounters = new(); + + // + // SampleInterval parameter. + // Defaults to 1 second. + // + [Parameter( + ParameterSetName = "GetCounterSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateRange((int)1, int.MaxValue)] + public int SampleInterval { get; set; } = 1; + + // + // MaxSamples parameter + // + private const Int64 KEEP_ON_SAMPLING = -1; + + [Parameter( + ParameterSetName = "GetCounterSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateRange((Int64)1, Int64.MaxValue)] + public Int64 MaxSamples + { + get + { + return _maxSamples; + } + + set + { + _maxSamples = value; + _maxSamplesSpecified = true; + } + } + + private Int64 _maxSamples = 1; + private bool _maxSamplesSpecified = false; + + // + // Continuous switch + // + [Parameter(ParameterSetName = "GetCounterSet")] + public SwitchParameter Continuous + { + get { return _continuous; } + + set { _continuous = value; } + } + + private bool _continuous = false; + + // + // ComputerName parameter + // + [Parameter( + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [ValidateNotNull] + [AllowEmptyCollection] + [Alias("Cn")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ComputerName", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ComputerName { get; set; } = Array.Empty(); + + private ResourceManager _resourceMgr = null; + + private PdhHelper _pdhHelper = null; + + private readonly EventWaitHandle _cancelEventArrived = new(false, EventResetMode.ManualReset); + + // Culture identifier(s) + private const string FrenchCultureId = "fr-FR"; + // The localized Pdh resource strings might use Unicode characters that are different from + // what the user can type with the keyboard to represent a special character. + // + // e.g. the apostrophe in French UI culture: it's [char]39 from keyboard, but it's [char]8217 + // in the resource strings. + // + // With this dictionary, we can add special mapping if we find other special cases in the future. + private readonly Dictionary>> _cultureAndSpecialCharacterMap = + new() + { + { + FrenchCultureId, new List>() + { + // 'APOSTROPHE' to 'RIGHT SINGLE QUOTATION MARK' + new Tuple((char)0x0027, (char)0x2019), + // 'MODIFIER LETTER APOSTROPHE' to 'RIGHT SINGLE QUOTATION MARK' + new Tuple((char)0x02BC, (char)0x2019), + // 'HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT' to 'RIGHT SINGLE QUOTATION MARK' + new Tuple((char)0x275C, (char)0x2019), + } + } + }; + + // + // BeginProcessing() is invoked once per pipeline + // + protected override void BeginProcessing() + { + if (Platform.IsIoT) + { + // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. + throw new PlatformNotSupportedException(); + } + + _pdhHelper = new PdhHelper(); + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + + uint res = _pdhHelper.ConnectToDataSource(); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReportPdhError(res, true); + return; + } + + if (Continuous.IsPresent && _maxSamplesSpecified) + { + Exception exc = new(string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterContinuousOrMaxSamples"))); + ThrowTerminatingError(new ErrorRecord(exc, "CounterContinuousOrMaxSamples", ErrorCategory.InvalidArgument, null)); + } + } + + // + // EndProcessing() is invoked once per pipeline + // + protected override void EndProcessing() + { + if (ParameterSetName == "GetCounterSet") + { + ProcessGetCounter(); + } + + _pdhHelper.Dispose(); + } + + // + // Handle Control-C + // + protected override void StopProcessing() + { + _cancelEventArrived.Set(); + _pdhHelper.Dispose(); + } + + // + // ProcessRecord() override. + // This is the main entry point for the cmdlet. + // + protected override void ProcessRecord() + { + try + { + switch (ParameterSetName) + { + case "ListSetSet": + ProcessListSet(); + break; + + case "GetCounterSet": + AccumulatePipelineCounters(); + break; + + default: + Debug.Fail(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); + break; + } + } + catch (Exception exc) + { + ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + } + + // + // AccumulatePipelineCounters() accumulates counter paths in the pipeline scenario: + // we do not want to start sampling until all the counters are supplied. + // + private void AccumulatePipelineCounters() + { + _accumulatedCounters.AddRange(_counter); + } + + // + // ProcessListSet() does the work to process ListSet parameter set. + // + private void ProcessListSet() + { + if (ComputerName.Length == 0) + { + ProcessListSetPerMachine(null); + } + else + foreach (string machine in ComputerName) + { + ProcessListSetPerMachine(machine); + } + } + + // + // ProcessListSetPerMachine() helper lists counter sets on a machine. + // NOTE: machine argument should be NULL for the local machine + // + private void ProcessListSetPerMachine(string machine) + { + StringCollection counterSets = new(); + uint res = _pdhHelper.EnumObjects(machine, ref counterSets); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // add an error message + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoCounterSetsOnComputer"), machine, res); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine)); + return; + } + + CultureInfo culture = GetCurrentCulture(); + List> characterReplacementList = null; + StringCollection validPaths = new(); + + _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList); + + foreach (string pattern in ListSet) + { + bool bMatched = false; + string normalizedPattern = pattern; + + if (characterReplacementList != null) + { + foreach (Tuple pair in characterReplacementList) + { + normalizedPattern = normalizedPattern.Replace(pair.Item1, pair.Item2); + } + } + + WildcardPattern wildLogPattern = new(normalizedPattern, WildcardOptions.IgnoreCase); + + foreach (string counterSet in counterSets) + { + if (!wildLogPattern.IsMatch(counterSet)) + { + continue; + } + + StringCollection counterSetCounters = new(); + StringCollection counterSetInstances = new(); + + res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); + if (res == PdhResults.PDH_ACCESS_DENIED) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSetEnumAccessDenied"), counterSet); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null)); + continue; + } + else if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReportPdhError(res, false); + continue; + } + + string[] instanceArray = new string[counterSetInstances.Count]; + int i = 0; + foreach (string instance in counterSetInstances) + { + instanceArray[i++] = instance; + } + + // + // Special case: no instances present: change to * to create a valid paths + // + if (instanceArray.Length == 1 && + instanceArray[0].Length == 0) + { + instanceArray[0] = "*"; + } + + Dictionary counterInstanceMapping = new(); + foreach (string counter in counterSetCounters) + { + counterInstanceMapping.TryAdd(counter, instanceArray); + } + + PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; + if (counterSetInstances.Count > 1) + { + categoryType = PerformanceCounterCategoryType.MultiInstance; + } + else // if (counterSetInstances.Count == 1) //??? + { + categoryType = PerformanceCounterCategoryType.SingleInstance; + } + + string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet); + + CounterSet setObj = new(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping); + WriteObject(setObj); + bMatched = true; + } + + if (!bMatched) + { + string msg = _resourceMgr.GetString("NoMatchingCounterSetsFound"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, + machine ?? "localhost", normalizedPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null)); + } + } + } + + // + // ProcessGetCounter() + // Does the work to process GetCounterSet parameter set. + // + private void ProcessGetCounter() + { + // 1. Combine machine names with paths, if needed, to construct full paths + // 2. Translate default paths into current locale + // 3. Expand wildcards and validate the paths and write errors for any invalid paths + // 4. OpenQuery/ AddCounters + // 5. Skip the first reading + + CultureInfo culture = GetCurrentCulture(); + List> characterReplacementList = null; + List paths = CombineMachinesAndCounterPaths(); + + if (!_defaultCounters) + { + _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList); + } + + StringCollection allExpandedPaths = new(); + uint res; + foreach (string path in paths) + { + string localizedPath = path; + if (_defaultCounters) + { + res = _pdhHelper.TranslateLocalCounterPath(path, out localizedPath); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathTranslationFailed"), res); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "CounterPathTranslationFailed", ErrorCategory.InvalidResult, null)); + + localizedPath = path; + } + } + else if (characterReplacementList != null) + { + foreach (Tuple pair in characterReplacementList) + { + localizedPath = localizedPath.Replace(pair.Item1, pair.Item2); + } + } + + StringCollection expandedPaths; + res = _pdhHelper.ExpandWildCardPath(localizedPath, out expandedPaths); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + WriteDebug("Could not expand path " + localizedPath); + ReportPdhError(res, false); + continue; + } + + foreach (string expandedPath in expandedPaths) + { + if (!_pdhHelper.IsPathValid(expandedPath)) + { + string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathIsInvalid"), localizedPath); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null)); + + continue; + } + + allExpandedPaths.Add(expandedPath); + } + } + + if (allExpandedPaths.Count == 0) + { + return; + } + + res = _pdhHelper.OpenQuery(); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReportPdhError(res, false); + } + + res = _pdhHelper.AddCounters(ref allExpandedPaths, true); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReportPdhError(res, true); + + return; + } + + PerformanceCounterSampleSet nextSet; + + bool bSkip = true; + uint sampleReads = 0; + + if (Continuous.IsPresent) + { + _maxSamples = KEEP_ON_SAMPLING; + } + + while (true) + { + // read the first set just to get the initial values + res = _pdhHelper.ReadNextSet(out nextSet, bSkip); + + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Display valid data + if (!bSkip) + { + WriteSampleSetObject(nextSet); + sampleReads++; + } + + // Don't need to skip anymore + bSkip = false; + } + else if (res == PdhResults.PDH_NO_DATA || res == PdhResults.PDH_INVALID_DATA) + { + // The provider may not be running. + // We should keep on trying - but skip the next valid reading. + + ReportPdhError(res, false); + + bSkip = true; + + // Count this failed attempt as a sample: + sampleReads++; + } + else + { + // Unexpected error, return + ReportPdhError(res, true); + return; + } + + if (_maxSamples != KEEP_ON_SAMPLING && sampleReads >= _maxSamples) + { + break; + } + + bool cancelled = _cancelEventArrived.WaitOne((int)SampleInterval * 1000, true); + if (cancelled) + { + break; + } + } + } + + private void ReportPdhError(uint res, bool bTerminate) + { + string msg; + uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); + if (formatRes != 0) + { + msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); + } + + Exception exc = new(msg); + if (bTerminate) + { + ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + else + { + WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + } + + // + // CombineMachinesAndCounterPaths() helper. + // For paths that do not contain machine names, creates a path for each machine in machineNames. + // Paths already containing a machine name will be preserved. + // + private List CombineMachinesAndCounterPaths() + { + List retColl = new(); + + if (ComputerName.Length == 0) + { + retColl.AddRange(_accumulatedCounters); + return retColl; + } + + foreach (string path in _accumulatedCounters) + { + if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) // NOTE: can we do anything smarter here? + { + retColl.Add(path); + } + else + { + foreach (string machine in ComputerName) + { + string slashBeforePath = path.Length > 0 && path[0] == '\\' ? string.Empty : "\\"; + if (machine.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) + { + retColl.Add(machine + slashBeforePath + path); + } + else + { + retColl.Add("\\\\" + machine + slashBeforePath + path); + } + } + } + } + + return retColl; + } + + // + // WriteSampleSetObject() helper. + // In addition to writing the PerformanceCounterSampleSet object, + // it writes a single error if one of the samples has an invalid (non-zero) status. + // + private void WriteSampleSetObject(PerformanceCounterSampleSet set) + { + foreach (PerformanceCounterSample sample in set.CounterSamples) + { + if (sample.Status != 0) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid")); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + break; + } + } + + WriteObject(set); + } + + private static CultureInfo GetCurrentCulture() + { + return Thread.CurrentThread.CurrentUICulture; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..c7a07bab6ece39b421fbf9bcc77f1d6b8a67f05a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -0,0 +1,2054 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Eventing.Reader; +using System.Globalization; +using System.Management.Automation; +using System.Net; +using System.Resources; +using System.Security.Principal; +using System.Text; +using System.Xml; + +[assembly: CLSCompliant(false)] + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class that implements the Get-WinEvent cmdlet. + /// + [OutputType(typeof(EventRecord), ParameterSetName = new string[] { "GetLogSet", "GetProviderSet", "FileSet", "HashQuerySet", "XmlQuerySet" })] + [OutputType(typeof(ProviderMetadata), ParameterSetName = new string[] { "ListProviderSet" })] + [OutputType(typeof(EventLogConfiguration), ParameterSetName = new string[] { "ListLogSet" })] + [Cmdlet(VerbsCommon.Get, "WinEvent", DefaultParameterSetName = "GetLogSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096581")] + public sealed class GetWinEventCommand : PSCmdlet + { + /// + /// ListLog parameter. + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "ListLogSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ListLogParamHelp")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.ListLog", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ListLog { get; set; } = { "*" }; + + /// + /// GetLog parameter. + /// + [Parameter( + Position = 0, + ParameterSetName = "GetLogSet", + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "GetLogParamHelp")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.LogName", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] LogName { get; set; } = { "*" }; + + /// + /// ListProvider parameter. + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "ListProviderSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ListProviderParamHelp")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.ListProvider", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ListProvider { get; set; } = { "*" }; + + /// + /// ProviderName parameter. + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "GetProviderSet", + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "GetProviderParamHelp")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.ProviderName", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ProviderName { get; set; } + + /// + /// Path parameter. + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "FileSet", + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "PathParamHelp")] + [Alias("PSPath")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.Path", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] Path { get; set; } + + /// + /// MaxEvents parameter. + /// + [Parameter( + ParameterSetName = "FileSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "GetProviderSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "GetLogSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "HashQuerySet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "XmlQuerySet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [ValidateRange((long)1, long.MaxValue)] + public long MaxEvents { get; set; } = -1; + + /// + /// ComputerName parameter. + /// + [Parameter( + ParameterSetName = "ListProviderSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "GetProviderSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "ListLogSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "GetLogSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "HashQuerySet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "XmlQuerySet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [ValidateNotNull] + [Alias("Cn")] + public string ComputerName { get; set; } = string.Empty; + + /// + /// Credential parameter. + /// + [Parameter(ParameterSetName = "ListProviderSet")] + [Parameter(ParameterSetName = "GetProviderSet")] + [Parameter(ParameterSetName = "ListLogSet")] + [Parameter(ParameterSetName = "GetLogSet")] + [Parameter(ParameterSetName = "HashQuerySet")] + [Parameter(ParameterSetName = "XmlQuerySet")] + [Parameter(ParameterSetName = "FileSet")] + [Credential] + public PSCredential Credential { get; set; } = PSCredential.Empty; + + /// + /// FilterXPath parameter. + /// + [Parameter( + ParameterSetName = "FileSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [Parameter( + ParameterSetName = "GetProviderSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [Parameter( + ParameterSetName = "GetLogSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateNotNull] + public string FilterXPath { get; set; } = "*"; + + /// + /// FilterXml parameter. + /// + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "XmlQuerySet", + HelpMessageBaseName = "GetEventResources")] + public XmlDocument FilterXml { get; set; } + + /// + /// FilterHashtable parameter. + /// + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "HashQuerySet", + HelpMessageBaseName = "GetEventResources")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.FilterHashtable", + Justification = "A string[] is required here because that is the type Powershell supports")] + public Hashtable[] FilterHashtable { get; set; } + + /// + /// Force switch. + /// + [Parameter(ParameterSetName = "ListLogSet")] + [Parameter(ParameterSetName = "GetProviderSet")] + [Parameter(ParameterSetName = "GetLogSet")] + [Parameter(ParameterSetName = "HashQuerySet")] + public SwitchParameter Force { get; set; } + + /// + /// Oldest switch. + /// + [Parameter(ParameterSetName = "FileSet")] + [Parameter(ParameterSetName = "GetProviderSet")] + [Parameter(ParameterSetName = "GetLogSet")] + [Parameter(ParameterSetName = "HashQuerySet")] + [Parameter(ParameterSetName = "XmlQuerySet")] + public SwitchParameter Oldest + { + get { return _oldest; } + + set { _oldest = value; } + } + + private bool _oldest = false; + + // + // Query builder constant strings + // + private const string queryListOpen = ""; + private const string queryListClose = ""; + private const string queryTemplate = ""; + private const string queryOpenerTemplate = ""; + private const string suppressOpener = "*"; + private const string suppressCloser = ""; + private const char propOpen = '['; + private const char propClose = ']'; + private const string filePrefix = "file://"; + private const string NamedDataTemplate = "((EventData[Data[@Name='{0}']='{1}']) or (UserData/*/{0}='{1}'))"; + private const string DataTemplate = "(EventData/Data='{0}')"; + private const string SystemTimePeriodTemplate = "(System/TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}'])"; + private const string SystemTimeStartTemplate = "(System/TimeCreated[@SystemTime>='{0}'])"; + private const string SystemTimeEndTemplate = "(System/TimeCreated[@SystemTime<='{0}'])"; + private const string SystemLevelTemplate = "(System/Level="; + private const string SystemEventIDTemplate = "(System/EventID="; + private const string SystemSecurityTemplate = "(System/Security[@UserID='{0}'])"; + private const string SystemKeywordsTemplate = "System[band(Keywords,{0})]"; + + // + // Other private members and constants + // + private ResourceManager _resourceMgr = null; + private readonly Dictionary _providersByLogMap = new(); + + private StringCollection _logNamesMatchingWildcard = null; + private readonly StringCollection _resolvedPaths = new(); + + private readonly List _accumulatedLogNames = new(); + private readonly List _accumulatedProviderNames = new(); + private readonly List _accumulatedFileNames = new(); + + private const uint MAX_EVENT_BATCH = 100; + + // + // Hashtable query key names + // + private const string hashkey_logname_lc = "logname"; + private const string hashkey_providername_lc = "providername"; + private const string hashkey_path_lc = "path"; + private const string hashkey_keywords_lc = "keywords"; + private const string hashkey_id_lc = "id"; + private const string hashkey_level_lc = "level"; + private const string hashkey_starttime_lc = "starttime"; + private const string hashkey_endtime_lc = "endtime"; + private const string hashkey_userid_lc = "userid"; + private const string hashkey_data_lc = "data"; + private const string hashkey_supress_lc = "suppresshashfilter"; + + /// + /// BeginProcessing() is invoked once per pipeline: we will load System.Core.dll here. + /// + protected override void BeginProcessing() + { + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + } + + /// + /// EndProcessing() is invoked once per pipeline. + /// + protected override void EndProcessing() + { + switch (ParameterSetName) + { + case "GetLogSet": + ProcessGetLog(); + break; + + case "FileSet": + ProcessFile(); + break; + + case "GetProviderSet": + ProcessGetProvider(); + break; + + default: + break; + } + } + + /// + /// ProcessRecord() override. + /// This is the main entry point for the cmdlet. + /// + protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case "ListLogSet": + ProcessListLog(); + break; + + case "ListProviderSet": + ProcessListProvider(); + break; + + case "GetLogSet": + AccumulatePipelineLogNames(); + break; + + case "FileSet": + AccumulatePipelineFileNames(); + break; + + case "HashQuerySet": + ProcessHashQuery(); + break; + + case "GetProviderSet": + AccumulatePipelineProviderNames(); + break; + + case "XmlQuerySet": + ProcessFilterXml(); + break; + + default: + WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); + break; + } + } + + // + // AccumulatePipelineCounters() accumulates log names in the pipeline scenario: + // we do not want to construct a query until all the log names are supplied. + // + private void AccumulatePipelineLogNames() + { + _accumulatedLogNames.AddRange(LogName); + } + + // + // AccumulatePipelineProviderNames() accumulates provider names in the pipeline scenario: + // we do not want to construct a query until all the provider names are supplied. + // + private void AccumulatePipelineProviderNames() + { + _accumulatedProviderNames.AddRange(LogName); + } + + // + // AccumulatePipelineFileNames() accumulates log file paths in the pipeline scenario: + // we do not want to construct a query until all the file names are supplied. + // + private void AccumulatePipelineFileNames() + { + _accumulatedFileNames.AddRange(LogName); + } + + // + // Process GetLog parameter set + // + private void ProcessGetLog() + { + using (EventLogSession eventLogSession = CreateSession()) + { + FindLogNamesMatchingWildcards(eventLogSession, _accumulatedLogNames); + if (_logNamesMatchingWildcard.Count == 0) + { + return; + } + + EventLogQuery logQuery; + if (_logNamesMatchingWildcard.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.LogName, query); + logQuery.TolerateQueryErrors = true; + } + else + { + logQuery = new EventLogQuery(_logNamesMatchingWildcard[0], PathType.LogName, FilterXPath); + } + + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + ReadEvents(logQuery); + } + } + + // + // Process GetProviderSet parameter set + // + private void ProcessGetProvider() + { + using (EventLogSession eventLogSession = CreateSession()) + { + FindProvidersByLogForWildcardPatterns(eventLogSession, ProviderName); + + if (_providersByLogMap.Count == 0) + { + // + // Just return: errors already written above for each unmatched provider name pattern. + // + return; + } + + EventLogQuery logQuery = null; + if (_providersByLogMap.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.LogName, query); + logQuery.TolerateQueryErrors = true; + } + else + { + // + // There's only one key at this point, but we need an enumerator to get to it. + // + foreach (string log in _providersByLogMap.Keys) + { + logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Log {log} will be queried")); + } + } + + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + ReadEvents(logQuery); + } + } + + // + // Process ListLog parameter set + // + private void ProcessListLog() + { + using (EventLogSession eventLogSession = CreateSession()) + { + foreach (string logPattern in ListLog) + { + bool bMatchFound = false; + WildcardPattern wildLogPattern = new(logPattern, WildcardOptions.IgnoreCase); + + foreach (string logName in eventLogSession.GetLogNames()) + { + if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) + && string.Equals(logPattern, logName, StringComparison.OrdinalIgnoreCase)) + || + (wildLogPattern.IsMatch(logName))) + { + try + { + EventLogConfiguration logObj = new(logName, eventLogSession); + + // + // Skip direct channels matching the wildcard unless -Force is present. + // + if (!Force.IsPresent && + WildcardPattern.ContainsWildcardCharacters(logPattern) && + (logObj.LogType == EventLogType.Debug || + logObj.LogType == EventLogType.Analytical)) + { + continue; + } + + EventLogInformation logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); + + PSObject outputObj = new(logObj); + + outputObj.Properties.Add(new PSNoteProperty("FileSize", logInfoObj.FileSize)); + outputObj.Properties.Add(new PSNoteProperty("IsLogFull", logInfoObj.IsLogFull)); + outputObj.Properties.Add(new PSNoteProperty("LastAccessTime", logInfoObj.LastAccessTime)); + outputObj.Properties.Add(new PSNoteProperty("LastWriteTime", logInfoObj.LastWriteTime)); + outputObj.Properties.Add(new PSNoteProperty("OldestRecordNumber", logInfoObj.OldestRecordNumber)); + outputObj.Properties.Add(new PSNoteProperty("RecordCount", logInfoObj.RecordCount)); + + WriteObject(outputObj); + bMatchFound = true; + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + logName, exc.Message); + Exception outerExc = new(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } + } + } + + if (!bMatchFound) + { + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, ComputerName, logPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, null)); + } + } + } + } + + // + // Process ListProvider parameter set + // + private void ProcessListProvider() + { + using (EventLogSession eventLogSession = CreateSession()) + { + foreach (string provPattern in ListProvider) + { + bool bMatchFound = false; + WildcardPattern wildProvPattern = new(provPattern, WildcardOptions.IgnoreCase); + + foreach (string provName in eventLogSession.GetProviderNames()) + { + if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) + && string.Equals(provPattern, provName, StringComparison.OrdinalIgnoreCase)) + || + (wildProvPattern.IsMatch(provName))) + { + try + { + ProviderMetadata provObj = new(provName, eventLogSession, CultureInfo.CurrentCulture); + WriteObject(provObj); + bMatchFound = true; + } + catch (System.Diagnostics.Eventing.Reader.EventLogException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("ProviderMetadataUnavailable"), + provName, exc.Message); + Exception outerExc = new(msg, exc); + WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } + } + } + + if (!bMatchFound) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoMatchingProvidersFound"), + ComputerName, provPattern); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, null)); + } + } + } + } + + // + // Process FilterXml parameter set + // + private void ProcessFilterXml() + { + using (EventLogSession eventLogSession = CreateSession()) + { + if (!Oldest.IsPresent) + { + // + // Do minimal parsing of xmlQuery to determine if any direct channels or ETL files are in it. + // + XmlElement root = FilterXml.DocumentElement; + XmlNodeList queryNodes = root.SelectNodes("//Query//Select"); + foreach (XmlNode queryNode in queryNodes) + { + XmlAttributeCollection attribs = queryNode.Attributes; + foreach (XmlAttribute attrib in attribs) + { + if (attrib.Name.Equals("Path", StringComparison.OrdinalIgnoreCase)) + { + string logName = attrib.Value; + + if (logName.StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase)) + { + TerminateForNonEvtxFileWithoutOldest(logName); + } + + ValidateLogName(logName, eventLogSession); + } + } + } + } + + EventLogQuery logQuery = new(null, PathType.LogName, FilterXml.InnerXml); + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + ReadEvents(logQuery); + } + } + + // + // Process FileSet parameter set + // + private void ProcessFile() + { + using (EventLogSession eventLogSession = CreateSession()) + { + // + // At this point, _path array contains paths that might have wildcards, + // environment variables or PS drives. Let's resolve those. + // + for (int i = 0; i < Path.Length; i++) + { + StringCollection resolvedPaths = ValidateAndResolveFilePath(Path[i]); + foreach (string resolvedPath in resolvedPaths) + { + _resolvedPaths.Add(resolvedPath); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found file {resolvedPath}")); + } + } + + EventLogQuery logQuery = null; + if (_resolvedPaths.Count == 0) + { + return; + } + else if (_resolvedPaths.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.FilePath, query); + logQuery.TolerateQueryErrors = true; + } + else + { + logQuery = new EventLogQuery(_resolvedPaths[0], PathType.FilePath, FilterXPath); + } + + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + ReadEvents(logQuery); + } + } + + // + // Process HashQuerySet parameter set + // + private void ProcessHashQuery() + { + CheckHashTablesForNullValues(); + + using (EventLogSession eventLogSession = CreateSession()) + { + string query = BuildStructuredQuery(eventLogSession); + if (query.Length == 0) + { + return; + } + + EventLogQuery logQuery = new(null, PathType.FilePath, query); + logQuery.Session = eventLogSession; + logQuery.TolerateQueryErrors = true; + logQuery.ReverseDirection = !_oldest; + + ReadEvents(logQuery); + } + } + + // + // CreateSession creates an EventLogSession connected to a target machine or localhost. + // If _credential argument is PSCredential.Empty, the session will be created for the current context. + // + private EventLogSession CreateSession() + { + EventLogSession eventLogSession = null; + + if (ComputerName == string.Empty) + { + // Set _computerName to "localhost" for future error messages, + // but do not use it for the connection to avoid RPC overhead. + ComputerName = "localhost"; + + if (Credential == PSCredential.Empty) + { + return new EventLogSession(); + } + } + else if (Credential == PSCredential.Empty) + { + return new EventLogSession(ComputerName); + } + + // If we are here, either both computer name and credential were passed initially, + // or credential only - we will use it with "localhost" + + NetworkCredential netCred = (NetworkCredential)Credential; + eventLogSession = new EventLogSession(ComputerName, + netCred.Domain, + netCred.UserName, + Credential.Password, + SessionAuthentication.Default + ); + // + // Force the destruction of cached password + // + netCred.Password = string.Empty; + + return eventLogSession; + } + + // + // ReadEvents helper. + // + private void ReadEvents(EventLogQuery logQuery) + { + using (EventLogReader readerObj = new(logQuery)) + { + long numEvents = 0; + EventRecord evtObj = null; + + while (true) + { + try + { + evtObj = readerObj.ReadEvent(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + continue; + } + + if (evtObj == null) + { + break; + } + + if (MaxEvents != -1 && numEvents >= MaxEvents) + { + break; + } + + PSObject outputObj = new(evtObj); + + string evtMessage = _resourceMgr.GetString("NoEventMessage"); + try + { + evtMessage = evtObj.FormatDescription(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + } + + outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); + + // + // Enumerate the object one level to get to event payload + // + WriteObject(outputObj, true); + numEvents++; + } + + if (numEvents == 0) + { + string msg = _resourceMgr.GetString("NoMatchingEventsFound"); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); + } + } + } + + // + // BuildStructuredQuery() builds a structured query from cmdlet arguments. + // + private string BuildStructuredQuery(EventLogSession eventLogSession) + { + StringBuilder result = new(); + + switch (ParameterSetName) + { + case "ListLogSet": + break; + + case "ListProviderSet": + break; + + case "GetProviderSet": + { + result.Append(queryListOpen); + uint queryId = 0; + + foreach (string log in _providersByLogMap.Keys) + { + string providerFilter = AddProviderPredicatesToFilter(_providersByLogMap[log]); + result.AppendFormat(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, providerFilter }); + } + + result.Append(queryListClose); + } + + break; + + case "GetLogSet": + { + const int WindowsEventLogAPILimit = 256; + if (_logNamesMatchingWildcard.Count > WindowsEventLogAPILimit) + { + string msg = _resourceMgr.GetString("LogCountLimitExceeded"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, _logNamesMatchingWildcard.Count, WindowsEventLogAPILimit)); + ThrowTerminatingError(new ErrorRecord(exc, "LogCountLimitExceeded", ErrorCategory.LimitsExceeded, null)); + } + + result.Append(queryListOpen); + uint queryId = 0; + foreach (string log in _logNamesMatchingWildcard) + { + result.AppendFormat(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, FilterXPath }); + } + + result.Append(queryListClose); + } + + break; + + case "FileSet": + { + result.Append(queryListOpen); + uint queryId = 0; + foreach (string filePath in _resolvedPaths) + { + string properFilePath = filePrefix + filePath; + result.AppendFormat(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, properFilePath, FilterXPath }); + } + + result.Append(queryListClose); + } + + break; + + case "HashQuerySet": + result.Append(BuildStructuredQueryFromHashTable(eventLogSession)); + break; + + default: + WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); + break; + } + + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("QueryTrace"), result.ToString())); + + return result.ToString(); + } + + // + // BuildXPathFromHashTable() build xpath from hashtable + // + private string BuildXPathFromHashTable(Hashtable hash) + { + StringBuilder xpathString = new(string.Empty); + bool bDateTimeHandled = false; + + foreach (string key in hash.Keys) + { + string added = string.Empty; + + switch (key.ToLowerInvariant()) + { + case hashkey_logname_lc: + case hashkey_path_lc: + case hashkey_providername_lc: + break; + case hashkey_id_lc: + added = HandleEventIdHashValue(hash[key]); + break; + + case hashkey_level_lc: + added = HandleLevelHashValue(hash[key]); + break; + + case hashkey_keywords_lc: + added = HandleKeywordHashValue(hash[key]); + break; + + case hashkey_starttime_lc: + if (bDateTimeHandled) + { + break; + } + + added = HandleStartTimeHashValue(hash[key], hash); + + bDateTimeHandled = true; + break; + + case hashkey_endtime_lc: + if (bDateTimeHandled) + { + break; + } + + added = HandleEndTimeHashValue(hash[key], hash); + + bDateTimeHandled = true; + break; + + case hashkey_data_lc: + added = HandleDataHashValue(hash[key]); + break; + + case hashkey_userid_lc: + added = HandleContextHashValue(hash[key]); + break; + + case hashkey_supress_lc: + break; + default: + { + // + // None of the recognized values: this must be a named event data field + // + // Fix Issue #2327 + added = HandleNamedDataHashValue(key, hash[key]); + } + + break; + } + + if (added.Length > 0) + { + if (xpathString.Length != 0) + { + xpathString.Append(" and "); + } + + xpathString.Append(added); + } + } + + return xpathString.ToString(); + } + + // + // BuildStructuredQueryFromHashTable() helper. + // Builds a structured query from the hashtable (Selector) argument. + // + private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession) + { + StringBuilder result = new(string.Empty); + + result.Append(queryListOpen); + + uint queryId = 0; + + foreach (Hashtable hash in FilterHashtable) + { + string xpathString = string.Empty; + string xpathStringSuppress = string.Empty; + + CheckHashTableForQueryPathPresence(hash); + + // + // Local queriedLogsQueryMap will hold names of logs or files to be queried + // mapped to the actual query strings being built up. + // + Dictionary queriedLogsQueryMap = new(); + + // + // queriedLogsQueryMapSuppress is the same as queriedLogsQueryMap but for + // + Dictionary queriedLogsQueryMapSuppress = new(); + + // + // Process log, _path, or provider parameters first + // to create initial partially-filled query templates. + // Error out for direct channels unless -oldest is present. + // + // Order is important! Process "providername" key after "logname" and "file". + // + if (hash.ContainsKey(hashkey_logname_lc)) + { + List logPatterns = new(); + if (hash[hashkey_logname_lc] is Array) + { + foreach (object elt in (Array)hash[hashkey_logname_lc]) + { + logPatterns.Add(elt.ToString()); + } + } + else + { + logPatterns.Add(hash[hashkey_logname_lc].ToString()); + } + + FindLogNamesMatchingWildcards(eventLogSession, logPatterns); + + foreach (string logName in _logNamesMatchingWildcard) + { + queriedLogsQueryMap.Add(logName.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, logName)); + queriedLogsQueryMapSuppress.Add(logName.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, suppressOpener, queryId++, logName)); + } + } + + if (hash.ContainsKey(hashkey_path_lc)) + { + if (hash[hashkey_path_lc] is Array) + { + foreach (object elt in (Array)hash[hashkey_path_lc]) + { + StringCollection resolvedPaths = ValidateAndResolveFilePath(elt.ToString()); + foreach (string resolvedPath in resolvedPaths) + { + queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath)); + queriedLogsQueryMapSuppress.Add(filePrefix + resolvedPath.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, suppressOpener, queryId++, filePrefix + resolvedPath)); + } + } + } + else + { + StringCollection resolvedPaths = ValidateAndResolveFilePath(hash[hashkey_path_lc].ToString()); + foreach (string resolvedPath in resolvedPaths) + { + queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath)); + queriedLogsQueryMapSuppress.Add(filePrefix + resolvedPath.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, suppressOpener, queryId++, filePrefix + resolvedPath)); + } + } + } + + if (hash.ContainsKey(hashkey_providername_lc)) + { + List provPatterns = new(); + if (hash[hashkey_providername_lc] is Array) + { + foreach (object elt in (Array)hash[hashkey_providername_lc]) + { + provPatterns.Add(elt.ToString()); + } + } + else + { + provPatterns.Add(hash[hashkey_providername_lc].ToString()); + } + + FindProvidersByLogForWildcardPatterns(eventLogSession, provPatterns); + + // + // If "providername" key is used alone, we will construct a query across all of the providers' logs. + // Otherwise, we will use the provider names to add predicates to "logname" and "path" queries. + // + if (!hash.ContainsKey(hashkey_path_lc) && !hash.ContainsKey(hashkey_logname_lc)) + { + foreach (string keyLogName in _providersByLogMap.Keys) + { + string providersPredicate = BuildProvidersPredicate(_providersByLogMap[keyLogName]); + string query = string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, keyLogName); + queriedLogsQueryMap.Add(keyLogName.ToLowerInvariant(), + query + "[" + providersPredicate); + queriedLogsQueryMapSuppress.Add(keyLogName.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, suppressOpener, queryId++, keyLogName.ToLowerInvariant())); + } + } + else + { + List keysList = new(queriedLogsQueryMap.Keys); + bool bRemovedIrrelevantLogs = false; + foreach (string queriedLog in keysList) + { + if (queriedLog.StartsWith(filePrefix, StringComparison.Ordinal)) + { + queriedLogsQueryMap[queriedLog] += "[" + BuildAllProvidersPredicate(); + } + else + { + if (_providersByLogMap.ContainsKey(queriedLog)) + { + string providersPredicate = BuildProvidersPredicate(_providersByLogMap[queriedLog]); + queriedLogsQueryMap[queriedLog] += "[" + providersPredicate; + } + else + { + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("SpecifiedProvidersDontWriteToLog"), queriedLog)); + queriedLogsQueryMap.Remove(queriedLog); + queriedLogsQueryMapSuppress.Remove(queriedLog); + bRemovedIrrelevantLogs = true; + } + } + } + // + // Write an error if we have removed all the logs as irrelevant + // + if (bRemovedIrrelevantLogs && (queriedLogsQueryMap.Count == 0)) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("LogsAndProvidersDontOverlap")); + Exception exc = new(msg); + WriteError(new ErrorRecord(exc, "LogsAndProvidersDontOverlap", ErrorCategory.InvalidArgument, null)); + continue; + } + } + } + + // + // If none of the logs/paths/providers were valid, queriedLogsQueryMap is empty. + // Simply continue to the next hashtable since all the errors have been written already. + // + if (queriedLogsQueryMap.Count == 0) + { + continue; + } + + // + // At this point queriedLogsQueryMap contains all the query openings: missing the actual XPaths + // Let's build xpathString to attach to each query opening. + // + xpathString = BuildXPathFromHashTable(hash); + + // + // Build xpath for + // + if (hash[hashkey_supress_lc] is Hashtable suppresshash) + { + xpathStringSuppress = BuildXPathFromHashTable(suppresshash); + } + + // + // Complete each query with the XPath. + // Handle the case where the query opener already has provider predicate(s). + // Add the queries from queriedLogsQueryMap into the resulting string. + // Add from queriedLogsQueryMapSuppress into the resulting string. + // + foreach (string keyLogName in queriedLogsQueryMap.Keys) + { + // For every Log a separate query is + string query = queriedLogsQueryMap[keyLogName]; + result.Append(query); + + if (query.EndsWith('*')) + { + // + // No provider predicate: just add the XPath string + // + if (xpathString.Length != 0) + { + result.Append(propOpen).Append(xpathString).Append(propClose); + } + } + else + { + // + // Add xpathString to provider predicates. + // + if (xpathString.Length != 0) + { + result.Append(" and ").Append(xpathString); + } + + result.Append(propClose); + } + + result.Append(SelectCloser); + + if (xpathStringSuppress.Length != 0) + { + // Add *xpathStringSuppress into query + string suppress = queriedLogsQueryMapSuppress[keyLogName]; + result.Append(suppress); + result.Append(propOpen).Append(xpathStringSuppress).Append(propClose); + result.Append(suppressCloser); + } + + result.Append(queryCloser); + } + } + + result.Append(queryListClose); + + return result.ToString(); + } + + // + // HandleEventIdHashValue helper for hashtable structured query builder. + // Constructs and returns EventId XPath portion as a string. + // + private static string HandleEventIdHashValue(object value) + { + StringBuilder ret = new(); + if (value is Array idsArray) + { + ret.Append('('); + for (int i = 0; i < idsArray.Length; i++) + { + ret.Append(SystemEventIDTemplate).Append(idsArray.GetValue(i).ToString()).Append(')'); + if (i < (idsArray.Length - 1)) + { + ret.Append(" or "); + } + } + + ret.Append(')'); + } + else + { + ret.Append(SystemEventIDTemplate).Append(value).Append(')'); + } + + return ret.ToString(); + } + + // + // HandleLevelHashValue helper for hashtable structured query builder. + // Constructs and returns Level XPath portion as a string. + // + private static string HandleLevelHashValue(object value) + { + StringBuilder ret = new(); + if (value is Array levelsArray) + { + ret.Append('('); + for (int i = 0; i < levelsArray.Length; i++) + { + ret.Append(SystemLevelTemplate).Append(levelsArray.GetValue(i).ToString()).Append(')'); + if (i < (levelsArray.Length - 1)) + { + ret.Append(" or "); + } + } + + ret.Append(')'); + } + else + { + ret.Append(SystemLevelTemplate).Append(value).Append(')'); + } + + return ret.ToString(); + } + + // + // HandleKeywordHashValue helper for hashtable structured query builder. + // Constructs and returns Keyword XPath portion as a string. + // + private string HandleKeywordHashValue(object value) + { + long keywordsMask = 0; + long keywordLong = 0; + + if (value is Array keywordArray) + { + foreach (object keyword in keywordArray) + { + if (KeywordStringToInt64(keyword.ToString(), ref keywordLong)) + { + keywordsMask |= keywordLong; + } + } + } + else + { + if (!KeywordStringToInt64(value.ToString(), ref keywordLong)) + { + return string.Empty; + } + + keywordsMask |= keywordLong; + } + + return string.Format(CultureInfo.InvariantCulture, SystemKeywordsTemplate, keywordsMask); + } + + // + // HandleContextHashValue helper for hashtable structured query builder. + // Constructs and returns UserID XPath portion as a string. + // Handles both SIDs and domain account names. + // Writes an error and returns an empty string if the SID or account names are not valid. + // + private string HandleContextHashValue(object value) + { + SecurityIdentifier sidCandidate = null; + try + { + sidCandidate = new SecurityIdentifier(value.ToString()); + } + catch (ArgumentException) + { + WriteDebug(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidSIDFormat"), value)); + } + + if (sidCandidate == null) + { + try + { + NTAccount acct = new(value.ToString()); + sidCandidate = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); + } + catch (ArgumentException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidContext"), value.ToString()); + Exception outerExc = new(msg, exc); + WriteError(new ErrorRecord(outerExc, "InvalidContext", ErrorCategory.InvalidArgument, null)); + return string.Empty; + } + } + + return string.Format(CultureInfo.InvariantCulture, SystemSecurityTemplate, sidCandidate.ToString()); + } + + // + // HandleStartTimeHashValue helper for hashtable structured query builder. + // Constructs and returns TimeCreated XPath portion as a string. + // NOTE that it also handles the hashtable "endtime" value (if supplied). + // + private string HandleStartTimeHashValue(object value, Hashtable hash) + { + StringBuilder ret = new(); + DateTime startTime = new(); + if (!StringToDateTime(value.ToString(), ref startTime)) + { + return string.Empty; + } + + startTime = startTime.ToUniversalTime(); + string startTimeFormatted = startTime.ToString("s", CultureInfo.InvariantCulture) + "." + startTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + + if (hash.ContainsKey(hashkey_endtime_lc)) + { + DateTime endTime = new(); + if (!StringToDateTime(hash[hashkey_endtime_lc].ToString(), ref endTime)) + { + return string.Empty; + } + + endTime = endTime.ToUniversalTime(); + string endTimeFormatted = endTime.ToString("s", CultureInfo.InvariantCulture) + "." + endTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + + ret.AppendFormat(CultureInfo.InvariantCulture, + SystemTimePeriodTemplate, + startTimeFormatted, + endTimeFormatted); + } + else + { + ret.AppendFormat(CultureInfo.InvariantCulture, + SystemTimeStartTemplate, + startTimeFormatted); + } + + return ret.ToString(); + } + + // + // HandleEndTimeHashValue helper for hashtable structured query builder. + // Constructs and returns TimeCreated XPath portion as a string. + // NOTE that it also handles the hashtable "starttime" value (if supplied). + // + private string HandleEndTimeHashValue(object value, Hashtable hash) + { + StringBuilder ret = new(); + DateTime endTime = new(); + if (!StringToDateTime(value.ToString(), ref endTime)) + { + return string.Empty; + } + + endTime = endTime.ToUniversalTime(); + string endTimeFormatted = endTime.ToString("s", CultureInfo.InvariantCulture) + "." + + endTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + + if (hash.ContainsKey(hashkey_starttime_lc)) + { + DateTime startTime = new(); + if (!StringToDateTime(hash[hashkey_starttime_lc].ToString(), ref startTime)) + { + return string.Empty; + } + + startTime = startTime.ToUniversalTime(); + string startTimeFormatted = startTime.ToString("s", CultureInfo.InvariantCulture) + "." + + startTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + + ret.AppendFormat(CultureInfo.InvariantCulture, + SystemTimePeriodTemplate, + startTimeFormatted, + endTimeFormatted); + } + else + { + ret.AppendFormat(CultureInfo.InvariantCulture, + SystemTimeEndTemplate, + endTimeFormatted); + } + + return ret.ToString(); + } + + // + // HandleDataHashValue helper for hashtable structured query builder. + // Constructs and returns EventData/Data XPath portion as a string. + // + private static string HandleDataHashValue(object value) + { + StringBuilder ret = new(); + if (value is Array dataArray) + { + ret.Append('('); + for (int i = 0; i < dataArray.Length; i++) + { + ret.AppendFormat(CultureInfo.InvariantCulture, DataTemplate, dataArray.GetValue(i).ToString()); + if (i < (dataArray.Length - 1)) + { + ret.Append(" or "); + } + } + + ret.Append(')'); + } + else + { + ret.AppendFormat(CultureInfo.InvariantCulture, DataTemplate, value); + } + + return ret.ToString(); + } + + // + // HandleNamedDataHashValue helper for hashtable structured query builder. + // Constructs and returns named event data field XPath portion as a string. + // Fix Issue #2327 + // + private static string HandleNamedDataHashValue(string key, object value) + { + StringBuilder ret = new(); + if (value is Array dataArray) + { + ret.Append('('); + for (int i = 0; i < dataArray.Length; i++) + { + ret.AppendFormat(CultureInfo.InvariantCulture, + NamedDataTemplate, + key, dataArray.GetValue(i).ToString()); + if (i < (dataArray.Length - 1)) + { + ret.Append(" or "); + } + } + + ret.Append(')'); + } + else + { + ret.AppendFormat(CultureInfo.InvariantCulture, + NamedDataTemplate, + key, value); + } + + return ret.ToString(); + } + + // + // Helper checking whether at least one of log, _path, provider is specified. + // It will ThrowTerminatingError in case none of those keys are present. + // + private void CheckHashTableForQueryPathPresence(Hashtable hash) + { + bool isLogHash = (hash.ContainsKey(hashkey_logname_lc)); + bool isPathHash = (hash.ContainsKey(hashkey_path_lc)); + bool isProviderHash = (hash.ContainsKey(hashkey_providername_lc)); + + if (!isLogHash && !isProviderHash && !isPathHash) + { + string msg = _resourceMgr.GetString("LogProviderOrPathNeeded"); + Exception exc = new(msg); + ThrowTerminatingError(new ErrorRecord(exc, "LogProviderOrPathNeeded", ErrorCategory.InvalidArgument, null)); + } + } + + // + // TerminateForNonEvtxFileWithoutOldest terminates for .evt and .etl files unless -Oldest is specified. + // + private void TerminateForNonEvtxFileWithoutOldest(string fileName) + { + if (!Oldest.IsPresent) + { + if (System.IO.Path.GetExtension(fileName).Equals(".etl", StringComparison.OrdinalIgnoreCase) || + System.IO.Path.GetExtension(fileName).Equals(".evt", StringComparison.OrdinalIgnoreCase)) + { + string msg = _resourceMgr.GetString("SpecifyOldestForEtlEvt"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, fileName)); + ThrowTerminatingError(new ErrorRecord(exc, "SpecifyOldestForEtlEvt", ErrorCategory.InvalidArgument, fileName)); + } + } + } + + // + // ValidateLogName writes an error if logName is not a valid log. + // It also terminates for direct ETW channels unless -Oldest is specified. + // + private bool ValidateLogName(string logName, EventLogSession eventLogSession) + { + EventLogConfiguration logObj; + try + { + logObj = new EventLogConfiguration(logName, eventLogSession); + } + catch (EventLogNotFoundException) + { + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, ComputerName, logName)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logName)); + return false; + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + logName, exc.Message); + Exception outerExc = new(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); + return false; + } + + if (!Oldest.IsPresent) + { + if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) + { + string msg = _resourceMgr.GetString("SpecifyOldestForLog"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, logName)); + ThrowTerminatingError(new ErrorRecord(exc, "SpecifyOldestForLog", ErrorCategory.InvalidArgument, logName)); + } + } + + return true; + } + + // + // KeywordStringToInt64 helper converts a string to Int64. + // Returns true and keyLong ref if successful. + // Writes an error and returns false if keyString cannot be converted. + // + private bool KeywordStringToInt64(string keyString, ref long keyLong) + { + try + { + keyLong = Convert.ToInt64(keyString, CultureInfo.InvariantCulture); + } + catch (Exception exc) + { + string msg = _resourceMgr.GetString("KeywordLongExpected"); + Exception outerExc = new(string.Format(CultureInfo.InvariantCulture, msg, keyString), exc); + WriteError(new ErrorRecord(outerExc, "KeywordLongExpected", ErrorCategory.InvalidArgument, null)); + return false; + } + + return true; + } + + // + // StringToDateTime helper converts a string to DateTime object. + // Returns true and DateTime ref if successful. + // Writes an error and returns false if dtString cannot be converted. + // + private bool StringToDateTime(string dtString, ref DateTime dt) + { + try + { + dt = DateTime.Parse(dtString, CultureInfo.CurrentCulture); + } + catch (FormatException exc) + { + string msg = _resourceMgr.GetString("DateTimeExpected"); + Exception outerExc = new(string.Format(CultureInfo.InvariantCulture, msg, dtString), exc); + WriteError(new ErrorRecord(outerExc, "DateTimeExpected", ErrorCategory.InvalidArgument, null)); + return false; + } + + return true; + } + + // + // ValidateAndResolveFilePath helper. + // Returns a string collection of resolved file paths. + // Writes non-terminating errors for invalid paths + // and returns an empty collection. + // + private StringCollection ValidateAndResolveFilePath(string path) + { + StringCollection retColl = new(); + + Collection resolvedPathSubset = null; + try + { + resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(path); + } + catch (PSNotSupportedException notSupported) + { + WriteError(new ErrorRecord(notSupported, string.Empty, ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (System.Management.Automation.DriveNotFoundException driveNotFound) + { + WriteError(new ErrorRecord(driveNotFound, string.Empty, ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError(new ErrorRecord(providerNotFound, string.Empty, ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError(new ErrorRecord(pathNotFound, string.Empty, ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, string.Empty, ErrorCategory.ObjectNotFound, path)); + return retColl; + } + + foreach (PathInfo pi in resolvedPathSubset) + { + // + // Check the provider: only FileSystem provider paths are acceptable. + // + if (pi.Provider.Name != "FileSystem") + { + string msg = _resourceMgr.GetString("NotAFileSystemPath"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, path)); + WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, path)); + continue; + } + + // + // Check the extension: only .evt, .evtx, and .etl files are allowed. + // If the file was specified without wildcards, display an error. + // Otherwise, skip silently. + // + if (!System.IO.Path.GetExtension(pi.Path).Equals(".evt", StringComparison.OrdinalIgnoreCase) && + !System.IO.Path.GetExtension(pi.Path).Equals(".evtx", StringComparison.OrdinalIgnoreCase) && + !System.IO.Path.GetExtension(pi.Path).Equals(".etl", StringComparison.OrdinalIgnoreCase)) + { + if (!WildcardPattern.ContainsWildcardCharacters(path)) + { + string msg = _resourceMgr.GetString("NotALogFile"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, pi.ProviderPath)); + WriteError(new ErrorRecord(exc, "NotALogFile", ErrorCategory.InvalidArgument, path)); + } + + continue; + } + + TerminateForNonEvtxFileWithoutOldest(pi.ProviderPath); + + retColl.Add(pi.ProviderPath.ToLowerInvariant()); + } + + return retColl; + } + + // + // CheckHashTablesForNullValues() checks all _selector values + // and writes a terminating error when it encounters a null + // as a single value or as part of an array. + // + private void CheckHashTablesForNullValues() + { + foreach (Hashtable hash in FilterHashtable) + { + foreach (string key in hash.Keys) + { + object value = hash[key]; + if (value == null) + { + string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, key)); + ThrowTerminatingError(new ErrorRecord(exc, "NullNotAllowedInHashtable", ErrorCategory.InvalidArgument, key)); + } + else + { + if (value is Array eltArray) + { + foreach (object elt in eltArray) + { + if (elt == null) + { + string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, key)); + ThrowTerminatingError(new ErrorRecord(exc, "NullNotAllowedInHashtable", ErrorCategory.InvalidArgument, key)); + } + } + } + } + } + } + } + + // + // AddProviderPredicatesToFilter() builds an XPath query + // by adding provider predicates to _filter. + // Note that this is by no means an XPath expression parser + // and will may produce garbage if the _filterXPath expression provided by the user is invalid. + // However, we are relying on the EventLog XPath parser to reject the garbage later on. + // + private string AddProviderPredicatesToFilter(StringCollection providers) + { + if (providers.Count == 0) + { + return FilterXPath; + } + + string ret = FilterXPath; + string predicate = BuildProvidersPredicate(providers); + + if (FilterXPath.Equals("*", StringComparison.OrdinalIgnoreCase)) + { + ret += "[" + predicate + "]"; + } + else + { + // + // Extend the XPath provided in the _filter + // + int lastPredClose = FilterXPath.LastIndexOf(']'); + if (lastPredClose == -1) + { + ret += "[" + predicate + "]"; + } + else + { + ret = ret.Insert(lastPredClose, " and " + predicate); + } + } + + return ret; + } + + // + // BuildProvidersPredicate() builds a predicate expression like: + // "System/Provider[@Name='a' or @Name='b']" + // for all provider names specified in the "providers" argument. + // + private static string BuildProvidersPredicate(StringCollection providers) + { + if (providers.Count == 0) + { + return string.Empty; + } + + StringBuilder predicate = new("System/Provider["); + for (int i = 0; i < providers.Count; i++) + { + predicate.Append("@Name='").Append(providers[i]).Append('\''); + if (i < (providers.Count - 1)) + { + predicate.Append(" or "); + } + } + + predicate.Append(']'); + + return predicate.ToString(); + } + + // + // BuildAllProvidersPredicate() builds a predicate expression like: + // "System/Provider[@Name='a' or @Name='b']" + // for all unique provider names specified in _providersByLogMap. + // Eliminates duplicates, too, since the same provider can + // be writing to several different logs. + // + private string BuildAllProvidersPredicate() + { + if (_providersByLogMap.Count == 0) + { + return string.Empty; + } + + StringBuilder predicate = new("System/Provider["); + + List uniqueProviderNames = new(); + + foreach (string logKey in _providersByLogMap.Keys) + { + for (int i = 0; i < _providersByLogMap[logKey].Count; i++) + { + string lowerCaseProviderName = _providersByLogMap[logKey][i].ToLowerInvariant(); + if (!uniqueProviderNames.Contains(lowerCaseProviderName)) + { + uniqueProviderNames.Add(lowerCaseProviderName); + } + } + } + + for (int i = 0; i < uniqueProviderNames.Count; i++) + { + predicate.Append("@Name='").Append(uniqueProviderNames[i]).Append('\''); + if (i < uniqueProviderNames.Count - 1) + { + predicate.Append(" or "); + } + } + + predicate.Append(']'); + + return predicate.ToString(); + } + + // + // AddLogsForProviderToInternalMap helper. + // Retrieves log names to which _providerName writes. + // NOTE: there are many misconfigured providers in the system. + // We therefore catch EventLogException exceptions and write them out as non-terminating errors. + // The results are added to _providersByLogMap dictionary. + // + private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, string providerName) + { + try + { + ProviderMetadata providerMetadata = new(providerName, eventLogSession, CultureInfo.CurrentCulture); + + System.Collections.IEnumerable logLinks = providerMetadata.LogLinks; + + foreach (EventLogLink logLink in logLinks) + { + if (!_providersByLogMap.ContainsKey(logLink.LogName.ToLowerInvariant())) + { + // + // Skip direct ETW channels unless -force is present. + // Error out for direct channels unless -oldest is present. + // + EventLogConfiguration logObj = new(logLink.LogName, eventLogSession); + if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) + { + if (!Force.IsPresent) + { + continue; + } + + ValidateLogName(logLink.LogName, eventLogSession); + } + + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName)); + + StringCollection provColl = new(); + provColl.Add(providerName.ToLowerInvariant()); + + _providersByLogMap.Add(logLink.LogName.ToLowerInvariant(), provColl); + } + else + { + // + // Log is there: add provider, if needed + // + StringCollection coll = _providersByLogMap[logLink.LogName.ToLowerInvariant()]; + + if (!coll.Contains(providerName.ToLowerInvariant())) + { + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName)); + + coll.Add(providerName.ToLowerInvariant()); + } + } + } + } + catch (System.Diagnostics.Eventing.Reader.EventLogException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("ProviderMetadataUnavailable"), + providerName, exc.Message); + Exception outerExc = new(msg, exc); + WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); + return; + } + } + + // + // FindLogNamesMatchingWildcards helper. + // Finds all logs whose names match wildcard patterns in the 'logPatterns' argument. + // For each non-matched pattern, a non-terminating error is written. + // The results are added to _logNamesMatchingWildcard array. + // + private void FindLogNamesMatchingWildcards(EventLogSession eventLogSession, IEnumerable logPatterns) + { + if (_logNamesMatchingWildcard == null) + { + _logNamesMatchingWildcard = new StringCollection(); + } + else + { + _logNamesMatchingWildcard.Clear(); + } + + foreach (string logPattern in logPatterns) + { + bool bMatched = false; + WildcardPattern wildLogPattern = new(logPattern, WildcardOptions.IgnoreCase); + + foreach (string actualLogName in eventLogSession.GetLogNames()) + { + if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) + && (logPattern.Equals(actualLogName, StringComparison.OrdinalIgnoreCase))) + || + (wildLogPattern.IsMatch(actualLogName))) + { + // + // Skip direct ETW channels matching wildcards unless -force is present. + // Error out for direct channels unless -oldest is present. + // + EventLogConfiguration logObj; + try + { + logObj = new EventLogConfiguration(actualLogName, eventLogSession); + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + actualLogName, exc.Message); + Exception outerExc = new(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } + + if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) + { + if (WildcardPattern.ContainsWildcardCharacters(logPattern) && !Force.IsPresent) + { + continue; + } + + ValidateLogName(actualLogName, eventLogSession); + } + + if (!_logNamesMatchingWildcard.Contains(actualLogName.ToLowerInvariant())) + { + _logNamesMatchingWildcard.Add(actualLogName.ToLowerInvariant()); + } + + bMatched = true; + } + } + + if (!bMatched) + { + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, ComputerName, logPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logPattern)); + } + } + } + + // + // FindProvidersByLogForWildcardPatterns helper. + // Finds all providers whose names match wildcard patterns in 'providerPatterns' argument. + // For each non-matched pattern, a non-terminating error is written. + // The results are added to _providersByLogMap dictionary (keyed by log names to which these providers write). + // + private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSession, IEnumerable providerPatterns) + { + _providersByLogMap.Clear(); + + foreach (string provPattern in providerPatterns) + { + bool bMatched = false; + WildcardPattern wildProvPattern = new(provPattern, WildcardOptions.IgnoreCase); + + foreach (string provName in eventLogSession.GetProviderNames()) + { + if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) + && (provPattern.Equals(provName, StringComparison.OrdinalIgnoreCase))) + || + (wildProvPattern.IsMatch(provName))) + { + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found matching provider: {provName}")); + AddLogsForProviderToInternalMap(eventLogSession, provName); + bMatched = true; + } + } + + if (!bMatched) + { + string msg = _resourceMgr.GetString("NoMatchingProvidersFound"); + Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg, ComputerName, provPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, provPattern)); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs new file mode 100644 index 0000000000000000000000000000000000000000..a4693c454c0d55aac801850ae8416d8f8b8fb04a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Management.Automation; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Create the PowerShell snap-in used to register the + /// Get-WinEvent cmdlet. Declaring the PSSnapIn class identifies + /// this .cs file as a PowerShell snap-in. + /// + [RunInstaller(true)] + public class GetEventPSSnapIn : PSSnapIn + { + /// + /// Create an instance of the GetEventPSSnapIn class. + /// + public GetEventPSSnapIn() + : base() + { + } + + /// + /// Specify the name of the PowerShell snap-in. + /// + public override string Name + { + get + { + return "Microsoft.Powershell.GetEvent"; + } + } + + /// + /// Specify the vendor of the PowerShell snap-in. + /// + public override string Vendor + { + get + { + return "Microsoft"; + } + } + + /// + /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. + /// + public override string VendorResource + { + get + { + return "GetEventResources,Vendor"; + } + } + + /// + /// Specifies the description of the PowerShell snap-in. + /// + public override string Description + { + get + { + return "This PS snap-in contains Get-WinEvent cmdlet used to read Windows event log data and configuration."; + } + } + + /// + /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. + /// + public override string DescriptionResource + { + get + { + return "GetEventResources,Description"; + } + } + + /// + /// Get type files to be used for this PSSnapin. + /// + public override string[] Types + { + get + { + return _types; + } + } + + private string[] _types = new string[] { "getevent.types.ps1xml" }; + + /// + /// Get format files to be used for this PSSnapin. + /// + public override string[] Formats + { + get + { + return _formats; + } + } + + private string[] _formats = new string[] { "Event.format.ps1xml" }; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..729334d06056b75b777199d00a5a0796843849db --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs @@ -0,0 +1,681 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Net; +using System.Reflection; +using System.Resources; +using System.Security; +using System.Security.Principal; +using System.Text; +using System.Threading; +using System.Xml; + +using Microsoft.PowerShell.Commands.Diagnostics.Common; +using Microsoft.PowerShell.Commands.GetCounter; +using Microsoft.Powershell.Commands.GetCounter.PdhNative; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class that implements the Get-Counter cmdlet. + /// + [Cmdlet(VerbsData.Import, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138338")] + public sealed class ImportCounterCommand : PSCmdlet + { + // + // Path parameter + // + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources")] + [Alias("PSPath")] + + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] Path + { + get { return _path; } + + set { _path = value; } + } + + private string[] _path; + + private StringCollection _resolvedPaths = new StringCollection(); + + private List _accumulatedFileNames = new List(); + + // + // ListSet parameter + // + [Parameter( + Mandatory = true, + ParameterSetName = "ListSetSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ListSet + { + get { return _listSet; } + + set { _listSet = value; } + } + + private string[] _listSet = Array.Empty(); + + // + // StartTime parameter + // + [Parameter( + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "GetCounterSet", + HelpMessageBaseName = "GetEventResources")] + public DateTime StartTime + { + get { return _startTime; } + + set { _startTime = value; } + } + + private DateTime _startTime = DateTime.MinValue; + + // + // EndTime parameter + // + [Parameter( + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "GetCounterSet", + HelpMessageBaseName = "GetEventResources")] + public DateTime EndTime + { + get { return _endTime; } + + set { _endTime = value; } + } + + private DateTime _endTime = DateTime.MaxValue; + + // + // Counter parameter + // + [Parameter( + Mandatory = false, + ParameterSetName = "GetCounterSet", + ValueFromPipeline = false, + HelpMessageBaseName = "GetEventResources")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] Counter + { + get { return _counter; } + + set { _counter = value; } + } + + private string[] _counter = Array.Empty(); + + // + // Summary switch + // + [Parameter(ParameterSetName = "SummarySet")] + public SwitchParameter Summary + { + get { return _summary; } + + set { _summary = value; } + } + + private SwitchParameter _summary; + + // + // MaxSamples parameter + // + private const Int64 KEEP_ON_SAMPLING = -1; + [Parameter( + ParameterSetName = "GetCounterSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateRange((Int64)1, Int64.MaxValue)] + public Int64 MaxSamples + { + get { return _maxSamples; } + + set { _maxSamples = value; } + } + + private Int64 _maxSamples = KEEP_ON_SAMPLING; + + private ResourceManager _resourceMgr = null; + + private PdhHelper _pdhHelper = null; + + private bool _stopping = false; + + // + // AccumulatePipelineFileNames() accumulates counter file paths in the pipeline scenario: + // we do not want to construct a Pdh query until all the file names are supplied. + // + private void AccumulatePipelineFileNames() + { + _accumulatedFileNames.AddRange(_path); + } + + // + // BeginProcessing() is invoked once per pipeline + // + protected override void BeginProcessing() + { + +#if CORECLR + if (Platform.IsIoT) + { + // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. + throw new PlatformNotSupportedException(); + } + + // PowerShell 7 requires at least Windows 7, + // so no version test is needed + _pdhHelper = new PdhHelper(false); +#else + _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); +#endif + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + } + + // + // EndProcessing() is invoked once per pipeline + // + protected override void EndProcessing() + { + // + // Resolve and validate the Path argument: present for all parametersets. + // + if (!ResolveFilePaths()) + { + return; + } + + ValidateFilePaths(); + + switch (ParameterSetName) + { + case "ListSetSet": + ProcessListSet(); + break; + + case "GetCounterSet": + ProcessGetCounter(); + break; + + case "SummarySet": + ProcessSummary(); + break; + + default: + Debug.Assert(false, $"Invalid parameter set name: {ParameterSetName}"); + break; + } + + _pdhHelper.Dispose(); + } + + // + // Handle Control-C + // + protected override void StopProcessing() + { + _stopping = true; + _pdhHelper.Dispose(); + } + + // + // ProcessRecord() override. + // This is the main entry point for the cmdlet. + // + protected override void ProcessRecord() + { + AccumulatePipelineFileNames(); + } + + // + // ProcessSummary(). + // Does the work to process Summary parameter set. + // + private void ProcessSummary() + { + uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); + if (res != 0) + { + ReportPdhError(res, true); + return; + } + + CounterFileInfo summaryObj; + res = _pdhHelper.GetFilesSummary(out summaryObj); + + if (res != 0) + { + ReportPdhError(res, true); + return; + } + + WriteObject(summaryObj); + } + + // + // ProcessListSet(). + // Does the work to process ListSet parameter set. + // + private void ProcessListSet() + { + uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); + if (res != 0) + { + ReportPdhError(res, true); + return; + } + + StringCollection machineNames = new StringCollection(); + res = _pdhHelper.EnumBlgFilesMachines(ref machineNames); + if (res != 0) + { + ReportPdhError(res, true); + return; + } + + foreach (string machine in machineNames) + { + StringCollection counterSets = new StringCollection(); + res = _pdhHelper.EnumObjects(machine, ref counterSets); + if (res != 0) + { + return; + } + + StringCollection validPaths = new StringCollection(); + + foreach (string pattern in _listSet) + { + bool bMatched = false; + + WildcardPattern wildLogPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase); + + foreach (string counterSet in counterSets) + { + if (!wildLogPattern.IsMatch(counterSet)) + { + continue; + } + + StringCollection counterSetCounters = new StringCollection(); + StringCollection counterSetInstances = new StringCollection(); + + res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); + if (res != 0) + { + ReportPdhError(res, false); + continue; + } + + string[] instanceArray = new string[counterSetInstances.Count]; + int i = 0; + foreach (string instance in counterSetInstances) + { + instanceArray[i++] = instance; + } + + Dictionary counterInstanceMapping = new Dictionary(); + foreach (string counter in counterSetCounters) + { + counterInstanceMapping.Add(counter, instanceArray); + } + + PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; + if (counterSetInstances.Count > 1) + { + categoryType = PerformanceCounterCategoryType.MultiInstance; + } + else // if (counterSetInstances.Count == 1) //??? + { + categoryType = PerformanceCounterCategoryType.SingleInstance; + } + + string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet); + + CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping); + WriteObject(setObj); + bMatched = true; + } + + if (!bMatched) + { + string msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, + CommonUtilities.StringArrayToString(_resolvedPaths), + pattern)); + WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null)); + } + } + } + } + + // + // ProcessGetCounter() + // Does the work to process GetCounterSet parameter set. + // + private void ProcessGetCounter() + { + // Validate StartTime-EndTime, if present + if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) + { + if (_startTime >= _endTime) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidDateRange")); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidDateRange", ErrorCategory.InvalidArgument, null)); + return; + } + } + + uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); + if (res != 0) + { + ReportPdhError(res, true); + return; + } + + StringCollection validPaths = new StringCollection(); + if (_counter.Length > 0) + { + foreach (string path in _counter) + { + StringCollection expandedPaths; + res = _pdhHelper.ExpandWildCardPath(path, out expandedPaths); + if (res != 0) + { + WriteDebug(path); + ReportPdhError(res, false); + continue; + } + + foreach (string expandedPath in expandedPaths) + { + if (!_pdhHelper.IsPathValid(expandedPath)) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathIsInvalid"), path); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null)); + + continue; + } + + validPaths.Add(expandedPath); + } + } + + if (validPaths.Count == 0) + { + return; + } + } + else + { + res = _pdhHelper.GetValidPathsFromFiles(ref validPaths); + if (res != 0) + { + ReportPdhError(res, false); + } + } + + if (validPaths.Count == 0) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathsInFilesInvalid")); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterPathsInFilesInvalid", ErrorCategory.InvalidResult, null)); + } + + res = _pdhHelper.OpenQuery(); + if (res != 0) + { + ReportPdhError(res, false); + } + + if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) + { + res = _pdhHelper.SetQueryTimeRange(_startTime, _endTime); + if (res != 0) + { + ReportPdhError(res, true); + } + } + + res = _pdhHelper.AddCounters(ref validPaths, true); + if (res != 0) + { + ReportPdhError(res, true); + } + + PerformanceCounterSampleSet nextSet; + + uint samplesRead = 0; + + while (!_stopping) + { + res = _pdhHelper.ReadNextSet(out nextSet, false); + if (res == PdhResults.PDH_NO_MORE_DATA) + { + break; + } + + if (res != 0 && res != PdhResults.PDH_INVALID_DATA) + { + ReportPdhError(res, false); + continue; + } + + // + // Display data + // + WriteSampleSetObject(nextSet, (samplesRead == 0)); + + samplesRead++; + + if (_maxSamples != KEEP_ON_SAMPLING && samplesRead >= _maxSamples) + { + break; + } + } + } + + // + // ValidateFilePaths() helper. + // Validates the _resolvedPaths: present for all parametersets. + // We cannot have more than 32 blg files, or more than one CSV or TSC file. + // Files have to all be of the same type (.blg, .csv, .tsv). + // + private void ValidateFilePaths() + { + Debug.Assert(_resolvedPaths.Count > 0); + + string firstExt = System.IO.Path.GetExtension(_resolvedPaths[0]); + foreach (string fileName in _resolvedPaths) + { + WriteVerbose(fileName); + string curExtension = System.IO.Path.GetExtension(fileName); + + if (!curExtension.Equals(".blg", StringComparison.OrdinalIgnoreCase) + && !curExtension.Equals(".csv", StringComparison.OrdinalIgnoreCase) + && !curExtension.Equals(".tsv", StringComparison.OrdinalIgnoreCase)) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNotALogFile"), fileName); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterNotALogFile", ErrorCategory.InvalidResult, null)); + return; + } + + if (!curExtension.Equals(firstExt, StringComparison.OrdinalIgnoreCase)) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNoMixedLogTypes"), fileName); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterNoMixedLogTypes", ErrorCategory.InvalidResult, null)); + return; + } + } + + if (firstExt.Equals(".blg", StringComparison.OrdinalIgnoreCase)) + { + if (_resolvedPaths.Count > 32) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter32FileLimit")); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "Counter32FileLimit", ErrorCategory.InvalidResult, null)); + return; + } + } + else if (_resolvedPaths.Count > 1) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter1FileLimit")); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "Counter1FileLimit", ErrorCategory.InvalidResult, null)); + return; + } + } + + // + // ResolveFilePath helper. + // Returns a string collection of resolved file paths. + // Writes non-terminating errors for invalid paths + // and returns an empty collection. + // + private bool ResolveFilePaths() + { + StringCollection retColl = new StringCollection(); + + foreach (string origPath in _accumulatedFileNames) + { + Collection resolvedPathSubset = null; + try + { + resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(origPath); + } + catch (PSNotSupportedException notSupported) + { + WriteError(new ErrorRecord(notSupported, string.Empty, ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (System.Management.Automation.DriveNotFoundException driveNotFound) + { + WriteError(new ErrorRecord(driveNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError(new ErrorRecord(providerNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError(new ErrorRecord(pathNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, string.Empty, ErrorCategory.ObjectNotFound, origPath)); + continue; + } + + foreach (PathInfo pi in resolvedPathSubset) + { + // + // Check the provider: only FileSystem provider paths are acceptable. + // + if (pi.Provider.Name != "FileSystem") + { + string msg = _resourceMgr.GetString("NotAFileSystemPath"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, origPath)); + WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, origPath)); + continue; + } + + _resolvedPaths.Add(pi.ProviderPath.ToLowerInvariant()); + } + } + + return (_resolvedPaths.Count > 0); + } + + private void ReportPdhError(uint res, bool bTerminate) + { + string msg; + uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); + if (formatRes != 0) + { + msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); + } + + Exception exc = new Exception(msg); + if (bTerminate) + { + ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + else + { + WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + } + + // + // WriteSampleSetObject() helper. + // In addition to writing the PerformanceCounterSampleSet object, + // it writes a single error if one of the samples has an invalid (non-zero) status. + // The only exception is the first set, where we allow for the formatted value to be 0 - + // this is expected for CSV and TSV files. + + private void WriteSampleSetObject(PerformanceCounterSampleSet set, bool firstSet) + { + if (!firstSet) + { + foreach (PerformanceCounterSample sample in set.CounterSamples) + { + if (sample.Status != 0) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid")); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + break; + } + } + } + + WriteObject(set); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj new file mode 100644 index 0000000000000000000000000000000000000000..8e5a6b3f2e39751c873353428dec3d1c4237dce2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -0,0 +1,36 @@ + + + + PowerShell's Microsoft.PowerShell.Commands.Diagnostics project + $(NoWarn);CS1591;CA1416 + Microsoft.PowerShell.Commands.Diagnostics + + + + + + + + + $(DefineConstants);CORECLR + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..cdddba939f3c3fb00f03df7f977e2df0a231979f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -0,0 +1,336 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Eventing; +using System.Diagnostics.Eventing.Reader; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Resources; +using System.Xml; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class that implements the New-WinEvent cmdlet. + /// This cmdlet writes a new Etw event using the provider specified in parameter. + /// + [Cmdlet(VerbsCommon.New, "WinEvent", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096808")] + public sealed class NewWinEventCommand : PSCmdlet + { + private ProviderMetadata _providerMetadata; + private EventDescriptor? _eventDescriptor; + + private const string TemplateTag = "template"; + private const string DataTag = "data"; + + private readonly ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + + /// + /// ProviderName. + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = ParameterAttribute.AllParameterSets)] + public string ProviderName { get; set; } + + /// + /// Id (EventId defined in manifest file) + /// + [Parameter( + Position = 1, + Mandatory = true, + ParameterSetName = ParameterAttribute.AllParameterSets)] + public int Id + { + get + { + return _id; + } + + set + { + _id = value; + _idSpecified = true; + } + } + + private int _id; + private bool _idSpecified = false; + + /// + /// Version (event version) + /// + [Parameter( + Mandatory = false, + ParameterSetName = ParameterAttribute.AllParameterSets)] + public byte Version + { + get + { + return _version; + } + + set + { + _version = value; + _versionSpecified = true; + } + } + + private byte _version; + private bool _versionSpecified = false; + + /// + /// Event Payload. + /// + [Parameter( + Position = 2, + Mandatory = false, + ParameterSetName = ParameterAttribute.AllParameterSets), + AllowEmptyCollection, + SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Target = "Microsoft.PowerShell.Commands", + Justification = "A string[] is required here because that is the type Powershell supports")] + public object[] Payload { get; set; } + + /// + /// BeginProcessing. + /// + protected override void BeginProcessing() + { + LoadProvider(); + LoadEventDescriptor(); + + base.BeginProcessing(); + } + + private void LoadProvider() + { + if (string.IsNullOrEmpty(ProviderName)) + { + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName"); + } + + using (EventLogSession session = new()) + { + foreach (string providerName in session.GetProviderNames()) + { + if (string.Equals(providerName, ProviderName, StringComparison.OrdinalIgnoreCase)) + { + try + { + _providerMetadata = new ProviderMetadata(providerName); + } + catch (EventLogException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message); + throw new Exception(msg, exc); + } + + break; + } + } + } + + if (_providerMetadata == null) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), ProviderName); + throw new ArgumentException(msg); + } + } + + private void LoadEventDescriptor() + { + if (_idSpecified) + { + List matchedEvents = new(); + foreach (EventMetadata emd in _providerMetadata.Events) + { + if (emd.Id == _id) + { + matchedEvents.Add(emd); + } + } + + if (matchedEvents.Count == 0) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("IncorrectEventId"), + _id, + ProviderName); + throw new EventWriteException(msg); + } + + EventMetadata matchedEvent = null; + if (!_versionSpecified && matchedEvents.Count == 1) + { + matchedEvent = matchedEvents[0]; + } + else + { + if (_versionSpecified) + { + foreach (EventMetadata emd in matchedEvents) + { + if (emd.Version == _version) + { + matchedEvent = emd; + break; + } + } + + if (matchedEvent == null) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("IncorrectEventVersion"), + _version, + _id, + ProviderName); + + throw new EventWriteException(msg); + } + } + else + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("VersionNotSpecified"), + _id, + ProviderName); + + throw new EventWriteException(msg); + } + } + + VerifyTemplate(matchedEvent); + _eventDescriptor = CreateEventDescriptor(_providerMetadata, matchedEvent); + } + else + { + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("EventIdNotSpecified")), "Id"); + } + } + + private bool VerifyTemplate(EventMetadata emd) + { + if (emd.Template != null) + { + XmlReaderSettings readerSettings = new() + { + CheckCharacters = false, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + MaxCharactersInDocument = 0, // no limit + ConformanceLevel = ConformanceLevel.Fragment, + XmlResolver = null + }; + + int definedParameterCount = 0; + using (XmlReader reader = XmlReader.Create(new StringReader(emd.Template), readerSettings)) + { + if (reader.ReadToFollowing(TemplateTag)) + { + bool found = reader.ReadToDescendant(DataTag); + while (found) + { + definedParameterCount++; + found = reader.ReadToFollowing(DataTag); + } + } + } + + if ((Payload == null && definedParameterCount != 0) + || ((Payload != null) && Payload.Length != definedParameterCount)) + { + string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template); + WriteWarning(warning); + + return false; + } + } + + return true; + } + + private static EventDescriptor CreateEventDescriptor(ProviderMetadata providerMetaData, EventMetadata emd) + { + long keywords = 0; + foreach (EventKeyword keyword in emd.Keywords) + { + keywords |= keyword.Value; + } + + byte channel = 0; + foreach (EventLogLink logLink in providerMetaData.LogLinks) + { + if (string.Equals(logLink.LogName, emd.LogLink.LogName, StringComparison.OrdinalIgnoreCase)) + break; + channel++; + } + + return new EventDescriptor( + (int)emd.Id, + emd.Version, + channel, + (byte)emd.Level.Value, + (byte)emd.Opcode.Value, + emd.Task.Value, + keywords); + } + + /// + /// ProcessRecord. + /// + protected override void ProcessRecord() + { + using (EventProvider provider = new(_providerMetadata.Id)) + { + EventDescriptor ed = _eventDescriptor.Value; + + if (Payload != null && Payload.Length > 0) + { + for (int i = 0; i < Payload.Length; i++) + { + if (Payload[i] == null) + { + Payload[i] = string.Empty; + } + } + + provider.WriteEvent(in ed, Payload); + } + else + { + provider.WriteEvent(in ed); + } + } + + base.ProcessRecord(); + } + + /// + /// EndProcessing. + /// + protected override void EndProcessing() + { + _providerMetadata?.Dispose(); + + base.EndProcessing(); + } + } + + internal sealed class EventWriteException : Exception + { + internal EventWriteException(string msg, Exception innerException) + : base(msg, innerException) + { } + + internal EventWriteException(string msg) + : base(msg) + { } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..6f5d8f6e5ec9c10c75db747da09d9a74114f8633 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -0,0 +1,1351 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; + +using Microsoft.PowerShell.Commands.GetCounter; +using Microsoft.Win32; + +namespace Microsoft.Powershell.Commands.GetCounter.PdhNative +{ + internal static class PdhResults + { + public const uint PDH_CSTATUS_VALID_DATA = 0x0; + public const uint PDH_CSTATUS_NEW_DATA = 0x1; + public const uint PDH_CSTATUS_NO_MACHINE = 0x800007D0; + public const uint PDH_CSTATUS_NO_INSTANCE = 0x800007D1; + public const uint PDH_MORE_DATA = 0x800007D2; + public const uint PDH_CSTATUS_ITEM_NOT_VALIDATED = 0x800007D3; + public const uint PDH_RETRY = 0x800007D4; + public const uint PDH_NO_DATA = 0x800007D5; + public const uint PDH_CALC_NEGATIVE_DENOMINATOR = 0x800007D6; + public const uint PDH_CALC_NEGATIVE_TIMEBASE = 0x800007D7; + public const uint PDH_CALC_NEGATIVE_VALUE = 0x800007D8; + public const uint PDH_DIALOG_CANCELLED = 0x800007D9; + public const uint PDH_END_OF_LOG_FILE = 0x800007DA; + public const uint PDH_ASYNC_QUERY_TIMEOUT = 0x800007DB; + public const uint PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE = 0x800007DC; + public const uint PDH_UNABLE_MAP_NAME_FILES = 0x80000BD5; + public const uint PDH_PLA_VALIDATION_WARNING = 0x80000BF3; + public const uint PDH_CSTATUS_NO_OBJECT = 0xC0000BB8; + public const uint PDH_CSTATUS_NO_COUNTER = 0xC0000BB9; + public const uint PDH_CSTATUS_INVALID_DATA = 0xC0000BBA; + public const uint PDH_MEMORY_ALLOCATION_FAILURE = 0xC0000BBB; + public const uint PDH_INVALID_HANDLE = 0xC0000BBC; + public const uint PDH_INVALID_ARGUMENT = 0xC0000BBD; + public const uint PDH_FUNCTION_NOT_FOUND = 0xC0000BBE; + public const uint PDH_CSTATUS_NO_COUNTERNAME = 0xC0000BBF; + public const uint PDH_CSTATUS_BAD_COUNTERNAME = 0xC0000BC0; + public const uint PDH_INVALID_BUFFER = 0xC0000BC1; + public const uint PDH_INSUFFICIENT_BUFFER = 0xC0000BC2; + public const uint PDH_CANNOT_CONNECT_MACHINE = 0xC0000BC3; + public const uint PDH_INVALID_PATH = 0xC0000BC4; + public const uint PDH_INVALID_INSTANCE = 0xC0000BC5; + public const uint PDH_INVALID_DATA = 0xC0000BC6; + public const uint PDH_NO_DIALOG_DATA = 0xC0000BC7; + public const uint PDH_CANNOT_READ_NAME_STRINGS = 0xC0000BC8; + public const uint PDH_LOG_FILE_CREATE_ERROR = 0xC0000BC9; + public const uint PDH_LOG_FILE_OPEN_ERROR = 0xC0000BCA; + public const uint PDH_LOG_TYPE_NOT_FOUND = 0xC0000BCB; + public const uint PDH_NO_MORE_DATA = 0xC0000BCC; + public const uint PDH_ENTRY_NOT_IN_LOG_FILE = 0xC0000BCD; + public const uint PDH_DATA_SOURCE_IS_LOG_FILE = 0xC0000BCE; + public const uint PDH_DATA_SOURCE_IS_REAL_TIME = 0xC0000BCF; + public const uint PDH_UNABLE_READ_LOG_HEADER = 0xC0000BD0; + public const uint PDH_FILE_NOT_FOUND = 0xC0000BD1; + public const uint PDH_FILE_ALREADY_EXISTS = 0xC0000BD2; + public const uint PDH_NOT_IMPLEMENTED = 0xC0000BD3; + public const uint PDH_STRING_NOT_FOUND = 0xC0000BD4; + public const uint PDH_UNKNOWN_LOG_FORMAT = 0xC0000BD6; + public const uint PDH_UNKNOWN_LOGSVC_COMMAND = 0xC0000BD7; + public const uint PDH_LOGSVC_QUERY_NOT_FOUND = 0xC0000BD8; + public const uint PDH_LOGSVC_NOT_OPENED = 0xC0000BD9; + public const uint PDH_WBEM_ERROR = 0xC0000BDA; + public const uint PDH_ACCESS_DENIED = 0xC0000BDB; + public const uint PDH_LOG_FILE_TOO_SMALL = 0xC0000BDC; + public const uint PDH_INVALID_DATASOURCE = 0xC0000BDD; + public const uint PDH_INVALID_SQLDB = 0xC0000BDE; + public const uint PDH_NO_COUNTERS = 0xC0000BDF; + public const uint PDH_SQL_ALLOC_FAILED = 0xC0000BE0; + public const uint PDH_SQL_ALLOCCON_FAILED = 0xC0000BE1; + public const uint PDH_SQL_EXEC_DIRECT_FAILED = 0xC0000BE2; + public const uint PDH_SQL_FETCH_FAILED = 0xC0000BE3; + public const uint PDH_SQL_ROWCOUNT_FAILED = 0xC0000BE4; + public const uint PDH_SQL_MORE_RESULTS_FAILED = 0xC0000BE5; + public const uint PDH_SQL_CONNECT_FAILED = 0xC0000BE6; + public const uint PDH_SQL_BIND_FAILED = 0xC0000BE7; + public const uint PDH_CANNOT_CONNECT_WMI_SERVER = 0xC0000BE8; + public const uint PDH_PLA_COLLECTION_ALREADY_RUNNING = 0xC0000BE9; + public const uint PDH_PLA_ERROR_SCHEDULE_OVERLAP = 0xC0000BEA; + public const uint PDH_PLA_COLLECTION_NOT_FOUND = 0xC0000BEB; + public const uint PDH_PLA_ERROR_SCHEDULE_ELAPSED = 0xC0000BEC; + public const uint PDH_PLA_ERROR_NOSTART = 0xC0000BED; + public const uint PDH_PLA_ERROR_ALREADY_EXISTS = 0xC0000BEE; + public const uint PDH_PLA_ERROR_TYPE_MISMATCH = 0xC0000BEF; + public const uint PDH_PLA_ERROR_FILEPATH = 0xC0000BF0; + public const uint PDH_PLA_SERVICE_ERROR = 0xC0000BF1; + public const uint PDH_PLA_VALIDATION_ERROR = 0xC0000BF2; + public const uint PDH_PLA_ERROR_NAME_TOO_LONG = 0xC0000BF4; + public const uint PDH_INVALID_SQL_LOG_FORMAT = 0xC0000BF5; + public const uint PDH_COUNTER_ALREADY_IN_QUERY = 0xC0000BF6; + public const uint PDH_BINARY_LOG_CORRUPT = 0xC0000BF7; + public const uint PDH_LOG_SAMPLE_TOO_SMALL = 0xC0000BF8; + public const uint PDH_OS_LATER_VERSION = 0xC0000BF9; + public const uint PDH_OS_EARLIER_VERSION = 0xC0000BFA; + public const uint PDH_INCORRECT_APPEND_TIME = 0xC0000BFB; + public const uint PDH_UNMATCHED_APPEND_COUNTER = 0xC0000BFC; + public const uint PDH_SQL_ALTER_DETAIL_FAILED = 0xC0000BFD; + public const uint PDH_QUERY_PERF_DATA_TIMEOUT = 0xC0000BFE; + } + + internal static class PerfDetail + { + public const uint PERF_DETAIL_NOVICE = 100; // The uninformed can understand it + public const uint PERF_DETAIL_ADVANCED = 200; // For the advanced user + public const uint PERF_DETAIL_EXPERT = 300; // For the expert user + public const uint PERF_DETAIL_WIZARD = 400; // For the system designer + } + + [StructLayout(LayoutKind.Sequential, Pack = 2, Size = 16)] + internal struct SYSTEMTIME + { + public UInt16 year; + public UInt16 month; + public UInt16 dayOfWeek; + public UInt16 day; + public UInt16 hour; + public UInt16 minute; + public UInt16 second; + public UInt16 milliseconds; + } + + internal static class PdhFormat + { + public const uint PDH_FMT_RAW = 0x00000010; + public const uint PDH_FMT_ANSI = 0x00000020; + public const uint PDH_FMT_UNICODE = 0x00000040; + public const uint PDH_FMT_LONG = 0x00000100; + public const uint PDH_FMT_DOUBLE = 0x00000200; + public const uint PDH_FMT_LARGE = 0x00000400; + public const uint PDH_FMT_NOSCALE = 0x00001000; + public const uint PDH_FMT_1000 = 0x00002000; + public const uint PDH_FMT_NODATA = 0x00004000; + public const uint PDH_FMT_NOCAP100 = 0x00008000; + public const uint PERF_DETAIL_COSTLY = 0x00010000; + public const uint PERF_DETAIL_STANDARD = 0x0000FFFF; + } + + internal static class PdhLogAccess + { + public const uint PDH_LOG_READ_ACCESS = 0x00010000; + public const uint PDH_LOG_WRITE_ACCESS = 0x00020000; + public const uint PDH_LOG_UPDATE_ACCESS = 0x00040000; + public const uint PDH_LOG_ACCESS_MASK = 0x000F0000; + } + + internal static class PdhLogOpenMode + { + public const uint PDH_LOG_CREATE_NEW = 0x00000001; + public const uint PDH_LOG_CREATE_ALWAYS = 0x00000002; + public const uint PDH_LOG_OPEN_ALWAYS = 0x00000003; + public const uint PDH_LOG_OPEN_EXISTING = 0x00000004; + public const uint PDH_LOG_CREATE_MASK = 0x0000000F; + } + + internal static class PdhLogOpenOption + { + public const uint PDH_LOG_OPT_USER_STRING = 0x01000000; + public const uint PDH_LOG_OPT_CIRCULAR = 0x02000000; + public const uint PDH_LOG_OPT_MAX_IS_BYTES = 0x04000000; + public const uint PDH_LOG_OPT_APPEND = 0x08000000; + } + + internal enum PdhLogFileType + { + PDH_LOG_TYPE_UNDEFINED = 0, + PDH_LOG_TYPE_CSV = 1, + PDH_LOG_TYPE_TSV = 2, + PDH_LOG_TYPE_TRACE_KERNEL = 4, + PDH_LOG_TYPE_TRACE_GENERIC = 5, + PDH_LOG_TYPE_PERFMON = 6, + PDH_LOG_TYPE_SQL = 7, + PDH_LOG_TYPE_BINARY = 8 + } + + internal static class PdhWildCardFlag + { + public const uint PDH_NOEXPANDCOUNTERS = 1; + public const uint PDH_NOEXPANDINSTANCES = 2; + public const uint PDH_REFRESHCOUNTERS = 4; + } + + internal struct CounterHandleNInstance + { + public IntPtr hCounter; + public string InstanceName; + } + + internal sealed class PdhHelper : IDisposable + { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct PDH_COUNTER_PATH_ELEMENTS + { + [MarshalAs(UnmanagedType.LPWStr)] + public string MachineName; + + [MarshalAs(UnmanagedType.LPWStr)] + public string ObjectName; + + [MarshalAs(UnmanagedType.LPWStr)] + public string InstanceName; + + [MarshalAs(UnmanagedType.LPWStr)] + public string ParentInstance; + + public UInt32 InstanceIndex; + + [MarshalAs(UnmanagedType.LPWStr)] + public string CounterName; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PDH_FMT_COUNTERVALUE_LARGE + { + public uint CStatus; + + public Int64 largeValue; + + // [FieldOffset (4), MarshalAs(UnmanagedType.LPStr)] + // public string AnsiStringValue; + + // [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)] + // public string WideStringValue; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PDH_FMT_COUNTERVALUE_DOUBLE + { + public uint CStatus; + + public double doubleValue; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PDH_FMT_COUNTERVALUE_UNICODE + { + public uint CStatus; + + [MarshalAs(UnmanagedType.LPWStr)] + public string WideStringValue; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PDH_RAW_COUNTER + { + public uint CStatus; + public System.Runtime.InteropServices.ComTypes.FILETIME TimeStamp; + public Int64 FirstValue; + public Int64 SecondValue; + public uint MultiCount; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PDH_TIME_INFO + { + public Int64 StartTime; + public Int64 EndTime; + public UInt32 SampleCount; + } + + // + // This is the structure returned by PdhGetCounterInfo(). + // We only need dwType and lDefaultScale fields from this structure. + // We access those fields directly. The struct is here for reference only. + // + [StructLayout(LayoutKind.Sequential)] + private unsafe struct PDH_COUNTER_INFO + { + public uint Length; + public uint Type; + public uint CVersion; + public uint CStatus; + public int Scale; + public int DefaultScale; + public ulong UserData; + public ulong QueryUserData; + public ushort* FullPath; + public _Anonymous_e__Union Anonymous; + public ushort* ExplainText; + public fixed uint DataBuffer[1]; + + [StructLayout(LayoutKind.Explicit)] + internal struct _Anonymous_e__Union + { + [FieldOffset(0)] + public PDH_DATA_ITEM_PATH_ELEMENTS_blittable DataItemPath; + + [FieldOffset(0)] + public PDH_COUNTER_PATH_ELEMENTS_blittable CounterPath; + + [FieldOffset(0)] + public _Anonymous_e__Struct Anonymous; + + [StructLayout(LayoutKind.Sequential)] + internal struct PDH_DATA_ITEM_PATH_ELEMENTS_blittable + { + public ushort* MachineName; + public Guid ObjectGUID; + public uint ItemId; + public ushort* InstanceName; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct PDH_COUNTER_PATH_ELEMENTS_blittable + { + public ushort* MachineName; + public ushort* ObjectName; + public ushort* InstanceName; + public ushort* ParentInstance; + public uint InstanceIndex; + public ushort* CounterName; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct _Anonymous_e__Struct + { + public ushort* MachineName; + public ushort* ObjectName; + public ushort* InstanceName; + public ushort* ParentInstance; + public uint InstanceIndex; + public ushort* CounterName; + } + } + } + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhBindInputDataSource(out PdhSafeDataSourceHandle phDataSource, string szLogFileNameList); + + [DllImport("pdh.dll")] + private static extern uint PdhOpenQueryH(PdhSafeDataSourceHandle hDataSource, IntPtr dwUserData, out PdhSafeQueryHandle phQuery); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhAddCounter(PdhSafeQueryHandle queryHandle, string counterPath, IntPtr userData, out IntPtr counterHandle); + + // not on XP + [DllImport("pdh.dll")] + private static extern uint PdhCollectQueryDataWithTime(PdhSafeQueryHandle queryHandle, ref Int64 pllTimeStamp); + + [DllImport("pdh.dll")] + private static extern uint PdhCollectQueryData(PdhSafeQueryHandle queryHandle); + + [DllImport("pdh.dll")] + internal static extern uint PdhCloseQuery(IntPtr queryHandle); + + [DllImport("pdh.dll")] + internal static extern uint PdhCloseLog(IntPtr logHandle, uint dwFlags); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhOpenLog(string szLogFileName, + uint dwAccessFlags, + ref PdhLogFileType lpdwLogType, + PdhSafeQueryHandle hQuery, + uint dwMaxSize, + string szUserCaption, + out PdhSafeLogHandle phLog + ); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetFormattedCounterValue(IntPtr counterHandle, uint dwFormat, out IntPtr lpdwType, out PDH_FMT_COUNTERVALUE_DOUBLE pValue); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetRawCounterValue(IntPtr hCounter, out IntPtr lpdwType, out PDH_RAW_COUNTER pValue); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhEnumMachinesH(PdhSafeDataSourceHandle hDataSource, IntPtr mszMachineNameList, ref IntPtr pcchBufferLength); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhEnumObjectsH(PdhSafeDataSourceHandle hDataSource, string szMachineName, IntPtr mszObjectList, ref IntPtr pcchBufferLength, uint dwDetailLevel, bool bRefresh); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhEnumObjectItemsH(PdhSafeDataSourceHandle hDataSource, + string szMachineName, + string szObjectName, + IntPtr mszCounterList, + ref IntPtr pcchCounterListLength, + IntPtr mszInstanceList, + ref IntPtr pcchInstanceListLength, + uint dwDetailLevel, + uint dwFlags); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhMakeCounterPath(ref PDH_COUNTER_PATH_ELEMENTS pCounterPathElements, + IntPtr szFullPathBuffer, + ref IntPtr pcchBufferSize, + UInt32 dwFlags); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhParseCounterPath(string szFullPathBuffer, + IntPtr pCounterPathElements, // PDH_COUNTER_PATH_ELEMENTS + ref IntPtr pdwBufferSize, + uint dwFlags); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhExpandWildCardPathH(PdhSafeDataSourceHandle hDataSource, + string szWildCardPath, + IntPtr mszExpandedPathList, + ref IntPtr pcchPathListLength, + uint dwFlags); + + // not available on XP + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhValidatePathEx(PdhSafeDataSourceHandle hDataSource, string szFullPathBuffer); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhValidatePath(string szFullPathBuffer); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetCounterInfo(IntPtr hCounter, [MarshalAs(UnmanagedType.U1)] bool bRetrieveExplainText, ref IntPtr pdwBufferSize, IntPtr lpBuffer); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetCounterTimeBase(IntPtr hCounter, out UInt64 pTimeBase); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetDataSourceTimeRangeH(PdhSafeDataSourceHandle hDataSource, ref IntPtr pdwNumEntries, ref PDH_TIME_INFO pInfo, ref IntPtr pdwBufferSize); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhSetQueryTimeRange(PdhSafeQueryHandle hQuery, ref PDH_TIME_INFO pInfo); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhLookupPerfNameByIndex(string szMachineName, UInt32 dwNameIndex, IntPtr szNameBuffer, ref int pcchNameBufferSize); + + private PdhSafeDataSourceHandle _hDataSource = null; + + private PdhSafeQueryHandle _hQuery = null; + + private bool _firstReading = true; + + private PdhSafeLogHandle _hOutputLog = null; + + // + // Implement IDisposable::Dispose() to close native safe handles + // + public void Dispose() + { + if (_hDataSource != null && !_hDataSource.IsInvalid) + { + _hDataSource.Dispose(); + } + + if (_hOutputLog != null && !_hOutputLog.IsInvalid) + { + _hOutputLog.Dispose(); + } + + if (_hQuery != null && !_hQuery.IsInvalid) + { + _hQuery.Dispose(); + } + + GC.SuppressFinalize(this); + } + + // + // m_ConsumerPathToHandleAndInstanceMap map is used for reading counter date (live or from files). + // + private readonly Dictionary _consumerPathToHandleAndInstanceMap = new(); + + /// + /// A helper reading in a Unicode string with embedded NULLs and splitting it into a StringCollection. + /// + /// + /// + /// + private static void ReadPdhMultiString(ref IntPtr strNative, Int32 strSize, ref StringCollection strColl) + { + Debug.Assert(strSize >= 2); + int offset = 0; + string allSubstringsWithNulls = string.Empty; + while (offset <= ((strSize * sizeof(char)) - 4)) + { + Int32 next4 = Marshal.ReadInt32(strNative, offset); + if (next4 == 0) + { + break; + } + + allSubstringsWithNulls += (char)next4; + + offset += 2; + } + + allSubstringsWithNulls = allSubstringsWithNulls.TrimEnd('\0'); + + strColl.AddRange(allSubstringsWithNulls.Split('\0')); + } + + private static uint GetCounterInfoPlus(IntPtr hCounter, out UInt32 counterType, out UInt32 defaultScale, out UInt64 timeBase) + { + counterType = 0; + defaultScale = 0; + timeBase = 0; + + Debug.Assert(hCounter != IntPtr.Zero); + + IntPtr pBufferSize = new(0); + uint res = PdhGetCounterInfo(hCounter, false, ref pBufferSize, IntPtr.Zero); + if (res != PdhResults.PDH_MORE_DATA) + { + return res; + } + + Int32 bufSize = pBufferSize.ToInt32(); + IntPtr bufCounterInfo = Marshal.AllocHGlobal(bufSize); + + try + { + res = PdhGetCounterInfo(hCounter, false, ref pBufferSize, bufCounterInfo); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA && bufCounterInfo != IntPtr.Zero) + { + PDH_COUNTER_INFO pdhCounterInfo = (PDH_COUNTER_INFO)Marshal.PtrToStructure(bufCounterInfo, typeof(PDH_COUNTER_INFO)); + counterType = pdhCounterInfo.Type; + defaultScale = (uint)pdhCounterInfo.DefaultScale; + } + } + finally + { + Marshal.FreeHGlobal(bufCounterInfo); + } + + res = PdhGetCounterTimeBase(hCounter, out timeBase); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + return res; + } + + public uint ConnectToDataSource() + { + if (_hDataSource != null && !_hDataSource.IsInvalid) + { + _hDataSource.Dispose(); + } + + uint res = PdhHelper.PdhBindInputDataSource(out _hDataSource, null); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Console.WriteLine("error in PdhBindInputDataSource: " + res); + return res; + } + + return PdhResults.PDH_CSTATUS_VALID_DATA; + } + /// + /// Connects to a single named datasource, initializing m_hDataSource variable. + /// + /// + /// + public uint ConnectToDataSource(string dataSourceName) + { + if (_hDataSource != null && !_hDataSource.IsInvalid) + { + _hDataSource.Dispose(); + } + + uint res = PdhHelper.PdhBindInputDataSource(out _hDataSource, dataSourceName); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Console.WriteLine("error in PdhBindInputDataSource: " + res); + } + + return res; + } + + public uint ConnectToDataSource(StringCollection blgFileNames) + { + if (blgFileNames.Count == 1) + { + return ConnectToDataSource(blgFileNames[0]); + } + + string doubleNullTerminated = string.Empty; + foreach (string fileName in blgFileNames) + { + doubleNullTerminated += fileName + '\0'; + } + + doubleNullTerminated += '\0'; + + return ConnectToDataSource(doubleNullTerminated); + } + + public uint OpenQuery() + { + uint res = PdhOpenQueryH(_hDataSource, IntPtr.Zero, out _hQuery); + + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Console.WriteLine("error in PdhOpenQueryH: " + res); + } + + return res; + } + + public uint OpenLogForWriting(string logName, PdhLogFileType logFileType, bool bOverwrite, UInt32 maxSize, bool bCircular, string caption) + { + Debug.Assert(_hQuery != null); + + UInt32 accessFlags = PdhLogAccess.PDH_LOG_WRITE_ACCESS; + accessFlags |= bCircular ? PdhLogOpenOption.PDH_LOG_OPT_CIRCULAR : 0; + accessFlags |= bOverwrite ? PdhLogOpenMode.PDH_LOG_CREATE_ALWAYS : PdhLogOpenMode.PDH_LOG_CREATE_NEW; + + uint res = PdhOpenLog(logName, + accessFlags, + ref logFileType, + _hQuery, + maxSize, + caption, + out _hOutputLog); + + return res; + } + + public uint SetQueryTimeRange(DateTime startTime, DateTime endTime) + { + Debug.Assert(_hQuery != null); + Debug.Assert(endTime >= startTime); + + PDH_TIME_INFO pTimeInfo = new(); + + if (startTime != DateTime.MinValue && startTime.Kind == DateTimeKind.Local) + { + startTime = new DateTime(startTime.Ticks, DateTimeKind.Utc); + } + + pTimeInfo.StartTime = (startTime == DateTime.MinValue) ? 0 : startTime.ToFileTimeUtc(); + + if (endTime != DateTime.MaxValue && endTime.Kind == DateTimeKind.Local) + { + endTime = new DateTime(endTime.Ticks, DateTimeKind.Utc); + } + + pTimeInfo.EndTime = (endTime == DateTime.MaxValue) ? Int64.MaxValue : endTime.ToFileTimeUtc(); + + pTimeInfo.SampleCount = 0; + + return PdhSetQueryTimeRange(_hQuery, ref pTimeInfo); + } + + public uint EnumBlgFilesMachines(ref StringCollection machineNames) + { + IntPtr MachineListTcharSizePtr = new(0); + uint res = PdhHelper.PdhEnumMachinesH(_hDataSource, IntPtr.Zero, ref MachineListTcharSizePtr); + if (res != PdhResults.PDH_MORE_DATA) + { + return res; + } + + Int32 cChars = MachineListTcharSizePtr.ToInt32(); // should be ok on 64 bit + IntPtr strMachineList = Marshal.AllocHGlobal(cChars * sizeof(char)); + + try + { + res = PdhHelper.PdhEnumMachinesH(_hDataSource, (IntPtr)strMachineList, ref MachineListTcharSizePtr); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReadPdhMultiString(ref strMachineList, MachineListTcharSizePtr.ToInt32(), ref machineNames); + } + } + finally + { + Marshal.FreeHGlobal(strMachineList); + } + + return res; + } + + public uint EnumObjects(string machineName, ref StringCollection objectNames) + { + IntPtr pBufferSize = new(0); + uint res = PdhEnumObjectsH(_hDataSource, machineName, IntPtr.Zero, ref pBufferSize, PerfDetail.PERF_DETAIL_WIZARD, false); + if (res != PdhResults.PDH_MORE_DATA) + { + return res; + } + + Int32 cChars = pBufferSize.ToInt32(); + IntPtr strObjectList = Marshal.AllocHGlobal(cChars * sizeof(char)); + + try + { + res = PdhEnumObjectsH(_hDataSource, machineName, (IntPtr)strObjectList, ref pBufferSize, PerfDetail.PERF_DETAIL_WIZARD, false); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReadPdhMultiString(ref strObjectList, pBufferSize.ToInt32(), ref objectNames); + } + } + finally + { + Marshal.FreeHGlobal(strObjectList); + } + + return res; + } + + public uint EnumObjectItems(string machineName, string objectName, ref StringCollection counterNames, ref StringCollection instanceNames) + { + IntPtr pCounterBufferSize = new(0); + IntPtr pInstanceBufferSize = new(0); + + uint res = PdhEnumObjectItemsH(_hDataSource, machineName, objectName, + IntPtr.Zero, ref pCounterBufferSize, + IntPtr.Zero, ref pInstanceBufferSize, + PerfDetail.PERF_DETAIL_WIZARD, 0); + if (res == PdhResults.PDH_CSTATUS_NO_INSTANCE) + { + instanceNames.Clear(); + return PdhResults.PDH_CSTATUS_VALID_DATA; // masking the error + } + else if (res == PdhResults.PDH_CSTATUS_NO_OBJECT) + { + counterNames.Clear(); + return PdhResults.PDH_CSTATUS_VALID_DATA; // masking the error + } + else if (res != PdhResults.PDH_MORE_DATA) + { + // Console.WriteLine("error in PdhEnumObjectItemsH 1st call: " + res); + return res; + } + + Int32 cChars = pCounterBufferSize.ToInt32(); + IntPtr strCountersList = (cChars > 0) ? + Marshal.AllocHGlobal((cChars) * sizeof(char)) : IntPtr.Zero; + // re-set count to 0 if it is lte 2 + if (cChars < 0) + { + pCounterBufferSize = new IntPtr(0); + } + + cChars = pInstanceBufferSize.ToInt32(); + IntPtr strInstancesList = (cChars > 0) ? + Marshal.AllocHGlobal((cChars) * sizeof(char)) : IntPtr.Zero; + + // re-set count to 0 if it is lte 2 + if (cChars < 0) + { + pInstanceBufferSize = new IntPtr(0); + } + + try + { + res = PdhEnumObjectItemsH(_hDataSource, machineName, objectName, + strCountersList, ref pCounterBufferSize, + strInstancesList, ref pInstanceBufferSize, + PerfDetail.PERF_DETAIL_WIZARD, 0); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Console.WriteLine("error in PdhEnumObjectItemsH 2nd call: " + res + "\n Counter buffer size is " + // + pCounterBufferSize.ToInt32() + "\n Instance buffer size is " + pInstanceBufferSize.ToInt32()); + } + else + { + ReadPdhMultiString(ref strCountersList, pCounterBufferSize.ToInt32(), ref counterNames); + if (strInstancesList != IntPtr.Zero) + { + ReadPdhMultiString(ref strInstancesList, pInstanceBufferSize.ToInt32(), ref instanceNames); + } + } + } + finally + { + if (strCountersList != IntPtr.Zero) + { + Marshal.FreeHGlobal(strCountersList); + } + + if (strInstancesList != IntPtr.Zero) + { + Marshal.FreeHGlobal(strInstancesList); + } + } + + return res; + } + + public uint GetValidPathsFromFiles(ref StringCollection validPaths) + { + Debug.Assert(_hDataSource != null && !_hDataSource.IsInvalid, "Call ConnectToDataSource before GetValidPathsFromFiles"); + + StringCollection machineNames = new(); + uint res = this.EnumBlgFilesMachines(ref machineNames); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + foreach (string machine in machineNames) + { + StringCollection counterSets = new(); + res = this.EnumObjects(machine, ref counterSets); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + foreach (string counterSet in counterSets) + { + // Console.WriteLine("Counter set " + counterSet); + + StringCollection counterSetCounters = new(); + StringCollection counterSetInstances = new(); + + res = this.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + res = this.GetValidPaths(machine, counterSet, ref counterSetCounters, ref counterSetInstances, ref validPaths); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + } + } + + return res; + } + + private bool IsPathValid(ref PDH_COUNTER_PATH_ELEMENTS pathElts, out string outPath) + { + bool ret = false; + outPath = string.Empty; + IntPtr pPathBufferSize = new(0); + + uint res = PdhMakeCounterPath(ref pathElts, IntPtr.Zero, ref pPathBufferSize, 0); + if (res != PdhResults.PDH_MORE_DATA) + { + return false; + } + + Int32 cChars = pPathBufferSize.ToInt32(); + IntPtr strPath = Marshal.AllocHGlobal(cChars * sizeof(char)); + + try + { + res = PdhMakeCounterPath(ref pathElts, strPath, ref pPathBufferSize, 0); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + outPath = Marshal.PtrToStringUni(strPath); + + ret = (PdhValidatePathEx(_hDataSource, outPath) == PdhResults.PDH_CSTATUS_VALID_DATA); + } + } + finally + { + Marshal.FreeHGlobal(strPath); + } + + return ret; + } + + public bool IsPathValid(string path) + { + return (PdhValidatePathEx(_hDataSource, path) == PdhResults.PDH_CSTATUS_VALID_DATA); + } + + private static uint MakePath(PDH_COUNTER_PATH_ELEMENTS pathElts, out string outPath, bool bWildcardInstances) + { + outPath = string.Empty; + IntPtr pPathBufferSize = new(0); + + if (bWildcardInstances) + { + pathElts.InstanceIndex = 0; + pathElts.InstanceName = "*"; + pathElts.ParentInstance = null; + } + + uint res = PdhMakeCounterPath(ref pathElts, IntPtr.Zero, ref pPathBufferSize, 0); + if (res != PdhResults.PDH_MORE_DATA) + { + return res; + } + + Int32 cChars = pPathBufferSize.ToInt32(); + IntPtr strPath = Marshal.AllocHGlobal(cChars * sizeof(char)); + + try + { + res = PdhMakeCounterPath(ref pathElts, strPath, ref pPathBufferSize, 0); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + outPath = Marshal.PtrToStringUni(strPath); + } + } + finally + { + Marshal.FreeHGlobal(strPath); + } + + return res; + } + + private static uint MakeAllInstancePath(string origPath, out string unifiedPath) + { + unifiedPath = origPath; + + PDH_COUNTER_PATH_ELEMENTS elts = new(); + + uint res = ParsePath(origPath, ref elts); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + return MakePath(elts, out unifiedPath, true); + } + + private static uint ParsePath(string fullPath, ref PDH_COUNTER_PATH_ELEMENTS pCounterPathElements) + { + IntPtr bufSize = new(0); + + uint res = PdhParseCounterPath(fullPath, + IntPtr.Zero, + ref bufSize, + 0); + if (res != PdhResults.PDH_MORE_DATA && res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Console.WriteLine("error in PdhParseCounterPath: " + res); + return res; + } + + IntPtr structPtr = Marshal.AllocHGlobal(bufSize.ToInt32()); + + try + { + res = PdhParseCounterPath(fullPath, + structPtr, + ref bufSize, + 0); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + // + // Marshal.PtrToStructure will allocate managed memory for the object, + // so the unmanaged ptr can be freed safely + // + pCounterPathElements = Marshal.PtrToStructure(structPtr); + } + } + finally + { + Marshal.FreeHGlobal(structPtr); + } + + return res; + } + + // + // TranslateLocalCounterPath() helper translates counter paths from English into the current locale language. + // NOTE: we can only translate counter set and counter names. + // Translated instance names come from providers + // This function will leave them unchanged: + // however, it works for common cases like "*" and "_total" + // and many instance names are just numbers, anyway. + // + // Also - this only supports local paths, b/c connecting to remote registry + // requires a different firewall exception. + // This function checks and Asserts if the path is not valid. + // + public uint TranslateLocalCounterPath(string englishPath, out string localizedPath) + { + uint res = PdhResults.PDH_CSTATUS_VALID_DATA; + localizedPath = string.Empty; + PDH_COUNTER_PATH_ELEMENTS pathElts = new(); + res = ParsePath(englishPath, ref pathElts); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + // Check if the path is local and assert if not: + string machineNameMassaged = pathElts.MachineName.ToLowerInvariant(); + machineNameMassaged = machineNameMassaged.TrimStart('\\'); + Debug.Assert(machineNameMassaged == System.Environment.MachineName.ToLowerInvariant()); + + string lowerEngCtrName = pathElts.CounterName.ToLowerInvariant(); + string lowerEngObjectName = pathElts.ObjectName.ToLowerInvariant(); + + // Get the registry index + RegistryKey rootKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib\\009"); + string[] regCounters = (string[])rootKey.GetValue("Counter"); + + // NOTE: 1-based enumeration because the name strings follow index strings in the array + Int32 counterIndex = -1; + Int32 objIndex = -1; + for (int enumIndex = 1; enumIndex < regCounters.Length; enumIndex++) + { + string regString = regCounters[enumIndex]; + if (regString.ToLowerInvariant() == lowerEngCtrName) + { + try + { + counterIndex = Convert.ToInt32(regCounters[enumIndex - 1], CultureInfo.InvariantCulture); + } + catch (Exception) + { + return PdhResults.PDH_INVALID_PATH; + } + } + else if (regString.ToLowerInvariant() == lowerEngObjectName) + { + try + { + objIndex = Convert.ToInt32(regCounters[enumIndex - 1], CultureInfo.InvariantCulture); + } + catch (Exception) + { + return PdhResults.PDH_INVALID_PATH; + } + } + + if (counterIndex != -1 && objIndex != -1) + { + break; + } + } + + if (counterIndex == -1 || objIndex == -1) + { + return PdhResults.PDH_INVALID_PATH; + } + + // Now, call retrieve the localized names of the object and the counter by index: + string objNameLocalized; + res = LookupPerfNameByIndex(pathElts.MachineName, (uint)objIndex, out objNameLocalized); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + pathElts.ObjectName = objNameLocalized; + + string ctrNameLocalized; + res = LookupPerfNameByIndex(pathElts.MachineName, (uint)counterIndex, out ctrNameLocalized); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + return res; + } + + pathElts.CounterName = ctrNameLocalized; + + // Assemble the path back by using the translated object and counter names: + + res = MakePath(pathElts, out localizedPath, false); + + return res; + } + + public uint LookupPerfNameByIndex(string machineName, uint index, out string locName) + { + // + // NOTE: to make PdhLookupPerfNameByIndex() work, + // localizedPath needs to be pre-allocated on the first call. + // This is different from most other PDH functions that tolerate NULL buffers and return required size. + // + + int strSize = 256; + IntPtr localizedPathPtr = Marshal.AllocHGlobal(strSize * sizeof(char)); + locName = string.Empty; + uint res; + try + { + res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); + if (res == PdhResults.PDH_MORE_DATA) + { + Marshal.FreeHGlobal(localizedPathPtr); + localizedPathPtr = Marshal.AllocHGlobal(strSize * sizeof(char)); + res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); + } + + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + locName = Marshal.PtrToStringUni(localizedPathPtr); + } + } + finally + { + Marshal.FreeHGlobal(localizedPathPtr); + } + + return res; + } + + public uint GetValidPaths(string machineName, + string objectName, + ref StringCollection counters, + ref StringCollection instances, + ref StringCollection validPaths) + { + PDH_COUNTER_PATH_ELEMENTS pathElts = new(); + pathElts.MachineName = machineName; + pathElts.ObjectName = objectName; + + foreach (string counterName in counters) + { + pathElts.CounterName = counterName; + + if (instances.Count == 0) + { + string pathCandidate; + if (IsPathValid(ref pathElts, out pathCandidate)) + { + validPaths.Add(pathCandidate); + } + } + else + { + foreach (string instanceName in instances) + { + pathElts.InstanceName = instanceName; + pathElts.InstanceIndex = 0; + + string pathCandidate; + if (IsPathValid(ref pathElts, out pathCandidate)) + { + validPaths.Add(pathCandidate); + } + } + } + } + + return PdhResults.PDH_CSTATUS_VALID_DATA; + } + + public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) + { + Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); + + if (bFlushOldCounters) + { + _consumerPathToHandleAndInstanceMap.Clear(); + } + + bool bAtLeastOneAdded = false; + uint res = PdhResults.PDH_CSTATUS_VALID_DATA; + + foreach (string counterPath in validPaths) + { + IntPtr counterHandle; + res = PdhAddCounter(_hQuery, counterPath, IntPtr.Zero, out counterHandle); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + CounterHandleNInstance chi = new(); + chi.hCounter = counterHandle; + chi.InstanceName = null; + + PDH_COUNTER_PATH_ELEMENTS pathElts = new(); + res = ParsePath(counterPath, ref pathElts); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA && pathElts.InstanceName != null) + { + chi.InstanceName = pathElts.InstanceName.ToLowerInvariant(); + } + + if (!_consumerPathToHandleAndInstanceMap.ContainsKey(counterPath.ToLowerInvariant())) + { + _consumerPathToHandleAndInstanceMap.Add(counterPath.ToLowerInvariant(), chi); + } + + bAtLeastOneAdded = true; + } + } + + return bAtLeastOneAdded ? PdhResults.PDH_CSTATUS_VALID_DATA : res; + } + + public string GetCounterSetHelp(string szMachineName, string szObjectName) + { + // API not available to retrieve + return string.Empty; + } + + public uint ReadNextSet(out PerformanceCounterSampleSet nextSet, bool bSkipReading) + { + Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); + + uint res = PdhResults.PDH_CSTATUS_VALID_DATA; + nextSet = null; + + Int64 batchTimeStampFT = 0; + + res = PdhCollectQueryDataWithTime(_hQuery, ref batchTimeStampFT); + if (bSkipReading) + { + return res; + } + + if (res != PdhResults.PDH_CSTATUS_VALID_DATA && res != PdhResults.PDH_NO_DATA) + { + return res; + } + + // + // NOTE: PDH returns the filetime as local time, therefore + // we need to call FromFileTimUtc() to avoid .NET applying the timezone adjustment. + // However, that would result in the DateTime object having Kind.Utc. + // We have to copy it once more to correct that (Kind is a read-only property). + // + DateTime batchStamp = DateTime.Now; + if (res != PdhResults.PDH_NO_DATA) + { + batchStamp = new DateTime(DateTime.FromFileTimeUtc(batchTimeStampFT).Ticks, DateTimeKind.Local); + } + + PerformanceCounterSample[] samplesArr = new PerformanceCounterSample[_consumerPathToHandleAndInstanceMap.Count]; + uint sampleIndex = 0; + uint numInvalidDataSamples = 0; + uint lastErr = PdhResults.PDH_CSTATUS_VALID_DATA; + + foreach (string path in _consumerPathToHandleAndInstanceMap.Keys) + { + IntPtr counterTypePtr = new(0); + UInt32 counterType = (UInt32)PerformanceCounterType.RawBase; + UInt32 defaultScale = 0; + UInt64 timeBase = 0; + + IntPtr hCounter = _consumerPathToHandleAndInstanceMap[path].hCounter; + Debug.Assert(hCounter != IntPtr.Zero); + + res = GetCounterInfoPlus(hCounter, out counterType, out defaultScale, out timeBase); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + // Console.WriteLine ("GetCounterInfoPlus for " + path + " failed with " + res); + } + + PDH_RAW_COUNTER rawValue; + res = PdhGetRawCounterValue(hCounter, out counterTypePtr, out rawValue); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + samplesArr[sampleIndex++] = new PerformanceCounterSample(path, + _consumerPathToHandleAndInstanceMap[path].InstanceName, + 0, + (ulong)0, + (ulong)0, + 0, + PerformanceCounterType.RawBase, + defaultScale, + timeBase, + batchStamp, + (UInt64)batchStamp.ToFileTime(), + (rawValue.CStatus == PdhResults.PDH_CSTATUS_VALID_DATA) ? res : rawValue.CStatus); + + numInvalidDataSamples++; + lastErr = res; + continue; + } + + long dtFT = (((long)rawValue.TimeStamp.dwHighDateTime) << 32) + + (uint)rawValue.TimeStamp.dwLowDateTime; + + DateTime dt = new(DateTime.FromFileTimeUtc(dtFT).Ticks, DateTimeKind.Local); + + PDH_FMT_COUNTERVALUE_DOUBLE fmtValueDouble; + res = PdhGetFormattedCounterValue(hCounter, + PdhFormat.PDH_FMT_DOUBLE | PdhFormat.PDH_FMT_NOCAP100, + out counterTypePtr, + out fmtValueDouble); + if (res != PdhResults.PDH_CSTATUS_VALID_DATA) + { + samplesArr[sampleIndex++] = new PerformanceCounterSample(path, + _consumerPathToHandleAndInstanceMap[path].InstanceName, + 0, + (ulong)rawValue.FirstValue, + (ulong)rawValue.SecondValue, + rawValue.MultiCount, + (PerformanceCounterType)counterType, + defaultScale, + timeBase, + dt, + (UInt64)dtFT, + (fmtValueDouble.CStatus == PdhResults.PDH_CSTATUS_VALID_DATA) ? res : rawValue.CStatus); + + numInvalidDataSamples++; + lastErr = res; + continue; + } + + samplesArr[sampleIndex++] = new PerformanceCounterSample(path, + _consumerPathToHandleAndInstanceMap[path].InstanceName, + fmtValueDouble.doubleValue, + (ulong)rawValue.FirstValue, + (ulong)rawValue.SecondValue, + rawValue.MultiCount, + (PerformanceCounterType)counterTypePtr.ToInt32(), + defaultScale, + timeBase, + dt, + (UInt64)dtFT, + fmtValueDouble.CStatus); + } + + nextSet = new PerformanceCounterSampleSet(batchStamp, samplesArr, _firstReading); + _firstReading = false; + + if (numInvalidDataSamples == samplesArr.Length) + { + res = lastErr; + } + else + { + // + // Reset the error - any errors are saved per sample in PerformanceCounterSample.Status for kvetching later + // + res = PdhResults.PDH_CSTATUS_VALID_DATA; + } + + return res; + } + + public uint ExpandWildCardPath(string path, out StringCollection expandedPaths) + { + expandedPaths = new StringCollection(); + IntPtr pcchPathListLength = new(0); + + uint res = PdhExpandWildCardPathH(_hDataSource, + path, + IntPtr.Zero, + ref pcchPathListLength, + PdhWildCardFlag.PDH_REFRESHCOUNTERS); + + if (res != PdhResults.PDH_MORE_DATA) + { + return res; + } + + Int32 cChars = pcchPathListLength.ToInt32(); + IntPtr strPathList = Marshal.AllocHGlobal(cChars * sizeof(char)); + + try + { + res = PdhExpandWildCardPathH(_hDataSource, path, strPathList, ref pcchPathListLength, PdhWildCardFlag.PDH_REFRESHCOUNTERS); + if (res == PdhResults.PDH_CSTATUS_VALID_DATA) + { + ReadPdhMultiString(ref strPathList, pcchPathListLength.ToInt32(), ref expandedPaths); + } + } + finally + { + Marshal.FreeHGlobal(strPathList); + } + + return res; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs new file mode 100644 index 0000000000000000000000000000000000000000..2fc58cc00e184fcd6bfdb66c2c0a1a9bab62fbbc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.Powershell.Commands.GetCounter.PdhNative +{ + internal sealed class PdhSafeDataSourceHandle : SafeHandle + { + private PdhSafeDataSourceHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid + { + get + { + return handle == IntPtr.Zero; + } + } + + protected override bool ReleaseHandle() + { + return (PdhHelper.PdhCloseLog(handle, 0) == 0); + } + } + + internal sealed class PdhSafeQueryHandle : SafeHandle + { + private PdhSafeQueryHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid + { + get + { + return handle == IntPtr.Zero; + } + } + + protected override bool ReleaseHandle() + { + return (PdhHelper.PdhCloseQuery(handle) == 0); + } + } + + internal sealed class PdhSafeLogHandle : SafeHandle + { + private PdhSafeLogHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid + { + get + { + return handle == IntPtr.Zero; + } + } + + protected override bool ReleaseHandle() + { + return (PdhHelper.PdhCloseLog(handle, 0) == 0); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..f8f41ecc2f525dfb4fd3a62fd5aa37c53afd65f3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The {0} file does not have the expected file name extension. Specify only .blg, .csv, or .tsv files when you use the Path parameter. + + + Internal performance counter API call failed. Error: {0:x8}. + + + You must specify at least one Log, Provider or Path key-value pair. + + + There is not an event provider on the {0} computer that matches "{1}". + + + A null value was encountered in the {0} hash table key. Null values are not permitted. + + + Constructed structured query: +{0}. + + + The {0} provider writes events to the {1} log. + + + The value of the StartTime parameter must be less than the value of the EndTime parameter. + + + There is not an event log on the {0} computer that matches "{1}". + + + Microsoft + + + The Circular parameter will be ignored unless the MaxSize parameter is also specified. + + + Unable to open the {0} file for writing. + + + Invalid value '{0}' specified for keyword. + + + The {0} performance counter cannot be exported to the {1} file because it was not part of the first sample set. + + + No events were found that match the specified selection criteria. + + + The default values for this command failed. Error: {0:x8}. + + + You cannot import different types of performance log files in the same command. Specify only one type of file in the Path parameter. + + + The {0} path does not appear to be a valid log file path. Specify a valid file system path. + + + A valid Event Id must be specified. + + + Could not retrieve information about the {0} provider. Error: {1}. + + + The {0} event log can be read only in the forward chronological order because it is an analytical or a debug log. To see events from the {0} event log, use the Oldest parameter in the command. + + + The following export destination path is ambiguous: {0}. + + + The {0} performance counter path is not valid. + + + The data in one of the performance counter samples is not valid. View the Status property for each PerformanceCounterSample object to make sure it contains valid data. + + + Provided payload does not match with the template that was defined for event id {0}. +The defined template is following: +{1} + + + Cannot find any performance counter sets on the {0} computer that match the following: {1}. + + + No valid counter paths were found in the files. + + + Unable to create the {0} file. Verify that the path is valid. + + + Could not find any performance counter sets on the {0} computer: error {1:x8}. Verify that the {0} computer exists, that it is discoverable, and that you have sufficient privileges to view performance counter data on that computer. + + + Event cannot be written because there are no events defined with id {0} for the provider {1}. Please correct the event id and try again. + + + The {0} Context key-value is not a valid SID or NT account name. + + + Event cannot be written because the specified version {0} for event {1} is not defined for the provider {2}. Please correct the version and try again. + + + You cannot import more than 32 .blg counter log files in each command. + + + The specified providers do not write events to the {0} log. This log will be ignored. + + + The following value is not in a valid security identifier (SID) format: {0}. Enter a valid SID, such as S-1-5-32-544. + + + No provider found with name {0}. + + + Cannot retrieve information about the {0} performance counter set because access was denied. + + + Event cannot be written because multiple events with id {0} have been defined for provider {1}. Please provide a version for the event and try again. + + + The {0} event log file can be read only in the forward chronological order because it is an .etl or an .evt file. To see events from the {0} event log, use the Oldest parameter in the command. + + + Provider name must be specified. + + + The {0} file does not appear to be a valid log file. Specify only .evtx, .etl, or .evt files as values of the Path parameter. + + + The {0} performance counter path is either not valid or it is not present in the following files: {1}. + + + Timestamp + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Cannot retrieve event message text. + + + The {0} file already exists. To overwrite this file, use the Force parameter in the Export-Counter command. + + + The Continuous parameter and the MaxSamples parameter cannot be used in the same command. + + + This cmdlet can be run only on Microsoft Windows 7 and above. + + + This PowerShell snap-in contains Windows Eventing and Performance Counter cmdlets. + + + Cannot find any performance counter sets in the {0} files that match the following: {1}. + + + The specified providers do not write events to any of the specified logs. + + + Cooked Values + + + You cannot import more than one comma-separated (.csv) or tab-separated (.tsv) performance counter file in each command. + + + Log count ({0}) is exceeded Windows Event Log API limit ({1}). Adjust filter to return less log names. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e0744889e7a9ab09bd01efb3236716bbd11af5a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt @@ -0,0 +1,59 @@ +#Copyright (c) Microsoft Corporation. + +Vendor=Microsoft +Description=This PowerShell snap-in contains Windows Eventing and Performance Counter cmdlets. + +NoMatchingEventsFound=No events were found that match the specified selection criteria. +NoMatchingLogsFound=There is not an event log on the {0} computer that matches "{1}". +NoMatchingProvidersFound=There is not an event provider on the {0} computer that matches "{1}". +NotALogFile=The {0} file does not appear to be a valid log file. Specify only .evtx, .etl, or .evt files as values of the Path parameter. +NotAFileSystemPath=The {0} path does not appear to be a valid log file path. Specify a valid file system path. +NoProviderFound=No provider found with name {0}. +NoEventMessage=Cannot retrieve event message text. + +QueryTrace=Constructed structured query:\n{0}. +LogProviderOrPathNeeded=You must specify at least one Log, Provider or Path key-value pair. +KeywordLongExpected=Invalid value '{0}' specified for keyword. +DateTimeExpected=The following value is not in a valid DateTime format: {0}. +InvalidSIDFormat=The following value is not in a valid security identifier (SID) format: {0}. Enter a valid SID, such as S-1-5-32-544. +InvalidContext=The {0} Context key-value is not a valid SID or NT account name. +ProviderLogLink=The {0} provider writes events to the {1} log. +SpecifiedProvidersDontWriteToLog=The specified providers do not write events to the {0} log. This log will be ignored. +LogsAndProvidersDontOverlap=The specified providers do not write events to any of the specified logs. +ProviderMetadataUnavailable=Could not retrieve information about the {0} provider. Error: {1}. +LogInfoUnavailable=Could not retrieve information about the {0} log. Error: {1}. +SpecifyOldestForLog=The {0} event log can be read only in the forward chronological order because it is an analytical or a debug log. To see events from the {0} event log, use the Oldest parameter in the command. +SpecifyOldestForEtlEvt=The {0} event log file can be read only in the forward chronological order because it is an .etl or an .evt file. To see events from the {0} event log, use the Oldest parameter in the command. +NullNotAllowedInHashtable=A null value was encountered in the {0} hash table key. Null values are not permitted. +IncorrectEventId=Event cannot be written because there are no events defined with id {0} for the provider {1}. Please correct the event id and try again. +IncorrectEventVersion=Event cannot be written because the specified version {0} for event {1} is not defined for the provider {2}. Please correct the version and try again. +VersionNotSpecified=Event cannot be written because multiple events with id {0} have been defined for provider {1}. Please provide a version for the event and try again. +ProviderNotSpecified=Provider name must be specified. +EventIdNotSpecified=A valid Event Id must be specified. +PayloadMismatch=Provided payload does not match with the template that was defined for event id {0}. \r\nThe defined template is following: \r\n{1} + +Timestamp=Timestamp +CookedValues=Cooked Values +CounterApiError=Internal performance counter API call failed. Error: {0:x8}. +CounterPathIsInvalid=The {0} performance counter path is not valid. +CounterPathInvalidOrNotInFile=The {0} performance counter path is either not valid or it is not present in the following files: {1}. +CounterPathsInFilesInvalid=No valid counter paths were found in the files. +CounterSetEnumAccessDenied=Cannot retrieve information about the {0} performance counter set because access was denied. +CounterInvalidDateRange=The value of the StartTime parameter must be less than the value of the EndTime parameter. +Counter32FileLimit=You cannot import more than 32 .blg counter log files in each command. +Counter1FileLimit=You cannot import more than one comma-separated (.csv) or tab-separated (.tsv) performance counter file in each command. +CounterNotALogFile=The {0} file does not have the expected file name extension. Specify only .blg, .csv, or .tsv files when you use the Path parameter. +CounterNoMixedLogTypes=You cannot import different types of performance log files in the same command. Specify only one type of file in the Path parameter. +NoMatchingCounterSetsFound=Cannot find any performance counter sets on the {0} computer that match the following: {1}. +NoMatchingCounterSetsInFile=Cannot find any performance counter sets in the {0} files that match the following: {1}. +NoCounterSetsOnComputer=Could not find any performance counter sets on the {0} computer: error {1:x8}. Verify that the {0} computer exists, that it is discoverable, and that you have sufficient privileges to view performance counter data on that computer. +CounterFileExists=The {0} file already exists. To overwrite this file, use the Force parameter in the Export-Counter command. +CounterExportSampleNotInInitialSet=The {0} performance counter cannot be exported to the {1} file because it was not part of the first sample set. +CounterPathTranslationFailed=The default values for this command failed. Error: {0:x8}. +CounterContinuousOrMaxSamples=The Continuous parameter and the MaxSamples parameter cannot be used in the same command. +CounterSampleDataInvalid=The data in one of the performance counter samples is not valid. View the Status property for each PerformanceCounterSample object to make sure it contains valid data. +CounterCircularNoMaxSize=The Circular parameter will be ignored unless the MaxSize parameter is also specified. +ExportCtrWin7Required=This cmdlet can be run only on Microsoft Windows 7 and above. +FileOpenFailed=Unable to open the {0} file for writing. +FileCreateFailed=Unable to create the {0} file. Verify that the path is valid. +ExportDestPathAmbiguous=The following export destination path is ambiguous: {0}. diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj new file mode 100644 index 0000000000000000000000000000000000000000..8bb897e00950acb2268cd227586aa9f02edb2f89 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -0,0 +1,53 @@ + + + + PowerShell's Microsoft.PowerShell.Commands.Management project + $(NoWarn);CS1570;CA1416 + Microsoft.PowerShell.Commands.Management + + + + + + + + $(DefineConstants);CORECLR + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs new file mode 100644 index 0000000000000000000000000000000000000000..3e26b2e2e989f08d5e56af5226a462e5a63f487d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -0,0 +1,699 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Cmdletization +{ + /// + /// Provides common code for processing session-based object models. The common code + /// Session, ThrottleLimit, AsJob parameters and delegates creation of jobs to derived classes. + /// + /// Type that represents instances of objects from the wrapped object model + /// Type representing remote sessions + [SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")] + public abstract class SessionBasedCmdletAdapter : CmdletAdapter, IDisposable + where TObjectInstance : class + where TSession : class + { + internal SessionBasedCmdletAdapter() + { + } + + #region Constants + + private const string CIMJobType = "CimJob"; + + #endregion + + #region IDisposable Members + + private bool _disposed; + + /// + /// Releases resources associated with this object. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases resources associated with this object. + /// + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + if (_parentJob != null) + { + _parentJob.Dispose(); + _parentJob = null; + } + } + + _disposed = true; + } + } + + #endregion + + #region Common parameters (AsJob, ThrottleLimit, Session) + + /// + /// Session to operate on. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + protected TSession[] Session + { + get + { + return _session ??= new TSession[] { this.DefaultSession }; + } + + set + { + ArgumentNullException.ThrowIfNull(value); + _session = value; + _sessionWasSpecified = true; + } + } + + private TSession[] _session; + private bool _sessionWasSpecified; + + /// + /// Whether to wrap and emit the whole operation as a background job. + /// + [Parameter] + public SwitchParameter AsJob + { + get { return _asJob; } + + set { _asJob = value; } + } + + private bool _asJob; + + /// + /// Maximum number of remote connections that can remain active at any given time. + /// + [Parameter] + public virtual int ThrottleLimit { get; set; } + + #endregion Common CIM-related parameters + + #region Abstract methods to be overridden in derived classes + + /// + /// Creates a object that performs a query against the wrapped object model. + /// + /// Remote session to query. + /// Query parameters. + /// + /// + /// This method shouldn't do any processing or interact with the remote session. + /// Doing so will interfere with ThrottleLimit functionality. + /// + /// + /// (and other methods returning job results) will block to support throttling and flow-control. + /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing, + /// until calls from (and other methods returning job results) return. + /// + /// + internal abstract StartableJob CreateQueryJob(TSession session, QueryBuilder query); + + private StartableJob DoCreateQueryJob(TSession sessionForJob, QueryBuilder query, Action actionAgainstResults) + { + StartableJob queryJob = this.CreateQueryJob(sessionForJob, query); + + if (queryJob != null) + { + if (actionAgainstResults != null) + { + queryJob.SuppressOutputForwarding = true; + } + + bool discardNonPipelineResults = (actionAgainstResults != null) || !this.AsJob.IsPresent; + HandleJobOutput( + queryJob, + sessionForJob, + discardNonPipelineResults, + actionAgainstResults == null + ? (Action)null + : ((PSObject pso) => + { + var objectInstance = + (TObjectInstance)LanguagePrimitives.ConvertTo( + pso, + typeof(TObjectInstance), + CultureInfo.InvariantCulture); + actionAgainstResults(sessionForJob, objectInstance); + })); + } + + return queryJob; + } + + /// + /// Creates a object that invokes an instance method in the wrapped object model. + /// + /// Remote session to invoke the method in. + /// The object on which to invoke the method. + /// Method invocation details. + /// if successful method invocations should emit downstream the being operated on. + /// + /// + /// This method shouldn't do any processing or interact with the remote session. + /// Doing so will interfere with ThrottleLimit functionality. + /// + /// + /// (and other methods returning job results) will block to support throttling and flow-control. + /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing, + /// until calls from (and other methods returning job results) return. + /// + /// + internal abstract StartableJob CreateInstanceMethodInvocationJob(TSession session, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru); + + private StartableJob DoCreateInstanceMethodInvocationJob(TSession sessionForJob, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru, bool asJob) + { + StartableJob methodInvocationJob = this.CreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru); + + if (methodInvocationJob != null) + { + bool discardNonPipelineResults = !asJob; + HandleJobOutput( + methodInvocationJob, + sessionForJob, + discardNonPipelineResults, + outputAction: null); + } + + return methodInvocationJob; + } + + /// + /// Creates a object that invokes a static method in the wrapped object model. + /// + /// Remote session to invoke the method in. + /// Method invocation details. + /// + /// + /// This method shouldn't do any processing or interact with the remote session. + /// Doing so will interfere with ThrottleLimit functionality. + /// + /// + /// (and other methods returning job results) will block to support throttling and flow-control. + /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing, + /// until calls from (and other methods returning job results) return. + /// + /// + internal abstract StartableJob CreateStaticMethodInvocationJob(TSession session, MethodInvocationInfo methodInvocationInfo); + + private StartableJob DoCreateStaticMethodInvocationJob(TSession sessionForJob, MethodInvocationInfo methodInvocationInfo) + { + StartableJob methodInvocationJob = this.CreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo); + + if (methodInvocationJob != null) + { + bool discardNonPipelineResults = !this.AsJob.IsPresent; + HandleJobOutput( + methodInvocationJob, + sessionForJob, + discardNonPipelineResults, + outputAction: null); + } + + return methodInvocationJob; + } + + private static void HandleJobOutput(Job job, TSession sessionForJob, bool discardNonPipelineResults, Action outputAction) + { + Action processOutput = + (PSObject pso) => + { + if (pso == null) + { + return; + } + + outputAction?.Invoke(pso); + }; + + job.Output.DataAdded += + (object sender, DataAddedEventArgs eventArgs) => + { + var dataCollection = (PSDataCollection)sender; + + if (discardNonPipelineResults) + { + foreach (PSObject pso in dataCollection.ReadAll()) + { + // TODO/FIXME - need to make sure that the dataCollection will be throttled + // (i.e. it won't accept more items - it will block in Add method) + // until this processOutput call completes + processOutput(pso); + } + } + else + { + PSObject pso = dataCollection[eventArgs.Index]; + processOutput(pso); + } + }; + + if (discardNonPipelineResults) + { + DiscardJobOutputs(job, JobOutputs.NonPipelineResults & (~JobOutputs.Output)); + } + } + + internal virtual TSession GetSessionOfOriginFromInstance(TObjectInstance instance) + { + return null; + } + + /// + /// Returns default sessions to use when the user doesn't specify the -Session cmdlet parameter. + /// + /// Default sessions to use when the user doesn't specify the -Session cmdlet parameter. + protected abstract TSession DefaultSession { get; } + + /// + /// A new job name to use for the parent job that handles throttling of the child jobs that actually perform querying and method invocation. + /// + protected abstract string GenerateParentJobName(); + + #endregion + + #region Helper methods + + private static void DiscardJobOutputs(PSDataCollection psDataCollection) + { + psDataCollection.DataAdded += + (object sender, DataAddedEventArgs e) => + { + var localDataCollection = (PSDataCollection)sender; + localDataCollection.Clear(); + }; + } + + [Flags] + private enum JobOutputs + { + Output = 0x1, + Error = 0x2, + Warning = 0x4, + Verbose = 0x8, + Debug = 0x10, + Progress = 0x20, + Results = 0x40, + + NonPipelineResults = Output | Error | Warning | Verbose | Debug | Progress, + PipelineResults = Results, + } + + private static void DiscardJobOutputs(Job job, JobOutputs jobOutputsToDiscard) + { + if ((jobOutputsToDiscard & JobOutputs.Output) == JobOutputs.Output) + { + DiscardJobOutputs(job.Output); + } + + if ((jobOutputsToDiscard & JobOutputs.Error) == JobOutputs.Error) + { + DiscardJobOutputs(job.Error); + } + + if ((jobOutputsToDiscard & JobOutputs.Warning) == JobOutputs.Warning) + { + DiscardJobOutputs(job.Warning); + } + + if ((jobOutputsToDiscard & JobOutputs.Verbose) == JobOutputs.Verbose) + { + DiscardJobOutputs(job.Verbose); + } + + if ((jobOutputsToDiscard & JobOutputs.Debug) == JobOutputs.Debug) + { + DiscardJobOutputs(job.Debug); + } + + if ((jobOutputsToDiscard & JobOutputs.Progress) == JobOutputs.Progress) + { + DiscardJobOutputs(job.Progress); + } + + if ((jobOutputsToDiscard & JobOutputs.Results) == JobOutputs.Results) + { + DiscardJobOutputs(job.Results); + } + } + + #endregion Helper methods + + #region Implementation of ObjectModelWrapper functionality + + private ThrottlingJob _parentJob; + + /// + /// Queries for object instances in the object model. + /// + /// Query parameters. + /// A lazy evaluated collection of object instances. + public override void ProcessRecord(QueryBuilder query) + { + _parentJob.DisableFlowControlForPendingCmdletActionsQueue(); + foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) + { + StartableJob childJob = this.DoCreateQueryJob(sessionForJob, query, actionAgainstResults: null); + if (childJob != null) + { + if (!this.AsJob.IsPresent) + { + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); + } + else + { + _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); + } + } + } + } + + /// + /// Queries for instance and invokes an instance method. + /// + /// Query parameters. + /// Method invocation details. + /// if successful method invocations should emit downstream the object instance being operated on. + public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) + { + _parentJob.DisableFlowControlForPendingJobsQueue(); + + ThrottlingJob closureOverParentJob = _parentJob; + SwitchParameter closureOverAsJob = this.AsJob; + + foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) + { + StartableJob queryJob = this.DoCreateQueryJob( + sessionForJob, + query, + (TSession sessionForMethodInvocationJob, TObjectInstance objectInstance) => + { + StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob( + sessionForMethodInvocationJob, + objectInstance, + methodInvocationInfo, + passThru, + closureOverAsJob.IsPresent); + + if (methodInvocationJob != null) + { + closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None); + } + }); + + if (queryJob != null) + { + if (!this.AsJob.IsPresent) + { + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); + } + else + { + _parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); + } + } + } + } + + private IEnumerable GetSessionsToActAgainst(TObjectInstance objectInstance) + { + if (_sessionWasSpecified) + { + return this.Session; + } + + TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); + if (associatedSession != null) + { + return new[] { associatedSession }; + } + + return new[] { this.GetImpliedSession() }; + } + + private TSession GetSessionAssociatedWithPipelineObject() + { + object inputVariableValue = this.Cmdlet.Context.GetVariableValue(SpecialVariables.InputVarPath, null); + if (inputVariableValue == null) + { + return null; + } + + IEnumerable inputEnumerable = LanguagePrimitives.GetEnumerable(inputVariableValue); + if (inputEnumerable == null) + { + return null; + } + + List inputCollection = inputEnumerable.Cast().ToList(); + if (inputCollection.Count != 1) + { + return null; + } + + TObjectInstance inputInstance; + if (!LanguagePrimitives.TryConvertTo(inputCollection[0], CultureInfo.InvariantCulture, out inputInstance)) + { + return null; + } + + TSession associatedSession = this.GetSessionOfOriginFromInstance(inputInstance); + return associatedSession; + } + + private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) + { + if (_sessionWasSpecified) + { + return this.Session; + } + + if (queryBuilder is ISessionBoundQueryBuilder sessionBoundQueryBuilder) + { + TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); + if (sessionOfTheQueryBuilder != null) + { + return new[] { sessionOfTheQueryBuilder }; + } + } + + TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject(); + if (sessionAssociatedWithPipelineObject != null) + { + return new[] { sessionAssociatedWithPipelineObject }; + } + + return new[] { this.GetImpliedSession() }; + } + + private IEnumerable GetSessionsToActAgainst(MethodInvocationInfo methodInvocationInfo) + { + if (_sessionWasSpecified) + { + return this.Session; + } + + var associatedSessions = new HashSet(); + foreach (TObjectInstance objectInstance in methodInvocationInfo.GetArgumentsOfType()) + { + TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); + if (associatedSession != null) + { + associatedSessions.Add(associatedSession); + } + } + + if (associatedSessions.Count == 1) + { + return associatedSessions; + } + + TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject(); + if (sessionAssociatedWithPipelineObject != null) + { + return new[] { sessionAssociatedWithPipelineObject }; + } + + return new[] { this.GetImpliedSession() }; + } + + internal PSModuleInfo PSModuleInfo + { + get + { + var scriptCommandInfo = this.Cmdlet.CommandInfo as IScriptCommandInfo; + return scriptCommandInfo.ScriptBlock.Module; + } + } + + private TSession GetImpliedSession() + { + TSession sessionFromImportModule; + // When being called from a CIM activity, this will be invoked as + // a function so there will be no module info + if (this.PSModuleInfo != null) + { + if (PSPrimitiveDictionary.TryPathGet( + this.PSModuleInfo.PrivateData as IDictionary, + out sessionFromImportModule, + ScriptWriter.PrivateDataKey_CmdletsOverObjects, + ScriptWriter.PrivateDataKey_DefaultSession)) + { + return sessionFromImportModule; + } + } + + return this.DefaultSession; + } + + /// + /// Invokes an instance method in the object model. + /// + /// The object on which to invoke the method. + /// Method invocation details. + /// if successful method invocations should emit downstream the being operated on. + public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) + { + ArgumentNullException.ThrowIfNull(objectInstance); + + ArgumentNullException.ThrowIfNull(methodInvocationInfo); + + foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) + { + StartableJob childJob = this.DoCreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru, this.AsJob.IsPresent); + if (childJob != null) + { + if (!this.AsJob.IsPresent) + { + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); + } + else + { + _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); + } + } + } + } + + /// + /// Invokes a static method in the object model. + /// + /// Method invocation details. + public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) + { + ArgumentNullException.ThrowIfNull(methodInvocationInfo); + + foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) + { + StartableJob childJob = this.DoCreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo); + if (childJob != null) + { + if (!this.AsJob.IsPresent) + { + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); + } + else + { + _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); + } + } + } + } + + /// + /// Performs initialization of cmdlet execution. + /// + public override void BeginProcessing() + { + if (this.AsJob.IsPresent) + { + MshCommandRuntime commandRuntime = (MshCommandRuntime)this.Cmdlet.CommandRuntime; // PSCmdlet.CommandRuntime is always MshCommandRuntime + string conflictingParameter = null; + if (commandRuntime.WhatIf.IsPresent) + { + conflictingParameter = "WhatIf"; + } + else if (commandRuntime.Confirm.IsPresent) + { + conflictingParameter = "Confirm"; + } + + if (conflictingParameter != null) + { + string errorMessage = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.SessionBasedWrapper_ShouldProcessVsJobConflict, + conflictingParameter); + throw new InvalidOperationException(errorMessage); + } + } + + _parentJob = new ThrottlingJob( + command: Job.GetCommandTextFromInvocationInfo(this.Cmdlet.MyInvocation), + jobName: this.GenerateParentJobName(), + jobTypeName: CIMJobType, + maximumConcurrentChildJobs: this.ThrottleLimit, + cmdletMode: !this.AsJob.IsPresent); + } + + /// + /// Performs cleanup after cmdlet execution. + /// + public override void EndProcessing() + { + _parentJob.EndOfChildJobs(); + if (this.AsJob.IsPresent) + { + this.Cmdlet.WriteObject(_parentJob); + this.Cmdlet.JobRepository.Add(_parentJob); + _parentJob = null; // this class doesn't own parentJob after it has been emitted to the outside world + } + else + { + _parentJob.ForwardAllResultsToCmdlet(this.Cmdlet); + _parentJob.Finished.WaitOne(); + } + } + + /// + /// Stops the parent job when called. + /// + public override void StopProcessing() + { + Job jobToStop = _parentJob; + jobToStop?.StopJob(); + + base.StopProcessing(); + } + + #endregion + } + + internal interface ISessionBoundQueryBuilder + { + TSession GetTargetSession(); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs new file mode 100644 index 0000000000000000000000000000000000000000..935cc960c6c5f9dfba9b306f209517008782c2a3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -0,0 +1,368 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Management.Automation; +using System.Runtime.Serialization; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Represents an error during execution of a CIM job. + /// + public class CimJobException : SystemException, IContainsErrorRecord + { + #region Standard constructors and methods required for all exceptions + + /// + /// Initializes a new instance of the class. + /// + public CimJobException() : this(null, null) + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public CimJobException(string message) : this(message, null) + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified. + public CimJobException(string message, Exception inner) : base(message, inner) + { + InitializeErrorRecord(null, "CimJob_ExternalError", ErrorCategory.NotSpecified); + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CimJobException( + SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + + #endregion + + internal static CimJobException CreateFromCimException( + string jobDescription, + CimJobContext jobContext, + CimException cimException) + { + Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null"); + Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); + Dbg.Assert(cimException != null, "Caller should verify cimException != null"); + + string message = BuildErrorMessage(jobDescription, jobContext, cimException.Message); + CimJobException cimJobException = new(message, cimException); + cimJobException.InitializeErrorRecord(jobContext, cimException); + return cimJobException; + } + + 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"); + + if (inner is CimException cimException) + { + return CreateFromCimException(jobDescription, jobContext, cimException); + } + + string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); + CimJobException cimJobException = new(message, inner); + if (inner is IContainsErrorRecord containsErrorRecord) + { + 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; + } + + internal static CimJobException CreateWithFullControl( + CimJobContext jobContext, + string message, + string errorId, + ErrorCategory errorCategory, + Exception inner = null) + { + Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); + Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null"); + Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null"); + + CimJobException cimJobException = new(jobContext.PrependComputerNameToMessage(message), inner); + cimJobException.InitializeErrorRecord(jobContext, errorId, errorCategory); + return cimJobException; + } + + internal static CimJobException CreateWithoutJobContext( + string message, + string errorId, + ErrorCategory errorCategory, + Exception inner = null) + { + Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null"); + Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null"); + + CimJobException cimJobException = new(message, inner); + cimJobException.InitializeErrorRecord(null, errorId, errorCategory); + return cimJobException; + } + + internal static CimJobException CreateFromMethodErrorCode(string jobDescription, CimJobContext jobContext, string methodName, string errorCodeFromMethod) + { + string rawErrorMessage = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_ErrorCodeFromMethod, + errorCodeFromMethod); + + string errorMessage = BuildErrorMessage(jobDescription, jobContext, rawErrorMessage); + + CimJobException cje = new(errorMessage); + cje.InitializeErrorRecord(jobContext, "CimJob_" + methodName + "_" + errorCodeFromMethod, ErrorCategory.InvalidResult); + + return cje; + } + + private static string BuildErrorMessage(string jobDescription, CimJobContext jobContext, string errorMessage) + { + Dbg.Assert(!string.IsNullOrEmpty(errorMessage), "Caller should verify !string.IsNullOrEmpty(errorMessage)"); + + if (string.IsNullOrEmpty(jobDescription)) + { + return jobContext.PrependComputerNameToMessage(errorMessage); + } + else + { + string errorMessageWithJobDescription = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_GenericCimFailure, + errorMessage, + jobDescription); + return jobContext.PrependComputerNameToMessage(errorMessageWithJobDescription); + } + } + + private void InitializeErrorRecordCore(CimJobContext jobContext, Exception exception, string errorId, ErrorCategory errorCategory) + { + ErrorRecord coreErrorRecord = new( + exception: exception, + errorId: errorId, + errorCategory: errorCategory, + targetObject: jobContext?.TargetObject); + + if (jobContext != null) + { + System.Management.Automation.Remoting.OriginInfo originInfo = new( + jobContext.Session.ComputerName, + Guid.Empty); + + _errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord( + coreErrorRecord, + originInfo); + + _errorRecord.SetInvocationInfo(jobContext.CmdletInvocationInfo); + _errorRecord.PreserveInvocationInfoOnce = true; + } + else + { + _errorRecord = coreErrorRecord; + } + } + + private void InitializeErrorRecord(CimJobContext jobContext, string errorId, ErrorCategory errorCategory) + { + InitializeErrorRecordCore( + jobContext: jobContext, + exception: this, + errorId: errorId, + errorCategory: errorCategory); + } + + private void InitializeErrorRecord(CimJobContext jobContext, CimException cimException) + { + InitializeErrorRecordCore( + jobContext: jobContext, + exception: cimException, + errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode, + errorCategory: ConvertCimExceptionToErrorCategory(cimException)); + + if (cimException.ErrorData != null) + { + _errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; + _errorRecord.CategoryInfo.TargetType = jobContext?.CmdletizationClassName; + } + } + + private static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cimException) + { + ErrorCategory result = ErrorCategory.NotSpecified; + + if (cimException.ErrorData != null) + { + result = ConvertCimErrorToErrorCategory(cimException.ErrorData); + } + + if (result == ErrorCategory.NotSpecified) + { + result = ConvertCimNativeErrorCodeToErrorCategory(cimException.NativeErrorCode); + } + + return result; + } + + private static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErrorCode nativeErrorCode) + { + switch (nativeErrorCode) + { + case NativeErrorCode.Ok: + return ErrorCategory.NotSpecified; + case NativeErrorCode.Failed: + return ErrorCategory.NotSpecified; + case NativeErrorCode.AccessDenied: + return ErrorCategory.PermissionDenied; + case NativeErrorCode.InvalidNamespace: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidParameter: + return ErrorCategory.InvalidArgument; + case NativeErrorCode.InvalidClass: + return ErrorCategory.MetadataError; + case NativeErrorCode.NotFound: + return ErrorCategory.ObjectNotFound; + case NativeErrorCode.NotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.ClassHasChildren: + return ErrorCategory.MetadataError; + case NativeErrorCode.ClassHasInstances: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidSuperClass: + return ErrorCategory.MetadataError; + case NativeErrorCode.AlreadyExists: + return ErrorCategory.ResourceExists; + case NativeErrorCode.NoSuchProperty: + return ErrorCategory.MetadataError; + case NativeErrorCode.TypeMismatch: + return ErrorCategory.InvalidType; + case NativeErrorCode.QueryLanguageNotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.InvalidQuery: + return ErrorCategory.InvalidArgument; + case NativeErrorCode.MethodNotAvailable: + return ErrorCategory.MetadataError; + case NativeErrorCode.MethodNotFound: + return ErrorCategory.MetadataError; + case NativeErrorCode.NamespaceNotEmpty: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidEnumerationContext: + return ErrorCategory.MetadataError; + case NativeErrorCode.InvalidOperationTimeout: + return ErrorCategory.InvalidArgument; + case NativeErrorCode.PullHasBeenAbandoned: + return ErrorCategory.OperationStopped; + case NativeErrorCode.PullCannotBeAbandoned: + return ErrorCategory.CloseError; + case NativeErrorCode.FilteredEnumerationNotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.ContinuationOnErrorNotSupported: + return ErrorCategory.NotImplemented; + case NativeErrorCode.ServerLimitsExceeded: + return ErrorCategory.ResourceBusy; + case NativeErrorCode.ServerIsShuttingDown: + return ErrorCategory.ResourceUnavailable; + default: + return ErrorCategory.NotSpecified; + } + } + + private static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError) + { + if (cimError == null) + { + return ErrorCategory.NotSpecified; + } + + CimProperty errorCategoryProperty = cimError.CimInstanceProperties["Error_Category"]; + if (errorCategoryProperty == null) + { + return ErrorCategory.NotSpecified; + } + + ErrorCategory errorCategoryValue; + if (!LanguagePrimitives.TryConvertTo(errorCategoryProperty.Value, CultureInfo.InvariantCulture, out errorCategoryValue)) + { + return ErrorCategory.NotSpecified; + } + + return errorCategoryValue; + } + + /// + /// which provides additional information about the error. + /// + public ErrorRecord ErrorRecord + { + get { return _errorRecord; } + } + + private ErrorRecord _errorRecord; + + internal bool IsTerminatingError + { + get + { + if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null)) + { + return false; + } + + CimProperty perceivedSeverityProperty = cimException.ErrorData.CimInstanceProperties["PerceivedSeverity"]; + if ((perceivedSeverityProperty == null) || (perceivedSeverityProperty.CimType != CimType.UInt16) || (perceivedSeverityProperty.Value == null)) + { + return false; + } + + ushort perceivedSeverityValue = (ushort)perceivedSeverityProperty.Value; + if (perceivedSeverityValue != 7) + { + /* from CIM Schema: Interop\CIM_Error.mof: + "7 - Fatal/NonRecoverable should be used to indicate an " + "error occurred, but it\'s too late to take remedial " + "action. \n" + */ + return false; + } + + return true; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..eb594dd4eea3823ccf5f5e3be64d0aa994bd6e6c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of a CreateInstance intrinsic CIM method. + /// + internal sealed class CreateInstanceJob : PropertySettingJob + { + private CimInstance _resultFromCreateInstance; + private CimInstance _resultFromGetInstance; + + private static CimInstance GetEmptyInstance(CimJobContext jobContext) + { + Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); + + var result = new CimInstance(jobContext.ClassName, jobContext.Namespace); + return result; + } + + internal CreateInstanceJob(CimJobContext jobContext, MethodInvocationInfo methodInvocationInfo) + : base(jobContext, true /* passThru */, GetEmptyInstance(jobContext), methodInvocationInfo) + { + } + + private IObservable GetCreateInstanceOperation() + { + CimInstance instanceToCreate = GetEmptyInstance(JobContext); + ModifyLocalCimInstance(instanceToCreate); + + IObservable observable = this.JobContext.Session.CreateInstanceAsync( + this.JobContext.Namespace, + instanceToCreate, + this.CreateOperationOptions()); + return observable; + } + + private IObservable GetGetInstanceOperation() + { + Dbg.Assert(_resultFromCreateInstance != null, "GetInstance should only be called after CreteInstance came back with a keyed instance"); + IObservable observable = this.JobContext.Session.GetInstanceAsync( + this.JobContext.Namespace, + _resultFromCreateInstance, + this.CreateOperationOptions()); + return observable; + } + +#if DEBUG + private bool _createInstanceOperationGotStarted; + private bool _getInstanceOperationGotStarted; +#endif + + internal override IObservable GetCimOperation() + { + if (_resultFromCreateInstance == null) + { + if (!this.ShouldProcess()) + { + return null; + } + +#if DEBUG + Dbg.Assert(!_getInstanceOperationGotStarted, "CreateInstance should be started *before* GetInstance"); + Dbg.Assert(!_createInstanceOperationGotStarted, "Should not start CreateInstance operation twice"); + _createInstanceOperationGotStarted = true; +#endif + return GetCreateInstanceOperation(); + } + else + { +#if DEBUG + Dbg.Assert(_createInstanceOperationGotStarted, "GetInstance should be started *after* CreateInstance"); + Dbg.Assert(!_getInstanceOperationGotStarted, "Should not start GetInstance operation twice"); + Dbg.Assert(_resultFromGetInstance == null, "GetInstance operation shouldn't happen twice"); + _getInstanceOperationGotStarted = true; +#endif + return GetGetInstanceOperation(); + } + } + + public override void OnNext(CimInstance item) + { + Dbg.Assert(item != null, "CreateInstance and GetInstance should never return null"); + if (_resultFromCreateInstance == null) + { + _resultFromCreateInstance = item; + } + else + { + Dbg.Assert(_resultFromGetInstance == null, "GetInstance operation shouldn't happen twice"); + _resultFromGetInstance = item; + } + } + + public override void OnError(Exception exception) + { + if (this.DidUserSuppressTheOperation) + { + // If user suppressed CreateInstance operation, then no instance should be returned by the cmdlet + // If the provider's CreateInstance implementation doesn't post an instance and returns a success, then WMI infra will error out to flag an incorrect implementation of CreateInstance (by design) + // Therefore cmdletization layer has to suppress the error and treat this as normal/successful completion + this.OnCompleted(); + } + else + { + base.OnError(exception); + } + } + + public override void OnCompleted() + { + Dbg.Assert(this.DidUserSuppressTheOperation || (_resultFromCreateInstance != null), "OnNext should always be called before OnComplete by CreateInstance"); +#if DEBUG + Dbg.Assert( + !_getInstanceOperationGotStarted || this.DidUserSuppressTheOperation || (_resultFromGetInstance != null), + // <=> (this._getInstanceOperationGotStarted => (this._resultFromGetInstance != null)) + "GetInstance should cause OnNext to be called which should set this._resultFromGetInstance to non-null"); +#endif + if (this.IsPassThruObjectNeeded() && (_resultFromGetInstance == null)) + { + IObservable observable = this.GetGetInstanceOperation(); + observable.Subscribe(this); + return; + } + else + { + base.OnCompleted(); + } + } + + internal override object PassThruObject + { + get + { + return _resultFromGetInstance; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..0432c6c9a8fbb94cc7377231753608c9b5746175 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of a DeleteInstance intrinsic CIM method. + /// + internal sealed class DeleteInstanceJob : MethodInvocationJobBase + { + private readonly CimInstance _objectToDelete; + + internal DeleteInstanceJob(CimJobContext jobContext, bool passThru, CimInstance objectToDelete, MethodInvocationInfo methodInvocationInfo) + : base( + jobContext, + passThru, + objectToDelete.ToString(), + methodInvocationInfo) + { + Dbg.Assert(objectToDelete != null, "Caller should verify objectToDelete != null"); + _objectToDelete = objectToDelete; + } + + internal override IObservable GetCimOperation() + { + if (!this.ShouldProcess()) + { + return null; + } + + IObservable observable = this.JobContext.Session.DeleteInstanceAsync( + this.JobContext.Namespace, + _objectToDelete, + this.CreateOperationOptions()); + return observable; + } + + public override void OnNext(object item) + { + Dbg.Assert(false, "DeleteInstance should not result in ObjectReady callbacks"); + } + + internal override object PassThruObject + { + get { return _objectToDelete; } + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + return CimCustomOptionsDictionary.MergeOptions( + base.CalculateJobSpecificCustomOptions(), + _objectToDelete); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..569740d0d1b0d91ac277eec57f883504e71b5ba1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job that handles executing a WQL (in the future CQL?) query on a remote CIM server. + /// + internal sealed class EnumerateAssociatedInstancesJob : QueryJobBase + { + private readonly CimInstance _associatedObject; + private readonly string _associationName; + private readonly string _resultRole; + private readonly string _sourceRole; + + internal EnumerateAssociatedInstancesJob(CimJobContext jobContext, CimQuery cimQuery, CimInstance associatedObject, string associationName, string resultRole, string sourceRole) + : base(jobContext, cimQuery) + { + _associatedObject = associatedObject; + Dbg.Assert(_associatedObject != null, "Caller should verify that associatedObject is not null"); + + _associationName = associationName; + Dbg.Assert(_associationName != null, "Caller should verify that associationName is not null"); + + _resultRole = resultRole; + Dbg.Assert(_resultRole != null, "Caller should verify that resultRole is not null"); + + _sourceRole = sourceRole; + Dbg.Assert(_sourceRole != null, "Caller should verify that sourceRole is not null"); + } + + internal override IObservable GetCimOperation() + { + this.WriteVerboseStartOfCimOperation(); + IObservable observable = this.JobContext.Session.EnumerateAssociatedInstancesAsync( + this.JobContext.Namespace, + _associatedObject, + _associationName, + this.JobContext.ClassNameOrNullIfResourceUriIsUsed, + _sourceRole, + _resultRole, + this.CreateOperationOptions()); + + return observable; + } + + internal override string Description + { + get + { + return string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_AssociationDescription, + this.JobContext.CmdletizationClassName, + this.JobContext.Session.ComputerName, + _associatedObject.ToString()); + } + } + + internal override string FailSafeDescription + { + get + { + return string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_SafeAssociationDescription, + this.JobContext.CmdletizationClassName, + this.JobContext.Session.ComputerName); + } + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + return CimCustomOptionsDictionary.MergeOptions( + base.CalculateJobSpecificCustomOptions(), + _associatedObject); + } + + internal override void WriteObject(object outputObject) + { + if (IsShowComputerNameMarkerPresent(_associatedObject)) + { + PSObject pso = PSObject.AsPSObject(outputObject); + AddShowComputerNameMarker(pso); + } + + base.WriteObject(outputObject); + } + + internal override string GetProviderVersionExpectedByJob() + { + // CDXML doesn't allow expressing of separate "ClassVersion" attribute for association operations - Windows 8 Bugs: #642140 + return null; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..9eaac2b3d7f4abe797afed3afd7e734859bca744 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; +using Microsoft.PowerShell.Cim; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of an extrinsic CIM method. + /// + internal abstract class ExtrinsicMethodInvocationJob : MethodInvocationJobBase + { + internal ExtrinsicMethodInvocationJob(CimJobContext jobContext, bool passThru, string methodSubject, MethodInvocationInfo methodInvocationInfo) + : base(jobContext, passThru, methodSubject, methodInvocationInfo) + { + } + + #region Processing of "in" parameters + + internal CimMethodParametersCollection GetCimMethodParametersCollection() + { + var methodParameters = new CimMethodParametersCollection(); + foreach (MethodParameter parameter in this.GetMethodInputParameters()) + { + CimValueConverter.AssertIntrinsicCimType(parameter.ParameterType); + var methodParameter = CimMethodParameter.Create( + parameter.Name, + parameter.Value, + CimValueConverter.GetCimTypeEnum(parameter.ParameterType), + CimFlags.None); + methodParameters.Add(methodParameter); + } + + return methodParameters; + } + + #endregion + + #region Processing of "out" parameters + + private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter methodParameter, IDictionary cmdletOutput) + { + Dbg.Assert(methodResult != null, "Caller should verify methodResult != null"); + Dbg.Assert(methodParameter != null, "Caller should verify methodParameter != null"); + Dbg.Assert((methodParameter.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error)) != 0, "Caller should verify that this is an out parameter"); + Dbg.Assert(cmdletOutput != null, "Caller should verify cmdletOutput != null"); + + Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + + CimMethodParameter outParameter = methodResult.OutParameters[methodParameter.Name]; + object valueReturnedFromMethod = outParameter?.Value; + + object dotNetValue = CimValueConverter.ConvertFromCimToDotNet(valueReturnedFromMethod, methodParameter.ParameterType); + if ((methodParameter.Bindings & MethodParameterBindings.Out) == MethodParameterBindings.Out) + { + methodParameter.Value = dotNetValue; + cmdletOutput.Add(methodParameter.Name, methodParameter); + + if (dotNetValue is CimInstance[] cimInstances) + { + foreach (var instance in cimInstances) + { + CimCmdletAdapter.AssociateSessionOfOriginWithInstance(instance, this.JobContext.Session); + } + } + + if (dotNetValue is CimInstance cimInstance) + { + CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); + } + } + else if ((methodParameter.Bindings & MethodParameterBindings.Error) == MethodParameterBindings.Error) + { + var gotError = (bool)LanguagePrimitives.ConvertTo(dotNetValue, typeof(bool), CultureInfo.InvariantCulture); + if (gotError) + { + var errorCodeAsString = (string)LanguagePrimitives.ConvertTo(dotNetValue, typeof(string), CultureInfo.InvariantCulture); + CimJobException cje = CimJobException.CreateFromMethodErrorCode(this.GetDescription(), this.JobContext, this.MethodName, errorCodeAsString); + throw cje; + } + } + } + + private void OnNext(CimMethodResult methodResult) + { + Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + + var cmdletOutput = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (MethodParameter methodParameter in this.GetMethodOutputParameters()) + { + ProcessOutParameter(methodResult, methodParameter, cmdletOutput); + } + + if (cmdletOutput.Count == 1) + { + var singleOutputParameter = cmdletOutput.Values.First(); + if (singleOutputParameter.Value == null) + { + return; + } + + IEnumerable enumerable = LanguagePrimitives.GetEnumerable(singleOutputParameter.Value); + if (enumerable != null) + { + foreach (object o in enumerable) + { + this.WriteObject(o, singleOutputParameter); + } + } + else + { + this.WriteObject(singleOutputParameter.Value, singleOutputParameter); + } + } + else if (cmdletOutput.Count > 1) + { + var propertyBag = new PSObject(); + foreach (var element in cmdletOutput) + { + var tmp = new PSNoteProperty(element.Key, element.Value.Value); + propertyBag.Properties.Add(tmp); + } + + this.WriteObject(propertyBag); + } + } + + private void OnNext(CimMethodStreamedResult streamedResult) + { + MethodParameter methodParameter = this.GetMethodOutputParameters() + .SingleOrDefault(p => p.Name.Equals(streamedResult.ParameterName, StringComparison.OrdinalIgnoreCase)); + if (methodParameter == null) + { + string errorMessage = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_InvalidOutputParameterName, + this.MethodSubject, + this.MethodName, + streamedResult.ParameterName); + + throw CimJobException.CreateWithFullControl( + this.JobContext, + errorMessage, + "CimJob_InvalidOutputParameterName", + ErrorCategory.MetadataError); + } + + var array = LanguagePrimitives.GetEnumerable(streamedResult.ItemValue); + if (array != null) + { + foreach (var element in array) + { + this.WriteObject(element, methodParameter); + } + } + else + { + this.WriteObject(streamedResult.ItemValue, methodParameter); + } + } + + private void WriteObject(object cmdletOutput, MethodParameter methodParameter) + { + Dbg.Assert(methodParameter != null, "Caller should verify that methodParameter != null"); + if ((cmdletOutput != null) && (!string.IsNullOrEmpty(methodParameter.ParameterTypeName))) + { + PSObject pso = PSObject.AsPSObject(cmdletOutput); + if (!pso.TypeNames.Contains(methodParameter.ParameterTypeName, StringComparer.OrdinalIgnoreCase)) + { + pso.TypeNames.Insert(0, methodParameter.ParameterTypeName); + } + } + + this.WriteObject(cmdletOutput); + } + + public override void OnNext(CimMethodResultBase item) + { + this.ExceptionSafeWrapper( + delegate + { + if (item is CimMethodResult methodResult) + { + this.OnNext(methodResult); + return; + } + + if (item is CimMethodStreamedResult streamedResult) + { + this.OnNext(streamedResult); + return; + } + + Dbg.Assert(false, "CimMethodResultBase has to be either a CimMethodResult or CimMethodStreamedResult"); + }); + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..06a4593352251f58c4d59d78690afdb9652ac685 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of an extrinsic CIM method. + /// + internal sealed class InstanceMethodInvocationJob : ExtrinsicMethodInvocationJob + { + private readonly CimInstance _targetInstance; + + internal InstanceMethodInvocationJob(CimJobContext jobContext, bool passThru, CimInstance targetInstance, MethodInvocationInfo methodInvocationInfo) + : base( + jobContext, + passThru, + targetInstance.ToString(), + methodInvocationInfo) + { + Dbg.Assert(targetInstance != null, "Caller should verify targetInstance != null"); + _targetInstance = targetInstance; + } + + internal override IObservable GetCimOperation() + { + if (!this.ShouldProcess()) + { + return null; + } + + CimMethodParametersCollection methodParameters = this.GetCimMethodParametersCollection(); + + CimOperationOptions operationOptions = this.CreateOperationOptions(); + operationOptions.EnableMethodResultStreaming = true; + + IObservable observable = this.JobContext.Session.InvokeMethodAsync( + this.JobContext.Namespace, + _targetInstance, + this.MethodName, + methodParameters, + operationOptions); + return observable; + } + + internal override object PassThruObject + { + get { return _targetInstance; } + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + return CimCustomOptionsDictionary.MergeOptions( + base.CalculateJobSpecificCustomOptions(), + _targetInstance); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..84b13b82097e79b92020ceec255ef2c7ae187b22 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Microsoft.PowerShell.Cim; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of an extrinsic CIM method. + /// + internal abstract class MethodInvocationJobBase : CimChildJobBase + { + internal MethodInvocationJobBase(CimJobContext jobContext, bool passThru, string methodSubject, MethodInvocationInfo methodInvocationInfo) + : base(jobContext) + { + Dbg.Assert(methodInvocationInfo != null, "Caller should verify methodInvocationInfo != null"); + Dbg.Assert(methodSubject != null, "Caller should verify methodSubject != null"); + + _passThru = passThru; + MethodSubject = methodSubject; + _methodInvocationInfo = methodInvocationInfo; + } + + private readonly bool _passThru; + private readonly MethodInvocationInfo _methodInvocationInfo; + + internal string MethodName + { + get { return _methodInvocationInfo.MethodName; } + } + + private const string CustomOperationOptionPrefix = "cim:operationOption:"; + + private IEnumerable GetMethodInputParametersCore(Func filter) + { + IEnumerable inputParameters = _methodInvocationInfo.Parameters.Where(filter); + + var result = new List(); + foreach (MethodParameter inputParameter in inputParameters) + { + object cimValue = CimSensitiveValueConverter.ConvertFromDotNetToCim(inputParameter.Value); + Type cimType = CimSensitiveValueConverter.GetCimType(inputParameter.ParameterType); + CimValueConverter.AssertIntrinsicCimType(cimType); + result.Add(new MethodParameter + { + Name = inputParameter.Name, + ParameterType = cimType, + Bindings = inputParameter.Bindings, + Value = cimValue, + IsValuePresent = inputParameter.IsValuePresent + }); + } + + return result; + } + + internal IEnumerable GetMethodInputParameters() + { + var allMethodParameters = this.GetMethodInputParametersCore(static p => !p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); + var methodParametersWithInputValue = allMethodParameters.Where(static p => p.IsValuePresent); + return methodParametersWithInputValue; + } + + internal IEnumerable GetCimInstancesFromArguments() + { + return _methodInvocationInfo.GetArgumentsOfType(); + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + IDictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); + + IEnumerable customOptions = this + .GetMethodInputParametersCore(static p => p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); + foreach (MethodParameter customOption in customOptions) + { + if (customOption.Value == null) + { + continue; + } + + result.Add(customOption.Name.Substring(CustomOperationOptionPrefix.Length), customOption.Value); + } + + return CimCustomOptionsDictionary.Create(result); + } + + internal IEnumerable GetMethodOutputParameters() + { + IEnumerable allParameters_plus_returnValue = _methodInvocationInfo.Parameters; + if (_methodInvocationInfo.ReturnValue != null) + { + allParameters_plus_returnValue = allParameters_plus_returnValue.Append(_methodInvocationInfo.ReturnValue); + } + + var outParameters = allParameters_plus_returnValue + .Where(static p => ((p.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error)) != 0)); + + return outParameters; + } + + internal string MethodSubject { get; } + + internal bool ShouldProcess() + { + Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + if (!this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess) + { + return true; + } + + bool shouldProcess; + if (!this.JobContext.SupportsShouldProcess) + { + shouldProcess = true; + this.WriteVerboseStartOfCimOperation(); + } + else + { + string target = this.MethodSubject; + string action = this.MethodName; + CimResponseType cimResponseType = this.ShouldProcess(target, action); + switch (cimResponseType) + { + case CimResponseType.Yes: + case CimResponseType.YesToAll: + shouldProcess = true; + break; + default: + shouldProcess = false; + break; + } + } + + if (!shouldProcess) + { + this.SetCompletedJobState(JobState.Completed, null); + } + + return shouldProcess; + } + + #region PassThru functionality + + internal abstract object PassThruObject { get; } + + internal bool IsPassThruObjectNeeded() + { + return (_passThru) && (!this.DidUserSuppressTheOperation) && (!this.JobHadErrors); + } + + public override void OnCompleted() + { + this.ExceptionSafeWrapper( + delegate + { + Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + + if (this.IsPassThruObjectNeeded()) + { + object passThruObject = this.PassThruObject; + if (passThruObject != null) + { + this.WriteObject(passThruObject); + } + } + }); + + base.OnCompleted(); + } + + #endregion + + #region Job descriptions + + internal override string Description + { + get + { + return string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_MethodDescription, + this.MethodSubject, + this.MethodName); + } + } + + internal override string FailSafeDescription + { + get + { + return string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_SafeMethodDescription, + this.JobContext.CmdletizationClassName, + this.JobContext.Session.ComputerName, + this.MethodName); + } + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..869002a55f4dc489f0c1275bb840487e18e95df4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of a ModifyInstance intrinsic CIM method. + /// + internal sealed class ModifyInstanceJob : PropertySettingJob + { + private CimInstance _resultFromModifyInstance; + private bool _resultFromModifyInstanceHasBeenPassedThru; + private readonly CimInstance _originalInstance; + private CimInstance _temporaryInstance; + + internal ModifyInstanceJob(CimJobContext jobContext, bool passThru, CimInstance managementObject, MethodInvocationInfo methodInvocationInfo) + : base(jobContext, passThru, managementObject, methodInvocationInfo) + { + Dbg.Assert(this.MethodSubject != null, "Caller should verify managementObject != null"); + _originalInstance = managementObject; + } + + internal override IObservable GetCimOperation() + { + if (!this.ShouldProcess()) + { + return null; + } + + _temporaryInstance = new CimInstance(_originalInstance); + ModifyLocalCimInstance(_temporaryInstance); + + IObservable observable = this.JobContext.Session.ModifyInstanceAsync( + this.JobContext.Namespace, + _temporaryInstance, + this.CreateOperationOptions()); + return observable; + } + + public override void OnNext(CimInstance item) + { + Dbg.Assert(item != null, "ModifyInstance and GetInstance should not return a null instance"); + _resultFromModifyInstance = item; + } + + public override void OnCompleted() + { + Dbg.Assert(_resultFromModifyInstance != null, "ModifyInstance should return an instance over DCOM and WSMan"); + ModifyLocalCimInstance(_originalInstance); /* modify input CimInstance only upon success (fix for bug WinBlue #) */ + base.OnCompleted(); + } + + internal override object PassThruObject + { + get + { + Dbg.Assert(_resultFromModifyInstance != null, "ModifyInstance should return an instance over DCOM and WSMan"); + if (IsShowComputerNameMarkerPresent(_originalInstance)) + { + PSObject pso = PSObject.AsPSObject(_resultFromModifyInstance); + AddShowComputerNameMarker(pso); + } + + _resultFromModifyInstanceHasBeenPassedThru = true; + return _resultFromModifyInstance; + } + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + return CimCustomOptionsDictionary.MergeOptions( + base.CalculateJobSpecificCustomOptions(), + _originalInstance); + } + + protected override void Dispose(bool disposing) + { + if (!_resultFromModifyInstanceHasBeenPassedThru && _resultFromModifyInstance != null) + { + _resultFromModifyInstance.Dispose(); + _resultFromModifyInstance = null; + } + + if (_temporaryInstance != null) + { + _temporaryInstance.Dispose(); + _temporaryInstance = null; + } + + base.Dispose(disposing); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..f5bdc0745cd333715d7f95a2bcfd20e05b97b24a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Management.Infrastructure; +using Microsoft.PowerShell.Cim; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of a CreateInstance or ModifyInstance intrinsic CIM method. + /// + internal abstract class PropertySettingJob : MethodInvocationJobBase + { + internal PropertySettingJob(CimJobContext jobContext, bool passThru, CimInstance objectToModify, MethodInvocationInfo methodInvocationInfo) + : base( + jobContext, + passThru, + objectToModify.ToString(), + methodInvocationInfo) + { + } + + internal void ModifyLocalCimInstance(CimInstance cimInstance) + { + foreach (MethodParameter methodParameter in this.GetMethodInputParameters()) + { + CimValueConverter.AssertIntrinsicCimType(methodParameter.ParameterType); + CimProperty propertyBeingModified = cimInstance.CimInstanceProperties[methodParameter.Name]; + if (propertyBeingModified != null) + { + propertyBeingModified.Value = methodParameter.Value; + } + else + { + CimProperty propertyBeingAdded = CimProperty.Create( + methodParameter.Name, + methodParameter.Value, + CimValueConverter.GetCimTypeEnum(methodParameter.ParameterType), + CimFlags.None); + cimInstance.CimInstanceProperties.Add(propertyBeingAdded); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..7bd2bd1753166ea50834062c07cb89f0e4cf2f48 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Text; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job that handles executing a WQL (in the future CQL?) query on a remote CIM server. + /// + internal sealed class QueryInstancesJob : QueryJobBase + { + private readonly string _wqlQuery; + private readonly bool _useEnumerateInstances; + + internal QueryInstancesJob(CimJobContext jobContext, CimQuery cimQuery, string wqlCondition) + : base(jobContext, cimQuery) + { + Dbg.Assert(wqlCondition != null, "Caller should verify that wqlCondition is not null"); + + var wqlQueryBuilder = new StringBuilder(); + wqlQueryBuilder.Append("SELECT * FROM "); + wqlQueryBuilder.Append(this.JobContext.ClassName); + wqlQueryBuilder.Append(' '); + wqlQueryBuilder.Append(wqlCondition); + _wqlQuery = wqlQueryBuilder.ToString(); + + if (string.IsNullOrWhiteSpace(wqlCondition)) + { + _useEnumerateInstances = true; + } + else + { + if (jobContext.CmdletInvocationContext.CmdletDefinitionContext.UseEnumerateInstancesInsteadOfWql) + { + _useEnumerateInstances = true; + } + } + } + + internal override IObservable GetCimOperation() + { + this.WriteVerboseStartOfCimOperation(); + + IObservable observable; + if (_useEnumerateInstances) + { + observable = this.JobContext.Session.EnumerateInstancesAsync( + this.JobContext.Namespace, + this.JobContext.ClassNameOrNullIfResourceUriIsUsed, + this.CreateOperationOptions()); + } + else + { + observable = this.JobContext.Session.QueryInstancesAsync( + this.JobContext.Namespace, + "WQL", + _wqlQuery, + this.CreateOperationOptions()); + } + + return observable; + } + + internal override string Description + { + get + { + return this.FailSafeDescription; + } + } + + internal override string FailSafeDescription + { + get + { + return string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_SafeQueryDescription, + this.JobContext.CmdletizationClassName, + this.JobContext.Session.ComputerName, + _wqlQuery); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..b52c23c3dd4a53faeea8c195d92e71d7bc5b60f4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Base job for queries. + /// + internal abstract class QueryJobBase : CimChildJobBase + { + private readonly CimQuery _cimQuery; + + internal QueryJobBase(CimJobContext jobContext, CimQuery cimQuery) + : base(jobContext) + { + Dbg.Assert(cimQuery != null, "Caller should verify cimQuery != null"); + _cimQuery = cimQuery; + } + + public override void OnNext(CimInstance item) + { + this.ExceptionSafeWrapper( + delegate + { + Dbg.Assert(item != null, "When OnNext is called from our IObservable, item parameter should always be != null"); + if (item == null) + { + return; + } + + if (!_cimQuery.IsMatchingResult(item)) + { + return; + } + + this.WriteObject(item); + }); + } + + public override void OnCompleted() + { + this.ExceptionSafeWrapper( + delegate + { + foreach (ClientSideQuery.NotFoundError notFoundError in _cimQuery.GenerateNotFoundErrors()) + { + string errorId = "CmdletizationQuery_NotFound"; + if (!string.IsNullOrEmpty(notFoundError.PropertyName)) + { + errorId = errorId + "_" + notFoundError.PropertyName; + } + + CimJobException cimJobException = CimJobException.CreateWithFullControl( + this.JobContext, + notFoundError.ErrorMessageGenerator(this.Description, this.JobContext.ClassName), + errorId, + ErrorCategory.ObjectNotFound); + if (!string.IsNullOrEmpty(notFoundError.PropertyName)) + { + cimJobException.ErrorRecord.SetTargetObject(notFoundError.PropertyValue); + } + + this.WriteError(cimJobException.ErrorRecord); + } + }); + base.OnCompleted(); + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + return CimCustomOptionsDictionary.Create(_cimQuery.queryOptions); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..3bc376ab3d56aea46ca1c555f1b5878e6acea197 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Job wrapping invocation of a static CIM method. + /// + internal sealed class StaticMethodInvocationJob : ExtrinsicMethodInvocationJob + { + internal StaticMethodInvocationJob(CimJobContext jobContext, MethodInvocationInfo methodInvocationInfo) + : base(jobContext, false /* passThru */, jobContext.CmdletizationClassName, methodInvocationInfo) + { + } + + internal override IObservable GetCimOperation() + { + if (!this.ShouldProcess()) + { + return null; + } + + CimMethodParametersCollection methodParameters = this.GetCimMethodParametersCollection(); + + CimOperationOptions operationOptions = this.CreateOperationOptions(); + operationOptions.EnableMethodResultStreaming = true; + + IObservable observable = this.JobContext.Session.InvokeMethodAsync( + this.JobContext.Namespace, + this.JobContext.ClassNameOrNullIfResourceUriIsUsed, + this.MethodName, + methodParameters, + operationOptions); + return observable; + } + + internal override object PassThruObject + { + get { return null; } + } + + internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() + { + return CimCustomOptionsDictionary.MergeOptions( + base.CalculateJobSpecificCustomOptions(), + this.GetCimInstancesFromArguments()); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs new file mode 100644 index 0000000000000000000000000000000000000000..6b716fa5501e1a44ddbf43d5a01180b088c84f17 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Remoting; +using System.Runtime.CompilerServices; +using System.Threading; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Tracks (per-session) terminating errors in a given cmdlet invocation. + /// + internal sealed class TerminatingErrorTracker + { + #region Getting tracker for a given cmdlet invocation + + private static readonly ConditionalWeakTable s_invocationToTracker = + new(); + + private static int GetNumberOfSessions(InvocationInfo invocationInfo) + { + // if user explicitly specifies CimSession, then the cmdlet runs against exactly those sessions + object cimSessionArgument; + if (invocationInfo.BoundParameters.TryGetValue("CimSession", out cimSessionArgument)) + { + IList cimSessionArgumentAsList = (IList)cimSessionArgument; + return cimSessionArgumentAsList.Count; + } + // else - either CimSession=localhost OR CimSession is based on CimInstance->CimSession affinity + + // CimInstance->CimSession affinity in instance cmdlets can come from: + // 1. InputObject (either passed through pipeline or explicitly bound to the parameter) + // 2. AssociatedObject (either passed through pipeline or explicitly bound to the parameter [we don't know the name of the parameter though]) + // CimInstance->CimSession affinity in static cmdlets can come from: + // 1. Any method argument that is either a CimInstance or CimInstance[] + // Additionally in both instance and static cmdlets, if the pipeline object is a CimInstance, then it can affect the session acted against + if (invocationInfo.ExpectingInput) + { + // can get unlimited number of CimInstances through pipeline + // - this translates into potentially unlimited number of CimSession we will work with + return int.MaxValue; + } + + int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1; + foreach (object cmdletArgument in invocationInfo.BoundParameters.Values) + { + if (cmdletArgument is CimInstance[] array) + { + int numberOfSessionsAssociatedWithArgument = array + .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance) + .Distinct() + .Count(); + maxNumberOfSessionsIndicatedByCimInstanceArguments = Math.Max( + maxNumberOfSessionsIndicatedByCimInstanceArguments, + numberOfSessionsAssociatedWithArgument); + } + } + + return maxNumberOfSessionsIndicatedByCimInstanceArguments; + } + + internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo, bool isStaticCmdlet) + { + var tracker = s_invocationToTracker.GetValue( + invocationInfo, + _ => new TerminatingErrorTracker(GetNumberOfSessions(invocationInfo))); + + return tracker; + } + + internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo) + { + TerminatingErrorTracker tracker; + bool foundTracker = s_invocationToTracker.TryGetValue(invocationInfo, out tracker); + Dbg.Assert(foundTracker, "The other overload of GetTracker should always be called first"); + return tracker; + } + + #endregion Getting tracker for a given cmdlet invocation + + #region Tracking terminating errors within a single cmdlet invocation + + private readonly int _numberOfSessions; + private int _numberOfReportedSessionTerminatingErrors; + + private TerminatingErrorTracker(int numberOfSessions) + { + _numberOfSessions = numberOfSessions; + } + + #region Tracking session's "connectivity" status + + private readonly ConcurrentDictionary _sessionToIsConnected = new(); + + internal void MarkSessionAsConnected(CimSession connectedSession) + { + _sessionToIsConnected.TryAdd(connectedSession, true); + } + + internal bool DidSessionAlreadyPassedConnectivityTest(CimSession session) + { + bool alreadyPassedConnectivityTest = false; + if (_sessionToIsConnected.TryGetValue(session, out alreadyPassedConnectivityTest)) + { + return alreadyPassedConnectivityTest; + } + + return false; + } + + internal Exception GetExceptionIfBrokenSession( + CimSession potentiallyBrokenSession, + bool skipTestConnection, + out bool sessionWasAlreadyTerminated) + { + if (IsSessionTerminated(potentiallyBrokenSession)) + { + sessionWasAlreadyTerminated = true; + return null; + } + + Exception sessionException = null; + if (!skipTestConnection && + !this.DidSessionAlreadyPassedConnectivityTest(potentiallyBrokenSession)) + { + try + { + CimInstance throwAwayCimInstance; + CimException cimException; + potentiallyBrokenSession.TestConnection(out throwAwayCimInstance, out cimException); + sessionException = cimException; + if (sessionException == null) + { + this.MarkSessionAsConnected(potentiallyBrokenSession); + } + } + catch (InvalidOperationException invalidOperationException) + { + sessionException = invalidOperationException; + } + } + + if (sessionException != null) + { + MarkSessionAsTerminated(potentiallyBrokenSession, out sessionWasAlreadyTerminated); + return sessionException; + } + else + { + sessionWasAlreadyTerminated = false; + return null; + } + } + + #endregion + + #region Tracking session's "terminated" status + + private readonly ConcurrentDictionary _sessionToIsTerminated = new(); + + internal void MarkSessionAsTerminated(CimSession terminatedSession, out bool sessionWasAlreadyTerminated) + { + bool closureSafeSessionWasAlreadyTerminated = false; + _sessionToIsTerminated.AddOrUpdate( + key: terminatedSession, + addValue: true, + updateValueFactory: + (CimSession key, bool isTerminatedValueInDictionary) => + { + closureSafeSessionWasAlreadyTerminated = isTerminatedValueInDictionary; + return true; + }); + + sessionWasAlreadyTerminated = closureSafeSessionWasAlreadyTerminated; + } + + internal bool IsSessionTerminated(CimSession session) + { + bool isTerminated = _sessionToIsTerminated.GetOrAdd(session, false); + return isTerminated; + } + + #endregion + + #region Reporting errors in a way that takes session's "terminated" status into account + + internal CmdletMethodInvoker GetErrorReportingDelegate(ErrorRecord errorRecord) + { + ManualResetEventSlim manualResetEventSlim = new(); + object lockObject = new(); + Func action = (Cmdlet cmdlet) => + { + _numberOfReportedSessionTerminatingErrors++; + if (_numberOfReportedSessionTerminatingErrors >= _numberOfSessions) + { + cmdlet.ThrowTerminatingError(errorRecord); + } + else + { + cmdlet.WriteError(errorRecord); + } + + return false; // not really needed here, but required by CmdletMethodInvoker + }; + + return new CmdletMethodInvoker + { + Action = action, + Finished = manualResetEventSlim, // not really needed here, but required by CmdletMethodInvoker + SyncObject = lockObject, // not really needed here, but required by CmdletMethodInvoker + }; + } + + #endregion + + #endregion Tracking terminating errors within a single cmdlet invocation + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..6bd2bee7feefc631db0f84c88502c23a2016b5c2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -0,0 +1,1081 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Concurrent; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Remoting; +using System.Management.Automation.Remoting.Internal; +using System.Threading; + +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Microsoft.PowerShell.Cim; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Base class for all child jobs that wrap CIM operations. + /// + internal abstract class CimChildJobBase : + StartableJob, + IObserver + { + private static long s_globalJobNumberCounter; + private readonly long _myJobNumber = Interlocked.Increment(ref s_globalJobNumberCounter); + + private const string CIMJobType = "CimJob"; + + internal CimJobContext JobContext + { + get + { + return _jobContext; + } + } + + private readonly CimJobContext _jobContext; + + internal CimChildJobBase(CimJobContext jobContext) + : base(Job.GetCommandTextFromInvocationInfo(jobContext.CmdletInvocationInfo), " " /* temporary name - reset below */) + { + _jobContext = jobContext; + this.PSJobTypeName = CIMJobType; + + this.Name = this.GetType().Name + _myJobNumber.ToString(CultureInfo.InvariantCulture); + UsesResultsCollection = true; + + lock (s_globalRandom) + { + _random = new Random(s_globalRandom.Next()); + } + + _jobSpecificCustomOptions = new Lazy(this.CalculateJobSpecificCustomOptions); + } + + private readonly CimSensitiveValueConverter _cimSensitiveValueConverter = new(); + + internal CimSensitiveValueConverter CimSensitiveValueConverter { get { return _cimSensitiveValueConverter; } } + + internal abstract IObservable GetCimOperation(); + + public abstract void OnNext(T item); + + // copied from sdpublic\sdk\inc\wsmerror.h + private enum WsManErrorCode : uint + { + ERROR_WSMAN_QUOTA_MAX_SHELLS = 0x803381A5, + ERROR_WSMAN_QUOTA_MAX_OPERATIONS = 0x803381A6, + ERROR_WSMAN_QUOTA_USER = 0x803381A7, + ERROR_WSMAN_QUOTA_SYSTEM = 0x803381A8, + ERROR_WSMAN_QUOTA_MAX_SHELLUSERS = 0x803381AB, + ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ = 0x803381E4, + ERROR_WSMAN_QUOTA_MAX_USERS_PPQ = 0x803381E5, + ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ = 0x803381E6, + ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ = 0x803381E7, + ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ = 0x803381E8, + ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ = 0x803381E9, + ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ = 0x803381EA, + } + + private static bool IsWsManQuotaReached(Exception exception) + { + if (exception is not CimException cimException) + { + return false; + } + + if (cimException.NativeErrorCode != NativeErrorCode.ServerLimitsExceeded) + { + return false; + } + + CimInstance cimError = cimException.ErrorData; + if (cimError == null) + { + return false; + } + + CimProperty errorCodeProperty = cimError.CimInstanceProperties["error_Code"]; + if (errorCodeProperty == null) + { + return false; + } + + if (errorCodeProperty.CimType != CimType.UInt32) + { + return false; + } + + WsManErrorCode wsManErrorCode = (WsManErrorCode)(uint)(errorCodeProperty.Value); + switch (wsManErrorCode) // error codes that should result in sleep-and-retry are based on an email from Ryan + { + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS: + case WsManErrorCode.ERROR_WSMAN_QUOTA_USER: + case WsManErrorCode.ERROR_WSMAN_QUOTA_SYSTEM: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLUSERS: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_USERS_PPQ: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ: + case WsManErrorCode.ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ: + return true; + + default: + return false; + } + } + + public virtual void OnError(Exception exception) + { + this.ExceptionSafeWrapper( + delegate + { + if (IsWsManQuotaReached(exception)) + { + this.SleepAndRetry(); + return; + } + + var cje = CimJobException.CreateFromAnyException(this.GetDescription(), this.JobContext, exception); + this.ReportJobFailure(cje); + }); + } + + public virtual void OnCompleted() + { + this.ExceptionSafeWrapper( + delegate + { + this.SetCompletedJobState(JobState.Completed, null); + }); + } + + private static readonly Random s_globalRandom = new(); + private readonly Random _random; + private int _sleepAndRetryDelayRangeMs = 1000; + private int _sleepAndRetryExtraDelayMs = 0; + + private const int MaxRetryDelayMs = 15 * 1000; + private const int MinRetryDelayMs = 100; + + private Timer _sleepAndRetryTimer; + + private void SleepAndRetry_OnWakeup(object state) + { + this.ExceptionSafeWrapper( + delegate + { + lock (_jobStateLock) + { + if (_sleepAndRetryTimer != null) + { + _sleepAndRetryTimer.Dispose(); + _sleepAndRetryTimer = null; + } + + if (_jobWasStopped) + { + this.SetCompletedJobState(JobState.Stopped, null); + return; + } + } + + this.StartJob(); + }); + } + + 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); + } + } + } + + /// + /// Indicates a location where this job is running. + /// + public override string Location + { + get + { + // this.JobContext is set in the constructor of CimChildJobBase, + // but the constructor of Job wants to access Location property + // before CimChildJobBase is fully initialized + if (this.JobContext == null) + { + return null; + } + + string location = this.JobContext.Session.ComputerName ?? Environment.MachineName; + return location; + } + } + + /// + /// Status message associated with the Job. + /// + public override string StatusMessage + { + get + { + return this.JobStateInfo.State.ToString(); + } + } + + /// + /// Indicates if job has more data available. + /// + public override bool HasMoreData + { + get + { + return (Results.IsOpen || Results.Count > 0); + } + } + + internal void WriteVerboseStartOfCimOperation() + { + if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideWriteVerbose) + { + string verboseMessage = string.Format( + CultureInfo.CurrentCulture, + CmdletizationResources.CimJob_VerboseExecutionMessage, + this.GetDescription()); + this.WriteVerbose(verboseMessage); + } + } + + internal override void StartJob() + { + lock (_jobStateLock) + { + if (_jobWasStopped) + { + this.SetCompletedJobState(JobState.Stopped, null); + return; + } + + Dbg.Assert(!_alreadyReachedCompletedState, "Job shouldn't reach completed state, before ThrottlingJob has a chance to register for job-completed/failed events"); + + TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo); + if (tracker.IsSessionTerminated(this.JobContext.Session)) + { + this.SetCompletedJobState(JobState.Failed, new OperationCanceledException()); + return; + } + + if (!_jobWasStarted) + { + _jobWasStarted = true; + this.SetJobState(JobState.Running); + } + } + + // This invocation can block (i.e. by calling Job.ShouldProcess) and wait for pipeline thread to unblock it + // Therefore we have to do the invocation outside of the pipeline thread. + ThreadPool.QueueUserWorkItem(delegate + { + this.ExceptionSafeWrapper(delegate + { + IObservable observable = this.GetCimOperation(); + observable?.Subscribe(this); + }); + }); + } + + internal string GetDescription() + { + try + { + return this.Description; + } + catch (Exception) + { + return this.FailSafeDescription; + } + } + + internal abstract string Description { get; } + + internal abstract string FailSafeDescription { get; } + + internal void ExceptionSafeWrapper(Action action) + { + try + { + try + { + Dbg.Assert(action != null, "Caller should verify action != null"); + action(); + } + catch (CimJobException e) + { + this.ReportJobFailure(e); + } + catch (PSInvalidCastException e) + { + this.ReportJobFailure(e); + } + catch (CimException e) + { + var cje = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, e); + this.ReportJobFailure(cje); + } + catch (PSInvalidOperationException) + { + lock (_jobStateLock) + { + bool everythingIsOk = false; + if (_jobWasStopped) + { + everythingIsOk = true; + } + + if (_alreadyReachedCompletedState && _jobHadErrors) + { + everythingIsOk = true; + } + + if (!everythingIsOk) + { + Dbg.Assert(false, "PSInvalidOperationException should only happen in certain job states"); + throw; + } + } + } + } + catch (Exception e) + { + var cje = CimJobException.CreateFromAnyException(this.GetDescription(), this.JobContext, e); + this.ReportJobFailure(cje); + } + } + + #region Operation options + + internal virtual string GetProviderVersionExpectedByJob() + { + return this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassVersion; + } + + internal CimOperationOptions CreateOperationOptions() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false) + { + CancellationToken = _cancellationTokenSource.Token, + WriteProgress = this.WriteProgressCallback, + WriteMessage = this.WriteMessageCallback, + WriteError = this.WriteErrorCallback, + PromptUser = this.PromptUserCallback, + }; + + operationOptions.SetOption("__MI_OPERATIONOPTIONS_IMPROVEDPERF_STREAMING", 1); + + operationOptions.Flags |= this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SchemaConformanceLevel; + + if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri != null) + { + operationOptions.ResourceUri = this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri; + } + + if (( + (_jobContext.WarningActionPreference == ActionPreference.SilentlyContinue) || + (_jobContext.WarningActionPreference == ActionPreference.Ignore) + ) && (!_jobContext.IsRunningInBackground)) + { + operationOptions.DisableChannel((uint)MessageChannel.Warning); + } + else + { + operationOptions.EnableChannel((uint)MessageChannel.Warning); + } + + if (( + (_jobContext.VerboseActionPreference == ActionPreference.SilentlyContinue) || + (_jobContext.VerboseActionPreference == ActionPreference.Ignore) + ) && (!_jobContext.IsRunningInBackground)) + { + operationOptions.DisableChannel((uint)MessageChannel.Verbose); + } + else + { + operationOptions.EnableChannel((uint)MessageChannel.Verbose); + } + + if (( + (_jobContext.DebugActionPreference == ActionPreference.SilentlyContinue) || + (_jobContext.DebugActionPreference == ActionPreference.Ignore) + ) && (!_jobContext.IsRunningInBackground)) + { + operationOptions.DisableChannel((uint)MessageChannel.Debug); + } + else + { + operationOptions.EnableChannel((uint)MessageChannel.Debug); + } + + switch (this.JobContext.ShouldProcessOptimization) + { + case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoNo_CanCallShouldProcessAsynchronously: + operationOptions.SetPromptUserRegularMode(CimCallbackMode.Report, automaticConfirmation: false); + break; + + case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanCallShouldProcessAsynchronously: + operationOptions.SetPromptUserRegularMode(CimCallbackMode.Report, automaticConfirmation: true); + break; + + case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanSkipShouldProcessCall: + operationOptions.SetPromptUserRegularMode(CimCallbackMode.Ignore, automaticConfirmation: true); + break; + + case MshCommandRuntime.ShouldProcessPossibleOptimization.NoOptimizationPossible: + default: + operationOptions.PromptUserMode = CimCallbackMode.Inquire; + break; + } + + switch (this.JobContext.ErrorActionPreference) + { + case ActionPreference.Continue: + case ActionPreference.SilentlyContinue: + case ActionPreference.Ignore: + operationOptions.WriteErrorMode = CimCallbackMode.Report; + break; + + case ActionPreference.Stop: + case ActionPreference.Inquire: + default: + operationOptions.WriteErrorMode = CimCallbackMode.Inquire; + break; + } + + if (!string.IsNullOrWhiteSpace(this.GetProviderVersionExpectedByJob())) + { + CimOperationOptionsHelper.SetCustomOption( + operationOptions, + "MI_OPERATIONOPTIONS_PROVIDERVERSION", + this.GetProviderVersionExpectedByJob(), + CimSensitiveValueConverter); + } + + if (this.JobContext.CmdletizationModuleVersion != null) + { + CimOperationOptionsHelper.SetCustomOption( + operationOptions, + "MI_OPERATIONOPTIONS_POWERSHELL_MODULEVERSION", + this.JobContext.CmdletizationModuleVersion, + CimSensitiveValueConverter); + } + + CimOperationOptionsHelper.SetCustomOption( + operationOptions, + "MI_OPERATIONOPTIONS_POWERSHELL_CMDLETNAME", + this.JobContext.CmdletInvocationInfo.MyCommand.Name, + CimSensitiveValueConverter); + if (!string.IsNullOrWhiteSpace(this.JobContext.Session.ComputerName)) + { + CimOperationOptionsHelper.SetCustomOption( + operationOptions, + "MI_OPERATIONOPTIONS_POWERSHELL_COMPUTERNAME", + this.JobContext.Session.ComputerName, + CimSensitiveValueConverter); + } + + CimCustomOptionsDictionary jobSpecificCustomOptions = this.GetJobSpecificCustomOptions(); + jobSpecificCustomOptions?.Apply(operationOptions, CimSensitiveValueConverter); + + return operationOptions; + } + + private readonly Lazy _jobSpecificCustomOptions; + + internal abstract CimCustomOptionsDictionary CalculateJobSpecificCustomOptions(); + + private CimCustomOptionsDictionary GetJobSpecificCustomOptions() + { + return _jobSpecificCustomOptions.Value; + } + + #endregion + + #region Controlling job state + + private readonly CancellationTokenSource _cancellationTokenSource = new(); + + /// + /// Stops this job. + /// + public override void StopJob() + { + lock (_jobStateLock) + { + if (_jobWasStopped || _alreadyReachedCompletedState) + { + return; + } + + _jobWasStopped = true; + + if (!_jobWasStarted) + { + this.SetCompletedJobState(JobState.Stopped, null); + } + else if (_sleepAndRetryTimer != null) + { + _sleepAndRetryTimer.Dispose(); + _sleepAndRetryTimer = null; + this.SetCompletedJobState(JobState.Stopped, null); + } + else + { + this.SetJobState(JobState.Stopping); + } + } + + _cancellationTokenSource.Cancel(); + } + + private readonly object _jobStateLock = new(); + private bool _jobHadErrors; + private bool _jobWasStarted; + private bool _jobWasStopped; + private bool _alreadyReachedCompletedState; + + internal bool JobHadErrors + { + get + { + lock (_jobStateLock) + { + return _jobHadErrors; + } + } + } + + internal void ReportJobFailure(IContainsErrorRecord exception) + { + TerminatingErrorTracker terminatingErrorTracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo); + + bool sessionWasAlreadyTerminated = false; + bool isThisTerminatingError = false; + Exception brokenSessionException = null; + lock (_jobStateLock) + { + if (!_jobWasStopped) + { + brokenSessionException = terminatingErrorTracker.GetExceptionIfBrokenSession( + this.JobContext.Session, + this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SkipTestConnection, + out sessionWasAlreadyTerminated); + } + } + + if (brokenSessionException != null) + { + string brokenSessionMessage = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_BrokenSession, + brokenSessionException.Message); + exception = CimJobException.CreateWithFullControl( + this.JobContext, + brokenSessionMessage, + "CimJob_BrokenCimSession", + ErrorCategory.ResourceUnavailable, + brokenSessionException); + isThisTerminatingError = true; + } + else + { + if ((exception is CimJobException cje) && (cje.IsTerminatingError)) + { + terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated); + isThisTerminatingError = true; + } + } + + bool writeError = !sessionWasAlreadyTerminated; + if (writeError) + { + lock (_jobStateLock) + { + if (_jobWasStopped) + { + writeError = false; + } + } + } + + ErrorRecord errorRecord = exception.ErrorRecord; + errorRecord.SetInvocationInfo(this.JobContext.CmdletInvocationInfo); + errorRecord.PreserveInvocationInfoOnce = true; + + if (writeError) + { + lock (_jobStateLock) + { + if (!_alreadyReachedCompletedState) + { + if (isThisTerminatingError) + { + this.Error.Add(errorRecord); + CmdletMethodInvoker methodInvoker = terminatingErrorTracker.GetErrorReportingDelegate(errorRecord); + this.Results.Add(new PSStreamObject(PSStreamObjectType.ShouldMethod, methodInvoker)); + } + else + { + this.WriteError(errorRecord); + } + } + } + } + + this.SetCompletedJobState(JobState.Failed, errorRecord.Exception); + } + + internal override void WriteWarning(string message) + { + message = this.JobContext.PrependComputerNameToMessage(message); + base.WriteWarning(message); + } + + internal override void WriteVerbose(string message) + { + message = this.JobContext.PrependComputerNameToMessage(message); + base.WriteVerbose(message); + } + + internal override void WriteDebug(string message) + { + message = this.JobContext.PrependComputerNameToMessage(message); + base.WriteDebug(message); + } + + internal void SetCompletedJobState(JobState state, Exception reason) + { + lock (_jobStateLock) + { + if (_alreadyReachedCompletedState) + { + return; + } + + _alreadyReachedCompletedState = true; + + if ((state == JobState.Failed) || (reason != null)) + { + _jobHadErrors = true; + } + + if (_jobWasStopped) + { + state = JobState.Stopped; + } + else if (_jobHadErrors) + { + state = JobState.Failed; + } + } + + this.FinishProgressReporting(); + this.SetJobState(state, reason); + this.CloseAllStreams(); + _cancellationTokenSource.Cancel(); + } + + #endregion + + #region Support for progress reporting + + private readonly ConcurrentDictionary _activityIdToLastProgressRecord = new(); + + internal override void WriteProgress(ProgressRecord progressRecord) + { + progressRecord.Activity = this.JobContext.PrependComputerNameToMessage(progressRecord.Activity); + + _activityIdToLastProgressRecord.AddOrUpdate( + progressRecord.ActivityId, + progressRecord, + (activityId, oldProgressRecord) => progressRecord); + + base.WriteProgress(progressRecord); + } + + internal void FinishProgressReporting() + { + foreach (ProgressRecord lastProgressRecord in _activityIdToLastProgressRecord.Values) + { + if (lastProgressRecord.RecordType != ProgressRecordType.Completed) + { + var newProgressRecord = new ProgressRecord(lastProgressRecord.ActivityId, lastProgressRecord.Activity, lastProgressRecord.StatusDescription); + newProgressRecord.RecordType = ProgressRecordType.Completed; + newProgressRecord.PercentComplete = 100; + newProgressRecord.SecondsRemaining = 0; + this.WriteProgress(newProgressRecord); + } + } + } + + #endregion + + #region Handling extended semantics callbacks + + private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, uint percentageCompleted, uint secondsRemaining) + { + if (string.IsNullOrEmpty(activity)) + { + activity = this.GetDescription(); + } + + if (string.IsNullOrEmpty(statusDescription)) + { + statusDescription = this.StatusMessage; + } + + int signedSecondsRemaining; + if (secondsRemaining == uint.MaxValue) + { + signedSecondsRemaining = -1; + } + else if (secondsRemaining <= int.MaxValue) + { + signedSecondsRemaining = (int)secondsRemaining; + } + else + { + signedSecondsRemaining = int.MaxValue; + } + + int signedPercentageComplete; + if (percentageCompleted == uint.MaxValue) + { + signedPercentageComplete = -1; + } + else if (percentageCompleted <= 100) + { + signedPercentageComplete = (int)percentageCompleted; + } + else + { + signedPercentageComplete = 100; + } + + var progressRecord = new ProgressRecord(unchecked((int)(_myJobNumber % int.MaxValue)), activity, statusDescription) + { + CurrentOperation = currentOperation, + PercentComplete = signedPercentageComplete, + SecondsRemaining = signedSecondsRemaining, + RecordType = ProgressRecordType.Processing, + }; + + this.ExceptionSafeWrapper( + delegate + { + this.WriteProgress(progressRecord); + }); + } + + private enum MessageChannel + { + Warning = 0, + Verbose = 1, + Debug = 2, + } + + private void WriteMessageCallback(uint channel, string message) + { + this.ExceptionSafeWrapper( + delegate + { + switch ((MessageChannel)channel) + { + case MessageChannel.Warning: + this.WriteWarning(message); + break; + + case MessageChannel.Verbose: + this.WriteVerbose(message); + break; + + case MessageChannel.Debug: + this.WriteDebug(message); + break; + + default: + Dbg.Assert(false, "We shouldn't get messages in channels that we didn't register for"); + break; + } + }); + } + + private CimResponseType BlockingWriteError(ErrorRecord errorRecord) + { + Exception exceptionThrownOnCmdletThread = null; + this.ExceptionSafeWrapper( + delegate + { + this.WriteError(errorRecord, out exceptionThrownOnCmdletThread); + }); + + return (exceptionThrownOnCmdletThread != null) + ? CimResponseType.NoToAll + : CimResponseType.Yes; + } + + private CimResponseType WriteErrorCallback(CimInstance cimError) + { + lock (_jobStateLock) + { + _jobHadErrors = true; + } + + var cimException = new CimException(cimError); + var jobException = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, cimException); + var errorRecord = jobException.ErrorRecord; + + switch (this.JobContext.ErrorActionPreference) + { + case ActionPreference.Stop: + case ActionPreference.Inquire: + return this.BlockingWriteError(errorRecord); + + default: + this.WriteError(errorRecord); + return CimResponseType.Yes; + } + } + + private bool _userWasPromptedForContinuationOfProcessing; + private bool _userRespondedYesToAtLeastOneShouldProcess; + + internal bool DidUserSuppressTheOperation + { + get + { + bool didUserSuppressTheOperation = _userWasPromptedForContinuationOfProcessing && (!_userRespondedYesToAtLeastOneShouldProcess); + return didUserSuppressTheOperation; + } + } + + internal CimResponseType ShouldProcess(string target, string action) + { + string verboseDescription = StringUtil.Format(CommandBaseStrings.ShouldProcessMessage, + action, + target, + null); + + return ShouldProcess(verboseDescription, null, null); + } + + internal CimResponseType ShouldProcess( + string verboseDescription, + string verboseWarning, + string caption) + { + if (this.JobContext.IsRunningInBackground) + { + return CimResponseType.YesToAll; + } + + if (this.JobContext.ShouldProcessOptimization == MshCommandRuntime.ShouldProcessPossibleOptimization.AutoNo_CanCallShouldProcessAsynchronously) + { + this.NonblockingShouldProcess(verboseDescription, verboseWarning, caption); + return CimResponseType.No; + } + + if (this.JobContext.ShouldProcessOptimization == MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanCallShouldProcessAsynchronously) + { + this.NonblockingShouldProcess(verboseDescription, verboseWarning, caption); + return CimResponseType.Yes; + } + + Dbg.Assert( + (this.JobContext.ShouldProcessOptimization != MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanSkipShouldProcessCall) || + (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess), + "MI layer should not call us when AutoYes_CanSkipShouldProcessCall optimization is in effect"); + Exception exceptionThrownOnCmdletThread; + ShouldProcessReason shouldProcessReason; + bool shouldProcessResponse = this.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason, out exceptionThrownOnCmdletThread); + if (exceptionThrownOnCmdletThread != null) + { + return CimResponseType.NoToAll; + } + else if (shouldProcessResponse) + { + return CimResponseType.Yes; + } + else + { + return CimResponseType.No; + } + } + + private CimResponseType PromptUserCallback(string message, CimPromptType promptType) + { + message = this.JobContext.PrependComputerNameToMessage(message); + + Exception exceptionThrownOnCmdletThread = null; + CimResponseType result = CimResponseType.No; + + _userWasPromptedForContinuationOfProcessing = true; + switch (promptType) + { + case CimPromptType.Critical: + this.ExceptionSafeWrapper( + delegate + { + if (this.ShouldContinue(message, null, out exceptionThrownOnCmdletThread)) + { + result = CimResponseType.Yes; + } + else + { + result = CimResponseType.No; + } + }); + break; + + case CimPromptType.Normal: + this.ExceptionSafeWrapper( + delegate + { + result = this.ShouldProcess(message, null, null); + }); + break; + + default: + Dbg.Assert(false, "Unrecognized CimPromptType"); + break; + } + + if (exceptionThrownOnCmdletThread != null) + { + result = CimResponseType.NoToAll; + } + + if ((result == CimResponseType.Yes) || (result == CimResponseType.YesToAll)) + { + _userRespondedYesToAtLeastOneShouldProcess = true; + } + + return result; + } + + #endregion + + internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) + { + PSObject pso = PSObject.AsPSObject(cimInstance); + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is not PSPropertyInfo psShowComputerNameProperty) + { + return false; + } + + return true.Equals(psShowComputerNameProperty.Value); + } + + internal static void AddShowComputerNameMarker(PSObject pso) + { + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty) + { + psShowComputerNameProperty.Value = true; + } + else + { + psShowComputerNameProperty = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true); + pso.InstanceMembers.Add(psShowComputerNameProperty); + } + } + + internal override void WriteObject(object outputObject) + { + CimInstance cimInstance = null; + PSObject pso = null; + if (outputObject is PSObject) + { + pso = PSObject.AsPSObject(outputObject); + cimInstance = pso.BaseObject as CimInstance; + } + else + { + cimInstance = outputObject as CimInstance; + } + + if (cimInstance != null) + { + CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); + CimCustomOptionsDictionary.AssociateCimInstanceWithCustomOptions(cimInstance, this.GetJobSpecificCustomOptions()); + } + + if (this.JobContext.ShowComputerName) + { + pso ??= PSObject.AsPSObject(outputObject); + + AddShowComputerNameMarker(pso); + if (cimInstance == null) + { + pso.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, this.JobContext.Session.ComputerName)); + } + } + + base.WriteObject(outputObject); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + bool isCompleted; + lock (_jobStateLock) + { + isCompleted = _alreadyReachedCompletedState; + } + + if (!isCompleted) + { + this.StopJob(); + this.Finished.WaitOne(); + } + + _cimSensitiveValueConverter.Dispose(); + _cancellationTokenSource.Dispose(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..8a4e427256146fbe76a44024050efa3357b0698b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure.Options; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + internal sealed class CimCmdletDefinitionContext + { + internal CimCmdletDefinitionContext( + string cmdletizationClassName, + string cmdletizationClassVersion, + Version cmdletizationModuleVersion, + bool supportsShouldProcess, + IDictionary privateData) + { + this.CmdletizationClassName = cmdletizationClassName; + this.CmdletizationClassVersion = cmdletizationClassVersion; + this.CmdletizationModuleVersion = cmdletizationModuleVersion; + this.SupportsShouldProcess = supportsShouldProcess; + _privateData = privateData; + } + + public string CmdletizationClassName { get; } + + public string CmdletizationClassVersion { get; } + + public Version CmdletizationModuleVersion { get; } + + public bool SupportsShouldProcess { get; } + + private readonly IDictionary _privateData; + + private const string QueryLanguageKey = "QueryDialect"; + + private bool? _useEnumerateInstancesInsteadOfWql; + + public bool UseEnumerateInstancesInsteadOfWql + { + get + { + if (!_useEnumerateInstancesInsteadOfWql.HasValue) + { + bool newValue = false; + string queryLanguage; + if (_privateData != null && + _privateData.TryGetValue(QueryLanguageKey, out queryLanguage) && + queryLanguage.Equals("None", StringComparison.OrdinalIgnoreCase)) + { + newValue = true; + } + + _useEnumerateInstancesInsteadOfWql = newValue; + } + + return _useEnumerateInstancesInsteadOfWql.Value; + } + } + + private const int FallbackDefaultThrottleLimit = 15; + /* PS> dir 'WSMan:\localhost\Plugin\WMI Provider\Quotas' | ft -auto + + WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\WMI Provider\Quotas + + Name Value Type + ---- ----- ---- + MaxConcurrentUsers 100 System.String + MaxConcurrentOperationsPerUser 15 System.String + MaxConcurrentOperations 1500 System.String + */ + + public int DefaultThrottleLimit + { + get + { + string defaultThrottleLimitString; + if (!_privateData.TryGetValue("DefaultThrottleLimit", out defaultThrottleLimitString)) + { + return FallbackDefaultThrottleLimit; + } + + int defaultThrottleLimitInteger; + if (!LanguagePrimitives.TryConvertTo(defaultThrottleLimitString, CultureInfo.InvariantCulture, out defaultThrottleLimitInteger)) + { + return FallbackDefaultThrottleLimit; + } + + return defaultThrottleLimitInteger; + } + } + + public bool ExposeCimNamespaceParameter + { + get { return _privateData.ContainsKey("CimNamespaceParameter"); } + } + + public bool ClientSideWriteVerbose + { + get { return _privateData.ContainsKey("ClientSideWriteVerbose"); } + } + + public bool ClientSideShouldProcess + { + get + { + return _privateData.ContainsKey("ClientSideShouldProcess"); + } + } + + private Uri _resourceUri; + private bool _resourceUriHasBeenCalculated; + + public Uri ResourceUri + { + get + { + if (!_resourceUriHasBeenCalculated) + { + string newResourceUriString; + Uri newResourceUri; + if (_privateData != null && + _privateData.TryGetValue("ResourceUri", out newResourceUriString) && + Uri.TryCreate(newResourceUriString, UriKind.RelativeOrAbsolute, out newResourceUri)) + { + _resourceUri = newResourceUri; + } + + _resourceUriHasBeenCalculated = true; + } + + return _resourceUri; + } + } + + public bool SkipTestConnection + { + get { return _privateData.ContainsKey("SkipTestConnection"); } + } + + private CimOperationFlags? _schemaConformanceLevel; + + public CimOperationFlags SchemaConformanceLevel + { + get + { + if (!_schemaConformanceLevel.HasValue) + { + CimOperationFlags newSchemaConformanceLevel = 0; + + string schemaConformanceFromCdxml; + if (_privateData != null && + _privateData.TryGetValue("TypeInformation", out schemaConformanceFromCdxml)) + { + if (schemaConformanceFromCdxml.Equals("Basic", StringComparison.OrdinalIgnoreCase)) + { + newSchemaConformanceLevel = CimOperationFlags.BasicTypeInformation; + } + else if (schemaConformanceFromCdxml.Equals("Full", StringComparison.OrdinalIgnoreCase)) + { + newSchemaConformanceLevel = CimOperationFlags.FullTypeInformation; + } + else if (schemaConformanceFromCdxml.Equals("None", StringComparison.OrdinalIgnoreCase)) + { + newSchemaConformanceLevel = (CimOperationFlags)0x0400; // this magic number should be changed to a named constant, once MI Client .NET API changes for schema support are completed + } + else if (schemaConformanceFromCdxml.Equals("Standard", StringComparison.OrdinalIgnoreCase)) + { + newSchemaConformanceLevel = (CimOperationFlags)0x0800; // this magic number should be changed to a named constant, once MI Client .NET API changes for schema support are completed + } + } + + _schemaConformanceLevel = newSchemaConformanceLevel; + } + + return _schemaConformanceLevel.Value; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..3bee74526fc8d6ac1c0a67023878782c1141ad42 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + internal sealed class CimCmdletInvocationContext + { + 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(); + } + + private static void WarnAboutUnsupportedActionPreferences( + Cmdlet cmdlet, + ActionPreference effectiveActionPreference, + string nameOfCommandLineParameter, + Func inquireMessageGetter, + Func stopMessageGetter) + { + string message; + switch (effectiveActionPreference) + { + case ActionPreference.Stop: + message = stopMessageGetter(); + break; + + case ActionPreference.Inquire: + message = inquireMessageGetter(); + break; + + default: + return; // we can handle everything that is not Stop or Inquire + } + + bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter); + if (actionPreferenceComesFromCommandLineParameter) + { + Exception exception = new ArgumentException(message); + ErrorRecord errorRecord = new(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null); + cmdlet.ThrowTerminatingError(errorRecord); + } + } + + public CimCmdletDefinitionContext CmdletDefinitionContext { get; } + + public InvocationInfo CmdletInvocationInfo { get; } + + public MshCommandRuntime.ShouldProcessPossibleOptimization ShouldProcessOptimization { get; } + + public ActionPreference ErrorActionPreference { get; } + + public ActionPreference WarningActionPreference { get; } + + public ActionPreference VerboseActionPreference { get; } + + public ActionPreference DebugActionPreference { get; } + + public string NamespaceOverride { get; } + + public bool IsRunningInBackground + { + get + { + return this.CmdletInvocationInfo.BoundParameters.ContainsKey("AsJob"); + } + } + + public bool ShowComputerName + { + get + { + return this.CmdletInvocationInfo.BoundParameters.ContainsKey("CimSession"); + } + } + + private readonly Lazy _defaultCimSession = new(CreateDefaultCimSession); + + private static CimSession CreateDefaultCimSession() + { + return CimSession.Create(null); + } + + public CimSession GetDefaultCimSession() + { + return _defaultCimSession.Value; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..da075286c34d1f471b90d0399ad4534815ec8839 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -0,0 +1,682 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Net; +using System.Net.Mail; +using System.Net.NetworkInformation; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.AccessControl; +using System.Security.Cryptography.X509Certificates; +using System.Xml; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +// TODO/FIXME: Move this class to src/cimSupport/other directory (to map to the namespace it lives in and functionality it implements [cmdletization independent]) + +namespace Microsoft.PowerShell.Cim +{ + internal sealed class CimSensitiveValueConverter : IDisposable + { + private sealed class SensitiveString : IDisposable + { + private GCHandle _gcHandle; + private string _string; + + public string Value { get { return _string; } } + + internal SensitiveString(int numberOfCharacters) + { + _string = new string('\0', numberOfCharacters); + + Debug.Assert( + string.IsInterned(_string) == null, + "We will overwrite string contents - we can't / shouldn't do this for interned strings."); + + /* The string is pinned (while still being filled with insignificant data) + * to prevent copying of sensitive data by garbage collection. + * This allows the sensitive data to be cleaned-up from SensitiveString.Dispose method. + */ + _gcHandle = GCHandle.Alloc(_string, GCHandleType.Pinned); + } + + private unsafe void Copy(char* source, int offset, int charsToCopy) + { + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(offset, _string.Length); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset + charsToCopy, _string.Length, nameof(charsToCopy)); + + fixed (char* target = _string) + { + for (int i = 0; i < charsToCopy; i++) + { + target[offset + i] = source[i]; + } + } + } + + internal void Copy(string source, int offset) + { + unsafe + { + fixed (char* sourcePointer = source) + { + Copy(sourcePointer, offset, source.Length); + } + } + } + + internal void Copy(SecureString source, int offset) + { + IntPtr plainTextString = Marshal.SecureStringToCoTaskMemUnicode(source); + try + { + unsafe + { + Copy((char*)plainTextString, offset, source.Length); + } + } + finally + { + Marshal.ZeroFreeCoTaskMemUnicode(plainTextString); + } + } + + ~SensitiveString() + { + Dispose(false); + } + + /// + /// Releases resources associated with this object. + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases resources associated with this object. + /// + private void Dispose(bool disposing) + { + if (_string == null) + { + return; + } + + /* this clobbers sensitive data */ + Copy(new string('\0', _string.Length), 0); + + /* this allows garbage collector to move and/or free the string */ + _gcHandle.Free(); + _string = null; + } + } + + private readonly List _trackedDisposables = new(); + + /// + /// Releases resources associated with this object. + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases resources associated with this object. + /// + private void Dispose(bool disposing) + { + lock (_trackedDisposables) + { + foreach (var d in _trackedDisposables) + { + d.Dispose(); + } + + _trackedDisposables.Clear(); + } + } + + private const string PSCredentialDelimiter = ":"; + + internal object ConvertFromDotNetToCim(object dotNetObject) + { + if (dotNetObject == null) + { + return null; + } + + PSObject psObject = PSObject.AsPSObject(dotNetObject); + Type dotNetType = psObject.BaseObject.GetType(); + if (typeof(PSCredential).IsAssignableFrom(dotNetType)) + { + var credential = (PSCredential)(psObject.BaseObject); + + string escapedUsername = credential.UserName; + escapedUsername = escapedUsername.Replace("\\", "\\\\"); // Esc backslashes + escapedUsername = escapedUsername.Replace(PSCredentialDelimiter, "\\" + PSCredentialDelimiter); + + var sensitiveString = new SensitiveString(escapedUsername.Length + PSCredentialDelimiter.Length + credential.Password.Length); + lock (_trackedDisposables) { _trackedDisposables.Add(sensitiveString); } + + sensitiveString.Copy(escapedUsername, 0); + sensitiveString.Copy(PSCredentialDelimiter, escapedUsername.Length); + sensitiveString.Copy(credential.Password, escapedUsername.Length + PSCredentialDelimiter.Length); + return sensitiveString.Value; + } + + if (typeof(SecureString).IsAssignableFrom(dotNetType)) + { + SecureString secureString = (SecureString)psObject.BaseObject; + var sensitiveString = new SensitiveString(secureString.Length); + lock (_trackedDisposables) { _trackedDisposables.Add(sensitiveString); } + + sensitiveString.Copy(secureString, 0); + return sensitiveString.Value; + } + + if (dotNetType.IsArray) + { + Type dotNetElementType = CimValueConverter.GetElementType(dotNetType); + if (dotNetElementType != null) + { + var dotNetArray = (Array)psObject.BaseObject; + Type cimElementType = 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; + } + } + + return CimValueConverter.ConvertFromDotNetToCim(dotNetObject); + } + + internal static Type GetCimType(Type dotNetType) + { + if (dotNetType == typeof(SecureString)) + { + return typeof(string); + } + + if (dotNetType == typeof(PSCredential)) + { + return typeof(string); + } + + return CimValueConverter.GetCimType(dotNetType); + } + } + + internal static class CimValueConverter + { + /// The only kind of exception this method can throw. + 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"); + + 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); + } + + /// The only kind of exception this method can throw. + internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType) + { + ArgumentNullException.ThrowIfNull(expectedDotNetType); + + if (cimObject == null) + { + return null; + } + + if (expectedDotNetType.GetTypeInfo().IsGenericType && expectedDotNetType.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + expectedDotNetType = expectedDotNetType.GetGenericArguments()[0]; + } + + if (LanguagePrimitives.IsCimIntrinsicScalarType(expectedDotNetType)) + { + return LanguagePrimitives.ConvertTo(cimObject, expectedDotNetType, CultureInfo.InvariantCulture); + } + + if (expectedDotNetType == typeof(CimInstance)) + { + return LanguagePrimitives.ConvertTo(cimObject, expectedDotNetType, CultureInfo.InvariantCulture); + } + + if (expectedDotNetType.IsArray) + { + Type dotNetElementType = GetElementType(expectedDotNetType); + if (dotNetElementType != null) + { + var cimArray = (Array)LanguagePrimitives.ConvertTo(cimObject, typeof(Array), CultureInfo.InvariantCulture); + Array dotNetArray = Array.CreateInstance(dotNetElementType, cimArray.Length); + for (int i = 0; i < dotNetArray.Length; i++) + { + object dotNetElement = ConvertFromCimToDotNet(cimArray.GetValue(i), dotNetElementType); + dotNetArray.SetValue(dotNetElement, i); + } + + return dotNetArray; + } + } + + Type convertibleCimType = GetConvertibleCimType(expectedDotNetType); + if (convertibleCimType != null) + { + object cimIntrinsicValue = LanguagePrimitives.ConvertTo(cimObject, convertibleCimType, CultureInfo.InvariantCulture); + object dotNetObject = LanguagePrimitives.ConvertTo(cimIntrinsicValue, expectedDotNetType, CultureInfo.InvariantCulture); + return dotNetObject; + } + + Func, object> exceptionSafeReturn = (Func innerAction) => + { + try + { + return innerAction(); + } + catch (Exception e) + { + throw CimValueConverter.GetInvalidCastException( + e, + "InvalidCimToDotNetCast", + cimObject, + expectedDotNetType.FullName); + } + }; + + if (typeof(ObjectSecurity).IsAssignableFrom(expectedDotNetType)) + { + var sddl = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture); + return exceptionSafeReturn(delegate + { + var objectSecurity = (ObjectSecurity)Activator.CreateInstance(expectedDotNetType); + objectSecurity.SetSecurityDescriptorSddlForm(sddl); + return objectSecurity; + }); + } + + if (typeof(X509Certificate2) == expectedDotNetType) + { + var cimIntrinsicValue = (byte[])LanguagePrimitives.ConvertTo(cimObject, typeof(byte[]), CultureInfo.InvariantCulture); + return exceptionSafeReturn(delegate + { + #pragma warning disable SYSLIB0057 + return new X509Certificate2(cimIntrinsicValue); + #pragma warning restore SYSLIB0057 + }); + } + + if (typeof(X500DistinguishedName) == expectedDotNetType) + { + var cimIntrinsicValue = (byte[])LanguagePrimitives.ConvertTo(cimObject, typeof(byte[]), CultureInfo.InvariantCulture); + return exceptionSafeReturn(delegate + { + return new X500DistinguishedName(cimIntrinsicValue); + }); + } + + if (typeof(PhysicalAddress) == expectedDotNetType) + { + var cimIntrinsicValue = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture); + return exceptionSafeReturn(delegate + { + return PhysicalAddress.Parse(cimIntrinsicValue); + }); + } + + if (typeof(IPEndPoint) == expectedDotNetType) + { + var cimIntrinsicValue = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture); + return exceptionSafeReturn(delegate + { + int indexOfLastColon = cimIntrinsicValue.LastIndexOf(':'); + int port = int.Parse(cimIntrinsicValue.AsSpan(indexOfLastColon + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); + IPAddress address = IPAddress.Parse(cimIntrinsicValue.AsSpan(0, indexOfLastColon)); + return new IPEndPoint(address, port); + }); + } + + // WildcardPattern is only supported as an "in" parameter - we do not support the reverse translation (i.e. from "a%" to "a*") + + if (typeof(XmlDocument) == expectedDotNetType) + { + var cimIntrinsicValue = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture); + return exceptionSafeReturn(delegate + { + XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( + cimIntrinsicValue, + true, /* preserve non elements: whitespace, processing instructions, comments, etc. */ + null); /* default maxCharactersInDocument */ + return doc; + }); + } + + // unrecognized type = throw invalid cast exception + throw CimValueConverter.GetInvalidCastException( + null, /* inner exception */ + "InvalidCimToDotNetCast", + cimObject, + expectedDotNetType.FullName); + } + + internal static CimType GetCimTypeEnum(Type dotNetType) + { + Dbg.Assert(dotNetType != null, "Caller should make sure that dotNetType != null"); + + if (typeof(PSReference).IsAssignableFrom(dotNetType)) + { + return CimType.Reference; + } + + if (typeof(PSReference[]).IsAssignableFrom(dotNetType)) + { + return CimType.ReferenceArray; + } + else + { + return CimConverter.GetCimType(dotNetType); + } + } + + 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; + } + + /// + /// Returns a type of CIM representation if conversion from/to CIM can be done purely with LanguagePrimitives.ConvertTo. + /// + /// + /// + private static Type GetConvertibleCimType(Type dotNetType) + { + Dbg.Assert( + !(dotNetType.GetTypeInfo().IsGenericType && dotNetType.GetGenericTypeDefinition() == typeof(Nullable<>)), + "Caller should strip out Nullable before calling CimValueConverter.GetConvertibleCimType"); + + if (dotNetType.GetTypeInfo().IsEnum) + { + return Enum.GetUnderlyingType(dotNetType); + } + + if (dotNetType == typeof(SwitchParameter)) + { + return typeof(bool); + } + + if (dotNetType == typeof(Guid) || + dotNetType == typeof(Uri) || // TODO/FIXME - CliXml does some magic around relative URIs - do we want to duplicate this? + dotNetType == typeof(Version) || + dotNetType == typeof(IPAddress) || + dotNetType == typeof(MailAddress)) + { + return typeof(string); + } + + return null; + } + + 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; + } + + internal static PSInvalidCastException GetInvalidCastException( + Exception innerException, + string errorId, + object sourceValue, + string descriptionOfTargetType) + { + Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify !string.IsNullOrEmpty(errorId)"); + Dbg.Assert(sourceValue != null, "Caller should verify sourceValue != null"); + Dbg.Assert(!string.IsNullOrEmpty(descriptionOfTargetType), "Caller should verify !string.IsNullOrEmpty(descriptionOfTargetType)"); + + throw new PSInvalidCastException( + errorId, + innerException, + ExtendedTypeSystem.InvalidCastException, + sourceValue, + PSObject.AsPSObject(sourceValue).BaseObject.GetType().FullName, + descriptionOfTargetType); + } + + [Conditional("DEBUG")] + internal static void AssertIntrinsicCimValue(object value) + { + Dbg.Assert(value != null, "Caller should verify value != null"); + Type type = value.GetType(); + AssertIntrinsicCimType(type); + Dbg.Assert(!typeof(PSReference).IsAssignableFrom(type) && typeof(PSReference[]) != type, + "PSReference cannot be used as a CIM *value* (PSReference is only ok as a type)"); + } + + [Conditional("DEBUG")] + internal static void AssertIntrinsicCimType(Type type) + { + Dbg.Assert(type != null, "Caller should verify type != null"); + Dbg.Assert( + LanguagePrimitives.IsCimIntrinsicScalarType(type) || + (type.IsArray && LanguagePrimitives.IsCimIntrinsicScalarType(type.GetElementType())) || + typeof(CimInstance).IsAssignableFrom(type) || + typeof(PSReference).IsAssignableFrom(type) || + type == typeof(CimInstance[]) || + type == typeof(PSReference[]), + "Caller should verify that type is an intrinsic CIM type"); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..27d48ccab9a587b2f6290258c7c32d5becbcd60f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + internal sealed class CimJobContext + { + internal CimJobContext( + CimCmdletInvocationContext cmdletInvocationContext, + CimSession session, + object targetObject) + { + this.CmdletInvocationContext = cmdletInvocationContext; + + this.Session = session; + this.TargetObject = targetObject ?? this.ClassName; + } + + public CimCmdletInvocationContext CmdletInvocationContext { get; } + + public CimSession Session { get; } + + public object TargetObject { get; } + + public string ClassName + { + get + { + return GetCimClassName(this.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassName); + } + } + + public string ClassNameOrNullIfResourceUriIsUsed + { + get + { + if (this.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri != null) + { + return null; + } + + return this.ClassName; + } + } + + public string Namespace + { + get + { + if (!string.IsNullOrEmpty(this.CmdletInvocationContext.NamespaceOverride)) + { + return this.CmdletInvocationContext.NamespaceOverride; + } + + return GetCimNamespace(this.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassName); + } + } + + private static void ExtractCimNamespaceAndClassName(string cmdletizationClassName, out string cimNamespace, out string cimClassName) + { + int indexOfLastBackslash = cmdletizationClassName.LastIndexOf('\\'); + int indexOfLastForwardSlash = cmdletizationClassName.LastIndexOf('/'); + int indexOfLastSeparator = Math.Max(indexOfLastBackslash, indexOfLastForwardSlash); + if (indexOfLastSeparator != (-1)) + { + cimNamespace = cmdletizationClassName.Substring(0, indexOfLastSeparator); + cimClassName = cmdletizationClassName.Substring(indexOfLastSeparator + 1, cmdletizationClassName.Length - indexOfLastSeparator - 1); + } + else + { + cimNamespace = null; + cimClassName = cmdletizationClassName; + } + } + + private static string GetCimClassName(string cmdletizationClassName) + { + string throwAway; + string cimClassName; + ExtractCimNamespaceAndClassName(cmdletizationClassName, out throwAway, out cimClassName); + return cimClassName; + } + + private static string GetCimNamespace(string cmdletizationClassName) + { + string cimNamespace; + string throwAway; + ExtractCimNamespaceAndClassName(cmdletizationClassName, out cimNamespace, out throwAway); + return cimNamespace; + } + + internal string PrependComputerNameToMessage(string message) + { + string computerName = this.Session.ComputerName; + if (computerName == null) + { + return message; + } + + return string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_ComputerNameConcatenationTemplate, + computerName, + message); + } + + public InvocationInfo CmdletInvocationInfo + { + get { return this.CmdletInvocationContext.CmdletInvocationInfo; } + } + + public string CmdletizationClassName + { + get { return this.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassName; } + } + + public Version CmdletizationModuleVersion + { + get { return this.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationModuleVersion; } + } + + public ActionPreference ErrorActionPreference + { + get { return this.CmdletInvocationContext.ErrorActionPreference; } + } + + public ActionPreference WarningActionPreference + { + get { return this.CmdletInvocationContext.WarningActionPreference; } + } + + public ActionPreference VerboseActionPreference + { + get { return this.CmdletInvocationContext.VerboseActionPreference; } + } + + public ActionPreference DebugActionPreference + { + get { return this.CmdletInvocationContext.DebugActionPreference; } + } + + public bool IsRunningInBackground + { + get { return this.CmdletInvocationContext.IsRunningInBackground; } + } + + public MshCommandRuntime.ShouldProcessPossibleOptimization ShouldProcessOptimization + { + get { return this.CmdletInvocationContext.ShouldProcessOptimization; } + } + + public bool ShowComputerName + { + get { return this.CmdletInvocationContext.ShowComputerName; } + } + + public bool SupportsShouldProcess + { + get { return this.CmdletInvocationContext.CmdletDefinitionContext.SupportsShouldProcess; } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..34c708b5f4cc5bfc222ab6d3860140bcff390413 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Microsoft.PowerShell.Cim; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + internal sealed class CimCustomOptionsDictionary + { + private readonly IDictionary _dict; + private readonly object _dictModificationLock = new(); + + private CimCustomOptionsDictionary(IEnumerable> wrappedDictionary) + { + // no need to lock _dictModificationLock inside the constructor + _dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var kvp in wrappedDictionary) + { + _dict[kvp.Key] = kvp.Value; + } + } + + private IEnumerable> GetSnapshot() + { + lock (_dictModificationLock) + { + return _dict.ToList(); + } + } + + internal static CimCustomOptionsDictionary Create(IEnumerable> wrappedDictionary) + { + return new CimCustomOptionsDictionary(wrappedDictionary); + } + + private static readonly ConditionalWeakTable s_cimInstanceToCustomOptions = new(); + + internal static void AssociateCimInstanceWithCustomOptions(CimInstance cimInstance, CimCustomOptionsDictionary newCustomOptions) + { + if (newCustomOptions == null) + { + return; + } + + lock (newCustomOptions._dictModificationLock) + { + if (newCustomOptions._dict.Count == 0) + { + return; + } + } + + bool foundAssociatedOptions = true; + CimCustomOptionsDictionary oldCustomOptions = s_cimInstanceToCustomOptions.GetValue( + cimInstance, + delegate + { + foundAssociatedOptions = false; + return newCustomOptions; + }); + + if (foundAssociatedOptions) + { + lock (oldCustomOptions._dictModificationLock) + { + foreach (KeyValuePair newCustomOption in newCustomOptions.GetSnapshot()) + { + oldCustomOptions._dict[newCustomOption.Key] = newCustomOption.Value; + } + } + } + } + + internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictionary optionsFromCommandLine, CimInstance instanceRelatedToThisOperation) + { + CimCustomOptionsDictionary instanceRelatedOptions; + if (s_cimInstanceToCustomOptions.TryGetValue(instanceRelatedToThisOperation, out instanceRelatedOptions) && instanceRelatedOptions != null) + { + IEnumerable> instanceRelatedOptionsSnapshot = instanceRelatedOptions.GetSnapshot(); + IEnumerable> optionsFromCommandLineSnapshot = optionsFromCommandLine.GetSnapshot(); + var mergedOptions = instanceRelatedOptionsSnapshot.Concat(optionsFromCommandLineSnapshot); // note - order matters here + return new CimCustomOptionsDictionary(mergedOptions); + } + else + { + return optionsFromCommandLine; + } + } + + internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictionary optionsFromCommandLine, IEnumerable instancesRelatedToThisOperation) + { + CimCustomOptionsDictionary result = optionsFromCommandLine; + if (instancesRelatedToThisOperation != null) + { + foreach (CimInstance instanceRelatedToThisOperation in instancesRelatedToThisOperation) + { + result = MergeOptions(result, instanceRelatedToThisOperation); + } + } + + return result; + } + + internal void Apply(CimOperationOptions cimOperationOptions, CimSensitiveValueConverter cimSensitiveValueConverter) + { + CimOperationOptionsHelper.SetCustomOptions(cimOperationOptions, this.GetSnapshot(), cimSensitiveValueConverter); + } + } + + /// + /// CimQuery supports building of queries against CIM object model. + /// + internal static class CimOperationOptionsHelper + { + internal static void SetCustomOptions( + CimOperationOptions operationOptions, + IEnumerable> customOptions, + CimSensitiveValueConverter cimSensitiveValueConverter) + { + if (customOptions != null) + { + foreach (KeyValuePair queryOption in customOptions) + { + SetCustomOption(operationOptions, queryOption.Key, queryOption.Value, cimSensitiveValueConverter); + } + } + } + + internal static void SetCustomOption( + CimOperationOptions operationOptions, + string optionName, + object optionValue, + CimSensitiveValueConverter cimSensitiveValueConverter) + { + Dbg.Assert(!string.IsNullOrWhiteSpace(optionName), "Caller should verify optionName != null"); + + if (optionValue == null) + { + return; + } + + object cimValue = cimSensitiveValueConverter.ConvertFromDotNetToCim(optionValue); + CimType cimType = CimConverter.GetCimType(CimSensitiveValueConverter.GetCimType(optionValue.GetType())); + + operationOptions.SetCustomOption(optionName, cimValue, cimType, mustComply: false); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs new file mode 100644 index 0000000000000000000000000000000000000000..f08c2ab3c11e6482d6f93d9c7196fc551a071516 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -0,0 +1,371 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Management.Automation; +using System.Text; + +using Microsoft.Management.Infrastructure; +using Microsoft.PowerShell.Cim; +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// CimQuery supports building of queries against CIM object model. + /// + internal sealed class CimQuery : QueryBuilder, ISessionBoundQueryBuilder + { + private readonly StringBuilder _wqlCondition; + + private CimInstance _associatedObject; + private string _associationName; + private string _resultRole; + private string _sourceRole; + + internal readonly Dictionary queryOptions = new(StringComparer.OrdinalIgnoreCase); + + internal ClientSideQuery ClientSideQuery { get; } + + internal CimQuery() + { + _wqlCondition = new StringBuilder(); + this.ClientSideQuery = new ClientSideQuery(); + } + + #region WQL processing + + private void AddWqlCondition(string condition) + { + _wqlCondition.Append(_wqlCondition.Length != 0 ? " AND " : " WHERE "); + + _wqlCondition.Append('('); + _wqlCondition.Append(condition); + _wqlCondition.Append(')'); + } + + private static string ObjectToWqlLiteral(object o) + { + if (LanguagePrimitives.IsNull(o)) + { + return "null"; // based on an example at https://msdn.microsoft.com/library/aa394054(VS.85).aspx + } + + o = CimValueConverter.ConvertFromDotNetToCim(o); + PSObject pso = PSObject.AsPSObject(o); + Type type = pso.BaseObject.GetType(); + TypeCode typeCode = LanguagePrimitives.GetTypeCode(type); + + if (typeCode == TypeCode.String) + { + string s = o.ToString(); + s = s.Replace("\\", "\\\\"); + s = s.Replace("'", "\\'"); + return "'" + s + "'"; + } + + if (typeCode == TypeCode.Char) + { + return ObjectToWqlLiteral(LanguagePrimitives.ConvertTo(o, typeof(string), CultureInfo.InvariantCulture)); + } + + if (typeCode == TypeCode.DateTime) + { + var dateTime = (DateTime)LanguagePrimitives.ConvertTo(o, typeof(DateTime), CultureInfo.InvariantCulture); + string result = ClrFacade.ToDmtfDateTime(dateTime); + return "'" + result + "'"; + } + + if (type == typeof(TimeSpan)) + { + // WMIv1 does not support using interval literals in a WQL query + return null; + } + + if (LanguagePrimitives.IsNumeric(typeCode)) + { + return (string)LanguagePrimitives.ConvertTo(o, typeof(string), CultureInfo.InvariantCulture); + } + + if (LanguagePrimitives.IsBooleanType(type)) + { + if ((bool)LanguagePrimitives.ConvertTo(o, typeof(bool), CultureInfo.InvariantCulture)) + { + return "TRUE"; // based on https://msdn.microsoft.com/library/aa394054(VS.85).aspx + } + + return "FALSE"; // based on https://msdn.microsoft.com/library/aa394054(VS.85).aspx + } + + throw CimValueConverter.GetInvalidCastException( + null, /* inner exception */ + "InvalidCimQueryCast", + o, + CmdletizationResources.CimConversion_WqlQuery); + } + + private static string WildcardToWqlLikeOperand(WildcardPattern wildcardPattern, out bool needsClientSideFiltering) + { + string nakedOperand = WildcardPatternToCimQueryParser.Parse(wildcardPattern, out needsClientSideFiltering); + + return ObjectToWqlLiteral(nakedOperand); + } + + #endregion + + 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; + } + + private static string GetMatchConditionForLikeOperator(string propertyName, object propertyValue) + { + var expectedPropertyValueAsString = (string)LanguagePrimitives.ConvertTo(propertyValue, typeof(string), CultureInfo.InvariantCulture); + var expectedPropertyValueAsPowerShellWildcard = WildcardPattern.Get(expectedPropertyValueAsString, WildcardOptions.IgnoreCase); + + bool needsClientSideFiltering; // not used because for simplicity all results go through post-filtering + var expectedPropertyValueAsWqlWildcard = CimQuery.WildcardToWqlLikeOperand(expectedPropertyValueAsPowerShellWildcard, out needsClientSideFiltering); + + string condition = string.Format( + CultureInfo.InvariantCulture, + "({0} LIKE {1})", + propertyName, + expectedPropertyValueAsWqlWildcard); + return condition; + } + + private static string GetMatchCondition(string propertyName, IEnumerable propertyValues, bool wildcardsEnabled) + { + List individualConditions = propertyValues + .Cast() + .Select(propertyValue => wildcardsEnabled + ? GetMatchConditionForLikeOperator(propertyName, propertyValue) + : GetMatchConditionForEqualityOperator(propertyName, propertyValue)) + .Where(static individualCondition => !string.IsNullOrWhiteSpace(individualCondition)) + .ToList(); + if (individualConditions.Count == 0) + { + return null; + } + + string result = string.Join(" OR ", individualConditions); + return result; + } + + #region Public inputs from cmdletization + + /// + /// Modifies the query, so that it only returns objects with a given property value. + /// + /// Property name to query on. + /// Property values to accept in the query. + /// + /// if should be treated as a containing a wildcard pattern; + /// otherwise. + /// + /// + /// Describes how to handle filters that didn't match any objects + /// + public override void FilterByProperty(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + { + this.ClientSideQuery.FilterByProperty(propertyName, allowedPropertyValues, wildcardsEnabled, behaviorOnNoMatch); + + string matchCondition = CimQuery.GetMatchCondition(propertyName, allowedPropertyValues, wildcardsEnabled); + if (!string.IsNullOrWhiteSpace(matchCondition)) + { + this.AddWqlCondition(matchCondition); + } + } + + /// + /// Modifies the query, so that it does not return objects with a given property value. + /// + /// Property name to query on. + /// Property values to reject in the query. + /// + /// if should be treated as a containing a wildcard pattern; + /// otherwise. + /// + /// + /// Describes how to handle filters that didn't match any objects + /// + public override void ExcludeByProperty(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + { + this.ClientSideQuery.ExcludeByProperty(propertyName, excludedPropertyValues, wildcardsEnabled, behaviorOnNoMatch); + + string positiveWqlCondition = CimQuery.GetMatchCondition(propertyName, excludedPropertyValues, wildcardsEnabled); + if (!string.IsNullOrWhiteSpace(positiveWqlCondition)) + { + string condition = string.Format( + CultureInfo.InvariantCulture, + "NOT ({0})", + positiveWqlCondition); + this.AddWqlCondition(condition); + } + } + + /// + /// Modifies the query, so that it returns only objects that have a property value greater than or equal to a threshold. + /// + /// Property name to query on. + /// Minimum property value. + /// + /// Describes how to handle filters that didn't match any objects + /// + public override void FilterByMinPropertyValue(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + this.ClientSideQuery.FilterByMinPropertyValue(propertyName, minPropertyValue, behaviorOnNoMatch); + + string wqlLiteral = CimQuery.ObjectToWqlLiteral(minPropertyValue); + if (!string.IsNullOrWhiteSpace(wqlLiteral)) + { + string condition = string.Format( + CultureInfo.InvariantCulture, + "{0} >= {1}", + propertyName, + wqlLiteral); + this.AddWqlCondition(condition); + } + } + + /// + /// Modifies the query, so that it returns only objects that have a property value less than or equal to a threshold. + /// + /// Property name to query on. + /// Maximum property value. + /// + /// Describes how to handle filters that didn't match any objects + /// + public override void FilterByMaxPropertyValue(string propertyName, object maxPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + this.ClientSideQuery.FilterByMaxPropertyValue(propertyName, maxPropertyValue, behaviorOnNoMatch); + + string wqlLiteral = CimQuery.ObjectToWqlLiteral(maxPropertyValue); + if (!string.IsNullOrWhiteSpace(wqlLiteral)) + { + string condition = string.Format( + CultureInfo.InvariantCulture, + "{0} <= {1}", + propertyName, + CimQuery.ObjectToWqlLiteral(maxPropertyValue)); + this.AddWqlCondition(condition); + } + } + + /// + /// Modifies the query, so that it returns only objects associated with + /// + /// Object that query results have to be associated with. + /// Name of the association. + /// Name of the role that has in the association. + /// Name of the role that query results have in the association. + /// + /// Describes how to handle filters that didn't match any objects + /// + public override void FilterByAssociatedInstance(object associatedInstance, string associationName, string sourceRole, string resultRole, BehaviorOnNoMatch behaviorOnNoMatch) + { + this.ClientSideQuery.FilterByAssociatedInstance(associatedInstance, associationName, sourceRole, resultRole, behaviorOnNoMatch); + _associatedObject = associatedInstance as CimInstance; + _associationName = associationName; + _resultRole = resultRole; + _sourceRole = sourceRole; + } + + /// + /// Sets a query option. + /// + /// + /// + public override void AddQueryOption(string optionName, object optionValue) + { + ArgumentException.ThrowIfNullOrEmpty(optionName); + ArgumentNullException.ThrowIfNull(optionValue); + + this.queryOptions[optionName] = optionValue; + } + + #endregion Cmdletization inputs + + #region Outputs for doing the query + + internal StartableJob GetQueryJob(CimJobContext jobContext) + { + if (_associationName == null) + { + return new QueryInstancesJob(jobContext, this, _wqlCondition.ToString()); + } + else + { + return new EnumerateAssociatedInstancesJob(jobContext, this, _associatedObject, _associationName, _resultRole, _sourceRole); + } + } + + internal bool IsMatchingResult(CimInstance result) + { + Dbg.Assert(result != null, "Caller should verify result != null"); + return this.ClientSideQuery.IsResultMatchingClientSideQuery(result); + } + + internal IEnumerable GenerateNotFoundErrors() + { + return this.ClientSideQuery.GenerateNotFoundErrors(); + } + + #endregion + + CimSession ISessionBoundQueryBuilder.GetTargetSession() + { + if (_associatedObject != null) + { + return CimCmdletAdapter.GetSessionOfOriginFromCimInstance(_associatedObject); + } + + return null; + } + + /// + /// Returns a string that represents the current CIM query. + /// + /// A string that represents the current CIM query. + public override string ToString() + { + return _wqlCondition.ToString(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs new file mode 100644 index 0000000000000000000000000000000000000000..472046b192f9819e73d1c969b59767107556d3cc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -0,0 +1,410 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Runtime.CompilerServices; +using System.Threading; + +using Microsoft.Management.Infrastructure; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// CIM-specific ObjectModelWrapper. + /// + public sealed class CimCmdletAdapter : + SessionBasedCmdletAdapter, + IDynamicParameters + { + #region Special method and parameter names + + internal const string CreateInstance_MethodName = "cim:CreateInstance"; + internal const string ModifyInstance_MethodName = "cim:ModifyInstance"; + internal const string DeleteInstance_MethodName = "cim:DeleteInstance"; + + #endregion + + #region Changing Session parameter to CimSession + + /// + /// CimSession to operate on. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [Alias("Session")] + public CimSession[] CimSession + { + get + { + return base.Session; + } + + set + { + base.Session = value; + } + } + + /// + /// Maximum number of remote connections that can remain active at any given time. + /// + [Parameter] + public override int ThrottleLimit + { + get + { + if (_throttleLimitIsSetExplicitly) + { + return base.ThrottleLimit; + } + + return this.CmdletDefinitionContext.DefaultThrottleLimit; + } + + set + { + base.ThrottleLimit = value; + _throttleLimitIsSetExplicitly = true; + } + } + + private bool _throttleLimitIsSetExplicitly; + + #endregion + + #region ObjectModelWrapper overrides + + /// + /// Creates a query builder for CIM OM. + /// + /// Query builder for CIM OM. + public override QueryBuilder GetQueryBuilder() + { + return new CimQuery(); + } + + internal CimCmdletInvocationContext CmdletInvocationContext + { + get + { + return _cmdletInvocationContext ??= new CimCmdletInvocationContext( + this.CmdletDefinitionContext, + this.Cmdlet, + this.GetDynamicNamespace()); + } + } + + private CimCmdletInvocationContext _cmdletInvocationContext; + + internal CimCmdletDefinitionContext CmdletDefinitionContext + { + get + { + _cmdletDefinitionContext ??= new CimCmdletDefinitionContext( + this.ClassName, + this.ClassVersion, + this.ModuleVersion, + this.Cmdlet.CommandInfo.CommandMetadata.SupportsShouldProcess, + this.PrivateData); + + return _cmdletDefinitionContext; + } + } + + private CimCmdletDefinitionContext _cmdletDefinitionContext; + + internal InvocationInfo CmdletInvocationInfo + { + get { return this.CmdletInvocationContext.CmdletInvocationInfo; } + } + + #endregion ObjectModelWrapper overrides + + #region SessionBasedCmdletAdapter overrides + + private static long s_jobNumber; + + /// + /// Returns a new job name to use for the parent job that handles throttling of the child jobs that actually perform querying and method invocation. + /// + /// Job name. + protected override string GenerateParentJobName() + { + return "CimJob" + Interlocked.Increment(ref CimCmdletAdapter.s_jobNumber).ToString(CultureInfo.InvariantCulture); + } + + /// + /// Returns default sessions to use when the user doesn't specify the -Session cmdlet parameter. + /// + /// Default sessions to use when the user doesn't specify the -Session cmdlet parameter. + protected override CimSession DefaultSession + { + get + { + return this.CmdletInvocationContext.GetDefaultCimSession(); + } + } + + private CimJobContext CreateJobContext(CimSession session, object targetObject) + { + return new CimJobContext( + this.CmdletInvocationContext, + session, + targetObject); + } + + /// + /// Creates a object that performs a query against the wrapped object model. + /// + /// Remote session to query. + /// Query parameters. + /// object that performs a query against the wrapped object model. + internal override StartableJob CreateQueryJob(CimSession session, QueryBuilder baseQuery) + { + if (baseQuery is not CimQuery query) + { + throw new ArgumentNullException(nameof(baseQuery)); + } + + TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: false); + if (tracker.IsSessionTerminated(session)) + { + return null; + } + + if (!IsSupportedSession(session, tracker)) + { + return null; + } + + CimJobContext jobContext = this.CreateJobContext(session, targetObject: null); + StartableJob queryJob = query.GetQueryJob(jobContext); + + return queryJob; + } + + /// + /// Creates a object that invokes an instance method in the wrapped object model. + /// + /// Remote session to invoke the method in. + /// The object on which to invoke the method. + /// Method invocation details. + /// if successful method invocations should emit downstream the being operated on. + /// + internal override StartableJob CreateInstanceMethodInvocationJob(CimSession session, CimInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) + { + TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: false); + if (tracker.IsSessionTerminated(session)) + { + return null; + } + + if (!IsSupportedSession(session, tracker)) + { + return null; + } + + CimJobContext jobContext = this.CreateJobContext(session, objectInstance); + + Dbg.Assert(objectInstance != null, "Caller should verify objectInstance != null"); + + StartableJob result; + if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.DeleteInstance_MethodName, StringComparison.OrdinalIgnoreCase)) + { + result = new DeleteInstanceJob( + jobContext, + passThru, + objectInstance, + methodInvocationInfo); + } + else if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.ModifyInstance_MethodName, StringComparison.OrdinalIgnoreCase)) + { + result = new ModifyInstanceJob( + jobContext, + passThru, + objectInstance, + methodInvocationInfo); + } + else + { + result = new InstanceMethodInvocationJob( + jobContext, + passThru, + objectInstance, + methodInvocationInfo); + } + + return result; + } + + private bool IsSupportedSession(CimSession cimSession, TerminatingErrorTracker terminatingErrorTracker) + { + bool confirmSwitchSpecified = this.CmdletInvocationInfo.BoundParameters.ContainsKey("Confirm"); + bool whatIfSwitchSpecified = this.CmdletInvocationInfo.BoundParameters.ContainsKey("WhatIf"); + if (confirmSwitchSpecified || whatIfSwitchSpecified) + { + if (cimSession.ComputerName != null && (!cimSession.ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))) + { + PSPropertyInfo protocolProperty = PSObject.AsPSObject(cimSession).Properties["Protocol"]; + if ((protocolProperty != null) && + (protocolProperty.Value != null) && + (protocolProperty.Value.ToString().Equals("DCOM", StringComparison.OrdinalIgnoreCase))) + { + bool sessionWasAlreadyTerminated; + terminatingErrorTracker.MarkSessionAsTerminated(cimSession, out sessionWasAlreadyTerminated); + if (!sessionWasAlreadyTerminated) + { + string nameOfUnsupportedSwitch; + if (confirmSwitchSpecified) + { + nameOfUnsupportedSwitch = "-Confirm"; + } + else + { + Dbg.Assert(whatIfSwitchSpecified, "Confirm and WhatIf are the only detected settings"); + nameOfUnsupportedSwitch = "-WhatIf"; + } + + string errorMessage = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimCmdletAdapter_RemoteDcomDoesntSupportExtendedSemantics, + cimSession.ComputerName, + nameOfUnsupportedSwitch); + Exception exception = new NotSupportedException(errorMessage); + ErrorRecord errorRecord = new( + exception, + "NoExtendedSemanticsSupportInRemoteDcomProtocol", + ErrorCategory.NotImplemented, + cimSession); + this.Cmdlet.WriteError(errorRecord); + } + } + } + } + + return true; + } + + /// + /// Creates a object that invokes a static method + /// (of the class named by ) + /// in the wrapped object model. + /// + /// Remote session to invoke the method in. + /// Method invocation details. + internal override StartableJob CreateStaticMethodInvocationJob(CimSession session, MethodInvocationInfo methodInvocationInfo) + { + TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: true); + if (tracker.IsSessionTerminated(session)) + { + return null; + } + + if (!IsSupportedSession(session, tracker)) + { + return null; + } + + CimJobContext jobContext = this.CreateJobContext(session, targetObject: null); + + StartableJob result; + if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.CreateInstance_MethodName, StringComparison.OrdinalIgnoreCase)) + { + result = new CreateInstanceJob( + jobContext, + methodInvocationInfo); + } + else + { + result = new StaticMethodInvocationJob( + jobContext, + methodInvocationInfo); + } + + return result; + } + + #endregion SessionBasedCmdletAdapter overrides + + #region Session affinity management + + private static readonly ConditionalWeakTable s_cimInstanceToSessionOfOrigin = new(); + + internal static void AssociateSessionOfOriginWithInstance(CimInstance cimInstance, CimSession sessionOfOrigin) + { + // GetValue adds value to the table, if the key is not present in the table + s_cimInstanceToSessionOfOrigin.GetValue(cimInstance, _ => sessionOfOrigin); + } + + internal static CimSession GetSessionOfOriginFromCimInstance(CimInstance instance) + { + CimSession result = null; + if (instance != null) + { + s_cimInstanceToSessionOfOrigin.TryGetValue(instance, out result); + } + + return result; + } + + internal override CimSession GetSessionOfOriginFromInstance(CimInstance instance) + { + return GetSessionOfOriginFromCimInstance(instance); + } + + #endregion + + #region Handling of dynamic parameters + + private RuntimeDefinedParameterDictionary _dynamicParameters; + + private const string CimNamespaceParameter = "CimNamespace"; + + private string GetDynamicNamespace() + { + if (_dynamicParameters == null) + { + return null; + } + + RuntimeDefinedParameter runtimeParameter; + if (!_dynamicParameters.TryGetValue(CimNamespaceParameter, out runtimeParameter)) + { + return null; + } + + return runtimeParameter.Value as string; + } + + object IDynamicParameters.GetDynamicParameters() + { + if (_dynamicParameters == null) + { + _dynamicParameters = new RuntimeDefinedParameterDictionary(); + + if (this.CmdletDefinitionContext.ExposeCimNamespaceParameter) + { + Collection namespaceAttributes = new(); + namespaceAttributes.Add(new ValidateNotNullOrEmptyAttribute()); + namespaceAttributes.Add(new ParameterAttribute()); + RuntimeDefinedParameter namespaceRuntimeParameter = new( + CimNamespaceParameter, + typeof(string), + namespaceAttributes); + _dynamicParameters.Add(CimNamespaceParameter, namespaceRuntimeParameter); + } + } + + return _dynamicParameters; + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs new file mode 100644 index 0000000000000000000000000000000000000000..c1a8552db8c1ff3b0e8be49fd7fdb4b182021b30 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -0,0 +1,704 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Management.Automation; + +using Microsoft.Management.Infrastructure; +using Microsoft.PowerShell.Cim; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Cmdletization.Cim +{ + /// + /// Client-side filtering for + /// 1) filtering that cannot be translated into a server-side query (i.e. when CimQuery.WildcardToWqlLikeOperand reports that it cannot translate into WQL) + /// 2) detecting if all expected results have been received and giving friendly user errors otherwise (i.e. could not find process with name='foo'; details in Windows 8 Bugs: #60926) + /// + internal sealed class ClientSideQuery : QueryBuilder + { + internal sealed class NotFoundError + { + public NotFoundError() + { + this.ErrorMessageGenerator = GetErrorMessageForNotFound; + } + + public NotFoundError(string propertyName, object propertyValue, bool wildcardsEnabled) + { + this.PropertyName = propertyName; + this.PropertyValue = propertyValue; + + if (wildcardsEnabled) + { + if ((propertyValue is string propertyValueAsString) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) + { + this.ErrorMessageGenerator = + (queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className); + } + else + { + this.ErrorMessageGenerator = + (queryDescription, className) => GetErrorMessageForNotFound_ForEquality(this.PropertyName, this.PropertyValue, className); + } + } + else + { + this.ErrorMessageGenerator = + (queryDescription, className) => GetErrorMessageForNotFound_ForEquality(this.PropertyName, this.PropertyValue, className); + } + } + + public string PropertyName { get; } + + public object PropertyValue { get; } + + public Func ErrorMessageGenerator { get; } + + private static string GetErrorMessageForNotFound(string queryDescription, string className) + { + string message = string.Format( + CultureInfo.InvariantCulture, // queryDescription should already be in the right format - can use invariant culture here + CmdletizationResources.CimJob_NotFound_ComplexCase, + queryDescription, + className); + return message; + } + + private static string GetErrorMessageForNotFound_ForEquality(string propertyName, object propertyValue, string className) + { + string message = string.Format( + CultureInfo.InvariantCulture, // queryDescription should already be in the right format - can use invariant culture here + CmdletizationResources.CimJob_NotFound_SimpleGranularCase_Equality, + propertyName, + propertyValue, + className); + return message; + } + + private static string GetErrorMessageForNotFound_ForWildcard(string propertyName, object propertyValue, string className) + { + string message = string.Format( + CultureInfo.InvariantCulture, // queryDescription should already be in the right format - can use invariant culture here + CmdletizationResources.CimJob_NotFound_SimpleGranularCase_Wildcard, + propertyName, + propertyValue, + className); + return message; + } + } + + private abstract class CimInstanceFilterBase + { + protected abstract bool IsMatchCore(CimInstance cimInstance); + + protected BehaviorOnNoMatch BehaviorOnNoMatch { get; set; } + + private bool HadMatches { get; set; } + + public bool IsMatch(CimInstance cimInstance) + { + bool isMatch = this.IsMatchCore(cimInstance); + this.HadMatches = this.HadMatches || isMatch; + return isMatch; + } + + public virtual bool ShouldReportErrorOnNoMatches_IfMultipleFilters() + { + switch (this.BehaviorOnNoMatch) + { + case BehaviorOnNoMatch.ReportErrors: + return true; + + case BehaviorOnNoMatch.SilentlyContinue: + return false; + + case BehaviorOnNoMatch.Default: + default: + Dbg.Assert(false, "BehaviorOnNoMatch.Default should be handled by derived classes"); + return false; + } + } + + public virtual IEnumerable GetNotFoundErrors_IfThisIsTheOnlyFilter() + { + switch (this.BehaviorOnNoMatch) + { + case BehaviorOnNoMatch.ReportErrors: + if (this.HadMatches) + { + return Enumerable.Empty(); + } + else + { + return new[] { new NotFoundError() }; + } + + case BehaviorOnNoMatch.SilentlyContinue: + return Enumerable.Empty(); + + case BehaviorOnNoMatch.Default: + default: + Dbg.Assert(false, "BehaviorOnNoMatch.Default should be handled by derived classes"); + return Enumerable.Empty(); + } + } + } + + private abstract class CimInstancePropertyBasedFilter : CimInstanceFilterBase + { + private readonly List _propertyValueFilters = new(); + + protected IEnumerable PropertyValueFilters { get { return _propertyValueFilters; } } + + protected void AddPropertyValueFilter(PropertyValueFilter propertyValueFilter) + { + _propertyValueFilters.Add(propertyValueFilter); + } + + protected override bool IsMatchCore(CimInstance cimInstance) + { + bool isMatch = false; + foreach (PropertyValueFilter propertyValueFilter in this.PropertyValueFilters) + { + if (propertyValueFilter.IsMatch(cimInstance)) + { + isMatch = true; + if (this.BehaviorOnNoMatch == BehaviorOnNoMatch.SilentlyContinue) + { + break; + } + } + } + + return isMatch; + } + } + + private sealed class CimInstanceRegularFilter : CimInstancePropertyBasedFilter + { + public CimInstanceRegularFilter(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + { + var valueBehaviors = new HashSet(); + + foreach (object allowedPropertyValue in allowedPropertyValues) + { + PropertyValueFilter filter = + new PropertyValueRegularFilter( + propertyName, + allowedPropertyValue, + wildcardsEnabled, + behaviorOnNoMatch); + this.AddPropertyValueFilter(filter); + + valueBehaviors.Add(filter.BehaviorOnNoMatch); + } + + if (valueBehaviors.Count == 1) + { + this.BehaviorOnNoMatch = valueBehaviors.First(); + } + else + { + this.BehaviorOnNoMatch = behaviorOnNoMatch; + } + } + + public override bool ShouldReportErrorOnNoMatches_IfMultipleFilters() + { + switch (this.BehaviorOnNoMatch) + { + case BehaviorOnNoMatch.ReportErrors: + return true; + + case BehaviorOnNoMatch.SilentlyContinue: + return false; + + case BehaviorOnNoMatch.Default: + default: + return this.PropertyValueFilters + .Any(static f => !f.HadMatch && f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors); + } + } + + public override IEnumerable GetNotFoundErrors_IfThisIsTheOnlyFilter() + { + foreach (PropertyValueFilter propertyValueFilter in this.PropertyValueFilters) + { + if (propertyValueFilter.BehaviorOnNoMatch != BehaviorOnNoMatch.ReportErrors) + { + continue; + } + + if (propertyValueFilter.HadMatch) + { + continue; + } + + var propertyValueRegularFilter = (PropertyValueRegularFilter)propertyValueFilter; + yield return propertyValueRegularFilter.GetGranularNotFoundError(); + } + } + } + + private sealed class CimInstanceExcludeFilter : CimInstancePropertyBasedFilter + { + public CimInstanceExcludeFilter(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + { + if (behaviorOnNoMatch == BehaviorOnNoMatch.Default) + { + this.BehaviorOnNoMatch = BehaviorOnNoMatch.SilentlyContinue; + } + else + { + this.BehaviorOnNoMatch = behaviorOnNoMatch; + } + + foreach (object excludedPropertyValue in excludedPropertyValues) + { + this.AddPropertyValueFilter( + new PropertyValueExcludeFilter( + propertyName, + excludedPropertyValue, + wildcardsEnabled, + behaviorOnNoMatch)); + } + } + } + + private sealed class CimInstanceMinFilter : CimInstancePropertyBasedFilter + { + public CimInstanceMinFilter(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + if (behaviorOnNoMatch == BehaviorOnNoMatch.Default) + { + this.BehaviorOnNoMatch = BehaviorOnNoMatch.SilentlyContinue; + } + else + { + this.BehaviorOnNoMatch = behaviorOnNoMatch; + } + + this.AddPropertyValueFilter( + new PropertyValueMinFilter( + propertyName, + minPropertyValue, + behaviorOnNoMatch)); + } + } + + private sealed class CimInstanceMaxFilter : CimInstancePropertyBasedFilter + { + public CimInstanceMaxFilter(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + if (behaviorOnNoMatch == BehaviorOnNoMatch.Default) + { + this.BehaviorOnNoMatch = BehaviorOnNoMatch.SilentlyContinue; + } + else + { + this.BehaviorOnNoMatch = behaviorOnNoMatch; + } + + this.AddPropertyValueFilter( + new PropertyValueMaxFilter( + propertyName, + minPropertyValue, + behaviorOnNoMatch)); + } + } + + private sealed class CimInstanceAssociationFilter : CimInstanceFilterBase + { + public CimInstanceAssociationFilter(BehaviorOnNoMatch behaviorOnNoMatch) + { + if (behaviorOnNoMatch == BehaviorOnNoMatch.Default) + { + this.BehaviorOnNoMatch = BehaviorOnNoMatch.ReportErrors; + } + else + { + this.BehaviorOnNoMatch = behaviorOnNoMatch; + } + } + + protected override bool IsMatchCore(CimInstance cimInstance) + { + return true; // the fact that this method is getting called means that CIM found associated instances (i.e. by definition the argument *is* matching) + } + } + + internal abstract class PropertyValueFilter + { + protected PropertyValueFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + PropertyName = propertyName; + _behaviorOnNoMatch = behaviorOnNoMatch; + OriginalExpectedPropertyValue = expectedPropertyValue; + CimTypedExpectedPropertyValue = CimValueConverter.ConvertFromDotNetToCim(expectedPropertyValue); + } + + public BehaviorOnNoMatch BehaviorOnNoMatch + { + get + { + if (_behaviorOnNoMatch == BehaviorOnNoMatch.Default) + { + _behaviorOnNoMatch = this.GetDefaultBehaviorWhenNoMatchesFound(this.CimTypedExpectedPropertyValue); + } + + return _behaviorOnNoMatch; + } + } + + protected abstract BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue); + + private BehaviorOnNoMatch _behaviorOnNoMatch; + + public string PropertyName { get; } + + public object CimTypedExpectedPropertyValue { get; } + + public object OriginalExpectedPropertyValue { get; } + + public bool HadMatch { get; private set; } + + public bool IsMatch(CimInstance o) + { + if (o == null) + { + return false; + } + + CimProperty propertyInfo = o.CimInstanceProperties[PropertyName]; + if (propertyInfo == null) + { + return false; + } + + object actualPropertyValue = propertyInfo.Value; + + if (CimTypedExpectedPropertyValue == null) + { + HadMatch = HadMatch || (actualPropertyValue == null); + return actualPropertyValue == null; + } + + CimValueConverter.AssertIntrinsicCimValue(actualPropertyValue); + CimValueConverter.AssertIntrinsicCimValue(CimTypedExpectedPropertyValue); + + actualPropertyValue = ConvertActualValueToExpectedType(actualPropertyValue, CimTypedExpectedPropertyValue); + Dbg.Assert(IsSameType(actualPropertyValue, CimTypedExpectedPropertyValue), "Types of actual vs expected property value should always match"); + + bool isMatch = this.IsMatchingValue(actualPropertyValue); + HadMatch = HadMatch || isMatch; + return isMatch; + } + + protected abstract bool IsMatchingValue(object actualPropertyValue); + + private object ConvertActualValueToExpectedType(object actualPropertyValue, object expectedPropertyValue) + { + if (actualPropertyValue is string && expectedPropertyValue is not string) + { + actualPropertyValue = LanguagePrimitives.ConvertTo(actualPropertyValue, expectedPropertyValue.GetType(), CultureInfo.InvariantCulture); + } + + if (!IsSameType(actualPropertyValue, expectedPropertyValue)) + { + var errorMessage = string.Format( + CultureInfo.InvariantCulture, + CmdletizationResources.CimJob_MismatchedTypeOfPropertyReturnedByQuery, + PropertyName, + actualPropertyValue.GetType().FullName, + expectedPropertyValue.GetType().FullName); + throw CimJobException.CreateWithoutJobContext( + errorMessage, + "CimJob_PropertyTypeUnexpectedByClientSideQuery", + ErrorCategory.InvalidType); + } + + return actualPropertyValue; + } + + private static bool IsSameType(object actualPropertyValue, object expectedPropertyValue) + { + if (actualPropertyValue == null) + { + return true; + } + + if (expectedPropertyValue == null) + { + return true; + } + + if (actualPropertyValue is TimeSpan || actualPropertyValue is DateTime) + { + return expectedPropertyValue is TimeSpan || expectedPropertyValue is DateTime; + } + + return actualPropertyValue.GetType() == expectedPropertyValue.GetType(); + } + } + + internal class PropertyValueRegularFilter : PropertyValueFilter + { + private readonly bool _wildcardsEnabled; + + public PropertyValueRegularFilter(string propertyName, object expectedPropertyValue, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + : base(propertyName, expectedPropertyValue, behaviorOnNoMatch) + { + _wildcardsEnabled = wildcardsEnabled; + } + + protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue) + { + if (!_wildcardsEnabled) + { + return BehaviorOnNoMatch.ReportErrors; + } + else + { + if (cimTypedExpectedPropertyValue is string expectedPropertyValueAsString && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) + { + return BehaviorOnNoMatch.SilentlyContinue; + } + else + { + return BehaviorOnNoMatch.ReportErrors; + } + } + } + + internal NotFoundError GetGranularNotFoundError() + { + return new NotFoundError(this.PropertyName, this.OriginalExpectedPropertyValue, _wildcardsEnabled); + } + + protected override bool IsMatchingValue(object actualPropertyValue) + { + if (_wildcardsEnabled) + { + return WildcardEqual(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue); + } + else + { + return NonWildcardEqual(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue); + } + } + + private static bool NonWildcardEqual(string propertyName, object actualPropertyValue, object expectedPropertyValue) + { + // perform .NET-based, case-insensitive equality test for 1) characters and 2) strings + if (expectedPropertyValue is char) + { + expectedPropertyValue = expectedPropertyValue.ToString(); + actualPropertyValue = actualPropertyValue.ToString(); + } + + if (expectedPropertyValue is string expectedPropertyValueAsString) + { + var actualPropertyValueAsString = (string)actualPropertyValue; + return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase); + } + + // perform .NET based equality for everything else + return actualPropertyValue.Equals(expectedPropertyValue); + } + + private static bool WildcardEqual(string propertyName, object actualPropertyValue, object expectedPropertyValue) + { + string actualPropertyValueAsString; + string expectedPropertyValueAsString; + if (!LanguagePrimitives.TryConvertTo(actualPropertyValue, out actualPropertyValueAsString)) + { + return false; + } + + if (!LanguagePrimitives.TryConvertTo(expectedPropertyValue, out expectedPropertyValueAsString)) + { + return false; + } + + return WildcardPattern.Get(expectedPropertyValueAsString, WildcardOptions.IgnoreCase).IsMatch(actualPropertyValueAsString); + } + } + + internal sealed class PropertyValueExcludeFilter : PropertyValueRegularFilter + { + public PropertyValueExcludeFilter(string propertyName, object expectedPropertyValue, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + : base(propertyName, expectedPropertyValue, wildcardsEnabled, behaviorOnNoMatch) + { + } + + protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue) + { + return BehaviorOnNoMatch.SilentlyContinue; + } + + protected override bool IsMatchingValue(object actualPropertyValue) + { + return !base.IsMatchingValue(actualPropertyValue); + } + } + + internal sealed class PropertyValueMinFilter : PropertyValueFilter + { + public PropertyValueMinFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + : base(propertyName, expectedPropertyValue, behaviorOnNoMatch) + { + } + + protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue) + { + return BehaviorOnNoMatch.SilentlyContinue; + } + + protected override bool IsMatchingValue(object actualPropertyValue) + { + return ActualValueGreaterThanOrEqualToExpectedValue(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue); + } + + private static bool ActualValueGreaterThanOrEqualToExpectedValue(string propertyName, object actualPropertyValue, object expectedPropertyValue) + { + try + { + if (expectedPropertyValue is not IComparable expectedComparable) + { + return false; + } + + return expectedComparable.CompareTo(actualPropertyValue) <= 0; + } + catch (ArgumentException) + { + return false; + } + } + } + + internal sealed class PropertyValueMaxFilter : PropertyValueFilter + { + public PropertyValueMaxFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + : base(propertyName, expectedPropertyValue, behaviorOnNoMatch) + { + } + + protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue) + { + return BehaviorOnNoMatch.SilentlyContinue; + } + + protected override bool IsMatchingValue(object actualPropertyValue) + { + return ActualValueLessThanOrEqualToExpectedValue(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue); + } + + private static bool ActualValueLessThanOrEqualToExpectedValue(string propertyName, object actualPropertyValue, object expectedPropertyValue) + { + try + { + if (actualPropertyValue is not IComparable actualComparable) + { + return false; + } + + return actualComparable.CompareTo(expectedPropertyValue) <= 0; + } + catch (ArgumentException) + { + return false; + } + } + } + + private int _numberOfResultsFromMi; + private int _numberOfMatchingResults; + + private readonly List _filters = new(); + private readonly object _myLock = new(); + + #region "Public" interface for client-side filtering + + internal bool IsResultMatchingClientSideQuery(CimInstance result) + { + lock (_myLock) + { + _numberOfResultsFromMi++; + + if (_filters.All(f => f.IsMatch(result))) + { + _numberOfMatchingResults++; + return true; + } + else + { + return false; + } + } + } + + internal IEnumerable GenerateNotFoundErrors() + { + if (_filters.Count > 1) + { + if (_numberOfMatchingResults > 0) + { + return Enumerable.Empty(); + } + + if (_filters.All(static f => !f.ShouldReportErrorOnNoMatches_IfMultipleFilters())) + { + return Enumerable.Empty(); + } + + return new[] { new NotFoundError() }; + } + + CimInstanceFilterBase filter = _filters.SingleOrDefault(); + if (filter != null) + { + return filter.GetNotFoundErrors_IfThisIsTheOnlyFilter(); + } + + return Enumerable.Empty(); + } + + #endregion + + #region QueryBuilder interface + + public override void FilterByProperty(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + { + _filters.Add(new CimInstanceRegularFilter(propertyName, allowedPropertyValues, wildcardsEnabled, behaviorOnNoMatch)); + } + + public override void ExcludeByProperty(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) + { + _filters.Add(new CimInstanceExcludeFilter(propertyName, excludedPropertyValues, wildcardsEnabled, behaviorOnNoMatch)); + } + + public override void FilterByMinPropertyValue(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + _filters.Add(new CimInstanceMinFilter(propertyName, minPropertyValue, behaviorOnNoMatch)); + } + + public override void FilterByMaxPropertyValue(string propertyName, object maxPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) + { + _filters.Add(new CimInstanceMaxFilter(propertyName, maxPropertyValue, behaviorOnNoMatch)); + } + + public override void FilterByAssociatedInstance(object associatedInstance, string associationName, string sourceRole, string resultRole, BehaviorOnNoMatch behaviorOnNoMatch) + { + _filters.Add(new CimInstanceAssociationFilter(behaviorOnNoMatch)); + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..0f9762084d5f764aa0eec899738bcb8e1fea032d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that appends the specified content to the item at the specified path. + /// + [Cmdlet(VerbsCommon.Add, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2096489")] + public class AddContentCommand : WriteContentCommandBase + { + #region protected members + + /// + /// Seeks to the end of the writer stream in each of the writers in the + /// content holders. + /// + /// + /// The content holders that contain the writers to be moved. + /// + /// + /// If calling Seek on the content writer throws an exception. + /// + internal override void SeekContentPosition(List contentHolders) + { + foreach (ContentHolder holder in contentHolders) + { + if (holder.Writer != null) + { + try + { + holder.Writer.Seek(0, System.IO.SeekOrigin.End); + } + catch (Exception e) // Catch-all OK, 3rd party callout + { + ProviderInvocationException providerException = + new( + "ProviderSeekError", + SessionStateStrings.ProviderSeekError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + + MshLog.LogProviderHealthEvent( + this.Context, + holder.PathInfo.Provider.Name, + providerException, + Severity.Warning); + + throw providerException; + } + } + } + } + + /// + /// Makes the call to ShouldProcess with appropriate action and target strings. + /// + /// + /// The path to the item on which the content will be added. + /// + /// + /// True if the action should continue or false otherwise. + /// + internal override bool CallShouldProcess(string path) + { + string action = NavigationResources.AddContentAction; + + string target = StringUtil.Format(NavigationResources.AddContentTarget, path); + + return ShouldProcess(target, action); + } + + #endregion protected members + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..688b6362e16a4c35cb324b0e20b76a7787bd4918 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Reflection; + +using Microsoft.Management.Infrastructure; + +namespace Microsoft.PowerShell.Commands +{ + using Extensions; + + internal static class CIMHelper + { + internal static class ClassNames + { + internal const string OperatingSystem = "Win32_OperatingSystem"; + internal const string PageFileUsage = "Win32_PageFileUsage"; + internal const string Bios = "Win32_BIOS"; + internal const string BaseBoard = "Win32_BaseBoard"; + internal const string ComputerSystem = "Win32_ComputerSystem"; + internal const string Keyboard = "Win32_Keyboard"; + internal const string DeviceGuard = "Win32_DeviceGuard"; + internal const string HotFix = "Win32_QuickFixEngineering"; + internal const string MicrosoftNetworkAdapter = "MSFT_NetAdapter"; + internal const string NetworkAdapter = "Win32_NetworkAdapter"; + internal const string NetworkAdapterConfiguration = "Win32_NetworkAdapterConfiguration"; + internal const string Processor = "Win32_Processor"; + internal const string PhysicalMemory = "Win32_PhysicalMemory"; + internal const string TimeZone = "Win32_TimeZone"; + } + + internal const string DefaultNamespace = @"root\cimv2"; + internal const string DeviceGuardNamespace = @"root\Microsoft\Windows\DeviceGuard"; + internal const string MicrosoftNetworkAdapterNamespace = "root/StandardCimv2"; + internal const string DefaultQueryDialect = "WQL"; + + /// + /// Create a WQL query string to retrieve all properties from + /// the specified WMI class. + /// + /// A string containing the WMI class name. + /// + /// A string containing the WQL query string + /// + internal static string WqlQueryAll(string from) + { + return "SELECT * from " + from; + } + + /// + /// Retrieve a new object of type T, whose properties and fields are + /// populated from an instance of the named WMI class. If the CIM + /// query results in multiple instances, only the first instance is + /// returned. + /// + /// + /// The type of the object to be created. Must be a default-constructable + /// reference type. + /// + /// + /// The CIM session to be queried. + /// + /// + /// A string containing the namespace to run the query against + /// + /// + /// A string containing the name of the WMI class from which to populate + /// the resultant object. + /// + /// + /// A new object of type T if successful, null otherwise. + /// + /// + /// This method matches property and field names of type T with identically + /// named properties in the WMI class instance. The WMI property is converted + /// to the type of T's property or field. + /// + internal static T GetFirst(CimSession session, string nameSpace, string wmiClassName) where T : class, new() + { + ArgumentException.ThrowIfNullOrEmpty(wmiClassName); + + try + { + var type = typeof(T); + const BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + T rv = new(); + + using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName))) + { + SetObjectDataMembers(rv, binding, instance); + } + + return rv; + } + catch (Exception /*ex*/) + { + // on any error fall through to the null return below + } + + return null; + } + + /// + /// Retrieve an array of new objects of type T, whose properties and fields are + /// populated from an instance of the specified WMI class on the specified CIM + /// session. + /// + /// + /// The type of the object to be created. Must be a default-constructable + /// reference type. + /// + /// + /// The CIM session to be queried. + /// + /// + /// A string containing the namespace to run the query against + /// + /// + /// A string containing the name of the WMI class from which to populate + /// the resultant array elements. + /// + /// + /// An array of new objects of type T if successful, null otherwise. + /// + /// + /// This method matches property and field names of type T with identically + /// named properties in the WMI class instance. The WMI property is converted + /// to the type of T's property or field. + /// + internal static T[] GetAll(CimSession session, string nameSpace, string wmiClassName) where T : class, new() + { + ArgumentException.ThrowIfNullOrEmpty(wmiClassName); + + var rv = new List(); + + try + { + var instances = session.QueryInstances(nameSpace, CIMHelper.WqlQueryAll(wmiClassName)); + + if (instances != null) + { + var type = typeof(T); + const BindingFlags binding = BindingFlags.Public | BindingFlags.Instance; + + foreach (var instance in instances) + { + T objT = new(); + + using (instance) + { + SetObjectDataMembers(objT, binding, instance); + } + + rv.Add(objT); + } + } + } + catch (Exception /*ex*/) + { + // on any error we'll just fall through to the return below + } + + return rv.ToArray(); + } + + /// + /// Retrieve an array of new objects of type T, whose properties and fields are + /// populated from an instance of the specified WMI class on the specified CIM + /// session. + /// + /// + /// The type of the object to be created. Must be a default-constructable + /// reference type. + /// + /// + /// The CIM session to be queried. + /// + /// + /// A string containing the name of the WMI class from which to populate + /// the resultant array elements. + /// + /// + /// An array of new objects of type T if successful, null otherwise. + /// + /// + /// This method matches property and field names of type T with identically + /// named properties in the WMI class instance. The WMI property is converted + /// to the type of T's property or field. + /// + internal static T[] GetAll(CimSession session, string wmiClassName) where T : class, new() + { + return GetAll(session, DefaultNamespace, wmiClassName); + } + + internal static void SetObjectDataMember(object obj, BindingFlags binding, CimProperty cimProperty) + { + var type = obj.GetType(); + + var pi = type.GetProperty(cimProperty.Name, binding); + + if (pi != null && pi.CanWrite) + { + pi.SetValue(obj, cimProperty.Value, null); + } + else + { + var fi = type.GetField(cimProperty.Name, binding); + + if (fi != null && !fi.IsInitOnly) + { + fi.SetValue(obj, cimProperty.Value); + } + } + } + + internal static void SetObjectDataMembers(object obj, BindingFlags binding, CimInstance instance) + { + foreach (var wmiProp in instance.CimInstanceProperties) + SetObjectDataMember(obj, binding, wmiProp); + } + + /// + /// Escape any backslash (\) characters in a path with an additional + /// backslash, allowing the path to be used within a WMI query. + /// + /// + /// A string that may contain backslash characters. + /// + /// + /// A new string in which any backslash characters have been "escaped" + /// by prefacing then with an additional backslash + /// + internal static string EscapePath(string path) + { + return string.Join(@"\\", path.Split('\\')); + } + } +} + +namespace Extensions +{ + using Microsoft.PowerShell.Commands; + + internal static class CIMExtensions + { + /// + /// An "overload" of the + /// .QueryInstances + /// method that takes only the namespace and query string as a parameters. + /// + /// The CimSession to be queried. + /// A string containing the namespace to run the query against. + /// A string containing the query to be run. + /// + /// An IEnumerable interface that can be used to enumerate the instances + /// + internal static IEnumerable QueryInstances(this CimSession session, string nameSpace, string query) + { + return session.QueryInstances(nameSpace, CIMHelper.DefaultQueryDialect, query); + } + + /// + /// Execute a CIM query and return only the first instance in the result. + /// + /// The CimSession to be queried. + /// A string containing the namespace to run the query against. + /// A string containing the query to be run. + /// + /// A object + /// representing the first instance in a query result if successful, null + /// otherwise. + /// + internal static CimInstance QueryFirstInstance(this CimSession session, string nameSpace, string query) + { + try + { + var instances = session.QueryInstances(nameSpace, query); + var enumerator = instances.GetEnumerator(); + + if (enumerator.MoveNext()) + return enumerator.Current; + } + catch (Exception /*ex*/) + { + // on any error, fall through to the null return below + } + + return null; + } + + /// + /// Execute a CIM query and return only the first instance in the result. + /// + /// The CimSession to be queried. + /// A string containing the query to be run. + /// + /// A object + /// representing the first instance in a query result if successful, null + /// otherwise. + /// + internal static CimInstance QueryFirstInstance(this CimSession session, string query) + { + return session.QueryFirstInstance(CIMHelper.DefaultNamespace, query); + } + + internal static T GetFirst(this CimSession session, string wmiClassName) where T : class, new() + { + return session.GetFirst(CIMHelper.DefaultNamespace, wmiClassName); + } + + internal static T GetFirst(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new() + { + return CIMHelper.GetFirst(session, wmiNamespace, wmiClassName); + } + + internal static T[] GetAll(this CimSession session, string wmiClassName) where T : class, new() + { + return Microsoft.PowerShell.Commands.CIMHelper.GetAll(session, wmiClassName); + } + + internal static T[] GetAll(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new() + { + return Microsoft.PowerShell.Commands.CIMHelper.GetAll(session, wmiNamespace, wmiClassName); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..bd6ba2ee726bcb55a73dd08c53fcf8b21bb9277b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that appends the specified content to the item at the specified path. + /// + [Cmdlet(VerbsCommon.Clear, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096807")] + public class ClearContentCommand : ContentCommandBase + { + #region Command code + + /// + /// Clears the contents from the item at the specified path. + /// + protected override void ProcessRecord() + { + // Default to the CmdletProviderContext that will direct output to + // the pipeline. + + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = false; + + foreach (string path in Path) + { + try + { + InvokeProvider.Content.Clear(path, currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + } + } + #endregion Command code + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess + { + get + { + return base.DoesProviderSupportShouldProcess(base.Path); + } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + // Go ahead an let any exceptions terminate the pipeline. + return InvokeProvider.Content.ClearContentDynamicParameters(Path[0], context); + } + + return InvokeProvider.Content.ClearContentDynamicParameters(".", context); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..f63eb8eed9172064e442109e2225b52283163eed --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.ObjectModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to clear the value of a property of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Clear, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096903")] + public class ClearItemPropertyCommand : PassThroughItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return paths; + } + + set + { + paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The properties to clear from the item. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string Name + { + get + { + return _property; + } + + set + { + _property = value; + } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + Collection propertyCollection = new(); + propertyCollection.Add(_property); + + if (Path != null && Path.Length > 0) + { + // Go ahead and let any exception terminate the pipeline. + + return InvokeProvider.Property.ClearPropertyDynamicParameters( + Path[0], + propertyCollection, + context); + } + + return InvokeProvider.Property.ClearPropertyDynamicParameters( + ".", + propertyCollection, + context); + } + + #endregion Parameters + + #region parameter data + + /// + /// The properties to be cleared. + /// + private string _property; + + #endregion parameter data + + #region Command code + + /// + /// Clears the properties of an item at the specified path. + /// + protected override void ProcessRecord() + { + CmdletProviderContext currentContext = CmdletProviderContext; + currentContext.PassThru = PassThru; + + Collection propertyCollection = new(); + propertyCollection.Add(_property); + + foreach (string path in Path) + { + try + { + InvokeProvider.Property.Clear( + path, + propertyCollection, + currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..bc4e44220dd1bc342d6edd3c24f7eca1324f9ab9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -0,0 +1,254 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; + +#if !UNIX + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the 'Clear-RecycleBin' cmdlet. + /// This cmdlet clear all files in the RecycleBin for the given DriveLetter. + /// If not DriveLetter is specified, then the RecycleBin for all drives are cleared. + /// + [Cmdlet(VerbsCommon.Clear, "RecycleBin", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2109377", ConfirmImpact = ConfirmImpact.High)] + public class ClearRecycleBinCommand : PSCmdlet + { + private string[] _drivesList; + private DriveInfo[] _availableDrives; + private bool _force; + + /// + /// Property that sets DriveLetter parameter. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] DriveLetter + { + get { return _drivesList; } + + set { _drivesList = value; } + } + + /// + /// Property that sets force parameter. This will allow to clear the recyclebin. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + /// + /// This method implements the BeginProcessing method for Clear-RecycleBin command. + /// + protected override void BeginProcessing() + { + _availableDrives = DriveInfo.GetDrives(); + } + + /// + /// This method implements the ProcessRecord method for Clear-RecycleBin command. + /// + protected override void ProcessRecord() + { + // There are two scenarios: + // 1) The user provides a list of drives. + if (_drivesList != null) + { + foreach (var drive in _drivesList) + { + if (!IsValidPattern(drive)) + { + WriteError(new ErrorRecord( + new ArgumentException( + string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveNameFormat, "C", "C:", "C:\\")), + "InvalidDriveNameFormat", + ErrorCategory.InvalidArgument, + drive)); + continue; + } + + // Get the full path for the drive. + string drivePath = GetDrivePath(drive); + if (ValidDrivePath(drivePath)) + { + EmptyRecycleBin(drivePath); + } + } + } + else + { + // 2) No drivesList is provided by the user. + EmptyRecycleBin(null); + } + } + + /// + /// Returns true if the given drive is 'fixed' and its path exist; otherwise, return false. + /// + /// + /// + private bool ValidDrivePath(string drivePath) + { + DriveInfo actualDrive = null; + if (_availableDrives != null) + { + foreach (DriveInfo drive in _availableDrives) + { + if (string.Equals(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase)) + { + actualDrive = drive; + break; + } + } + } + + // The drive was not found. + if (actualDrive == null) + { + WriteError(new ErrorRecord( + new System.IO.DriveNotFoundException( + string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.DriveNotFound, drivePath, "Get-Volume")), + "DriveNotFound", + ErrorCategory.InvalidArgument, + drivePath)); + } + else + { + if (actualDrive.DriveType == DriveType.Fixed) + { + // The drive path exists, and the drive is 'fixed'. + return true; + } + + WriteError(new ErrorRecord( + new ArgumentException( + string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveType, drivePath, "Get-Volume")), + "InvalidDriveType", + ErrorCategory.InvalidArgument, + drivePath)); + } + + return false; + } + + /// + /// Returns true if the given input is of the form c, c:, c:\, C, C: or C:\ + /// + /// + /// + private static bool IsValidPattern(string input) + { + return Regex.IsMatch(input, @"^[a-z]{1}$|^[a-z]{1}:$|^[a-z]{1}:\\$", RegexOptions.IgnoreCase); + } + + /// + /// Returns a drive path of the form C:\ for the given drive driveName. + /// Supports the following inputs: C, C:, C:\ + /// + /// + /// + private static string GetDrivePath(string driveName) + { + string drivePath; + if (driveName.EndsWith(":\\", StringComparison.OrdinalIgnoreCase)) + { + drivePath = driveName; + } + else if (driveName.EndsWith(':')) + { + drivePath = driveName + "\\"; + } + else + { + drivePath = driveName + ":\\"; + } + + return drivePath; + } + + /// + /// Clear the recyclebin for the given drive name. + /// If no driveName is provided, it clears the recyclebin for all drives. + /// + /// + private void EmptyRecycleBin(string drivePath) + { + string clearRecycleBinShouldProcessTarget; + if (drivePath == null) + { + clearRecycleBinShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, + ClearRecycleBinResources.ClearRecycleBinContent); + } + else + { + clearRecycleBinShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, + ClearRecycleBinResources.ClearRecycleBinContentForDrive, + drivePath); + } + + if (_force || (ShouldProcess(clearRecycleBinShouldProcessTarget, "Clear-RecycleBin"))) + { + // If driveName is null, then clear the recyclebin for all drives; otherwise, just for the specified driveName. + + string activity = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinProgressActivity); + string statusDescription; + + if (drivePath == null) + { + statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionForAllDrives); + } + else + { + statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionByDrive, drivePath); + } + + ProgressRecord progress = new(0, activity, statusDescription); + progress.PercentComplete = 30; + progress.RecordType = ProgressRecordType.Processing; + WriteProgress(progress); + + // no need to check result as a failure is returned only if recycle bin is already empty + uint result = NativeMethod.SHEmptyRecycleBin(IntPtr.Zero, drivePath, + NativeMethod.RecycleFlags.SHERB_NOCONFIRMATION | + NativeMethod.RecycleFlags.SHERB_NOPROGRESSUI | + NativeMethod.RecycleFlags.SHERB_NOSOUND); + progress.PercentComplete = 100; + progress.RecordType = ProgressRecordType.Completed; + WriteProgress(progress); + } + } + } + + internal static partial class NativeMethod + { + // Internal code to SHEmptyRecycleBin + internal enum RecycleFlags : uint + { + SHERB_NOCONFIRMATION = 0x00000001, + SHERB_NOPROGRESSUI = 0x00000002, + SHERB_NOSOUND = 0x00000004 + } + + [LibraryImport("Shell32.dll", StringMarshalling = StringMarshalling.Utf16, EntryPoint = "SHEmptyRecycleBinW")] + internal static partial uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); + } +} +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs new file mode 100644 index 0000000000000000000000000000000000000000..77e1b497b95d5e9ea85d987286f7466955c09923 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs @@ -0,0 +1,390 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Microsoft.PowerShell.Commands.Internal +{ + internal static partial class Clipboard + { + private static bool? _clipboardSupported; + + // Used if an external clipboard is not available, e.g. if xclip is missing. + // This is useful for testing in CI as well. + private static string _internalClipboard; + + private static string StartProcess( + string tool, + string args, + string stdin = "", + bool readStdout = true) + { + ProcessStartInfo startInfo = new(); + startInfo.UseShellExecute = false; + startInfo.RedirectStandardInput = true; + startInfo.RedirectStandardOutput = true; + startInfo.RedirectStandardError = true; + startInfo.FileName = tool; + startInfo.Arguments = args; + string stdout = string.Empty; + + using (Process process = new()) + { + process.StartInfo = startInfo; + try + { + process.Start(); + } + catch (System.ComponentModel.Win32Exception) + { + _clipboardSupported = false; + return string.Empty; + } + + process.StandardInput.Write(stdin); + process.StandardInput.Close(); + + if (readStdout) + { + stdout = process.StandardOutput.ReadToEnd(); + } + + process.WaitForExit(250); + _clipboardSupported = process.ExitCode == 0; + } + + return stdout; + } + + public static string GetText() + { + if (_clipboardSupported == false) + { + return _internalClipboard ?? string.Empty; + } + + string tool = string.Empty; + string args = string.Empty; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + string clipboardText = string.Empty; + ExecuteOnStaThread(() => GetTextImpl(out clipboardText)); + return clipboardText; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + tool = "xclip"; + args = "-selection clipboard -out"; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + tool = "pbpaste"; + } + else + { + _clipboardSupported = false; + return string.Empty; + } + + return StartProcess(tool, args); + } + + public static void SetText(string text) + { + if (_clipboardSupported == false) + { + _internalClipboard = text; + return; + } + + string tool = string.Empty; + string args = string.Empty; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + ExecuteOnStaThread(() => SetClipboardData(Tuple.Create(text, CF_UNICODETEXT))); + return; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + tool = "xclip"; + if (string.IsNullOrEmpty(text)) + { + args = "-selection clipboard /dev/null"; + } + else + { + args = "-selection clipboard -in"; + } + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + tool = "pbcopy"; + } + else + { + _clipboardSupported = false; + return; + } + + StartProcess(tool, args, text, readStdout: false); + if (_clipboardSupported == false) + { + _internalClipboard = text; + } + } + + public static void SetRtf(string plainText, string rtfText) + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + if (s_CF_RTF == 0) + { + s_CF_RTF = RegisterClipboardFormat("Rich Text Format"); + } + + ExecuteOnStaThread(() => SetClipboardData( + Tuple.Create(plainText, CF_UNICODETEXT), + Tuple.Create(rtfText, s_CF_RTF))); + } + + private const uint GMEM_MOVEABLE = 0x0002; + private const uint GMEM_ZEROINIT = 0x0040; + private const uint GHND = GMEM_MOVEABLE | GMEM_ZEROINIT; + + [LibraryImport("kernel32.dll")] + private static partial IntPtr GlobalAlloc(uint flags, UIntPtr dwBytes); + + [LibraryImport("kernel32.dll")] + private static partial IntPtr GlobalFree(IntPtr hMem); + + [LibraryImport("kernel32.dll")] + private static partial IntPtr GlobalLock(IntPtr hMem); + + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool GlobalUnlock(IntPtr hMem); + + [LibraryImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] + private static partial void CopyMemory(IntPtr dest, IntPtr src, uint count); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool IsClipboardFormatAvailable(uint format); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool OpenClipboard(IntPtr hWndNewOwner); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CloseClipboard(); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool EmptyClipboard(); + + [LibraryImport("user32.dll")] + private static partial IntPtr GetClipboardData(uint format); + + [LibraryImport("user32.dll")] + private static partial IntPtr SetClipboardData(uint format, IntPtr data); + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial uint RegisterClipboardFormat(string lpszFormat); + + private const uint CF_TEXT = 1; + private const uint CF_UNICODETEXT = 13; + + private static uint s_CF_RTF; + + private static bool GetTextImpl(out string text) + { + try + { + if (IsClipboardFormatAvailable(CF_UNICODETEXT)) + { + if (OpenClipboard(IntPtr.Zero)) + { + var data = GetClipboardData(CF_UNICODETEXT); + if (data != IntPtr.Zero) + { + data = GlobalLock(data); + text = Marshal.PtrToStringUni(data); + GlobalUnlock(data); + return true; + } + } + } + else if (IsClipboardFormatAvailable(CF_TEXT)) + { + if (OpenClipboard(IntPtr.Zero)) + { + var data = GetClipboardData(CF_TEXT); + if (data != IntPtr.Zero) + { + data = GlobalLock(data); + text = Marshal.PtrToStringAnsi(data); + GlobalUnlock(data); + return true; + } + } + } + } + catch + { + // Ignore exceptions + } + finally + { + CloseClipboard(); + } + + text = string.Empty; + return false; + } + + private static bool SetClipboardData(params Tuple[] data) + { + try + { + if (!OpenClipboard(IntPtr.Zero)) + { + return false; + } + + EmptyClipboard(); + + foreach (var d in data) + { + if (!SetSingleClipboardData(d.Item1, d.Item2)) + { + return false; + } + } + } + finally + { + CloseClipboard(); + } + + return true; + } + + private static bool SetSingleClipboardData(string text, uint format) + { + IntPtr hGlobal = IntPtr.Zero; + IntPtr data = IntPtr.Zero; + + try + { + uint bytes; + if (format == s_CF_RTF || format == CF_TEXT) + { + bytes = (uint)(text.Length + 1); + data = Marshal.StringToHGlobalAnsi(text); + } + else if (format == CF_UNICODETEXT) + { + bytes = (uint)((text.Length + 1) * 2); + data = Marshal.StringToHGlobalUni(text); + } + else + { + // Not yet supported format. + return false; + } + + if (data == IntPtr.Zero) + { + return false; + } + + hGlobal = GlobalAlloc(GHND, (UIntPtr)bytes); + if (hGlobal == IntPtr.Zero) + { + return false; + } + + IntPtr dataCopy = GlobalLock(hGlobal); + if (dataCopy == IntPtr.Zero) + { + return false; + } + + CopyMemory(dataCopy, data, bytes); + GlobalUnlock(hGlobal); + + if (SetClipboardData(format, hGlobal) != IntPtr.Zero) + { + // The clipboard owns this memory now, so don't free it. + hGlobal = IntPtr.Zero; + } + } + catch + { + // Ignore failures + } + finally + { + if (data != IntPtr.Zero) + { + Marshal.FreeHGlobal(data); + } + + if (hGlobal != IntPtr.Zero) + { + GlobalFree(hGlobal); + } + } + + return true; + } + + private static void ExecuteOnStaThread(Func action) + { + const int RetryCount = 5; + int tries = 0; + + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + { + while (tries++ < RetryCount && !action()) + { + // wait until RetryCount or action + } + + return; + } + + Exception exception = null; + var thread = new Thread(() => + { + try + { + while (tries++ < RetryCount && !action()) + { + // wait until RetryCount or action + } + } + catch (Exception e) + { + exception = e; + } + }); + + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + + if (exception != null) + { + throw exception; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..79b1c862bfda5624cbb79277e2c511db24e29fef --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs @@ -0,0 +1,250 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that adds the parent and child parts of a path together + /// with the appropriate path separator. + /// + [Cmdlet(VerbsCommon.Join, "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096811")] + [OutputType(typeof(string))] + public class JoinPathCommand : CoreCommandWithCredentialsBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath")] + public string[] Path { get; set; } + + /// + /// Gets or sets the childPath parameter to the command. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [AllowNull] + [AllowEmptyString] + [AllowEmptyCollection] + public string[] ChildPath { get; set; } + + /// + /// Gets or sets additional childPaths to the command. + /// + [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromRemainingArguments = true)] + [AllowNull] + [AllowEmptyString] + [AllowEmptyCollection] + public string[] AdditionalChildPath { get; set; } = Array.Empty(); + + /// + /// Determines if the path should be resolved after being joined. + /// + /// + [Parameter] + public SwitchParameter Resolve { get; set; } + + /// + /// Gets or sets the extension to use for the resulting path. + /// If not specified, the original extension (if any) is preserved. + /// + /// Behavior: + /// - If the path has an existing extension, it will be replaced with the specified extension. + /// - If the path does not have an extension, the specified extension will be added. + /// - If an empty string is provided, any existing extension will be removed. + /// - A leading dot in the extension is optional; if omitted, one will be added automatically. + /// + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNull] + public string Extension { get; set; } + + #endregion Parameters + + #region Command code + + /// + /// Parses the specified path and returns the portion determined by the + /// boolean parameters. + /// + protected override void ProcessRecord() + { + Dbg.Diagnostics.Assert( + Path != null, + "Since Path is a mandatory parameter, paths should never be null"); + + string combinedChildPath = string.Empty; + + if (this.ChildPath != null) + { + foreach (string childPath in this.ChildPath) + { + combinedChildPath = SessionState.Path.Combine(combinedChildPath, childPath, CmdletProviderContext); + } + } + + // join the ChildPath elements + if (AdditionalChildPath != null) + { + foreach (string childPath in AdditionalChildPath) + { + combinedChildPath = SessionState.Path.Combine(combinedChildPath, childPath, CmdletProviderContext); + } + } + + foreach (string path in Path) + { + // First join the path elements + + string joinedPath = null; + + try + { + joinedPath = + SessionState.Path.Combine(path, combinedChildPath, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + // If Extension parameter is present it is not null due to [ValidateNotNull]. + if (Extension is not null) + { + joinedPath = System.IO.Path.ChangeExtension(joinedPath, Extension.Length == 0 ? null : Extension); + } + + if (Resolve) + { + // Resolve the paths. The default API (GetResolvedPSPathFromPSPath) + // does not allow non-existing paths. + Collection resolvedPaths = null; + try + { + resolvedPaths = + SessionState.Path.GetResolvedPSPathFromPSPath(joinedPath, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + for (int index = 0; index < resolvedPaths.Count; ++index) + { + try + { + if (resolvedPaths[index] != null) + { + WriteObject(resolvedPaths[index].Path); + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + else + { + if (joinedPath != null) + { + WriteObject(joinedPath); + } + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..94e923bfa6e210b8ae494837695cce00e3e0c620 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that commits a transaction. + /// + [Cmdlet(VerbsLifecycle.Complete, "Transaction", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135200")] + public class CompleteTransactionCommand : PSCmdlet + { + /// + /// Commits the current transaction. + /// + protected override void EndProcessing() + { + // Commit the transaction + if (ShouldProcess( + NavigationResources.TransactionResource, + NavigationResources.CommitAction)) + { + this.Context.TransactionManager.Commit(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs new file mode 100644 index 0000000000000000000000000000000000000000..ea8c111531c9c3e98c87a3c31c721e0c10bad680 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -0,0 +1,2255 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Net; +using System.Runtime.Serialization; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Microsoft.Win32; +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + #region Restart-Computer + + /// + /// This exception is thrown when the timeout expires before a computer finishes restarting. + /// + public sealed class RestartComputerTimeoutException : RuntimeException + { + /// + /// Name of the computer that is restarting. + /// + public string ComputerName { get; } + + /// + /// The timeout value specified by the user. It indicates the seconds to wait before timeout. + /// + public int Timeout { get; } + + /// + /// Construct a RestartComputerTimeoutException. + /// + /// + /// + /// + /// + internal RestartComputerTimeoutException(string computerName, int timeout, string message, string errorId) + : base(message) + { + SetErrorId(errorId); + SetErrorCategory(ErrorCategory.OperationTimeout); + ComputerName = computerName; + Timeout = timeout; + } + + /// + /// Construct a RestartComputerTimeoutException. + /// + public RestartComputerTimeoutException() : base() { } + + /// + /// Constructs a RestartComputerTimeoutException. + /// + /// + /// The message used in the exception. + /// + public RestartComputerTimeoutException(string message) : base(message) { } + + /// + /// Constructs a RestartComputerTimeoutException. + /// + /// + /// The message used in the exception. + /// + /// + /// An exception that led to this exception. + /// + public RestartComputerTimeoutException(string message, Exception innerException) : base(message, innerException) { } + } + + /// + /// Defines the services that Restart-Computer can wait on. + /// + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] + public enum WaitForServiceTypes + { + /// + /// Wait for the WMI service to be ready. + /// + Wmi = 0x0, + + /// + /// Wait for the WinRM service to be ready. + /// + WinRM = 0x1, + + /// + /// Wait for the PowerShell to be ready. + /// + PowerShell = 0x2, + } + + /// + /// Restarts the computer. + /// + [Cmdlet(VerbsLifecycle.Restart, "Computer", SupportsShouldProcess = true, DefaultParameterSetName = DefaultParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097060", RemotingCapability = RemotingCapability.OwnedByCommand)] + public class RestartComputerCommand : PSCmdlet, IDisposable + { + #region "Parameters and PrivateData" + + private const string DefaultParameterSet = "DefaultSet"; + private const int forcedReboot = 6; // see https://msdn.microsoft.com/library/aa394058(v=vs.85).aspx + + /// + /// The authentication options for CIM_WSMan connection. + /// + [Parameter(ParameterSetName = DefaultParameterSet)] + [ValidateSet( + "Default", + "Basic", + "Negotiate", // can be used with and without credential (without -> PSRP mapped to NegotiateWithImplicitCredential) + "CredSSP", + "Digest", + "Kerberos")] // can be used with explicit or implicit credential + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public string WsmanAuthentication { get; set; } + + /// + /// Specifies the computer (s)Name on which this command is executed. + /// When this parameter is omitted, this cmdlet restarts the local computer. + /// Type the NETBIOS name, IP address, or fully-qualified domain name of one + /// or more computers in a comma-separated list. To specify the local computer, type the computername or "localhost". + /// + [Parameter(Position = 0, ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [Alias("CN", "__SERVER", "Server", "IPAddress")] + public string[] ComputerName { get; set; } = new string[] { "." }; + + private List _validatedComputerNames = new(); + private readonly List _waitOnComputers = new(); + private readonly HashSet _uniqueComputerNames = new(StringComparer.OrdinalIgnoreCase); + + /// + /// The following is the definition of the input parameter "Credential". + /// Specifies a user account that has permission to perform this action. Type a + /// user-name, such as "User01" or "Domain01\User01", or enter a PSCredential + /// object, such as one from the Get-Credential cmdlet. + /// + [Parameter(Position = 1)] + [ValidateNotNullOrEmpty] + [Credential] + public PSCredential Credential { get; set; } + + /// + /// Using Force in conjunction with Reboot on a + /// remote computer immediately reboots the remote computer. + /// + [Parameter] + [Alias("f")] + public SwitchParameter Force { get; set; } + + /// + /// Specify the Wait parameter. Prompt will be blocked is the Timeout is not 0. + /// + [Parameter(ParameterSetName = DefaultParameterSet)] + public SwitchParameter Wait { get; set; } + + /// + /// Specify the Timeout parameter. + /// Negative value indicates wait infinitely. + /// Positive value indicates the seconds to wait before timeout. + /// + [Parameter(ParameterSetName = DefaultParameterSet)] + [Alias("TimeoutSec")] + [ValidateRange(-1, int.MaxValue)] + public int Timeout + { + get + { + return _timeout; + } + + set + { + _timeout = value; + _timeoutSpecified = true; + } + } + + private int _timeout = -1; + private bool _timeoutSpecified = false; + + /// + /// Specify the For parameter. + /// Wait for the specific service before unblocking the prompt. + /// + [Parameter(ParameterSetName = DefaultParameterSet)] + public WaitForServiceTypes For + { + get + { + return _waitFor; + } + + set + { + _waitFor = value; + _waitForSpecified = true; + } + } + + private WaitForServiceTypes _waitFor = WaitForServiceTypes.PowerShell; + private bool _waitForSpecified = false; + + /// + /// Specify the Delay parameter. + /// The specific time interval (in second) to wait between network pings or service queries. + /// + [Parameter(ParameterSetName = DefaultParameterSet)] + [ValidateRange(1, short.MaxValue)] + public short Delay + { + get + { + return (short)_delay; + } + + set + { + _delay = value; + _delaySpecified = true; + } + } + + private int _delay = 5; + private bool _delaySpecified = false; + + /// + /// Script to test if the PowerShell is ready. + /// + private const string TestPowershellScript = @" +$array = @($input) +$result = @{} +foreach ($computerName in $array[1]) +{ + $ret = $null + $arguments = @{ + ComputerName = $computerName + ScriptBlock = { $true } + + SessionOption = New-PSSessionOption -NoMachineProfile + ErrorAction = 'SilentlyContinue' + } + + if ( $null -ne $array[0] ) + { + $arguments['Credential'] = $array[0] + } + + $result[$computerName] = (Invoke-Command @arguments) -as [bool] +} +$result +"; + + /// + /// The indicator to use when show progress. + /// + private readonly string[] _indicator = { "|", "/", "-", "\\" }; + + /// + /// The activity id. + /// + private int _activityId; + + /// + /// After call 'Shutdown' on the target computer, wait a few + /// seconds for the restart to begin. + /// + private const int SecondsToWaitForRestartToBegin = 25; + + /// + /// Actual time out in seconds. + /// + private int _timeoutInMilliseconds; + + /// + /// Indicate to exit. + /// + private bool _exit, _timeUp; + private readonly CancellationTokenSource _cancel = new(); + + /// + /// A waithandler to wait on. Current thread will wait on it during the delay interval. + /// + private readonly ManualResetEventSlim _waitHandler = new(false); + private readonly Dictionary _computerInfos = new(StringComparer.OrdinalIgnoreCase); + + // CLR 4.0 Port note - use https://msdn.microsoft.com/library/system.net.networkinformation.ipglobalproperties.hostname(v=vs.110).aspx + private readonly string _shortLocalMachineName = Dns.GetHostName(); + + // And for this, use PsUtils.GetHostname() + private readonly string _fullLocalMachineName = Dns.GetHostEntryAsync(string.Empty).Result.HostName; + + private int _percent; + private string _status; + private string _activity; + private Timer _timer; + private System.Management.Automation.PowerShell _powershell; + + private const string StageVerification = "VerifyStage"; + private const string WmiConnectionTest = "WMI"; + private const string WinrmConnectionTest = "WinRM"; + private const string PowerShellConnectionTest = "PowerShell"; + + #endregion "parameters and PrivateData" + + #region "IDisposable Members" + + /// + /// Dispose Method. + /// + public void Dispose() + { + this.Dispose(true); + // Use SuppressFinalize in case a subclass + // of this type implements a finalizer. + GC.SuppressFinalize(this); + } + + /// + /// Dispose Method. + /// + /// + public void Dispose(bool disposing) + { + if (disposing) + { + _timer?.Dispose(); + _waitHandler.Dispose(); + _cancel.Dispose(); + _powershell?.Dispose(); + } + } + + #endregion "IDisposable Members" + + #region "Private Methods" + + /// + /// Validate parameters for 'DefaultSet' + /// 1. When the Wait is specified, the computername cannot contain the local machine + /// 2. If the local machine is present, make sure it is at the end of the list (so the remote ones get restarted before the local machine reboot). + /// + private void ValidateComputerNames() + { + bool containLocalhost = false; + _validatedComputerNames.Clear(); + + foreach (string name in ComputerName) + { + ErrorRecord error = null; + string targetComputerName = ComputerWMIHelper.ValidateComputerName(name, _shortLocalMachineName, _fullLocalMachineName, ref error); + if (targetComputerName == null) + { + if (error != null) + { + WriteError(error); + } + + continue; + } + + if (targetComputerName.Equals(ComputerWMIHelper.localhostStr, StringComparison.OrdinalIgnoreCase)) + { + containLocalhost = true; + } + else if (!_uniqueComputerNames.Contains(targetComputerName)) + { + _validatedComputerNames.Add(targetComputerName); + _uniqueComputerNames.Add(targetComputerName); + } + } + + // Force wait with a test hook even if we're on the local computer + if (!InternalTestHooks.TestWaitStopComputer && Wait && containLocalhost) + { + // The local machine will be ignored, and an error will be emitted. + InvalidOperationException ex = new(ComputerResources.CannotWaitLocalComputer); + WriteError(new ErrorRecord(ex, "CannotWaitLocalComputer", ErrorCategory.InvalidOperation, null)); + containLocalhost = false; + } + + // Add the localhost to the end of the list, so we will restart remote machines + // before we restart the local one. + if (containLocalhost) + { + _validatedComputerNames.Add(ComputerWMIHelper.localhostStr); + } + } + + /// + /// Write out progress. + /// + /// + /// + /// + /// + private void WriteProgress(string activity, string status, int percent, ProgressRecordType progressRecordType) + { + ProgressRecord progress = new(_activityId, activity, status); + progress.PercentComplete = percent; + progress.RecordType = progressRecordType; + WriteProgress(progress); + } + + /// + /// Calculate the progress percentage. + /// + /// + /// + private int CalculateProgressPercentage(string currentStage) + { + switch (currentStage) + { + case StageVerification: + return _waitFor.Equals(WaitForServiceTypes.Wmi) || _waitFor.Equals(WaitForServiceTypes.WinRM) + ? 33 + : 20; + case WmiConnectionTest: + return _waitFor.Equals(WaitForServiceTypes.Wmi) ? 66 : 40; + case WinrmConnectionTest: + return _waitFor.Equals(WaitForServiceTypes.WinRM) ? 66 : 60; + case PowerShellConnectionTest: + return 80; + default: + break; + } + + Dbg.Diagnostics.Assert(false, "CalculateProgressPercentage should never hit the default case"); + return 0; + } + + /// + /// Event handler for the timer. + /// + /// + private void OnTimedEvent(object s) + { + _exit = _timeUp = true; + _cancel.Cancel(); + _waitHandler.Set(); + + if (_powershell != null) + { + _powershell.Stop(); + _powershell.Dispose(); + } + } + + private sealed class ComputerInfo + { + internal string LastBootUpTime; + internal bool RebootComplete; + } + + private List TestRestartStageUsingWsman(IEnumerable computerNames, List nextTestList, CancellationToken token) + { + var restartStageTestList = new List(); + var operationOptions = new CimOperationOptions + { + Timeout = TimeSpan.FromMilliseconds(2000), + CancellationToken = token + }; + foreach (var computer in computerNames) + { + try + { + if (token.IsCancellationRequested) + { + break; + } + + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, isLocalHost: false, this, token)) + { + bool itemRetrieved = false; + IEnumerable mCollection = cimSession.QueryInstances( + ComputerWMIHelper.CimOperatingSystemNamespace, + ComputerWMIHelper.CimQueryDialect, + "Select * from " + ComputerWMIHelper.WMI_Class_OperatingSystem, + operationOptions); + foreach (CimInstance os in mCollection) + { + itemRetrieved = true; + string newLastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString(); + string oldLastBootUpTime = _computerInfos[computer].LastBootUpTime; + + if (!string.Equals(newLastBootUpTime, oldLastBootUpTime, StringComparison.OrdinalIgnoreCase)) + { + _computerInfos[computer].RebootComplete = true; + nextTestList.Add(computer); + } + else + { + restartStageTestList.Add(computer); + } + } + + if (!itemRetrieved) + { + restartStageTestList.Add(computer); + } + } + } + catch (CimException) + { + restartStageTestList.Add(computer); + } + catch (Exception) + { + restartStageTestList.Add(computer); + } + } + + return restartStageTestList; + } + + private List SetUpComputerInfoUsingWsman(IEnumerable computerNames, CancellationToken token) + { + var validComputerNameList = new List(); + var operationOptions = new CimOperationOptions + { + Timeout = TimeSpan.FromMilliseconds(2000), + CancellationToken = token + }; + foreach (var computer in computerNames) + { + try + { + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, isLocalHost: false, this, token)) + { + bool itemRetrieved = false; + IEnumerable mCollection = cimSession.QueryInstances( + ComputerWMIHelper.CimOperatingSystemNamespace, + ComputerWMIHelper.CimQueryDialect, + "Select * from " + ComputerWMIHelper.WMI_Class_OperatingSystem, + operationOptions); + foreach (CimInstance os in mCollection) + { + itemRetrieved = true; + if (!_computerInfos.ContainsKey(computer)) + { + var info = new ComputerInfo + { + LastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString(), + RebootComplete = false + }; + _computerInfos.Add(computer, info); + validComputerNameList.Add(computer); + } + } + + if (!itemRetrieved) + { + string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ComputerResources.CannotGetOperatingSystemObject); + var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped", + ErrorCategory.OperationStopped, computer); + this.WriteError(error); + } + } + } + catch (CimException ex) + { + string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message); + var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped", + ErrorCategory.OperationStopped, computer); + this.WriteError(error); + } + catch (Exception ex) + { + string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message); + var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped", + ErrorCategory.OperationStopped, computer); + this.WriteError(error); + } + } + + return validComputerNameList; + } + + private void WriteOutTimeoutError(IEnumerable computerNames) + { + const string errorId = "RestartComputerTimeout"; + foreach (string computer in computerNames) + { + string errorMsg = StringUtil.Format(ComputerResources.RestartcomputerFailed, computer, ComputerResources.TimeoutError); + var exception = new RestartComputerTimeoutException(computer, Timeout, errorMsg, errorId); + var error = new ErrorRecord(exception, errorId, ErrorCategory.OperationTimeout, computer); + if (!InternalTestHooks.TestWaitStopComputer) + { + WriteError(error); + } + } + } + + #endregion "Private Methods" + + #region "Internal Methods" + + internal static List TestWmiConnectionUsingWsman(List computerNames, List nextTestList, PSCredential credential, string wsmanAuthentication, PSCmdlet cmdlet, CancellationToken token) + { + // Check if the WMI service "Winmgmt" is started + const string wmiServiceQuery = "Select * from " + ComputerWMIHelper.WMI_Class_Service + " Where name = 'Winmgmt'"; + var wmiTestList = new List(); + var operationOptions = new CimOperationOptions + { + Timeout = TimeSpan.FromMilliseconds(2000), + CancellationToken = token + }; + foreach (var computer in computerNames) + { + try + { + if (token.IsCancellationRequested) + { + break; + } + + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credential, wsmanAuthentication, isLocalHost: false, cmdlet, token)) + { + bool itemRetrieved = false; + IEnumerable mCollection = cimSession.QueryInstances( + ComputerWMIHelper.CimOperatingSystemNamespace, + ComputerWMIHelper.CimQueryDialect, + wmiServiceQuery, + operationOptions); + foreach (CimInstance service in mCollection) + { + itemRetrieved = true; + if (LanguagePrimitives.IsTrue(service.CimInstanceProperties["Started"].Value)) + { + nextTestList.Add(computer); + } + else + { + wmiTestList.Add(computer); + } + } + + if (!itemRetrieved) + { + wmiTestList.Add(computer); + } + } + } + catch (CimException) + { + wmiTestList.Add(computer); + } + catch (Exception) + { + wmiTestList.Add(computer); + } + } + + return wmiTestList; + } + + /// + /// Test the PowerShell state for the restarting computer. + /// + /// + /// + /// + /// + /// + internal static List TestPowerShell(List computerNames, List nextTestList, System.Management.Automation.PowerShell powershell, PSCredential credential) + { + List psList = new(); + + try + { + Collection psObjectCollection = powershell.Invoke(new object[] { credential, computerNames.ToArray() }); + if (psObjectCollection == null) + { + Dbg.Diagnostics.Assert(false, "This should never happen. Invoke should never return null."); + } + + // If ^C or timeout happens when we are in powershell.Invoke(), the psObjectCollection might be empty + if (psObjectCollection.Count == 0) + { + return computerNames; + } + + object result = PSObject.Base(psObjectCollection[0]); + Hashtable data = result as Hashtable; + + Dbg.Diagnostics.Assert(data != null, "data should never be null"); + Dbg.Diagnostics.Assert(data.Count == computerNames.Count, "data should contain results for all computers in computerNames"); + + foreach (string computer in computerNames) + { + if (LanguagePrimitives.IsTrue(data[computer])) + { + nextTestList.Add(computer); + } + else + { + psList.Add(computer); + } + } + } + catch (PipelineStoppedException) + { + // powershell.Stop() is invoked because timeout expires, or Ctrl+C is pressed + } + catch (ObjectDisposedException) + { + // powershell.dispose() is invoked because timeout expires, or Ctrl+C is pressed + } + + return psList; + } + + #endregion "Internal Methods" + + #region "Overrides" + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + // Timeout, For, Delay, Progress cannot be present if Wait is not present + if ((_timeoutSpecified || _waitForSpecified || _delaySpecified) && !Wait) + { + InvalidOperationException ex = new(ComputerResources.RestartComputerInvalidParameter); + ThrowTerminatingError(new ErrorRecord(ex, "RestartComputerInvalidParameter", ErrorCategory.InvalidOperation, null)); + } + + if (Wait) + { + _activityId = Random.Shared.Next(); + if (_timeout == -1 || _timeout >= int.MaxValue / 1000) + { + _timeoutInMilliseconds = int.MaxValue; + } + else + { + _timeoutInMilliseconds = _timeout * 1000; + } + + // We don't support combined service types for now + switch (_waitFor) + { + case WaitForServiceTypes.Wmi: + case WaitForServiceTypes.WinRM: + break; + case WaitForServiceTypes.PowerShell: + _powershell = System.Management.Automation.PowerShell.Create(); + _powershell.AddScript(TestPowershellScript); + break; + default: + InvalidOperationException ex = new(ComputerResources.NoSupportForCombinedServiceType); + ErrorRecord error = new(ex, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (int)_waitFor); + ThrowTerminatingError(error); + break; + } + } + } + + /// + /// ProcessRecord method. + /// + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] + protected override void ProcessRecord() + { + // Validate parameters + ValidateComputerNames(); + + object[] flags = new object[] { 2, 0 }; + if (Force) + { + flags[0] = forcedReboot; + } + + if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase)) + { + if (Wait && _timeout != 0) + { + _validatedComputerNames = + SetUpComputerInfoUsingWsman(_validatedComputerNames, _cancel.Token); + } + + foreach (string computer in _validatedComputerNames) + { + bool isLocal = false; + string compname; + + if (computer.Equals("localhost", StringComparison.OrdinalIgnoreCase)) + { + compname = _shortLocalMachineName; + isLocal = true; + } + else + { + compname = computer; + } + + // Generate target and action strings + string action = + StringUtil.Format( + ComputerResources.RestartComputerAction, + isLocal ? ComputerResources.LocalShutdownPrivilege : ComputerResources.RemoteShutdownPrivilege); + string target = + isLocal ? StringUtil.Format(ComputerResources.DoubleComputerName, "localhost", compname) : compname; + + if (!ShouldProcess(target, action)) + { + continue; + } + + bool isSuccess = + ComputerWMIHelper.InvokeWin32ShutdownUsingWsman(this, isLocal, compname, flags, Credential, WsmanAuthentication, ComputerResources.RestartcomputerFailed, "RestartcomputerFailed", _cancel.Token); + + if (isSuccess && Wait && _timeout != 0) + { + _waitOnComputers.Add(computer); + } + } + + if (_waitOnComputers.Count > 0) + { + var restartStageTestList = new List(_waitOnComputers); + var wmiTestList = new List(); + var winrmTestList = new List(); + var psTestList = new List(); + var allDoneList = new List(); + + bool isForWmi = _waitFor.Equals(WaitForServiceTypes.Wmi); + bool isForWinRm = _waitFor.Equals(WaitForServiceTypes.WinRM); + bool isForPowershell = _waitFor.Equals(WaitForServiceTypes.PowerShell); + + int indicatorIndex = 0; + int machineCompleteRestart = 0; + int actualDelay = SecondsToWaitForRestartToBegin; + bool first = true; + bool waitComplete = false; + + _percent = 0; + _status = ComputerResources.WaitForRestartToBegin; + _activity = _waitOnComputers.Count == 1 ? + StringUtil.Format(ComputerResources.RestartSingleComputerActivity, _waitOnComputers[0]) : + ComputerResources.RestartMultipleComputersActivity; + + _timer = new Timer(OnTimedEvent, null, _timeoutInMilliseconds, System.Threading.Timeout.Infinite); + + while (true) + { + // (delay * 1000)/250ms + int loopCount = actualDelay * 4; + while (loopCount > 0) + { + WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); + + loopCount--; + _waitHandler.Wait(250); + if (_exit) + { + break; + } + } + + if (first) + { + actualDelay = _delay; + first = false; + + if (_waitOnComputers.Count > 1) + { + _status = StringUtil.Format(ComputerResources.WaitForMultipleComputers, machineCompleteRestart, _waitOnComputers.Count); + WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); + } + } + + do + { + // Test restart stage. + // We check if the target machine has already rebooted by querying the LastBootUpTime from the Win32_OperatingSystem object. + // So after this step, we are sure that both the Network and the WMI or WinRM service have already come up. + if (_exit) + { + break; + } + + if (restartStageTestList.Count > 0) + { + if (_waitOnComputers.Count == 1) + { + _status = ComputerResources.VerifyRebootStage; + _percent = CalculateProgressPercentage(StageVerification); + WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); + } + + List nextTestList = (isForWmi || isForPowershell) ? wmiTestList : winrmTestList; + restartStageTestList = TestRestartStageUsingWsman(restartStageTestList, nextTestList, _cancel.Token); + } + + // Test WMI service + if (_exit) + { + break; + } + + if (wmiTestList.Count > 0) + { + // This statement block executes for both CLRs. + // In the "full" CLR, it serves as the else case. + { + if (_waitOnComputers.Count == 1) + { + _status = ComputerResources.WaitForWMI; + _percent = CalculateProgressPercentage(WmiConnectionTest); + WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); + } + + wmiTestList = TestWmiConnectionUsingWsman(wmiTestList, winrmTestList, Credential, WsmanAuthentication, this, _cancel.Token); + } + } + + if (isForWmi) + { + break; + } + + // Test WinRM service + if (_exit) + { + break; + } + + if (winrmTestList.Count > 0) + { + // This statement block executes for both CLRs. + // In the "full" CLR, it serves as the else case. + { + // CIM-WSMan in use. In this case, restart stage checking is done by using WMIv2, + // so the WinRM service on the target machine is already up at this point. + psTestList.AddRange(winrmTestList); + winrmTestList.Clear(); + + if (_waitOnComputers.Count == 1) + { + // This is to simulate the test for WinRM service + _status = ComputerResources.WaitForWinRM; + _percent = CalculateProgressPercentage(WinrmConnectionTest); + + loopCount = actualDelay * 4; // (delay * 1000)/250ms + while (loopCount > 0) + { + WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); + + loopCount--; + _waitHandler.Wait(250); + if (_exit) + { + break; + } + } + } + } + } + + if (isForWinRm) + { + break; + } + + // Test PowerShell + if (_exit) + { + break; + } + + if (psTestList.Count > 0) + { + if (_waitOnComputers.Count == 1) + { + _status = ComputerResources.WaitForPowerShell; + _percent = CalculateProgressPercentage(PowerShellConnectionTest); + WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); + } + + psTestList = TestPowerShell(psTestList, allDoneList, _powershell, this.Credential); + } + } while (false); + + // if time is up or Ctrl+c is typed, break out + if (_exit) + { + break; + } + + // Check if the restart completes + switch (_waitFor) + { + case WaitForServiceTypes.Wmi: + waitComplete = (winrmTestList.Count == _waitOnComputers.Count); + machineCompleteRestart = winrmTestList.Count; + break; + case WaitForServiceTypes.WinRM: + waitComplete = (psTestList.Count == _waitOnComputers.Count); + machineCompleteRestart = psTestList.Count; + break; + case WaitForServiceTypes.PowerShell: + waitComplete = (allDoneList.Count == _waitOnComputers.Count); + machineCompleteRestart = allDoneList.Count; + break; + } + + // Wait is done or time is up + if (waitComplete || _exit) + { + if (waitComplete) + { + _status = ComputerResources.RestartComplete; + WriteProgress(_indicator[indicatorIndex % 4] + _activity, _status, 100, ProgressRecordType.Completed); + _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); + } + + break; + } + + if (_waitOnComputers.Count > 1) + { + _status = StringUtil.Format(ComputerResources.WaitForMultipleComputers, machineCompleteRestart, _waitOnComputers.Count); + _percent = machineCompleteRestart * 100 / _waitOnComputers.Count; + } + } + + if (_timeUp) + { + // The timeout expires. Write out timeout error messages for the computers that haven't finished restarting + do + { + if (restartStageTestList.Count > 0) + { + WriteOutTimeoutError(restartStageTestList); + } + + if (wmiTestList.Count > 0) + { + WriteOutTimeoutError(wmiTestList); + } + + // Wait for WMI. All computers that finished restarting are put in "winrmTestList" + if (isForWmi) + { + break; + } + + // Wait for WinRM. All computers that finished restarting are put in "psTestList" + if (winrmTestList.Count > 0) + { + WriteOutTimeoutError(winrmTestList); + } + + if (isForWinRm) + { + break; + } + + if (psTestList.Count > 0) + { + WriteOutTimeoutError(psTestList); + } + + // Wait for PowerShell. All computers that finished restarting are put in "allDoneList" + } while (false); + } + } + } + } + + /// + /// To implement ^C. + /// + protected override void StopProcessing() + { + _exit = true; + _cancel.Cancel(); + _waitHandler.Set(); + + _timer?.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); + + if (_powershell != null) + { + _powershell.Stop(); + _powershell.Dispose(); + } + } + + #endregion "Overrides" + } + + #endregion Restart-Computer + + #region Stop-Computer + + /// + /// Cmdlet to stop computer. + /// + [Cmdlet(VerbsLifecycle.Stop, "Computer", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097151", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class StopComputerCommand : PSCmdlet, IDisposable + { + #region Private Members + + private readonly CancellationTokenSource _cancel = new(); + + private const int forcedShutdown = 5; // See https://msdn.microsoft.com/library/aa394058(v=vs.85).aspx + + #endregion + + #region "Parameters" + + /// + /// The authentication options for CIM_WSMan connection. + /// + [Parameter] + [ValidateSet( + "Default", + "Basic", + "Negotiate", // can be used with and without credential (without -> PSRP mapped to NegotiateWithImplicitCredential) + "CredSSP", + "Digest", + "Kerberos")] // can be used with explicit or implicit credential + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public string WsmanAuthentication { get; set; } = "Default"; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Value of the address requested. The form of the value can be either the + /// computer name ("wxyz1234"), IPv4 address ("192.168.177.124"), or IPv6 + /// address ("2010:836B:4179::836B:4179"). + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [Alias("CN", "__SERVER", "Server", "IPAddress")] + public string[] ComputerName { get; set; } = new string[] { "." }; + + /// + /// The following is the definition of the input parameter "Credential". + /// Specifies a user account that has permission to perform this action. Type a + /// user-name, such as "User01" or "Domain01\User01", or enter a PSCredential + /// object, such as one from the Get-Credential cmdlet. + /// + [Parameter(Position = 1)] + [ValidateNotNullOrEmpty] + [Credential] + public PSCredential Credential { get; set; } + + /// + /// Force the operation to take place if possible. + /// + [Parameter] + public SwitchParameter Force { get; set; } = false; + + #endregion "parameters" + + #region "IDisposable Members" + + /// + /// Dispose Method. + /// + public void Dispose() + { + _cancel.Dispose(); + } + + #endregion "IDisposable Members" + + #region "Overrides" + + /// + /// ProcessRecord. + /// + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] + protected override void ProcessRecord() + { + object[] flags = new object[] { 1, 0 }; + if (Force.IsPresent) + flags[0] = forcedShutdown; + + ProcessWSManProtocol(flags); + } + + /// + /// To implement ^C. + /// + protected override void StopProcessing() + { + try + { + _cancel.Cancel(); + } + catch (ObjectDisposedException) { } + catch (AggregateException) { } + } + + #endregion "Overrides" + + #region Private Methods + + private void ProcessWSManProtocol(object[] flags) + { + foreach (string computer in ComputerName) + { + string compname = string.Empty; + string strLocal = string.Empty; + bool isLocalHost = false; + + if (_cancel.Token.IsCancellationRequested) + { + break; + } + + if ((computer.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (computer.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + compname = Dns.GetHostName(); + strLocal = "localhost"; + isLocalHost = true; + } + else + { + compname = computer; + } + + if (!ShouldProcess(StringUtil.Format(ComputerResources.DoubleComputerName, strLocal, compname))) + { + continue; + } + else + { + ComputerWMIHelper.InvokeWin32ShutdownUsingWsman( + this, + isLocalHost, + compname, + flags, + Credential, + WsmanAuthentication, + ComputerResources.StopcomputerFailed, + "StopComputerException", + _cancel.Token); + } + } + } + + #endregion + } + + #endregion + + #region Rename-Computer + + /// + /// Renames a domain computer and its corresponding domain account or a + /// workgroup computer. Use this command to rename domain workstations and local + /// machines only. It cannot be used to rename Domain Controllers. + /// + [Cmdlet(VerbsCommon.Rename, "Computer", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097054", RemotingCapability = RemotingCapability.SupportedByCommand)] + [OutputType(typeof(RenameComputerChangeInfo))] + public class RenameComputerCommand : PSCmdlet + { + #region Private Members + + private bool _containsLocalHost = false; + private string _newNameForLocalHost = null; + + private readonly string _shortLocalMachineName = Dns.GetHostName(); + private readonly string _fullLocalMachineName = Dns.GetHostEntryAsync(string.Empty).Result.HostName; + + #endregion + + #region Parameters + + /// + /// Target computers to rename. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string ComputerName { get; set; } = "localhost"; + + /// + /// Emit the output. + /// + // [Alias("Restart")] + [Parameter] + public SwitchParameter PassThru { get; set; } + + /// + /// The domain credential of the domain the target computer joined. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Credential] + public PSCredential DomainCredential { get; set; } + + /// + /// The administrator credential of the target computer. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Credential] + public PSCredential LocalCredential { get; set; } + + /// + /// New names for the target computers. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string NewName { get; set; } + + /// + /// Suppress the ShouldContinue. + /// + [Parameter] + public SwitchParameter Force + { + get { return _force; } + + set { _force = value; } + } + + private bool _force; + + /// + /// To restart the target computer after rename it. + /// + [Parameter] + public SwitchParameter Restart + { + get { return _restart; } + + set { _restart = value; } + } + + private bool _restart; + + /// + /// The authentication options for CIM_WSMan connection. + /// + [Parameter] + [ValidateSet( + "Default", + "Basic", + "Negotiate", // can be used with and without credential (without -> PSRP mapped to NegotiateWithImplicitCredential) + "CredSSP", + "Digest", + "Kerberos")] // can be used with implicit or explicit credential + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public string WsmanAuthentication { get; set; } = "Default"; + + #endregion + + #region "Private Methods" + + /// + /// Check to see if the target computer is the local machine. + /// + private string ValidateComputerName() + { + // Validate target name. + ErrorRecord targetError = null; + string targetComputer = ComputerWMIHelper.ValidateComputerName(ComputerName, _shortLocalMachineName, _fullLocalMachineName, ref targetError); + if (targetComputer == null) + { + if (targetError != null) + { + WriteError(targetError); + } + + return null; + } + + // Validate *new* name. Validate the format of the new name. Check if the old name is the same as the + // new name later. + if (!ComputerWMIHelper.IsComputerNameValid(NewName)) + { + bool isLocalhost = targetComputer.Equals(ComputerWMIHelper.localhostStr, StringComparison.OrdinalIgnoreCase); + string errMsg = StringUtil.Format(ComputerResources.InvalidNewName, isLocalhost ? _shortLocalMachineName : targetComputer, NewName); + ErrorRecord error = new( + new InvalidOperationException(errMsg), "InvalidNewName", + ErrorCategory.InvalidArgument, NewName); + WriteError(error); + return null; + } + + return targetComputer; + } + + private void DoRenameComputerAction(string computer, string newName, bool isLocalhost) + { + string computerName = isLocalhost ? _shortLocalMachineName : computer; + + if (!ShouldProcess(computerName)) + { + return; + } + + // Check the length of the new name + if (newName != null && newName.Length > ComputerWMIHelper.NetBIOSNameMaxLength) + { + string truncatedName = newName.Substring(0, ComputerWMIHelper.NetBIOSNameMaxLength); + string query = StringUtil.Format(ComputerResources.TruncateNetBIOSName, truncatedName); + string caption = ComputerResources.TruncateNetBIOSNameCaption; + if (!Force && !ShouldContinue(query, caption)) + { + return; + } + } + + DoRenameComputerWsman(computer, computerName, newName, isLocalhost); + } + + private void DoRenameComputerWsman(string computer, string computerName, string newName, bool isLocalhost) + { + bool successful = false; + int retVal; + PSCredential credToUse = isLocalhost ? null : (LocalCredential ?? DomainCredential); + + try + { + using (CancellationTokenSource cancelTokenSource = new()) + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credToUse, WsmanAuthentication, isLocalhost, this, cancelTokenSource.Token)) + { + var operationOptions = new CimOperationOptions + { + Timeout = TimeSpan.FromMilliseconds(10000), + CancellationToken = cancelTokenSource.Token, + // This prefix works against all versions of the WinRM server stack, both win8 and win7 + ResourceUriPrefix = new Uri(ComputerWMIHelper.CimUriPrefix) + }; + + IEnumerable mCollection = cimSession.QueryInstances( + ComputerWMIHelper.CimOperatingSystemNamespace, + ComputerWMIHelper.CimQueryDialect, + "Select * from " + ComputerWMIHelper.WMI_Class_ComputerSystem, + operationOptions); + + foreach (CimInstance cimInstance in mCollection) + { + var oldName = cimInstance.CimInstanceProperties["DNSHostName"].Value.ToString(); + if (oldName.Equals(newName, StringComparison.OrdinalIgnoreCase)) + { + string errMsg = StringUtil.Format(ComputerResources.NewNameIsOldName, computerName, newName); + ErrorRecord error = new( + new InvalidOperationException(errMsg), "NewNameIsOldName", + ErrorCategory.InvalidArgument, newName); + WriteError(error); + + continue; + } + + // If the target computer is in a domain, always use the DomainCred. If the DomainCred is not given, + // use null for UserName and Password, so the context of the caller will be used. + // If the target computer is not in a domain, just use null for the UserName and Password + string dUserName = null; + string dPassword = null; + if (((bool)cimInstance.CimInstanceProperties["PartOfDomain"].Value) && (DomainCredential != null)) + { + dUserName = DomainCredential.UserName; + dPassword = Utils.GetStringFromSecureString(DomainCredential.Password); + } + + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create( + "Name", + newName, + Microsoft.Management.Infrastructure.CimType.String, + CimFlags.None)); + + methodParameters.Add(CimMethodParameter.Create( + "UserName", + dUserName, + Microsoft.Management.Infrastructure.CimType.String, + (dUserName == null) ? CimFlags.NullValue : CimFlags.None)); + + methodParameters.Add( + CimMethodParameter.Create( + "Password", + dPassword, + Microsoft.Management.Infrastructure.CimType.String, + (dPassword == null) ? CimFlags.NullValue : CimFlags.None)); + + if (!InternalTestHooks.TestRenameComputer) + { + CimMethodResult result = cimSession.InvokeMethod( + ComputerWMIHelper.CimOperatingSystemNamespace, + cimInstance, + "Rename", + methodParameters, + operationOptions); + + retVal = Convert.ToInt32(result.ReturnValue.Value, CultureInfo.CurrentCulture); + } + else + { + retVal = InternalTestHooks.TestRenameComputerResults; + } + + if (retVal != 0) + { + var ex = new Win32Exception(retVal); + string errMsg = StringUtil.Format(ComputerResources.FailToRename, computerName, newName, ex.Message); + ErrorRecord error = new(new InvalidOperationException(errMsg), "FailToRenameComputer", ErrorCategory.OperationStopped, computerName); + WriteError(error); + } + else + { + successful = true; + } + + if (PassThru) + { + WriteObject(ComputerWMIHelper.GetRenameComputerStatusObject(retVal, newName, computerName)); + } + + if (successful) + { + if (_restart) + { + // If successful and the Restart parameter is specified, restart the computer + object[] flags = new object[] { 6, 0 }; + ComputerWMIHelper.InvokeWin32ShutdownUsingWsman( + this, + isLocalhost, + computerName, + flags, + credToUse, + WsmanAuthentication, + ComputerResources.RestartcomputerFailed, + "RestartcomputerFailed", + cancelTokenSource.Token); + } + else + { + WriteWarning(StringUtil.Format(ComputerResources.RestartNeeded, null, computerName)); + } + } + } + } + } + catch (CimException ex) + { + string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message); + ErrorRecord error = new(new InvalidOperationException(errMsg), "RenameComputerException", + ErrorCategory.OperationStopped, computerName); + WriteError(error); + } + catch (Exception ex) + { + string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message); + ErrorRecord error = new(new InvalidOperationException(errMsg), "RenameComputerException", + ErrorCategory.OperationStopped, computerName); + WriteError(error); + } + } + + #endregion "Private Methods" + + #region "Override Methods" + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + string targetComputer = ValidateComputerName(); + if (targetComputer == null) + { + return; + } + + bool isLocalhost = targetComputer.Equals("localhost", StringComparison.OrdinalIgnoreCase); + if (isLocalhost) + { + if (!_containsLocalHost) + _containsLocalHost = true; + _newNameForLocalHost = NewName; + + return; + } + + DoRenameComputerAction(targetComputer, NewName, false); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (!_containsLocalHost) + { + return; + } + + DoRenameComputerAction("localhost", _newNameForLocalHost, true); + } + + #endregion "Override Methods" + } + + #endregion Rename-Computer + + #region "Public API" + /// + /// The object returned by SAM Computer cmdlets representing the status of the target machine. + /// + public sealed class ComputerChangeInfo + { + private const string MatchFormat = "{0}:{1}"; + + /// + /// The HasSucceeded which shows the operation was success or not. + /// + public bool HasSucceeded { get; set; } + + /// + /// The ComputerName on which the operation is done. + /// + public string ComputerName { get; set; } + + /// + /// Returns the string representation of this object. + /// + /// + public override string ToString() + { + return FormatLine(this.HasSucceeded.ToString(), this.ComputerName); + } + + /// + /// Formats a line for use in ToString. + /// + /// + /// + /// + private static string FormatLine(string HasSucceeded, string computername) + { + return StringUtil.Format(MatchFormat, HasSucceeded, computername); + } + } + + /// + /// The object returned by Rename-Computer cmdlet representing the status of the target machine. + /// + public sealed class RenameComputerChangeInfo + { + private const string MatchFormat = "{0}:{1}:{2}"; + + /// + /// The status which shows the operation was success or failure. + /// + public bool HasSucceeded { get; set; } + + /// + /// The NewComputerName which represents the target machine. + /// + public string NewComputerName { get; set; } + + /// + /// The OldComputerName which represented the target machine. + /// + public string OldComputerName { get; set; } + + /// + /// Returns the string representation of this object. + /// + /// + public override string ToString() + { + return FormatLine(this.HasSucceeded.ToString(), this.NewComputerName, this.OldComputerName); + } + + /// + /// Formats a line for use in ToString. + /// + /// + /// + /// + /// + private static string FormatLine(string HasSucceeded, string newcomputername, string oldcomputername) + { + return StringUtil.Format(MatchFormat, HasSucceeded, newcomputername, oldcomputername); + } + } + #endregion "Public API" + + #region Helper + /// + /// Helper Class used by Stop-Computer,Restart-Computer and Test-Connection + /// Also Contain constants used by System Restore related Cmdlets. + /// + internal static class ComputerWMIHelper + { + /// + /// The maximum length of a valid NetBIOS name. + /// + internal const int NetBIOSNameMaxLength = 15; + + /// + /// System Restore Class used by Cmdlets. + /// + internal const string WMI_Class_SystemRestore = "SystemRestore"; + + /// + /// OperatingSystem WMI class used by Cmdlets. + /// + internal const string WMI_Class_OperatingSystem = "Win32_OperatingSystem"; + + /// + /// Service WMI class used by Cmdlets. + /// + internal const string WMI_Class_Service = "Win32_Service"; + + /// + /// Win32_ComputerSystem WMI class used by Cmdlets. + /// + internal const string WMI_Class_ComputerSystem = "Win32_ComputerSystem"; + + /// + /// Ping Class used by Cmdlet. + /// + internal const string WMI_Class_PingStatus = "Win32_PingStatus"; + + /// + /// CIMV2 path. + /// + internal const string WMI_Path_CIM = "\\root\\cimv2"; + + /// + /// Default path. + /// + internal const string WMI_Path_Default = "\\root\\default"; + + /// + /// The error says The interface is unknown. + /// + internal const int ErrorCode_Interface = 1717; + + /// + /// This error says An instance of the service is already running. + /// + internal const int ErrorCode_Service = 1056; + + /// + /// The name of the privilege to shutdown a local system. + /// + internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; + + /// + /// The name of the privilege to shutdown a remote system. + /// + internal const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"; + + /// + /// CimUriPrefix. + /// + internal const string CimUriPrefix = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2"; + + /// + /// CimOperatingSystemNamespace. + /// + internal const string CimOperatingSystemNamespace = "root/cimv2"; + + /// + /// CimOperatingSystemShutdownMethod. + /// + internal const string CimOperatingSystemShutdownMethod = "Win32shutdown"; + + /// + /// CimQueryDialect. + /// + internal const string CimQueryDialect = "WQL"; + + /// + /// Local host name. + /// + internal const string localhostStr = "localhost"; + + /// + /// Get the local admin user name from a local NetworkCredential. + /// + /// + /// + /// + internal static string GetLocalAdminUserName(string computerName, PSCredential psLocalCredential) + { + string localUserName = null; + + // The format of local admin username should be "ComputerName\AdminName" + if (psLocalCredential.UserName.Contains('\\')) + { + localUserName = psLocalCredential.UserName; + } + else + { + int dotIndex = computerName.IndexOf('.'); + if (dotIndex == -1) + { + localUserName = computerName + "\\" + psLocalCredential.UserName; + } + else + { + localUserName = string.Concat(computerName.AsSpan(0, dotIndex), "\\", psLocalCredential.UserName); + } + } + + return localUserName; + } + + /// + /// Generate a random password. + /// + /// + /// + internal static string GetRandomPassword(int passwordLength) + { + const int charMin = 32, charMax = 122; + const int allowedCharsCount = charMax - charMin + 1; + byte[] randomBytes = new byte[passwordLength]; + char[] chars = new char[passwordLength]; + + RandomNumberGenerator rng = RandomNumberGenerator.Create(); + rng.GetBytes(randomBytes); + + for (int i = 0; i < passwordLength; i++) + { + chars[i] = (char)(randomBytes[i] % allowedCharsCount + charMin); + } + + return new string(chars); + } + + /// + /// Gets the Scope. + /// + /// + /// + /// + internal static string GetScopeString(string computer, string namespaceParameter) + { + StringBuilder returnValue = new("\\\\"); + if (computer.Equals("::1", StringComparison.OrdinalIgnoreCase) || computer.Equals("[::1]", StringComparison.OrdinalIgnoreCase)) + { + returnValue.Append("localhost"); + } + else + { + returnValue.Append(computer); + } + + returnValue.Append(namespaceParameter); + return returnValue.ToString(); + } + + /// + /// Returns true if it is a valid drive on the system. + /// + /// + /// + internal static bool IsValidDrive(string drive) + { + DriveInfo[] drives = DriveInfo.GetDrives(); + foreach (DriveInfo logicalDrive in drives) + { + if (logicalDrive.DriveType.Equals(DriveType.Fixed)) + { + if (drive.Equals(logicalDrive.Name, System.StringComparison.OrdinalIgnoreCase)) + return true; + } + } + + return false; + } + + /// + /// Checks whether string[] contains System Drive. + /// + /// + /// + /// + internal static bool ContainsSystemDrive(string[] drives, string sysdrive) + { + string driveApp; + foreach (string drive in drives) + { + if (!drive.EndsWith('\\')) + { + driveApp = string.Concat(drive, "\\"); + } + else + driveApp = drive; + if (driveApp.Equals(sysdrive, StringComparison.OrdinalIgnoreCase)) + return true; + } + + return false; + } + + /// + /// Returns the given computernames in a string. + /// + /// + internal static string GetMachineNames(string[] computerNames) + { + string separator = ","; + RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\International"); + if (regKey != null) + { + object sListValue = regKey.GetValue("sList"); + if (sListValue != null) + { + separator = sListValue.ToString(); + } + } + + string compname = string.Empty; + StringBuilder strComputers = new(); + int i = 0; + foreach (string computer in computerNames) + { + if (i > 0) + { + strComputers.Append(separator); + } + else + { + i++; + } + + if ((computer.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (computer.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + compname = Dns.GetHostName(); + } + else + { + compname = computer; + } + + strComputers.Append(compname); + } + + return strComputers.ToString(); + } + + internal static ComputerChangeInfo GetComputerStatusObject(int errorcode, string computername) + { + ComputerChangeInfo computerchangeinfo = new(); + computerchangeinfo.ComputerName = computername; + if (errorcode != 0) + { + computerchangeinfo.HasSucceeded = false; + } + else + { + computerchangeinfo.HasSucceeded = true; + } + + return computerchangeinfo; + } + + internal static RenameComputerChangeInfo GetRenameComputerStatusObject(int errorcode, string newcomputername, string oldcomputername) + { + RenameComputerChangeInfo renamecomputerchangeinfo = new(); + renamecomputerchangeinfo.OldComputerName = oldcomputername; + renamecomputerchangeinfo.NewComputerName = newcomputername; + if (errorcode != 0) + { + renamecomputerchangeinfo.HasSucceeded = false; + } + else + { + renamecomputerchangeinfo.HasSucceeded = true; + } + + return renamecomputerchangeinfo; + } + + internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, string computername) + { + Win32Exception ex = new(errorcode); + string additionalmessage = string.Empty; + if (ex.NativeErrorCode.Equals(0x00000035)) + { + additionalmessage = StringUtil.Format(ComputerResources.NetworkPathNotFound, computername); + } + + string message = StringUtil.Format(ComputerResources.OperationFailed, ex.Message, computername, additionalmessage); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, computername); + cmdlet.WriteError(er); + } + + /// + /// Check whether the new computer name is valid. + /// + /// + /// + internal static bool IsComputerNameValid(string computerName) + { + bool hasAsciiLetterOrHyphen = false; + + if (computerName.Length >= 64) + return false; + + foreach (char t in computerName) + { + if (char.IsAsciiLetter(t) || t is '-') + { + hasAsciiLetterOrHyphen = true; + } + else if (!char.IsAsciiDigit(t)) + { + return false; + } + } + + return hasAsciiLetterOrHyphen; + } + + /// + /// Invokes the Win32Shutdown command on provided target computer using WSMan + /// over a CIMSession. The flags parameter determines the type of shutdown operation + /// such as shutdown, reboot, force etc. + /// + /// Cmdlet host for reporting errors. + /// True if local host computer. + /// Target computer. + /// Win32Shutdown flags. + /// Optional credential. + /// Optional authentication. + /// Error message format string that takes two parameters. + /// Fully qualified error Id. + /// Cancel token. + /// True on success. + internal static bool InvokeWin32ShutdownUsingWsman( + PSCmdlet cmdlet, + bool isLocalhost, + string computerName, + object[] flags, + PSCredential credential, + string authentication, + string formatErrorMessage, + string ErrorFQEID, + CancellationToken cancelToken) + { + Dbg.Diagnostics.Assert(flags.Length == 2, "Caller need to verify the flags passed in"); + + bool isSuccess = false; + string targetMachine = isLocalhost ? "localhost" : computerName; + string authInUse = isLocalhost ? null : authentication; + PSCredential credInUse = isLocalhost ? null : credential; + var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); + var operationOptions = new CimOperationOptions + { + Timeout = TimeSpan.FromMilliseconds(10000), + CancellationToken = cancelToken, + // This prefix works against all versions of the WinRM server stack, both win8 and win7 + ResourceUriPrefix = new Uri(ComputerWMIHelper.CimUriPrefix) + }; + + try + { + if (!(isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) && + !(!isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState))) + { + string message = + StringUtil.Format(ComputerResources.PrivilegeNotEnabled, computerName, + isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME); + ErrorRecord errorRecord = new(new InvalidOperationException(message), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null); + cmdlet.WriteError(errorRecord); + return false; + } + + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(targetMachine, credInUse, authInUse, isLocalhost, cmdlet, cancelToken)) + { + var methodParameters = new CimMethodParametersCollection(); + int retVal; + methodParameters.Add(CimMethodParameter.Create( + "Flags", + flags[0], + Microsoft.Management.Infrastructure.CimType.SInt32, + CimFlags.None)); + + methodParameters.Add(CimMethodParameter.Create( + "Reserved", + flags[1], + Microsoft.Management.Infrastructure.CimType.SInt32, + CimFlags.None)); + + if (!InternalTestHooks.TestStopComputer) + { + CimMethodResult result = null; + + if (isLocalhost) + { + // Win32_ComputerSystem is a singleton hence FirstOrDefault() return the only instance returned by EnumerateInstances. + var computerSystem = cimSession.EnumerateInstances(ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.WMI_Class_OperatingSystem).FirstOrDefault(); + + result = cimSession.InvokeMethod( + ComputerWMIHelper.CimOperatingSystemNamespace, + computerSystem, + ComputerWMIHelper.CimOperatingSystemShutdownMethod, + methodParameters, + operationOptions); + } + else + { + result = cimSession.InvokeMethod( + ComputerWMIHelper.CimOperatingSystemNamespace, + ComputerWMIHelper.WMI_Class_OperatingSystem, + ComputerWMIHelper.CimOperatingSystemShutdownMethod, + methodParameters, + operationOptions); + } + + retVal = Convert.ToInt32(result.ReturnValue.Value, CultureInfo.CurrentCulture); + } + else + { + retVal = InternalTestHooks.TestStopComputerResults; + } + + if (retVal != 0) + { + var ex = new Win32Exception(retVal); + string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); + ErrorRecord error = new( + new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); + cmdlet.WriteError(error); + } + else + { + isSuccess = true; + } + } + } + catch (CimException ex) + { + string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); + ErrorRecord error = new(new InvalidOperationException(errMsg), ErrorFQEID, + ErrorCategory.OperationStopped, computerName); + cmdlet.WriteError(error); + } + catch (Exception ex) + { + string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); + ErrorRecord error = new(new InvalidOperationException(errMsg), ErrorFQEID, + ErrorCategory.OperationStopped, computerName); + cmdlet.WriteError(error); + } + finally + { + // Restore the previous privilege state if something unexpected happened + PlatformInvokes.RestoreTokenPrivilege( + isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState); + } + + return isSuccess; + } + + /// + /// Returns valid computer name or null on failure. + /// + /// Computer name to validate. + /// + /// + /// + /// Valid computer name. + internal static string ValidateComputerName( + string nameToCheck, + string shortLocalMachineName, + string fullLocalMachineName, + ref ErrorRecord error) + { + string validatedComputerName = null; + + if (nameToCheck.Equals(".", StringComparison.OrdinalIgnoreCase) || + nameToCheck.Equals(localhostStr, StringComparison.OrdinalIgnoreCase) || + nameToCheck.Equals(shortLocalMachineName, StringComparison.OrdinalIgnoreCase) || + nameToCheck.Equals(fullLocalMachineName, StringComparison.OrdinalIgnoreCase)) + { + validatedComputerName = localhostStr; + } + else + { + bool isIPAddress = false; + try + { + isIPAddress = IPAddress.TryParse(nameToCheck, out _); + } + catch (Exception) + { + } + + try + { + string fqcn = Dns.GetHostEntryAsync(nameToCheck).Result.HostName; + if (fqcn.Equals(shortLocalMachineName, StringComparison.OrdinalIgnoreCase) || + fqcn.Equals(fullLocalMachineName, StringComparison.OrdinalIgnoreCase)) + { + // The IPv4 or IPv6 of the local machine is specified + validatedComputerName = localhostStr; + } + else + { + validatedComputerName = nameToCheck; + } + } + catch (Exception e) + { + // If GetHostEntry() throw exception, then the target should not be the local machine + if (!isIPAddress) + { + // Return error if the computer name is not an IP address. Dns.GetHostEntry() may not work on IP addresses. + string errMsg = StringUtil.Format(ComputerResources.CannotResolveComputerName, nameToCheck, e.Message); + error = new ErrorRecord( + new InvalidOperationException(errMsg), "AddressResolutionException", + ErrorCategory.InvalidArgument, nameToCheck); + + return null; + } + + validatedComputerName = nameToCheck; + } + } + + return validatedComputerName; + } + } + #endregion Helper +} + +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs new file mode 100644 index 0000000000000000000000000000000000000000..22092116330dcd366189e14a61872c09f4c5f07a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if UNIX + +using System; +using System.Diagnostics; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Runtime.InteropServices; + +#nullable enable + +namespace Microsoft.PowerShell.Commands +{ +#region Restart-Computer + + /// + /// Cmdlet to restart computer. + /// + [Cmdlet(VerbsLifecycle.Restart, "Computer", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097060", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class RestartComputerCommand : CommandLineCmdletBase + { + // TODO: Support remote computers? + +#region "Overrides" + + /// + /// BeginProcessing. + /// + protected override void BeginProcessing() + { + if (InternalTestHooks.TestStopComputer) + { + var retVal = InternalTestHooks.TestStopComputerResults; + if (retVal != 0) + { + string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal); + ErrorRecord error = new ErrorRecord( + new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost"); + WriteError(error); + } + return; + } + + RunShutdown("-r now"); + } +#endregion "Overrides" + } +#endregion Restart-Computer + +#region Stop-Computer + + /// + /// Cmdlet to stop computer. + /// + [Cmdlet(VerbsLifecycle.Stop, "Computer", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097151", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class StopComputerCommand : CommandLineCmdletBase + { + // TODO: Support remote computers? + +#region "Overrides" + + /// + /// BeginProcessing. + /// + protected override void BeginProcessing() + { + var args = "-P now"; + if (Platform.IsMacOS) + { + args = "now"; + } + if (InternalTestHooks.TestStopComputer) + { + var retVal = InternalTestHooks.TestStopComputerResults; + if (retVal != 0) + { + string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal); + ErrorRecord error = new ErrorRecord( + new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost"); + WriteError(error); + } + return; + } + + RunShutdown(args); + } +#endregion "Overrides" + } + + /// + /// A base class for cmdlets that can run shell commands. + /// + public class CommandLineCmdletBase : PSCmdlet, IDisposable + { +#region Private Members + private Process? _process = null; +#endregion + +#region "IDisposable Members" + + /// + /// Releases all resources used by the . + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases the unmanaged resources used by the + /// and optionally releases the managed resources. + /// + /// + /// to release both managed and unmanaged resources; + /// to release only unmanaged resources. + /// + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + _process?.Dispose(); + } + } + +#endregion "IDisposable Members" + +#region "Overrides" + /// + /// To implement ^C. + /// + protected override void StopProcessing() + { + if (_process == null) { + return; + } + + try { + if (!_process.HasExited) { + _process.Kill(); + } + WriteObject(_process.ExitCode); + } + catch (InvalidOperationException) {} + catch (NotSupportedException) {} + } +#endregion "Overrides" + +#region "Internals" + + private static string? shutdownPath; + + /// + /// Run shutdown command. + /// + protected void RunShutdown(string args) + { + if (shutdownPath is null) + { + CommandInfo cmdinfo = CommandDiscovery.LookupCommandInfo( + "shutdown", CommandTypes.Application, + SearchResolutionOptions.None, CommandOrigin.Internal, this.Context); + + if (cmdinfo is not null) + { + shutdownPath = cmdinfo.Definition; + } + else + { + ErrorRecord error = new ErrorRecord( + new InvalidOperationException(ComputerResources.ShutdownCommandNotFound), "CommandNotFound", ErrorCategory.ObjectNotFound, targetObject: null); + ThrowTerminatingError(error); + } + } + + _process = new Process() + { + StartInfo = new ProcessStartInfo + { + FileName = shutdownPath, + Arguments = string.Empty, + RedirectStandardOutput = false, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + } + }; + _process.Start(); + _process.WaitForExit(); + if (_process.ExitCode != 0) + { + string stderr = _process.StandardError.ReadToEnd(); + ErrorRecord error = new ErrorRecord( + new InvalidOperationException(stderr), "CommandFailed", ErrorCategory.OperationStopped, null); + ThrowTerminatingError(error); + } + } +#endregion + } +#endregion +} +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..e7b3ada4ebb85ff94ce987dd4521d66e41839922 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -0,0 +1,707 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Provider; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The base class for the */content commands. + /// + public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string[] Path { get; set; } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return Path; + } + + set + { + base.SuppressWildcardExpansion = true; + Path = value; + } + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get { return base.Filter; } + + set { base.Filter = value; } + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get { return base.Include; } + + set { base.Include = value; } + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get { return base.Exclude; } + + set { base.Exclude = value; } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get { return base.Force; } + + set { base.Force = value; } + } + + #endregion Parameters + + #region parameter data + + #endregion parameter data + + #region protected members + + /// + /// An array of content holder objects that contain the path information + /// and content readers/writers for the item represented by the path information. + /// + internal List contentStreams = new(); + + /// + /// Wraps the content into a PSObject and adds context information as notes. + /// + /// + /// The content being written out. + /// + /// + /// The number of blocks that have been read so far. + /// + /// + /// The context the content was retrieved from. + /// + /// + /// The context the command is being run under. + /// + internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context) + { + Dbg.Diagnostics.Assert( + content != null, + "The caller should verify the content."); + + Dbg.Diagnostics.Assert( + pathInfo != null, + "The caller should verify the pathInfo."); + + Dbg.Diagnostics.Assert( + context != null, + "The caller should verify the context."); + + PSObject result = PSObject.AsPSObject(content); + + Dbg.Diagnostics.Assert( + result != null, + "A PSObject should always be constructed."); + + // Use the cached notes if the cache exists and the path is still the same + PSNoteProperty note; + + if (_currentContentItem != null && + ((_currentContentItem.PathInfo == pathInfo) || + string.Equals( + pathInfo.Path, + _currentContentItem.PathInfo.Path, + StringComparison.OrdinalIgnoreCase))) + { + result = _currentContentItem.AttachNotes(result); + } + else + { + // Generate a new cache item and cache the notes + + _currentContentItem = new ContentPathsCache(pathInfo); + + // Construct a provider qualified path as the Path note + string psPath = pathInfo.Path; + note = new PSNoteProperty("PSPath", psPath); + result.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath); + _currentContentItem.PSPath = psPath; + + try + { + // Now get the parent path and child name + + string parentPath = null; + + if (pathInfo.Drive != null) + { + parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context); + } + else + { + parentPath = SessionState.Path.ParseParent(pathInfo.Path, string.Empty, context); + } + + note = new PSNoteProperty("PSParentPath", parentPath); + result.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); + _currentContentItem.ParentPath = parentPath; + + // Get the child name + + string childName = SessionState.Path.ParseChildName(pathInfo.Path, context); + note = new PSNoteProperty("PSChildName", childName); + result.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); + _currentContentItem.ChildName = childName; + } + catch (NotSupportedException) + { + // Ignore. The object just won't have ParentPath or ChildName set. + } + + // PSDriveInfo + + if (pathInfo.Drive != null) + { + PSDriveInfo drive = pathInfo.Drive; + note = new PSNoteProperty("PSDrive", drive); + result.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive); + _currentContentItem.Drive = drive; + } + + // ProviderInfo + + ProviderInfo provider = pathInfo.Provider; + note = new PSNoteProperty("PSProvider", provider); + result.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider); + _currentContentItem.Provider = provider; + } + + // Add the ReadCount note + note = new PSNoteProperty("ReadCount", readCount); + result.Properties.Add(note, true); + + WriteObject(result); + } + + /// + /// A cache of the notes that get added to the content items as they are written + /// to the pipeline. + /// + private ContentPathsCache _currentContentItem; + + /// + /// A class that stores a cache of the notes that get attached to content items + /// as they get written to the pipeline. An instance of this cache class is + /// only valid for a single path. + /// + internal sealed class ContentPathsCache + { + /// + /// Constructs a content cache item. + /// + /// + /// The path information for which the cache will be bound. + /// + public ContentPathsCache(PathInfo pathInfo) + { + PathInfo = pathInfo; + } + + /// + /// The path information for the cached item. + /// + public PathInfo PathInfo { get; } + + /// + /// The cached PSPath of the item. + /// + public string PSPath { get; set; } + + /// + /// The cached parent path of the item. + /// + public string ParentPath { get; set; } + + /// + /// The cached drive for the item. + /// + public PSDriveInfo Drive { get; set; } + + /// + /// The cached provider of the item. + /// + public ProviderInfo Provider { get; set; } + + /// + /// The cached child name of the item. + /// + public string ChildName { get; set; } + + /// + /// Attaches the cached notes to the specified PSObject. + /// + /// + /// The PSObject to attached the cached notes to. + /// + /// + /// The PSObject that was passed in with the cached notes added. + /// + public PSObject AttachNotes(PSObject content) + { + // Construct a provider qualified path as the Path note + + PSNoteProperty note = new("PSPath", PSPath); + content.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath); + + // Now attach the parent path and child name + + note = new PSNoteProperty("PSParentPath", ParentPath); + content.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", ParentPath); + + // Attach the child name + + note = new PSNoteProperty("PSChildName", ChildName); + content.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSChildName", ChildName); + + // PSDriveInfo + + if (PathInfo.Drive != null) + { + note = new PSNoteProperty("PSDrive", Drive); + content.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSDrive", Drive); + } + + // ProviderInfo + + note = new PSNoteProperty("PSProvider", Provider); + content.Properties.Add(note, true); + tracer.WriteLine("Attaching {0} = {1}", "PSProvider", Provider); + + return content; + } + } + + /// + /// A struct to hold the path information and the content readers/writers + /// for an item. + /// + internal readonly struct ContentHolder + { + internal ContentHolder( + PathInfo pathInfo, + IContentReader reader, + IContentWriter writer) + { + if (pathInfo == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(pathInfo)); + } + + PathInfo = pathInfo; + Reader = reader; + Writer = writer; + } + + internal PathInfo PathInfo { get; } + + internal IContentReader Reader { get; } + + internal IContentWriter Writer { get; } + } + + /// + /// Closes the content readers and writers in the content holder array. + /// + internal void CloseContent(List contentHolders, bool disposing) + { + if (contentHolders == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(contentHolders)); + } + + foreach (ContentHolder holder in contentHolders) + { + try + { + holder.Writer?.Close(); + } + catch (Exception e) // Catch-all OK. 3rd party callout + { + // Catch all the exceptions caused by closing the writer + // and write out an error. + + ProviderInvocationException providerException = + new( + "ProviderContentCloseError", + SessionStateStrings.ProviderContentCloseError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + + MshLog.LogProviderHealthEvent( + this.Context, + holder.PathInfo.Provider.Name, + providerException, + Severity.Warning); + + if (!disposing) + { + WriteError( + new ErrorRecord( + providerException.ErrorRecord, + providerException)); + } + } + + try + { + holder.Reader?.Close(); + } + catch (Exception e) // Catch-all OK. 3rd party callout + { + // Catch all the exceptions caused by closing the writer + // and write out an error. + + ProviderInvocationException providerException = + new( + "ProviderContentCloseError", + SessionStateStrings.ProviderContentCloseError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + + MshLog.LogProviderHealthEvent( + this.Context, + holder.PathInfo.Provider.Name, + providerException, + Severity.Warning); + + if (!disposing) + { + WriteError( + new ErrorRecord( + providerException.ErrorRecord, + providerException)); + } + } + } + } + + /// + /// Overridden by derived classes to support ShouldProcess with + /// the appropriate information. + /// + /// + /// The path to the item from which the content writer will be + /// retrieved. + /// + /// + /// True if the action should continue or false otherwise. + /// + internal virtual bool CallShouldProcess(string path) + { + return true; + } + + /// + /// Gets the IContentReaders for the current path(s) + /// + /// + /// An array of IContentReaders for the current path(s) + /// + internal List GetContentReaders( + string[] readerPaths, + CmdletProviderContext currentCommandContext) + { + // Resolve all the paths into PathInfo objects + + Collection pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext); + + // Create the results array + + List results = new(); + + foreach (PathInfo pathInfo in pathInfos) + { + // For each path, get the content writer + + Collection readers = null; + + try + { + string pathToProcess = WildcardPattern.Escape(pathInfo.Path); + + if (currentCommandContext.SuppressWildcardExpansion) + { + pathToProcess = pathInfo.Path; + } + + readers = + InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + if (readers != null && readers.Count > 0) + { + if (readers.Count == 1 && readers[0] != null) + { + ContentHolder holder = + new(pathInfo, readers[0], null); + + results.Add(holder); + } + } + } + + return results; + } + + /// + /// Resolves the specified paths to PathInfo objects. + /// + /// + /// The paths to be resolved. Each path may contain glob characters. + /// + /// + /// If true, resolves the path even if it doesn't exist. + /// + /// + /// If true, allows a wildcard that returns no results. + /// + /// + /// The context under which the command is running. + /// + /// + /// An array of PathInfo objects that are the resolved paths for the + /// parameter. + /// + internal Collection ResolvePaths( + string[] pathsToResolve, + bool allowNonexistingPaths, + bool allowEmptyResult, + CmdletProviderContext currentCommandContext) + { + Collection results = new(); + + foreach (string path in pathsToResolve) + { + bool pathNotFound = false; + bool filtersHidPath = false; + + ErrorRecord pathNotFoundErrorRecord = null; + + try + { + // First resolve each of the paths + Collection pathInfos = + SessionState.Path.GetResolvedPSPathFromPSPath( + path, + currentCommandContext); + + if (pathInfos.Count == 0) + { + pathNotFound = true; + + // If the item simply did not exist, + // we would have got an ItemNotFoundException. + // If we get here, it's because the filters + // excluded the file. + if (!currentCommandContext.SuppressWildcardExpansion) + { + filtersHidPath = true; + } + } + + foreach (PathInfo pathInfo in pathInfos) + { + results.Add(pathInfo); + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFoundException) + { + pathNotFound = true; + pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException); + } + + if (pathNotFound) + { + if (allowNonexistingPaths && + (!filtersHidPath) && + (currentCommandContext.SuppressWildcardExpansion || + (!WildcardPattern.ContainsWildcardCharacters(path)))) + { + ProviderInfo provider = null; + PSDriveInfo drive = null; + string unresolvedPath = + SessionState.Path.GetUnresolvedProviderPathFromPSPath( + path, + currentCommandContext, + out provider, + out drive); + + PathInfo pathInfo = + new( + drive, + provider, + unresolvedPath, + SessionState); + results.Add(pathInfo); + } + else + { + if (pathNotFoundErrorRecord == null) + { + // Detect if the path resolution failed to resolve to a file. + string error = StringUtil.Format(NavigationResources.ItemNotFound, Path); + Exception e = new(error); + + pathNotFoundErrorRecord = new ErrorRecord( + e, + "ItemNotFound", + ErrorCategory.ObjectNotFound, + Path); + } + + WriteError(pathNotFoundErrorRecord); + } + } + } + + return results; + } + + #endregion protected members + + #region IDisposable + + internal void Dispose(bool isDisposing) + { + if (isDisposing) + { + CloseContent(contentStreams, true); + contentStreams = new List(); + } + } + + /// + /// Dispose method in IDisposable. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + #endregion IDisposable + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..3734eb82b0c0d9b9207a630e86823ec46a4f0f29 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs @@ -0,0 +1,762 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Microsoft.Win32; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Represent a control panel item. + /// + public sealed class ControlPanelItem + { + /// + /// Control panel applet name. + /// + public string Name { get; } + + /// + /// Control panel applet canonical name. + /// + public string CanonicalName { get; } + + /// + /// Control panel applet category. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Category { get; } + + /// + /// Control panel applet description. + /// + public string Description { get; } + + /// + /// Control panel applet path. + /// + internal string Path { get; } + + /// + /// Internal constructor for ControlPanelItem. + /// + /// + /// + /// + /// + /// + internal ControlPanelItem(string name, string canonicalName, string[] category, string description, string path) + { + Name = name; + Path = path; + CanonicalName = canonicalName; + Category = category; + Description = description; + } + + /// + /// ToString method. + /// + /// + public override string ToString() + { + return this.Name; + } + } + + /// + /// This class implements the base for ControlPanelItem commands. + /// + public abstract class ControlPanelItemBaseCommand : PSCmdlet + { + /// + /// Locale specific verb action Open string exposed by the control panel item. + /// + private static string s_verbActionOpenName = null; + + /// + /// Canonical name of the control panel item used as a reference to fetch the verb + /// action Open string. This control panel item exists on all SKU's. + /// + private const string RegionCanonicalName = "Microsoft.RegionAndLanguage"; + + private const string ControlPanelShellFolder = "shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}"; + private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" }; + private const string TestHeadlessServerScript = @" +$result = $false +$serverManagerModule = Get-Module -ListAvailable | Where-Object {$_.Name -eq 'ServerManager'} +if ($serverManagerModule -ne $null) +{ + Import-Module ServerManager + $Gui = (Get-WindowsFeature Server-Gui-Shell).Installed + if ($Gui -eq $false) + { + $result = $true + } +} +$result +"; + internal readonly Dictionary CategoryMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + + internal string[] CategoryNames = { "*" }; + internal string[] RegularNames = { "*" }; + internal string[] CanonicalNames = { "*" }; + internal ControlPanelItem[] ControlPanelItems = new ControlPanelItem[0]; + + /// + /// Get all executable control panel items. + /// + internal List AllControlPanelItems + { + get + { + if (_allControlPanelItems == null) + { + _allControlPanelItems = new List(); + string allItemFolderPath = ControlPanelShellFolder + "\\0"; + IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); + Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath); + FolderItems3 allItems = (FolderItems3)allItemFolder.Items(); + + bool applyControlPanelItemFilterList = IsServerCoreOrHeadLessServer(); + + foreach (ShellFolderItem item in allItems) + { + if (applyControlPanelItemFilterList) + { + bool match = false; + foreach (string name in s_controlPanelItemFilterList) + { + if (name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)) + { + match = true; + break; + } + } + + if (match) + continue; + } + + if (ContainVerbOpen(item)) + _allControlPanelItems.Add(item); + } + } + + return _allControlPanelItems; + } + } + + private List _allControlPanelItems; + + #region Cmdlet Overrides + + /// + /// Does the preprocessing for ControlPanelItem cmdlets. + /// + protected override void BeginProcessing() + { + System.OperatingSystem osInfo = System.Environment.OSVersion; + PlatformID platform = osInfo.Platform; + Version version = osInfo.Version; + + if (platform.Equals(PlatformID.Win32NT) && + ((version.Major < 6) || + ((version.Major == 6) && (version.Minor < 2)) + )) + { + // Below Win8, this cmdlet is not supported because of Win8:794135 + // throw terminating + string message = string.Format(CultureInfo.InvariantCulture, + ControlPanelResources.ControlPanelItemCmdletNotSupported, + this.CommandInfo.Name); + throw new PSNotSupportedException(message); + } + } + + #endregion + + /// + /// Test if an item can be invoked. + /// + /// + /// + private bool ContainVerbOpen(ShellFolderItem item) + { + bool result = false; + FolderItemVerbs verbs = item.Verbs(); + foreach (FolderItemVerb verb in verbs) + { + if (!string.IsNullOrEmpty(verb.Name) && + (verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) || + CompareVerbActionOpen(verb.Name))) + { + result = true; + break; + } + } + + return result; + } + + /// + /// CompareVerbActionOpen is a helper function used to perform locale specific + /// comparison of the verb action Open exposed by various control panel items. + /// + /// Locale specific verb action exposed by the control panel item. + /// True if the control panel item supports verb action open or else returns false. + private static bool CompareVerbActionOpen(string verbActionName) + { + if (s_verbActionOpenName == null) + { + const string allItemFolderPath = ControlPanelShellFolder + "\\0"; + IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); + Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath); + FolderItems3 allItems = (FolderItems3)allItemFolder.Items(); + + foreach (ShellFolderItem item in allItems) + { + string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); + canonicalName = !string.IsNullOrEmpty(canonicalName) + ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) + : null; + + if (canonicalName != null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase)) + { + // The 'Region' control panel item always has '&Open' (english or other locale) as the first verb name + s_verbActionOpenName = item.Verbs().Item(0).Name; + break; + } + } + + Dbg.Assert(s_verbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always " + + "has '&Open' as the first verb item, so VerbActionOpenName should never be null at this point"); + } + + return s_verbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase); + } + + /// + /// IsServerCoreORHeadLessServer is a helper function that checks if the current SKU is a + /// Server Core machine or if the Server-GUI-Shell feature is removed on the machine. + /// + /// True if the current SKU is a Server Core machine or if the Server-GUI-Shell + /// feature is removed on the machine or else returns false. + private bool IsServerCoreOrHeadLessServer() + { + bool result = false; + + using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")) + { + Dbg.Assert(installation != null, "the CurrentVersion subkey should exist"); + + string installationType = (string)installation.GetValue("InstallationType", string.Empty); + + if (installationType.Equals("Server Core")) + { + result = true; + } + else if (installationType.Equals("Server")) + { + using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) + { + ps.AddScript(TestHeadlessServerScript); + Collection psObjectCollection = ps.Invoke(Array.Empty()); + Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item"); + if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0]))) + { + result = true; + } + } + } + } + + return result; + } + + /// + /// Get the category number and name map. + /// + internal void GetCategoryMap() + { + if (CategoryMap.Count != 0) + { + return; + } + + IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); + Folder2 categoryFolder = (Folder2)shell2.NameSpace(ControlPanelShellFolder); + FolderItems3 catItems = (FolderItems3)categoryFolder.Items(); + + foreach (ShellFolderItem category in catItems) + { + string path = category.Path; + string catNum = path.Substring(path.LastIndexOf('\\') + 1); + + CategoryMap.Add(catNum, category.Name); + } + } + + /// + /// Get control panel item by the category. + /// + /// + /// + internal List GetControlPanelItemByCategory(List controlPanelItems) + { + List list = new List(); + HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (string pattern in CategoryNames) + { + bool found = false; + WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + foreach (ShellFolderItem item in controlPanelItems) + { + string path = item.Path; + int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category"); + foreach (int cat in categories) + { + string catStr = (string)LanguagePrimitives.ConvertTo(cat, typeof(string), CultureInfo.InvariantCulture); + Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in _categoryMap"); + string catName = CategoryMap[catStr]; + + if (!wildcard.IsMatch(catName)) + continue; + if (itemSet.Contains(path)) + { + found = true; + break; + } + + found = true; + itemSet.Add(path); + list.Add(item); + break; + } + } + + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) + { + string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenCategory, pattern); + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), + "NoControlPanelItemFoundForGivenCategory", + ErrorCategory.InvalidArgument, pattern); + WriteError(error); + } + } + + return list; + } + + /// + /// Get control panel item by the regular name. + /// + /// + /// + /// + internal List GetControlPanelItemByName(List controlPanelItems, bool withCategoryFilter) + { + List list = new List(); + HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (string pattern in RegularNames) + { + bool found = false; + WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + foreach (ShellFolderItem item in controlPanelItems) + { + string name = item.Name; + string path = item.Path; + if (!wildcard.IsMatch(name)) + continue; + if (itemSet.Contains(path)) + { + found = true; + continue; + } + + found = true; + itemSet.Add(path); + list.Add(item); + } + + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) + { + string formatString = withCategoryFilter + ? ControlPanelResources.NoControlPanelItemFoundForGivenNameWithCategory + : ControlPanelResources.NoControlPanelItemFoundForGivenName; + string errMsg = StringUtil.Format(formatString, pattern); + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), + "NoControlPanelItemFoundForGivenName", + ErrorCategory.InvalidArgument, pattern); + WriteError(error); + } + } + + return list; + } + + /// + /// Get control panel item by the canonical name. + /// + /// + /// + /// + internal List GetControlPanelItemByCanonicalName(List controlPanelItems, bool withCategoryFilter) + { + List list = new List(); + HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); + + if (CanonicalNames == null) + { + bool found = false; + foreach (ShellFolderItem item in controlPanelItems) + { + string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); + if (canonicalName == null) + { + found = true; + list.Add(item); + } + } + + if (!found) + { + string errMsg = withCategoryFilter + ? ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalNameWithCategory + : ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalName; + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), string.Empty, + ErrorCategory.InvalidArgument, CanonicalNames); + WriteError(error); + } + + return list; + } + + foreach (string pattern in CanonicalNames) + { + bool found = false; + WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + foreach (ShellFolderItem item in controlPanelItems) + { + string path = item.Path; + string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); + canonicalName = canonicalName != null + ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) + : null; + + if (canonicalName == null) + { + if (pattern.Equals("*", StringComparison.OrdinalIgnoreCase)) + { + found = true; + if (!itemSet.Contains(path)) + { + itemSet.Add(path); + list.Add(item); + } + } + } + else + { + if (!wildcard.IsMatch(canonicalName)) + continue; + if (itemSet.Contains(path)) + { + found = true; + continue; + } + + found = true; + itemSet.Add(path); + list.Add(item); + } + } + + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) + { + string formatString = withCategoryFilter + ? ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalNameWithCategory + : ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalName; + string errMsg = StringUtil.Format(formatString, pattern); + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), + "NoControlPanelItemFoundForGivenCanonicalName", + ErrorCategory.InvalidArgument, pattern); + WriteError(error); + } + } + + return list; + } + + /// + /// Get control panel item by the ControlPanelItem instances. + /// + /// + /// + internal List GetControlPanelItemsByInstance(List controlPanelItems) + { + List list = new List(); + HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (ControlPanelItem controlPanelItem in ControlPanelItems) + { + bool found = false; + + foreach (ShellFolderItem item in controlPanelItems) + { + string path = item.Path; + if (!controlPanelItem.Path.Equals(path, StringComparison.OrdinalIgnoreCase)) + continue; + if (itemSet.Contains(path)) + { + found = true; + break; + } + + found = true; + itemSet.Add(path); + list.Add(item); + break; + } + + if (!found) + { + string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenInstance, + controlPanelItem.GetType().Name); + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), + "NoControlPanelItemFoundForGivenInstance", + ErrorCategory.InvalidArgument, controlPanelItem); + WriteError(error); + } + } + + return list; + } + } + + /// + /// Get all control panel items that is available in the "All Control Panel Items" category. + /// + [Cmdlet(VerbsCommon.Get, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219982")] + [OutputType(typeof(ControlPanelItem))] + public sealed class GetControlPanelItemCommand : ControlPanelItemBaseCommand + { + private const string RegularNameParameterSet = "RegularName"; + private const string CanonicalNameParameterSet = "CanonicalName"; + + #region "Parameters" + + /// + /// Control panel item names. + /// + [Parameter(Position = 0, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return RegularNames; } + + set + { + RegularNames = value; + _nameSpecified = true; + } + } + + private bool _nameSpecified = false; + + /// + /// Canonical names of control panel items. + /// + [Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)] + [AllowNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] CanonicalName + { + get { return CanonicalNames; } + + set + { + CanonicalNames = value; + _canonicalNameSpecified = true; + } + } + + private bool _canonicalNameSpecified = false; + + /// + /// Category of control panel items. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Category + { + get { return CategoryNames; } + + set + { + CategoryNames = value; + _categorySpecified = true; + } + } + + private bool _categorySpecified = false; + + #endregion "Parameters" + + /// + /// + protected override void ProcessRecord() + { + GetCategoryMap(); + List items = GetControlPanelItemByCategory(AllControlPanelItems); + + if (_nameSpecified) + { + items = GetControlPanelItemByName(items, _categorySpecified); + } + else if (_canonicalNameSpecified) + { + items = GetControlPanelItemByCanonicalName(items, _categorySpecified); + } + + List results = new List(); + foreach (ShellFolderItem item in items) + { + string name = item.Name; + string path = item.Path; + string description = (string)item.ExtendedProperty("InfoTip"); + string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); + canonicalName = canonicalName != null + ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) + : null; + int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category"); + string[] cateStrings = new string[categories.Length]; + for (int i = 0; i < categories.Length; i++) + { + string catStr = (string)LanguagePrimitives.ConvertTo(categories[i], typeof(string), CultureInfo.InvariantCulture); + Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in CategoryMap"); + cateStrings[i] = CategoryMap[catStr]; + } + + ControlPanelItem controlPanelItem = new ControlPanelItem(name, canonicalName, cateStrings, description, path); + results.Add(controlPanelItem); + } + + // Sort the results by Canonical Name + results.Sort(CompareControlPanelItems); + foreach (ControlPanelItem controlPanelItem in results) + { + WriteObject(controlPanelItem); + } + } + + #region "Private Methods" + + private static int CompareControlPanelItems(ControlPanelItem x, ControlPanelItem y) + { + // In the case that at least one of them is null + if (x.CanonicalName == null && y.CanonicalName == null) + return 0; + if (x.CanonicalName == null) + return 1; + if (y.CanonicalName == null) + return -1; + + // In the case that both are not null + return string.Compare(x.CanonicalName, y.CanonicalName, StringComparison.OrdinalIgnoreCase); + } + + #endregion "Private Methods" + } + + /// + /// Show the specified control panel applet. + /// + [Cmdlet(VerbsCommon.Show, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219983")] + public sealed class ShowControlPanelItemCommand : ControlPanelItemBaseCommand + { + private const string RegularNameParameterSet = "RegularName"; + private const string CanonicalNameParameterSet = "CanonicalName"; + private const string ControlPanelItemParameterSet = "ControlPanelItem"; + + #region "Parameters" + + /// + /// Control panel item names. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return RegularNames; } + + set { RegularNames = value; } + } + + /// + /// Canonical names of control panel items. + /// + [Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)] + [AllowNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] CanonicalName + { + get { return CanonicalNames; } + + set { CanonicalNames = value; } + } + + /// + /// Control panel items returned by Get-ControlPanelItem. + /// + [Parameter(Position = 0, ParameterSetName = ControlPanelItemParameterSet, ValueFromPipeline = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public ControlPanelItem[] InputObject + { + get { return ControlPanelItems; } + + set { ControlPanelItems = value; } + } + + #endregion "Parameters" + + /// + /// + protected override void ProcessRecord() + { + List items; + if (ParameterSetName == RegularNameParameterSet) + { + items = GetControlPanelItemByName(AllControlPanelItems, false); + } + else if (ParameterSetName == CanonicalNameParameterSet) + { + items = GetControlPanelItemByCanonicalName(AllControlPanelItems, false); + } + else + { + items = GetControlPanelItemsByInstance(AllControlPanelItems); + } + + foreach (ShellFolderItem item in items) + { + item.InvokeVerb(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..33796b23378af5425b74736c87f0db3ccd820450 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.ObjectModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to convert a drive qualified or provider qualified path to + /// a provider internal path. + /// + [Cmdlet(VerbsData.Convert, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096588", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(string))] + public class ConvertPathCommand : CoreCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the force property. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + #endregion Parameters + + #region parameter data + + /// + /// The path(s) to the item(s) to convert. + /// + private string[] _paths; + + #endregion parameter data + + #region Command code + + /// + /// Converts a drive qualified or provider qualified path to a provider + /// internal path. + /// + protected override void ProcessRecord() + { + ProviderInfo provider = null; + + foreach (string path in Path) + { + try + { + Collection results = + SessionState.Path.GetResolvedProviderPathFromPSPath( + path, + CmdletProviderContext, + out provider); + + WriteObject(results, true); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..ff13448bc092265c642a0b4cd298061222c06f19 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to copy a property on an item. + /// + [Cmdlet(VerbsCommon.Copy, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096589")] + public class CopyItemPropertyCommand : PassThroughItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get { return paths; } + + set { paths = value; } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The name of the property to create on the item. + /// + [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Alias("PSProperty")] + public string Name { get; set; } + + /// + /// The path to the destination item to copy the property to. + /// + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] + public string Destination { get; set; } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.CopyPropertyDynamicParameters( + Path[0], + Name, + Destination, + Name, + context); + } + + return InvokeProvider.Property.CopyPropertyDynamicParameters( + ".", + Name, + Destination, + Name, + context); + } + + #endregion Parameters + + #region parameter data + + #endregion parameter data + + #region Command code + + /// + /// Copies the property from one item to another. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + try + { + InvokeProvider.Property.Copy( + path, + Name, + Destination, + Name, + GetCurrentContext()); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs new file mode 100644 index 0000000000000000000000000000000000000000..c667116fdd048f72b3fd209b447913376a2bbc2c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -0,0 +1,1467 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; // Win32Exception +using System.Diagnostics; // Eventlog class +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + #region GetEventLogCommand + /// + /// This class implements the Get-EventLog command. + /// + /// + /// The CLR EventLogEntryCollection class has problems with managing + /// rapidly spinning logs (i.e. logs set to "Overwrite" which are + /// rapidly getting new events and discarding old events). + /// In particular, if you enumerate forward + /// EventLogEntryCollection entries = log.Entries; + /// foreach (EventLogEntry entry in entries) + /// it will occasionally skip an entry. Conversely, if you are + /// enumerating backward + /// EventLogEntryCollection entries = log.Entries; + /// int count = entries.Count; + /// for (int i = count-1; i >= 0; i--) { + /// EventLogEntry entry = entries[i]; + /// it will occasionally repeat an entry. Accordingly, we enumerate + /// backward and try to leave off the repeated entries. + /// + [Cmdlet(VerbsCommon.Get, "EventLog", DefaultParameterSetName = "LogName", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113314", RemotingCapability = RemotingCapability.SupportedByCommand)] + [OutputType(typeof(EventLog), typeof(EventLogEntry), typeof(string))] + public sealed class GetEventLogCommand : PSCmdlet + { + #region Parameters + /// + /// Read eventlog entries from this log. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "LogName")] + [Alias("LN")] + public string LogName { get; set; } + + /// + /// Read eventlog entries from this computer. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("Cn")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName { get; set; } = Array.Empty(); + + /// + /// Read only this number of entries. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateRange(0, Int32.MaxValue)] + public int Newest { get; set; } = Int32.MaxValue; + + /// + /// Return entries "after " this date. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + public DateTime After + { + get { return _after; } + + set + { + _after = value; + _isDateSpecified = true; + _isFilterSpecified = true; + } + } + + private DateTime _after; + + /// + /// Return entries "Before" this date. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + public DateTime Before + { + get { return _before; } + + set + { + _before = value; + _isDateSpecified = true; + _isFilterSpecified = true; + } + } + + private DateTime _before; + + /// + /// Return entries for this user.Wild characters is supported. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] UserName + { + get { return _username; } + + set + { + _username = value; + _isFilterSpecified = true; + } + } + + private string[] _username; + + /// + /// Match eventlog entries by the InstanceIds + /// gets or sets an array of instanceIds. + /// + [Parameter(Position = 1, ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + [ValidateRangeAttribute((long)0, long.MaxValue)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public long[] InstanceId + { + get { return _instanceIds; } + + set + { + _instanceIds = value; + _isFilterSpecified = true; + } + } + + private long[] _instanceIds = null; + + /// + /// Match eventlog entries by the Index + /// gets or sets an array of indexes. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + [ValidateRangeAttribute((int)1, int.MaxValue)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] Index + { + get { return _indexes; } + + set + { + _indexes = value; + _isFilterSpecified = true; + } + } + + private int[] _indexes = null; + + /// + /// Match eventlog entries by the EntryType + /// gets or sets an array of EntryTypes. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + [ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [Alias("ET")] + public string[] EntryType + { + get { return _entryTypes; } + + set + { + _entryTypes = value; + _isFilterSpecified = true; + } + } + + private string[] _entryTypes = null; + + /// + /// Get or sets an array of Source. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + [Alias("ABO")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Source + { + get + { return _sources; } + + set + { + _sources = value; + _isFilterSpecified = true; + } + } + + private string[] _sources; + + /// + /// Get or Set Message string to searched in EventLog. + /// + [Parameter(ParameterSetName = "LogName")] + [ValidateNotNullOrEmpty] + [Alias("MSG")] + public string Message + { + get + { + return _message; + } + + set + { + _message = value; + _isFilterSpecified = true; + } + } + + private string _message; + + /// + /// Returns Log Entry as base object. + /// + [Parameter(ParameterSetName = "LogName")] + public SwitchParameter AsBaseObject { get; set; } + + /// + /// Return the Eventlog objects rather than the log contents. + /// + [Parameter(ParameterSetName = "List")] + public SwitchParameter List { get; set; } + + /// + /// Return the log names rather than the EventLog objects. + /// + [Parameter(ParameterSetName = "List")] + public SwitchParameter AsString + { + get + { + return _asString; + } + + set + { + _asString = value; + } + } + + private bool _asString /* = false */; + #endregion Parameters + + #region Overrides + + /// + /// Sets true when Filter is Specified. + /// + private bool _isFilterSpecified = false; + private bool _isDateSpecified = false; + private bool _isThrowError = true; + + /// + /// Process the specified logs. + /// + protected override void BeginProcessing() + { + if (ParameterSetName == "List") + { + if (ComputerName.Length > 0) + { + foreach (string computerName in ComputerName) + { + foreach (EventLog log in EventLog.GetEventLogs(computerName)) + { + if (AsString) + WriteObject(log.Log); + else + WriteObject(log); + } + } + } + else + { + foreach (EventLog log in EventLog.GetEventLogs()) + { + if (AsString) + WriteObject(log.Log); + else + WriteObject(log); + } + } + } + else + { + Diagnostics.Assert(ParameterSetName == "LogName", "Unexpected parameter set"); + + if (!WildcardPattern.ContainsWildcardCharacters(LogName)) + { + OutputEvents(LogName); + } + else + { + // + // If we were given a wildcard that matches more than one log, output the matching logs. Otherwise output the events in the matching log. + // + List matchingLogs = GetMatchingLogs(LogName); + + if (matchingLogs.Count == 1) + { + OutputEvents(matchingLogs[0].Log); + } + else + { + foreach (EventLog log in matchingLogs) + { + WriteObject(log); + } + } + } + } + } + #endregion Overrides + + #region Private + + private void OutputEvents(string logName) + { + // 2005/04/21-JonN This somewhat odd structure works + // around the FXCOP DisposeObjectsBeforeLosingScope rule. + bool processing = false; + try + { + if (ComputerName.Length == 0) + { + using (EventLog specificLog = new EventLog(logName)) + { + processing = true; + Process(specificLog); + } + } + else + { + processing = true; + + foreach (string computerName in ComputerName) + { + using (EventLog specificLog = new EventLog(logName, computerName)) + { + Process(specificLog); + } + } + } + } + catch (InvalidOperationException e) + { + if (processing) + { + throw; + } + + ThrowTerminatingError(new ErrorRecord( + e, // default exception text is OK + "EventLogNotFound", + ErrorCategory.ObjectNotFound, + logName)); + } + } + + private void Process(EventLog log) + { + bool matchesfound = false; + if (Newest == 0) + { + return; + } + + // enumerate backward, skipping repeat entries + EventLogEntryCollection entries = log.Entries; + + int count = entries.Count; + int lastindex = Int32.MinValue; + int processed = 0; + + for (int i = count - 1; (i >= 0) && (processed < Newest); i--) + { + EventLogEntry entry = null; + try + { + entry = entries[i]; + } + catch (ArgumentException e) + { + ErrorRecord er = new ErrorRecord( + e, + "LogReadError", + ErrorCategory.ReadError, + null + ); + er.ErrorDetails = new ErrorDetails( + this, + "EventlogResources", + "LogReadError", + log.Log, + e.Message + ); + WriteError(er); + + // NTRAID#Windows Out Of Band Releases-2005/09/27-JonN + // Break after the first one, rather than repeating this + // over and over + break; + } + catch (Exception e) + { + Diagnostics.Assert(false, + "EventLogEntryCollection error " + + e.GetType().FullName + + ": " + e.Message); + throw; + } + + if ((entry != null) && + ((lastindex == Int32.MinValue + || lastindex - entry.Index == 1))) + { + lastindex = entry.Index; + if (_isFilterSpecified) + { + if (!FiltersMatch(entry)) + continue; + } + + if (!AsBaseObject) + { + // wrapping in PSobject to insert into PStypesnames + PSObject logentry = new PSObject(entry); + // inserting at zero position in reverse order + logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source); + logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source + "/" + entry.InstanceId); + WriteObject(logentry); + matchesfound = true; + } + else + { + WriteObject(entry); + matchesfound = true; + } + + processed++; + } + } + + if (!matchesfound && _isThrowError) + { + Exception Ex = new ArgumentException(StringUtil.Format(EventlogResources.NoEntriesFound, log.Log, string.Empty)); + WriteError(new ErrorRecord(Ex, "GetEventLogNoEntriesFound", ErrorCategory.ObjectNotFound, null)); + } + } + + private bool FiltersMatch(EventLogEntry entry) + { + if (_indexes != null) + { + if (!((IList)_indexes).Contains(entry.Index)) + { + return false; + } + } + + if (_instanceIds != null) + { + if (!((IList)_instanceIds).Contains(entry.InstanceId)) + { + return false; + } + } + + if (_entryTypes != null) + { + bool entrymatch = false; + foreach (string type in _entryTypes) + { + if (type.Equals(entry.EntryType.ToString(), StringComparison.OrdinalIgnoreCase)) + { + entrymatch = true; + break; + } + } + + if (!entrymatch) + { + return entrymatch; + } + } + + if (_sources != null) + { + bool sourcematch = false; + foreach (string source in _sources) + { + if (WildcardPattern.ContainsWildcardCharacters(source)) + { + _isThrowError = false; + } + + WildcardPattern wildcardpattern = WildcardPattern.Get(source, WildcardOptions.IgnoreCase); + if (wildcardpattern.IsMatch(entry.Source)) + { + sourcematch = true; + break; + } + } + + if (!sourcematch) + { + return sourcematch; + } + } + + if (_message != null) + { + if (WildcardPattern.ContainsWildcardCharacters(_message)) + { + _isThrowError = false; + } + + WildcardPattern wildcardpattern = WildcardPattern.Get(_message, WildcardOptions.IgnoreCase); + if (!wildcardpattern.IsMatch(entry.Message)) + { + return false; + } + } + + if (_username != null) + { + bool usernamematch = false; + foreach (string user in _username) + { + _isThrowError = false; + if (entry.UserName != null) + { + WildcardPattern wildcardpattern = WildcardPattern.Get(user, WildcardOptions.IgnoreCase); + if (wildcardpattern.IsMatch(entry.UserName)) + { + usernamematch = true; + break; + } + } + } + + if (!usernamematch) + { + return usernamematch; + } + } + + if (_isDateSpecified) + { + _isThrowError = false; + bool datematch = false; + if (!_after.Equals(_initial) && _before.Equals(_initial)) + { + if (entry.TimeGenerated > _after) + { + datematch = true; + } + } + else if (!_before.Equals(_initial) && _after.Equals(_initial)) + { + if (entry.TimeGenerated < _before) + { + datematch = true; + } + } + else if (!_after.Equals(_initial) && !_before.Equals(_initial)) + { + if (_after > _before || _after == _before) + { + if ((entry.TimeGenerated > _after) || (entry.TimeGenerated < _before)) + datematch = true; + } + else + { + if ((entry.TimeGenerated > _after) && (entry.TimeGenerated < _before)) + { + datematch = true; + } + } + } + + if (!datematch) + { + return datematch; + } + } + + return true; + } + + private List GetMatchingLogs(string pattern) + { + WildcardPattern wildcardPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + List matchingLogs = new List(); + if (ComputerName.Length == 0) + { + foreach (EventLog log in EventLog.GetEventLogs()) + { + if (wildcardPattern.IsMatch(log.Log)) + { + matchingLogs.Add(log); + } + } + } + else + { + foreach (string computerName in ComputerName) + { + foreach (EventLog log in EventLog.GetEventLogs(computerName)) + { + if (wildcardPattern.IsMatch(log.Log)) + { + matchingLogs.Add(log); + } + } + } + } + + return matchingLogs; + } + // private string ErrorBase = "EventlogResources"; + private DateTime _initial = new DateTime(); + + #endregion Private + } + #endregion GetEventLogCommand + + #region ClearEventLogCommand + /// + /// This class implements the Clear-EventLog command. + /// + + [Cmdlet(VerbsCommon.Clear, "EventLog", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135198", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class ClearEventLogCommand : PSCmdlet + { + #region Parameters + /// + /// Clear these logs. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Alias("LN")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LogName { get; set; } + + /// + /// Clear eventlog entries from these Computers. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [Alias("Cn")] + public string[] ComputerName { get; set; } = { "." }; + + #endregion Parameters + + #region Overrides + + /// + /// Does the processing. + /// + protected override void BeginProcessing() + { + string computer = string.Empty; + foreach (string compName in ComputerName) + { + if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computer = "localhost"; + } + else + { + computer = compName; + } + + foreach (string eventString in LogName) + { + try + { + if (!EventLog.Exists(eventString, compName)) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, eventString, computer)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + + if (!ShouldProcess(StringUtil.Format(EventlogResources.ClearEventLogWarning, eventString, computer))) + { + continue; + } + + EventLog Log = new EventLog(eventString, compName); + Log.Clear(); + } + catch (System.IO.IOException) + { + ErrorRecord er = new ErrorRecord(new System.IO.IOException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + catch (Win32Exception) + { + ErrorRecord er = new ErrorRecord(new Win32Exception(StringUtil.Format(EventlogResources.NoAccess, null, computer)), null, ErrorCategory.PermissionDenied, null); + WriteError(er); + continue; + } + catch (InvalidOperationException) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.OSWritingError)), null, ErrorCategory.ReadError, null); + WriteError(er); + continue; + } + } + } + } + + // beginprocessing + + #endregion Overrides + } + #endregion ClearEventLogCommand + + #region WriteEventLogCommand + /// + /// This class implements the Write-EventLog command. + /// + + [Cmdlet(VerbsCommunications.Write, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135281", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class WriteEventLogCommand : PSCmdlet + { + #region Parameters + /// + /// Write eventlog entries in this log. + /// + [Parameter(Position = 0, Mandatory = true)] + [Alias("LN")] + [ValidateNotNullOrEmpty] + public string LogName { get; set; } + + /// + /// The source by which the application is registered on the specified computer. + /// + [Parameter(Position = 1, Mandatory = true)] + [Alias("SRC")] + [ValidateNotNullOrEmpty] + public string Source { get; set; } + + /// + /// String which represents One of the EventLogEntryType values. + /// + [Parameter(Position = 3)] + [Alias("ET")] + [ValidateNotNullOrEmpty] + [ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })] + public EventLogEntryType EntryType { get; set; } = EventLogEntryType.Information; + + /// + /// The application-specific subcategory associated with the message. + /// + [Parameter] + public Int16 Category { get; set; } = 1; + + /// + /// The application-specific identifier for the event. + /// + [Parameter(Position = 2, Mandatory = true)] + [Alias("ID", "EID")] + [ValidateNotNullOrEmpty] + [ValidateRange(0, UInt16.MaxValue)] + public Int32 EventId { get; set; } + + /// + /// The message goes here. + /// + [Parameter(Position = 4, Mandatory = true)] + [Alias("MSG")] + [ValidateNotNullOrEmpty] + [ValidateLength(0, 32766)] + public string Message { get; set; } + + /// + /// Write eventlog entries of this log. + /// + [Parameter] + [Alias("RD")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public byte[] RawData { get; set; } + + /// + /// Write eventlog entries of this log. + /// + [Parameter] + [Alias("CN")] + [ValidateNotNullOrEmpty] + + public string ComputerName { get; set; } = "."; + + #endregion Parameters + #region private + + private void WriteNonTerminatingError(Exception exception, string errorId, string errorMessage, + ErrorCategory category) + { + Exception ex = new Exception(errorMessage, exception); + WriteError(new ErrorRecord(ex, errorId, category, null)); + } + + #endregion private + #region Overrides + + /// + /// Does the processing. + /// + protected override void BeginProcessing() + { + string _computerName = string.Empty; + if ((ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (ComputerName.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + _computerName = "localhost"; + } + else + { + _computerName = ComputerName; + } + + try + { + if (!(EventLog.SourceExists(Source, ComputerName))) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, null, _computerName, Source)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + } + else + { + if (!(EventLog.Exists(LogName, ComputerName))) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, LogName, _computerName)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + } + else + { + EventLog _myevent = new EventLog(LogName, ComputerName, Source); + _myevent.WriteEntry(Message, EntryType, EventId, Category, RawData); + } + } + } + catch (ArgumentException ex) + { + WriteNonTerminatingError(ex, ex.Message, ex.Message, ErrorCategory.InvalidOperation); + } + catch (InvalidOperationException ex) + { + WriteNonTerminatingError(ex, "AccessDenied", StringUtil.Format(EventlogResources.AccessDenied, LogName, null, Source), ErrorCategory.PermissionDenied); + } + catch (Win32Exception ex) + { + WriteNonTerminatingError(ex, "OSWritingError", StringUtil.Format(EventlogResources.OSWritingError, null, null, null), ErrorCategory.WriteError); + } + catch (System.IO.IOException ex) + { + WriteNonTerminatingError(ex, "PathDoesNotExist", StringUtil.Format(EventlogResources.PathDoesNotExist, null, ComputerName, null), ErrorCategory.InvalidOperation); + } + } + + #endregion Overrides + } + #endregion WriteEventLogCommand + + #region LimitEventLogCommand + /// + /// This class implements the Limit-EventLog command. + /// + + [Cmdlet(VerbsData.Limit, "EventLog", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135227", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class LimitEventLogCommand : PSCmdlet + { + #region Parameters + /// + /// Limit the properties of this log. + /// + [Parameter(Position = 0, Mandatory = true)] + [Alias("LN")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LogName { get; set; } + + /// + /// Limit eventlog entries of this computer. + /// + [Parameter] + [Alias("CN")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName { get; set; } = { "." }; + + /// + /// Minimum retention days for this log. + /// + [Parameter] + [Alias("MRD")] + [ValidateNotNullOrEmpty] + [ValidateRange(1, 365)] + public Int32 RetentionDays + { + get { return _retention; } + + set + { + _retention = value; + _retentionSpecified = true; + } + } + + private Int32 _retention; + private bool _retentionSpecified = false; + /// + /// Overflow action to be taken. + /// + [Parameter] + [Alias("OFA")] + [ValidateNotNullOrEmpty] + [ValidateSetAttribute(new string[] { "OverwriteOlder", "OverwriteAsNeeded", "DoNotOverwrite" })] + + public System.Diagnostics.OverflowAction OverflowAction + { + get { return _overflowaction; } + + set + { + _overflowaction = value; + _overflowSpecified = true; + } + } + + private System.Diagnostics.OverflowAction _overflowaction; + private bool _overflowSpecified = false; + /// + /// Maximum size of this log. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public Int64 MaximumSize + { + get { return _maximumKilobytes; } + + set + { + _maximumKilobytes = value; + _maxkbSpecified = true; + } + } + + private Int64 _maximumKilobytes; + private bool _maxkbSpecified = false; + #endregion Parameters + + #region private + private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId, + ErrorCategory category, string _logName, string _compName) + { + Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName), exception); + WriteError(new ErrorRecord(ex, errorId, category, null)); + } + + #endregion private + + #region Overrides + + /// + /// Does the processing. + /// + protected override + void + BeginProcessing() + { + string computer = string.Empty; + foreach (string compname in ComputerName) + { + if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computer = "localhost"; + } + else + { + computer = compname; + } + + foreach (string logname in LogName) + { + try + { + if (!EventLog.Exists(logname, compname)) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, logname, computer)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + else + { + if (!ShouldProcess(StringUtil.Format(EventlogResources.LimitEventLogWarning, logname, computer))) + { + continue; + } + else + { + EventLog newLog = new EventLog(logname, compname); + int _minRetention = newLog.MinimumRetentionDays; + System.Diagnostics.OverflowAction _newFlowAction = newLog.OverflowAction; + if (_retentionSpecified && _overflowSpecified) + { + if (_overflowaction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0) + { + newLog.ModifyOverflowPolicy(_overflowaction, _retention); + } + else + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + else if (_retentionSpecified && !_overflowSpecified) + { + if (_newFlowAction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0) + { + newLog.ModifyOverflowPolicy(_newFlowAction, _retention); + } + else + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + else if (!_retentionSpecified && _overflowSpecified) + { + newLog.ModifyOverflowPolicy(_overflowaction, _minRetention); + } + + if (_maxkbSpecified) + { + int kiloByte = 1024; + _maximumKilobytes = _maximumKilobytes / kiloByte; + newLog.MaximumKilobytes = _maximumKilobytes; + } + } + } + } + catch (InvalidOperationException ex) + { + WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, logname, computer); + continue; + } + catch (System.IO.IOException ex) + { + WriteNonTerminatingError(ex, EventlogResources.PathDoesNotExist, "PathDoesNotExist", ErrorCategory.InvalidOperation, null, computer); + continue; + } + catch (ArgumentOutOfRangeException ex) + { + if (!_retentionSpecified && !_maxkbSpecified) + { + WriteNonTerminatingError(ex, EventlogResources.InvalidArgument, "InvalidArgument", ErrorCategory.InvalidData, null, null); + } + else + { + WriteNonTerminatingError(ex, EventlogResources.ValueOutofRange, "ValueOutofRange", ErrorCategory.InvalidData, null, null); + } + + continue; + } + } + } + } + #endregion override + + } + #endregion LimitEventLogCommand + + #region ShowEventLogCommand + /// + /// This class implements the Show-EventLog command. + /// + + [Cmdlet(VerbsCommon.Show, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135257", RemotingCapability = RemotingCapability.SupportedByCommand)] + public sealed class ShowEventLogCommand : PSCmdlet + { + #region Parameters + + /// + /// Show eventviewer of this computer. + /// + [Parameter(Position = 0)] + [Alias("CN")] + [ValidateNotNullOrEmpty] + + public string ComputerName { get; set; } = "."; + + #endregion Parameters + + #region Overrides + + /// + /// Does the processing. + /// + protected override + void + BeginProcessing() + { + try + { + string eventVwrExe = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), + "eventvwr.exe"); + Process.Start(eventVwrExe, ComputerName); + } + catch (Win32Exception e) + { + if (e.NativeErrorCode.Equals(0x00000002)) + { + string message = StringUtil.Format(EventlogResources.NotSupported); + InvalidOperationException ex = new InvalidOperationException(message); + ErrorRecord er = new ErrorRecord(ex, "Win32Exception", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + else + { + ErrorRecord er = new ErrorRecord(e, "Win32Exception", ErrorCategory.InvalidArgument, null); + WriteError(er); + } + } + catch (SystemException ex) + { + ErrorRecord er = new ErrorRecord(ex, "InvalidComputerName", ErrorCategory.InvalidArgument, ComputerName); + WriteError(er); + } + } + #endregion override + } + #endregion ShowEventLogCommand + + #region NewEventLogCommand + /// + /// This cmdlet creates the new event log .This cmdlet can also be used to + /// configure a new source for writing entries to an event log on the local + /// computer or a remote computer. + /// You can create an event source for an existing event log or a new event log. + /// When you create a new source for a new event log, the system registers the + /// source for that log, but the log is not created until the first entry is + /// written to it. + /// The operating system stores event logs as files. The associated file is + /// stored in the %SystemRoot%\System32\Config directory on the specified + /// computer. The file name is set by appending the first 8 characters of the + /// Log property with the ".evt" file name extension. + /// You can register the event source with localized resource file(s) for your + /// event category and message strings. Your application can write event log + /// entries using resource identifiers, rather than specifying the actual + /// string. You can register a separate file for event categories, messages and + /// parameter insertion strings, or you can register the same resource file for + /// all three types of strings. + /// + + [Cmdlet(VerbsCommon.New, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135235", RemotingCapability = RemotingCapability.SupportedByCommand)] + public class NewEventLogCommand : PSCmdlet + { + #region Parameter + /// + /// The following is the definition of the input parameter "CategoryResourceFile". + /// Specifies the path of the resource file that contains category strings for + /// the source + /// Resource File is expected to be present in Local/Remote Machines. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("CRF")] + public string CategoryResourceFile { get; set; } + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specify the Computer Name. The default is local computer. + /// + [Parameter(Position = 2)] + [ValidateNotNullOrEmpty] + [Alias("CN")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName { get; set; } = { "." }; + + /// + /// The following is the definition of the input parameter "LogName". + /// Specifies the name of the log. + /// + [Parameter(Mandatory = true, + Position = 0)] + [ValidateNotNullOrEmpty] + [Alias("LN")] + public string LogName { get; set; } + + /// + /// The following is the definition of the input parameter "MessageResourceFile". + /// Specifies the path of the message resource file that contains message + /// formatting strings for the source + /// Resource File is expected to be present in Local/Remote Machines. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("MRF")] + public string MessageResourceFile { get; set; } + + /// + /// The following is the definition of the input parameter "ParameterResourceFile". + /// Specifies the path of the resource file that contains message parameter + /// strings for the source + /// Resource File is expected to be present in Local/Remote Machines. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("PRF")] + public string ParameterResourceFile { get; set; } + + /// + /// The following is the definition of the input parameter "Source". + /// Specifies the Source of the EventLog. + /// + [Parameter(Mandatory = true, + Position = 1)] + [ValidateNotNullOrEmpty] + [Alias("SRC")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Source { get; set; } + + #endregion Parameter + + #region private + private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId, + ErrorCategory category, string _logName, string _compName, string _source, string _resourceFile) + { + Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName, _source, _resourceFile), exception); + WriteError(new ErrorRecord(ex, errorId, category, null)); + } + + #endregion private + + #region override + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + string computer = string.Empty; + foreach (string compname in ComputerName) + { + if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computer = "localhost"; + } + else + { + computer = compname; + } + + try + { + foreach (string _sourceName in Source) + { + if (!EventLog.SourceExists(_sourceName, compname)) + { + EventSourceCreationData newEventSource = new EventSourceCreationData(_sourceName, LogName); + newEventSource.MachineName = compname; + if (!string.IsNullOrEmpty(MessageResourceFile)) + newEventSource.MessageResourceFile = MessageResourceFile; + if (!string.IsNullOrEmpty(ParameterResourceFile)) + newEventSource.ParameterResourceFile = ParameterResourceFile; + if (!string.IsNullOrEmpty(CategoryResourceFile)) + newEventSource.CategoryResourceFile = CategoryResourceFile; + EventLog.CreateEventSource(newEventSource); + } + else + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceExistInComp, null, computer, _sourceName)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + } + catch (InvalidOperationException ex) + { + WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, LogName, computer, null, null); + continue; + } + catch (ArgumentException ex) + { + ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.InvalidArgument, null); + WriteError(er); + continue; + } + catch (System.Security.SecurityException ex) + { + WriteNonTerminatingError(ex, EventlogResources.AccessIsDenied, "AccessIsDenied", ErrorCategory.InvalidOperation, null, null, null, null); + continue; + } + } + } + // End BeginProcessing() + #endregion override + } + #endregion NewEventLogCommand + + #region RemoveEventLogCommand + /// + /// This cmdlet is used to delete the specified event log from the specified + /// computer. This can also be used to Clear the entries of the specified event + /// log and also to unregister the Source associated with the eventlog. + /// + + [Cmdlet(VerbsCommon.Remove, "EventLog", + SupportsShouldProcess = true, DefaultParameterSetName = "Default", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135248", RemotingCapability = RemotingCapability.SupportedByCommand)] + public class RemoveEventLogCommand : PSCmdlet + { + /// + /// The following is the definition of the input parameter "ComputerName". + /// Specifies the Computer Name. + /// + [Parameter(Position = 1)] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + [Alias("CN")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName { get; set; } = { "." }; + + /// + /// The following is the definition of the input parameter "LogName". + /// Specifies the Event Log Name. + /// + [Parameter(Mandatory = true, + Position = 0, ParameterSetName = "Default")] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + [Alias("LN")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LogName { get; set; } + + /// + /// The following is the definition of the input parameter "RemoveSource". + /// Specifies either to remove the event log and associated source or + /// source. alone. + /// When this parameter is not specified, the cmdlet uses Delete Method which + /// clears the eventlog and also the source associated with it. + /// When this parameter value is true, then this cmdlet uses DeleteEventSource + /// Method to delete the Source alone. + /// + [Parameter(ParameterSetName = "Source")] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + [Alias("SRC")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Source { get; set; } + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + try + { + string computer = string.Empty; + foreach (string compName in ComputerName) + { + if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computer = "localhost"; + } + else + { + computer = compName; + } + + if (ParameterSetName.Equals("Default")) + { + foreach (string log in LogName) + { + try + { + if (EventLog.Exists(log, compName)) + { + if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveEventLogWarning, log, computer))) + { + continue; + } + + EventLog.Delete(log, compName); + } + else + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, log, computer)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + catch (System.IO.IOException) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + } + else + { + foreach (string src in Source) + { + try + { + if (EventLog.SourceExists(src, compName)) + { + if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveSourceWarning, src, computer))) + { + continue; + } + + EventLog.DeleteEventSource(src, compName); + } + else + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, string.Empty, computer, src)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + catch (System.IO.IOException) + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); + WriteError(er); + continue; + } + } + } + } + } + catch (System.Security.SecurityException ex) + { + ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.SecurityError, null); + WriteError(er); + } + } + } + + #endregion RemoveEventLogCommand +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..c049370e4b45cfcaa713e0189e91c47ca47cf169 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -0,0 +1,366 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The get-childitem command class. + /// This command lists the contents of a container. + /// + /// + /// + [Cmdlet(VerbsCommon.Get, "ChildItem", DefaultParameterSetName = "Items", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096492")] + public class GetChildItemCommand : CoreCommandBase + { + /// + /// The string declaration for the Items parameter set in this command. + /// + /// + /// The "Items" parameter set includes the following parameters: + /// -filter + /// -recurse + /// + private const string childrenSet = "Items"; + private const string literalChildrenSet = "LiteralItems"; + + #region Command parameters + + /// + /// Gets or sets the path for the operation. + /// + [Parameter(Position = 0, ParameterSetName = childrenSet, + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = literalChildrenSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the filter property. + /// + [Parameter(Position = 1)] + public override string Filter + { + get + { + return base.Filter; + } + + set + { + base.Filter = value; + } + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get + { + return base.Include; + } + + set + { + base.Include = value; + } + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get + { + return base.Exclude; + } + + set + { + base.Exclude = value; + } + } + + /// + /// Gets or sets the recurse switch. + /// + [Parameter] + [Alias("s", "r")] + public SwitchParameter Recurse + { + get + { + return _recurse; + } + + set + { + _recurse = value; + } + } + + /// + /// Gets or sets max depth of recursion; automatically sets Recurse parameter; + /// Value '0' will show only contents of container specified by -Path (same result as running 'Get-ChildItem' without '-Recurse'); + /// Value '1' will show 1 level deep, etc...; + /// Default is uint.MaxValue - it performs full recursion (this parameter has no effect). + /// + [Parameter] + public uint Depth + { + get + { + return _depth; + } + + set + { + _depth = value; + this.Recurse = true; // Bug 2391925 - Get-ChildItem -Depth should auto-set -Recurse + } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get + { + return base.Force; + } + + set + { + base.Force = value; + } + } + + /// + /// Gets or sets the names switch. + /// + [Parameter] + public SwitchParameter Name + { + get + { + return _childNames; + } + + set + { + _childNames = value; + } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + object result = null; + string path = string.Empty; + + if (_paths != null && _paths.Length > 0) + { + path = _paths[0]; + } + else + { + path = "."; + } + + switch (ParameterSetName) + { + case childrenSet: + case literalChildrenSet: + if (Name) + { + result = InvokeProvider.ChildItem.GetChildNamesDynamicParameters(path, context); + } + else + { + result = InvokeProvider.ChildItem.GetChildItemsDynamicParameters(path, Recurse, context); + } + + break; + + default: + result = InvokeProvider.ChildItem.GetChildItemsDynamicParameters(path, Recurse, context); + break; + } + + return result; + } + + #endregion Command parameters + + #region command data + + /// + /// The path for the get-location operation. + /// + private string[] _paths; + + /// + /// Determines if the command should do recursion. + /// + private bool _recurse; + + /// + /// Limits the depth of recursion; used with Recurse parameter; + /// Value '0' will show only contents of container specified by -Path (same result as running 'Get-ChildItem' without '-Recurse'); + /// Value '1' will show 1 level deep, etc...; + /// Default is uint.MaxValue - it performs full recursion (this parameter has no effect). + /// + private uint _depth = uint.MaxValue; + + /// + /// The flag that specifies whether to retrieve the child names or the child items. + /// + private bool _childNames = false; + + #endregion command data + + #region command code + + /// + /// The main execution method for the get-childitem command. + /// + protected override void ProcessRecord() + { + CmdletProviderContext currentContext = CmdletProviderContext; + + if (_paths == null || _paths.Length == 0) + { + _paths = new string[] { string.Empty }; + } + + foreach (string path in _paths) + { + switch (ParameterSetName) + { + case childrenSet: + case literalChildrenSet: + try + { + if (Name) + { + // Get the names of the child items using the static namespace method. + // The child names should be written directly to the pipeline using the + // context.WriteObject method. + + InvokeProvider.ChildItem.GetNames(path, ReturnContainers.ReturnMatchingContainers, Recurse, Depth, currentContext); + } + else + { + // Get the children using the static namespace method. + // The children should be written directly to the pipeline using + // the context.WriteObject method. + + InvokeProvider.ChildItem.Get(path, Recurse, Depth, currentContext); + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + break; + + default: + Dbg.Diagnostics.Assert( + false, + "Only one of the specified parameter sets should be called."); + break; + } + } + } + + #endregion command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..a2b7f03ce705d443960cebcc8011ae5b3847ccbd --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation; +using System.Management.Automation.Language; +using Microsoft.PowerShell.Commands.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the 'Get-Clipboard' cmdlet. + /// This cmdlet get the content from system clipboard. + /// + [Cmdlet(VerbsCommon.Get, "Clipboard", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2109905")] + [Alias("gcb")] + [OutputType(typeof(string))] + public class GetClipboardCommand : PSCmdlet + { + /// + /// Property that sets raw parameter. This will allow clipboard return text or file list as one string. + /// + [Parameter] + public SwitchParameter Raw + { + get + { + return _raw; + } + + set + { + _raw = value; + } + } + + /// + /// Gets or sets the delimiters to use when splitting the clipboard content. + /// + [Parameter] + [ArgumentCompleter(typeof(DelimiterCompleter))] + public string[] Delimiter { get; set; } = [Environment.NewLine]; + + private bool _raw; + + /// + /// This method implements the ProcessRecord method for Get-Clipboard command. + /// + protected override void BeginProcessing() + { + this.WriteObject(GetClipboardContentAsText(), true); + } + + /// + /// Returns the clipboard content as text format. + /// + /// Array of strings representing content from clipboard. + private List GetClipboardContentAsText() + { + var result = new List(); + string textContent = null; + + try + { + textContent = Clipboard.GetText(); + } + catch (PlatformNotSupportedException) + { + ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(ClipboardResources.UnsupportedPlatform), "FailedToGetClipboardUnsupportedPlatform", ErrorCategory.InvalidOperation, "Clipboard")); + } + + if (_raw) + { + result.Add(textContent); + } + else + { + result.AddRange(textContent.Split(Delimiter, StringSplitOptions.None)); + } + + return result; + } + } + + /// + /// Provides argument completion for the Delimiter parameter. + /// + public sealed class DelimiterCompleter : IArgumentCompleter + { + /// + /// Provides argument completion for the Delimiter parameter. + /// + /// The name of the command that is being completed. + /// The name of the parameter that is being completed. + /// The input text to filter the results by. + /// The ast of the command that triggered the completion. + /// The parameters bound to the command. + /// Completion results. + public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) + { + wordToComplete ??= string.Empty; + var pattern = new WildcardPattern(wordToComplete + '*', WildcardOptions.IgnoreCase); + if (pattern.IsMatch("CRLF") || pattern.IsMatch("Windows")) + { + yield return new CompletionResult("\"`r`n\"", "CRLF", CompletionResultType.ParameterValue, "Windows (CRLF)"); + } + + if (pattern.IsMatch("LF") || pattern.IsMatch("Unix") || pattern.IsMatch("Linux")) + { + yield return new CompletionResult("\"`n\"", "LF", CompletionResultType.ParameterValue, "UNIX (LF)"); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..87f96c436ea212d93f1623eea4287ddff686f4fc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -0,0 +1,5158 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq.Expressions; +using System.Management.Automation; +using System.Reflection; +using System.Runtime.InteropServices; + +using Microsoft.Management.Infrastructure; +using Microsoft.Win32; + +namespace Microsoft.PowerShell.Commands +{ + using Extensions; + + #region GetComputerInfoCommand cmdlet implementation + /// + /// The Get-ComputerInfo cmdlet gathers and reports information + /// about a computer. + /// + [Cmdlet(VerbsCommon.Get, "ComputerInfo", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096810")] + [Alias("gin")] + [OutputType(typeof(ComputerInfo), typeof(PSObject))] + public class GetComputerInfoCommand : PSCmdlet + { + #region Inner Types + private sealed class OSInfoGroup + { + public WmiOperatingSystem os; + public HotFix[] hotFixes; + public WmiPageFileUsage[] pageFileUsage; + public string halVersion; + public TimeSpan? upTime; + public RegWinNtCurrentVersion regCurVer; + } + + private sealed class SystemInfoGroup + { + public WmiBaseBoard baseboard; + public WmiBios bios; + public WmiComputerSystem computer; + public Processor[] processors; + public NetworkAdapter[] networkAdapters; + } + + private sealed class HyperVInfo + { + public bool? Present; + public bool? VMMonitorModeExtensions; + public bool? SecondLevelAddressTranslation; + public bool? VirtualizationFirmwareEnabled; + public bool? DataExecutionPreventionAvailable; + } + + private sealed class DeviceGuardInfo + { + public DeviceGuardSmartStatus status; + public DeviceGuard deviceGuard; + } + + private sealed class MiscInfoGroup + { + public ulong? physicallyInstalledMemory; + public string timeZone; + public string logonServer; + public FirmwareType? firmwareType; + public PowerPlatformRole? powerPlatformRole; + public WmiKeyboard[] keyboards; + public HyperVInfo hyperV; + public ServerLevel? serverLevel; + public DeviceGuardInfo deviceGuard; + } + #endregion Inner Types + + #region Static Data and Constants + private const string activity = "Get-ComputerInfo"; + private const string localMachineName = null; + #endregion Static Data and Constants + + #region Instance Data + private readonly string _machineName = localMachineName; // we might need to have cmdlet work on another machine + + /// + /// Collection of property names from the Property parameter, + /// including any names resulting from the expansion of wild-card + /// patterns given. This list will itself contain no wildcard patterns. + /// + private List _namedProperties = null; + #endregion Instance Data + + #region Parameters + /// + /// The Property parameter contains the names of properties to be retrieved. + /// If this parameter is given, the cmdlet returns a PSCustomObject + /// containing only the requested properties. + /// Wild-card patterns may be provided. + /// + /// + /// + /// Any named properties that are not recognized are ignored. If no + /// recognized properties are provided the cmdlet returns an empty + /// PSCustomObject. + /// + /// + /// If a provided wild-card pattern contains only an asterisk ("*"), + /// the cmdlet will operate as if the parameter were not given at all + /// and will return a fully-populated ComputerInfo object. + /// + /// + [Parameter(Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Property { get; set; } + #endregion Parameters + + #region Cmdlet Overrides + /// + /// Perform any first-stage processing. + /// + protected override void BeginProcessing() + { + // if the Property parameter was given, determine the requested + // property names + if (Property != null && Property.Length > 0) + { + try + { + _namedProperties = CollectPropertyNames(Property); + } + catch (WildcardPatternException ex) + { + WriteError(new ErrorRecord(ex, "WildcardPattern", ErrorCategory.InvalidArgument, this)); + } + } + } + + /// + /// Performs the cmdlet's work. + /// + protected override void ProcessRecord() + { + // if the user provided property names but no matching properties + // were found, return an empty custom object + if (_namedProperties != null && _namedProperties.Count == 0) + { + WriteObject(new PSObject()); + return; + } + + MiscInfoGroup miscInfo = null; + var osInfo = new OSInfoGroup(); + var systemInfo = new SystemInfoGroup(); + var now = DateTime.Now; + + using (var session = CimSession.Create(_machineName)) + { + UpdateProgress(ComputerInfoResources.LoadingOperationSystemInfo); + + osInfo.os = session.GetFirst(CIMHelper.ClassNames.OperatingSystem); + osInfo.pageFileUsage = session.GetAll(CIMHelper.ClassNames.PageFileUsage); + + if (osInfo.os != null) + { + osInfo.halVersion = GetHalVersion(session, osInfo.os.SystemDirectory); + + if (osInfo.os.LastBootUpTime != null) + osInfo.upTime = now - osInfo.os.LastBootUpTime.Value; + } + + UpdateProgress(ComputerInfoResources.LoadingHotPatchInfo); + osInfo.hotFixes = session.GetAll(CIMHelper.ClassNames.HotFix); + + UpdateProgress(ComputerInfoResources.LoadingRegistryInfo); + osInfo.regCurVer = RegistryInfo.GetWinNtCurrentVersion(); + + UpdateProgress(ComputerInfoResources.LoadingBiosInfo); + systemInfo.bios = session.GetFirst(CIMHelper.ClassNames.Bios); + + UpdateProgress(ComputerInfoResources.LoadingMotherboardInfo); + systemInfo.baseboard = session.GetFirst(CIMHelper.ClassNames.BaseBoard); + + UpdateProgress(ComputerInfoResources.LoadingComputerInfo); + systemInfo.computer = session.GetFirst(CIMHelper.ClassNames.ComputerSystem); + miscInfo = GetOtherInfo(session); + + UpdateProgress(ComputerInfoResources.LoadingProcessorInfo); + systemInfo.processors = GetProcessors(session); + + UpdateProgress(ComputerInfoResources.LoadingNetworkAdapterInfo); + systemInfo.networkAdapters = GetNetworkAdapters(session); + + UpdateProgress(null); // close the progress bar + } + + var infoOutput = CreateFullOutputObject(systemInfo, osInfo, miscInfo); + + if (_namedProperties != null) + { + // var output = CreateCustomOutputObject(namedProperties, systemInfo, osInfo, miscInfo); + var output = CreateCustomOutputObject(infoOutput, _namedProperties); + + WriteObject(output); + } + else + { + WriteObject(infoOutput); + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Display progress. + /// + /// + /// Text to be displayed in status bar + /// + private void UpdateProgress(string status) + { + ProgressRecord progress = new(0, activity, status ?? ComputerResources.ProgressStatusCompleted); + progress.RecordType = status == null ? ProgressRecordType.Completed : ProgressRecordType.Processing; + + WriteProgress(progress); + } + + /// + /// Retrieves the version of the system's hal.dll. + /// + /// + /// A object + /// representing the CIM session to query. + /// + /// + /// Path to the system directory, which should contain the hal.dll file. + /// + private static string GetHalVersion(CimSession session, string systemDirectory) + { + string halVersion = null; + + try + { + var halPath = CIMHelper.EscapePath(System.IO.Path.Combine(systemDirectory, "hal.dll")); + var query = string.Create(CultureInfo.InvariantCulture, $"SELECT * FROM CIM_DataFile Where Name='{halPath}'"); + var instance = session.QueryFirstInstance(query); + + if (instance != null) + halVersion = instance.CimInstanceProperties["Version"].Value.ToString(); + } + catch (Exception) + { + // On any error, fall through to the return + } + + return halVersion; + } + + /// + /// Create an array of object from values in + /// Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration instances. + /// + /// + /// A object representing + /// a CIM session. + /// + /// + /// An array of NetworkAdapter objects. + /// + /// + /// This method matches network adapters associated network adapter configurations. + /// The returned array contains entries only for matched adapter/configuration objects. + /// + private static NetworkAdapter[] GetNetworkAdapters(CimSession session) + { + var adaptersMsft = session.GetAll(CIMHelper.MicrosoftNetworkAdapterNamespace, CIMHelper.ClassNames.MicrosoftNetworkAdapter); + var adapters = session.GetAll(CIMHelper.ClassNames.NetworkAdapter); + var configs = session.GetAll(CIMHelper.ClassNames.NetworkAdapterConfiguration); + + var list = new List(); + + if (adapters != null && configs != null) + { + var configDict = new Dictionary(); + + foreach (var config in configs) + { + if (config.Index != null) + configDict[config.Index.Value] = config; + } + + if (configDict.Count > 0) + { + foreach (var adapter in adapters) + { + // Only include adapters that have a non-null connection status + // and a non-null index + if (adapter.NetConnectionStatus != null + && adapter.Index != null) + { + if (configDict.ContainsKey(adapter.Index.Value)) + { + var config = configDict[adapter.Index.Value]; + var nwAdapter = new NetworkAdapter + { + Description = adapter.Description, + ConnectionID = adapter.NetConnectionID + }; + + var status = EnumConverter.Convert(adapter.NetConnectionStatus); + nwAdapter.ConnectionStatus = status == null ? NetConnectionStatus.Other + : status.Value; + + if (nwAdapter.ConnectionStatus == NetConnectionStatus.Connected) + { + nwAdapter.DHCPEnabled = config.DHCPEnabled; + nwAdapter.DHCPServer = config.DHCPServer; + nwAdapter.IPAddresses = config.IPAddress; + } + + list.Add(nwAdapter); + } + } + } + } + } + + return list.ToArray(); + } + + /// + /// Create an array of objects, using data acquired + /// from WMI via the Win32_Processor class. + /// + /// + /// + private static Processor[] GetProcessors(CimSession session) + { + var processors = session.GetAll(CIMHelper.ClassNames.Processor); + + if (processors != null) + { + var list = new List(); + + foreach (var processor in processors) + { + var proc = new Processor(); + + proc.AddressWidth = processor.AddressWidth; + proc.Architecture = EnumConverter.Convert(processor.Architecture); + proc.Availability = EnumConverter.Convert(processor.Availability); + proc.CpuStatus = EnumConverter.Convert(processor.CpuStatus); + proc.CurrentClockSpeed = processor.CurrentClockSpeed; + proc.DataWidth = processor.DataWidth; + proc.Description = processor.Description; + proc.Manufacturer = processor.Manufacturer; + proc.MaxClockSpeed = processor.MaxClockSpeed; + proc.Name = processor.Name; + proc.NumberOfCores = processor.NumberOfCores; + proc.NumberOfLogicalProcessors = processor.NumberOfLogicalProcessors; + proc.ProcessorID = processor.ProcessorId; + proc.ProcessorType = EnumConverter.Convert(processor.ProcessorType); + proc.Role = processor.Role; + proc.SocketDesignation = processor.SocketDesignation; + proc.Status = processor.Status; + + list.Add(proc); + } + + return list.ToArray(); + } + + return null; + } + + private static bool CheckDeviceGuardLicense() + { + const string propertyName = "CodeIntegrity-AllowConfigurablePolicy"; + + // DeviceGuard is supported on all versions of PowerShell that execute on "full" SKUs + if (Platform.IsWindows && + !(Platform.IsNanoServer || Platform.IsIoT)) + { + try + { + int policy = 0; + + if (Native.SLGetWindowsInformationDWORD(propertyName, out policy) == Native.S_OK + && policy == 1) + { + return true; + } + } + catch (Exception) + { + // if we fail to load the native dll or if the call fails + // catastrophically there's not much we can do except to + // consider there to be no license. + } + } + + return false; + } + + /// + /// Retrieve information related to Device Guard. + /// + /// + /// A object representing + /// a CIM session. + /// + /// + /// A object containing information related to + /// the Device Guard feature + /// + private static DeviceGuardInfo GetDeviceGuard(CimSession session) + { + DeviceGuard guard = null; + var status = DeviceGuardSmartStatus.Off; + + if (CheckDeviceGuardLicense()) + { + var wmiGuard = session.GetFirst(CIMHelper.DeviceGuardNamespace, + CIMHelper.ClassNames.DeviceGuard); + + if (wmiGuard != null) + { + var smartStatus = EnumConverter.Convert((int?)wmiGuard.VirtualizationBasedSecurityStatus ?? 0); + if (smartStatus != null) + { + status = (DeviceGuardSmartStatus)smartStatus; + } + + guard = wmiGuard.AsOutputType; + } + } + + return new DeviceGuardInfo + { + status = status, + deviceGuard = guard + }; + } + + /// + /// A helper method used by GetHyperVisorInfo to retrieve a boolean + /// property value. + /// + private static bool? GetBooleanProperty(CimInstance instance, string propertyName) + { + if (instance != null) + { + try + { + var property = instance.CimInstanceProperties[propertyName]; + + if (property != null && property.Value != null) + return (bool)property.Value; + } + catch (Exception) + { + // just in case the cast fails + // fall through to the null return + } + } + + return null; + } + + /// + /// Retrieve information related to HyperVisor. + /// + /// + /// A object representing + /// a CIM session. + /// + /// + /// A object containing information related to + /// HyperVisor + /// + private static HyperVInfo GetHyperVisorInfo(CimSession session) + { + HyperVInfo info = new(); + bool ok = false; + CimInstance instance = null; + + using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.ComputerSystem))) + { + if (instance != null) + { + info.Present = GetBooleanProperty(instance, "HypervisorPresent"); + ok = true; + } + } + + // don't bother checking requirements if the HyperV in present + // when the HyperV is present, the requirements values are misleading + if (ok && info.Present != null && info.Present.Value) + return info; + + using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.OperatingSystem))) + { + if (instance != null) + { + info.DataExecutionPreventionAvailable = GetBooleanProperty(instance, "DataExecutionPrevention_Available"); + ok = true; + } + } + + using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.Processor))) + { + if (instance != null) + { + info.SecondLevelAddressTranslation = GetBooleanProperty(instance, "SecondLevelAddressTranslationExtensions"); + info.VirtualizationFirmwareEnabled = GetBooleanProperty(instance, "VirtualizationFirmwareEnabled"); + info.VMMonitorModeExtensions = GetBooleanProperty(instance, "VMMonitorModeExtensions"); + ok = true; + } + } + + return ok ? info : null; + } + + /// + /// Retrieve miscellaneous system information. + /// + /// + /// A object representing + /// a CIM session. + /// + /// + /// A object containing miscellaneous + /// system information + /// + private static MiscInfoGroup GetOtherInfo(CimSession session) + { + var rv = new MiscInfoGroup(); + + // get platform role + try + { + // TODO: Local machine only. Check for that? + uint powerRole = Native.PowerDeterminePlatformRoleEx(Native.POWER_PLATFORM_ROLE_V2); + if (powerRole >= (uint)PowerPlatformRole.MaximumEnumValue) + rv.powerPlatformRole = PowerPlatformRole.Unspecified; + else + rv.powerPlatformRole = EnumConverter.Convert((int)powerRole); + } + catch (Exception) + { + // probably failed to load the DLL with PowerDeterminePlatformRoleEx + // either way, move on + } + + // get secure-boot info + // TODO: Local machine only? Check for that? + rv.firmwareType = GetFirmwareType(); + + // get amount of memory physically installed + // TODO: Local machine only. Check for that? + rv.physicallyInstalledMemory = GetPhysicallyInstalledSystemMemory(); + + // get time zone + // we'll use .Net's TimeZoneInfo for now. systeminfo uses Caption from Win32_TimeZone + var tzi = TimeZoneInfo.Local; + if (tzi != null) + rv.timeZone = tzi.DisplayName; + + rv.logonServer = RegistryInfo.GetLogonServer(); + + rv.keyboards = session.GetAll(CIMHelper.ClassNames.Keyboard); + + rv.hyperV = GetHyperVisorInfo(session); + + var serverLevels = RegistryInfo.GetServerLevels(); + uint value; + + if (serverLevels.TryGetValue("NanoServer", out value) && value == 1) + { + rv.serverLevel = ServerLevel.NanoServer; + } + else if (serverLevels.TryGetValue("ServerCore", out value) && value == 1) + { + rv.serverLevel = ServerLevel.ServerCore; + + if (serverLevels.TryGetValue("Server-Gui-Mgmt", out value) && value == 1) + { + rv.serverLevel = ServerLevel.ServerCoreWithManagementTools; + + if (serverLevels.TryGetValue("Server-Gui-Shell", out value) && value == 1) + rv.serverLevel = ServerLevel.FullServer; + } + } + + rv.deviceGuard = GetDeviceGuard(session); + + return rv; + } + + /// + /// Wrapper around the native GetFirmwareType function. + /// + /// + /// null if unsuccessful, otherwise FirmwareType enum specifying + /// the firmware type. + /// + private static FirmwareType? GetFirmwareType() + { + try + { + FirmwareType firmwareType; + + if (Native.GetFirmwareType(out firmwareType)) + return firmwareType; + } + catch (Exception) + { + // Probably failed to load the DLL or to file the function entry point. + // Fail silently + } + + return null; + } + + /// + /// Wrapper around the native GetPhysicallyInstalledSystemMemory function. + /// + /// + /// null if unsuccessful, otherwise the amount of physically installed memory. + /// + private static ulong? GetPhysicallyInstalledSystemMemory() + { + try + { + ulong memory; + if (Native.GetPhysicallyInstalledSystemMemory(out memory)) + return memory; + } + catch (Exception) + { + // Probably failed to load the DLL or to file the function entry point. + // Fail silently + } + + return null; + } + + /// + /// Create a new ComputerInfo object populated with the specified data objects. + /// + /// + /// A object containing system-related info + /// such as BIOS, mother-board, computer system, etc. + /// + /// + /// An object containing operating-system information. + /// + /// + /// A object containing other information to be reported. + /// + /// + /// A new ComputerInfo object to be output to PowerShell. + /// + private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, OSInfoGroup osInfo, MiscInfoGroup otherInfo) + { + var output = new ComputerInfo(); + + var regCurVer = osInfo.regCurVer; + if (regCurVer != null) + { + output.WindowsBuildLabEx = regCurVer.BuildLabEx; + output.WindowsCurrentVersion = regCurVer.CurrentVersion; + output.WindowsEditionId = regCurVer.EditionId; + output.WindowsInstallationType = regCurVer.InstallationType; + output.WindowsInstallDateFromRegistry = regCurVer.InstallDate; + output.WindowsProductId = regCurVer.ProductId; + output.WindowsProductName = regCurVer.ProductName; + output.WindowsRegisteredOrganization = regCurVer.RegisteredOrganization; + output.WindowsRegisteredOwner = regCurVer.RegisteredOwner; + output.WindowsSystemRoot = regCurVer.SystemRoot; + output.WindowsVersion = regCurVer.ReleaseId; + output.WindowsUBR = regCurVer.UBR; + } + + var os = osInfo.os; + if (os != null) + { + output.OsName = os.Caption; + output.OsBootDevice = os.BootDevice; + output.OsBuildNumber = os.BuildNumber; + output.OsBuildType = os.BuildType; + output.OsCodeSet = os.CodeSet; + output.OsCountryCode = os.CountryCode; + output.OsCSDVersion = os.CSDVersion; + output.OsCurrentTimeZone = os.CurrentTimeZone; + output.OsDataExecutionPreventionAvailable = os.DataExecutionPrevention_Available; + output.OsDataExecutionPrevention32BitApplications = os.DataExecutionPrevention_32BitApplications; + output.OsDataExecutionPreventionDrivers = os.DataExecutionPrevention_Drivers; + output.OsDataExecutionPreventionSupportPolicy = + EnumConverter.Convert(os.DataExecutionPrevention_SupportPolicy); + output.OsDebug = os.Debug; + + output.OsDistributed = os.Distributed; + output.OsEncryptionLevel = EnumConverter.Convert((int?)os.EncryptionLevel); + output.OsForegroundApplicationBoost = EnumConverter.Convert(os.ForegroundApplicationBoost); + output.OsTotalSwapSpaceSize = os.TotalSwapSpaceSize; + output.OsTotalVisibleMemorySize = os.TotalVisibleMemorySize; + output.OsFreePhysicalMemory = os.FreePhysicalMemory; + output.OsFreeSpaceInPagingFiles = os.FreeSpaceInPagingFiles; + output.OsTotalVirtualMemorySize = os.TotalVirtualMemorySize; + output.OsFreeVirtualMemory = os.FreeVirtualMemory; + if (os.TotalVirtualMemorySize != null && os.FreeVirtualMemory != null) + output.OsInUseVirtualMemory = os.TotalVirtualMemorySize - os.FreeVirtualMemory; + output.OsInstallDate = os.InstallDate; + output.OsLastBootUpTime = os.LastBootUpTime; + output.OsLocalDateTime = os.LocalDateTime; + output.OsLocaleID = os.Locale; + output.OsManufacturer = os.Manufacturer; + output.OsMaxNumberOfProcesses = os.MaxNumberOfProcesses; + output.OsMaxProcessMemorySize = os.MaxProcessMemorySize; + output.OsMuiLanguages = os.MUILanguages; + output.OsNumberOfLicensedUsers = os.NumberOfLicensedUsers; + output.OsNumberOfProcesses = os.NumberOfProcesses; + output.OsNumberOfUsers = os.NumberOfUsers; + output.OsOperatingSystemSKU = EnumConverter.Convert((int?)os.OperatingSystemSKU); + output.OsOrganization = os.Organization; + output.OsArchitecture = os.OSArchitecture; + output.OsLanguage = os.LanguageName; + output.OsProductSuites = os.ProductSuites; + output.OsOtherTypeDescription = os.OtherTypeDescription; + output.OsPAEEnabled = os.PAEEnabled; + output.OsPortableOperatingSystem = os.PortableOperatingSystem; + output.OsPrimary = os.Primary; + output.OsProductType = EnumConverter.Convert((int?)os.ProductType); + output.OsRegisteredUser = os.RegisteredUser; + output.OsSerialNumber = os.SerialNumber; + output.OsServicePackMajorVersion = os.ServicePackMajorVersion; + output.OsServicePackMinorVersion = os.ServicePackMinorVersion; + output.OsSizeStoredInPagingFiles = os.SizeStoredInPagingFiles; + output.OsStatus = os.Status; + output.OsSuites = os.Suites; + output.OsSystemDevice = os.SystemDevice; + output.OsSystemDirectory = os.SystemDirectory; + output.OsSystemDrive = os.SystemDrive; + output.OsType = EnumConverter.Convert(os.OSType); + output.OsVersion = os.Version; + output.OsWindowsDirectory = os.WindowsDirectory; + + output.OsHardwareAbstractionLayer = osInfo.halVersion; + output.OsLocale = os.GetLocale(); + output.OsUptime = osInfo.upTime; + output.OsHotFixes = osInfo.hotFixes; + + var pageFileUsage = osInfo.pageFileUsage; + if (pageFileUsage != null) + { + output.OsPagingFiles = new string[pageFileUsage.Length]; + + for (int i = 0; i < pageFileUsage.Length; i++) + output.OsPagingFiles[i] = pageFileUsage[i].Caption; + } + } + + var bios = systemInfo.bios; + if (bios != null) + { + output.BiosCharacteristics = bios.BiosCharacteristics; + output.BiosBuildNumber = bios.BuildNumber; + output.BiosBIOSVersion = bios.BIOSVersion; + output.BiosCaption = bios.Caption; + output.BiosCodeSet = bios.CodeSet; + output.BiosCurrentLanguage = bios.CurrentLanguage; + output.BiosDescription = bios.Description; + output.BiosEmbeddedControllerMajorVersion = bios.EmbeddedControllerMajorVersion; + output.BiosEmbeddedControllerMinorVersion = bios.EmbeddedControllerMinorVersion; + output.BiosIdentificationCode = bios.IdentificationCode; + output.BiosInstallableLanguages = bios.InstallableLanguages; + output.BiosInstallDate = bios.InstallDate; + output.BiosLanguageEdition = bios.LanguageEdition; + output.BiosListOfLanguages = bios.ListOfLanguages; + output.BiosManufacturer = bios.Manufacturer; + output.BiosName = bios.Name; + output.BiosOtherTargetOS = bios.OtherTargetOS; + output.BiosPrimaryBIOS = bios.PrimaryBIOS; + output.BiosReleaseDate = bios.ReleaseDate; + output.BiosSerialNumber = bios.SerialNumber; + output.BiosSMBIOSBIOSVersion = bios.SMBIOSBIOSVersion; + output.BiosSMBIOSMajorVersion = bios.SMBIOSMajorVersion; + output.BiosSMBIOSMinorVersion = bios.SMBIOSMinorVersion; + output.BiosSMBIOSPresent = bios.SMBIOSPresent; + output.BiosSoftwareElementState = EnumConverter.Convert(bios.SoftwareElementState); + output.BiosStatus = bios.Status; + output.BiosSystemBiosMajorVersion = bios.SystemBiosMajorVersion; + output.BiosSystemBiosMinorVersion = bios.SystemBiosMinorVersion; + output.BiosTargetOperatingSystem = bios.TargetOperatingSystem; + output.BiosVersion = bios.Version; + + if (otherInfo != null) + output.BiosFirmwareType = otherInfo.firmwareType; + } + + var computer = systemInfo.computer; + if (computer != null) + { + output.CsAdminPasswordStatus = EnumConverter.Convert(computer.AdminPasswordStatus); + output.CsAutomaticManagedPagefile = computer.AutomaticManagedPagefile; + output.CsAutomaticResetBootOption = computer.AutomaticResetBootOption; + output.CsAutomaticResetCapability = computer.AutomaticResetCapability; + output.CsBootOptionOnLimit = EnumConverter.Convert(computer.BootOptionOnLimit); + output.CsBootOptionOnWatchDog = EnumConverter.Convert(computer.BootOptionOnWatchDog); + output.CsBootROMSupported = computer.BootROMSupported; + output.CsBootStatus = computer.BootStatus; + output.CsBootupState = computer.BootupState; + output.CsCaption = computer.Caption; + output.CsChassisBootupState = EnumConverter.Convert(computer.ChassisBootupState); + output.CsChassisSKUNumber = computer.ChassisSKUNumber; + output.CsCurrentTimeZone = computer.CurrentTimeZone; + output.CsDaylightInEffect = computer.DaylightInEffect; + output.CsDescription = computer.Description; + output.CsDNSHostName = computer.DNSHostName; + output.CsDomain = computer.Domain; + output.CsDomainRole = EnumConverter.Convert(computer.DomainRole); + output.CsEnableDaylightSavingsTime = computer.EnableDaylightSavingsTime; + output.CsFrontPanelResetStatus = EnumConverter.Convert(computer.FrontPanelResetStatus); + output.CsHypervisorPresent = computer.HypervisorPresent; + output.CsInfraredSupported = computer.InfraredSupported; + output.CsInitialLoadInfo = computer.InitialLoadInfo; + output.CsInstallDate = computer.InstallDate; + output.CsKeyboardPasswordStatus = EnumConverter.Convert(computer.KeyboardPasswordStatus); + output.CsLastLoadInfo = computer.LastLoadInfo; + output.CsManufacturer = computer.Manufacturer; + output.CsModel = computer.Model; + output.CsName = computer.Name; + output.CsNetworkAdapters = systemInfo.networkAdapters; + output.CsNetworkServerModeEnabled = computer.NetworkServerModeEnabled; + output.CsNumberOfLogicalProcessors = computer.NumberOfLogicalProcessors; + output.CsNumberOfProcessors = computer.NumberOfProcessors; + output.CsProcessors = systemInfo.processors; + output.CsOEMStringArray = computer.OEMStringArray; + output.CsPartOfDomain = computer.PartOfDomain; + output.CsPauseAfterReset = computer.PauseAfterReset; + output.CsPCSystemType = EnumConverter.Convert(computer.PCSystemType); + output.CsPCSystemTypeEx = EnumConverter.Convert(computer.PCSystemTypeEx); + output.CsPowerManagementCapabilities = computer.GetPowerManagementCapabilities(); + output.CsPowerManagementSupported = computer.PowerManagementSupported; + output.CsPowerOnPasswordStatus = EnumConverter.Convert(computer.PowerOnPasswordStatus); + output.CsPowerState = EnumConverter.Convert(computer.PowerState); + output.CsPowerSupplyState = EnumConverter.Convert(computer.PowerSupplyState); + output.CsPrimaryOwnerContact = computer.PrimaryOwnerContact; + output.CsPrimaryOwnerName = computer.PrimaryOwnerName; + output.CsResetCapability = EnumConverter.Convert(computer.ResetCapability); + output.CsResetCount = computer.ResetCount; + output.CsResetLimit = computer.ResetLimit; + output.CsRoles = computer.Roles; + output.CsStatus = computer.Status; + output.CsSupportContactDescription = computer.SupportContactDescription; + output.CsSystemFamily = computer.SystemFamily; + output.CsSystemSKUNumber = computer.SystemSKUNumber; + output.CsSystemType = computer.SystemType; + output.CsThermalState = EnumConverter.Convert(computer.ThermalState); + output.CsTotalPhysicalMemory = computer.TotalPhysicalMemory; + output.CsUserName = computer.UserName; + output.CsWakeUpType = EnumConverter.Convert(computer.WakeUpType); + output.CsWorkgroup = computer.Workgroup; + + if (otherInfo != null) + { + output.CsPhysicallyInstalledMemory = otherInfo.physicallyInstalledMemory; + } + } + + if (otherInfo != null) + { + output.TimeZone = otherInfo.timeZone; + output.LogonServer = otherInfo.logonServer; + output.PowerPlatformRole = otherInfo.powerPlatformRole; + + if (otherInfo.keyboards.Length > 0) + { + // TODO: handle multiple keyboards? + // there might be several keyboards found. For the moment + // we display info for only one + + string layout = otherInfo.keyboards[0].Layout; + + output.KeyboardLayout = Conversion.GetLocaleName(layout); + } + + if (otherInfo.hyperV != null) + { + output.HyperVisorPresent = otherInfo.hyperV.Present; + output.HyperVRequirementDataExecutionPreventionAvailable = otherInfo.hyperV.DataExecutionPreventionAvailable; + output.HyperVRequirementSecondLevelAddressTranslation = otherInfo.hyperV.SecondLevelAddressTranslation; + output.HyperVRequirementVirtualizationFirmwareEnabled = otherInfo.hyperV.VirtualizationFirmwareEnabled; + output.HyperVRequirementVMMonitorModeExtensions = otherInfo.hyperV.VMMonitorModeExtensions; + } + + output.OsServerLevel = otherInfo.serverLevel; + + var deviceGuardInfo = otherInfo.deviceGuard; + if (deviceGuardInfo != null) + { + output.DeviceGuardSmartStatus = deviceGuardInfo.status; + + var deviceGuard = deviceGuardInfo.deviceGuard; + if (deviceGuard != null) + { + output.DeviceGuardRequiredSecurityProperties = deviceGuard.RequiredSecurityProperties; + output.DeviceGuardAvailableSecurityProperties = deviceGuard.AvailableSecurityProperties; + output.DeviceGuardSecurityServicesConfigured = deviceGuard.SecurityServicesConfigured; + output.DeviceGuardSecurityServicesRunning = deviceGuard.SecurityServicesRunning; + output.DeviceGuardCodeIntegrityPolicyEnforcementStatus = deviceGuard.CodeIntegrityPolicyEnforcementStatus; + output.DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus = deviceGuard.UserModeCodeIntegrityPolicyEnforcementStatus; + } + } + } + + return output; + } + + /// + /// Create a new PSObject, containing only those properties named in the + /// namedProperties parameter. + /// + /// + /// A containing all the acquired system information + /// + /// + /// A list of property names to be included in the returned object + /// + /// + /// A new PSObject with the properties specified in the + /// parameter + /// + private static PSObject CreateCustomOutputObject(ComputerInfo info, List namedProperties) + { + var rv = new PSObject(); + + if (info != null && namedProperties != null && namedProperties.Count > 0) + { + // Walk the list of named properties, find a matching property in the + // info object, and create a new property on the results object + // with the associated value. + var type = info.GetType(); + + foreach (var propertyName in namedProperties) + { + var propInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); + + if (propInfo != null) + { + object value = propInfo.GetValue(info); + rv.Properties.Add(new PSNoteProperty(propertyName, value)); + } + } + } + + return rv; + } + + /// + /// Get the names of all properties. This is + /// part of the processes of validating property names provided by the user. + /// + /// + private static List GetComputerInfoPropertyNames() + { + var rv = new List(); + var type = typeof(ComputerInfo); + + foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + rv.Add(prop.Name); + + return rv; + } + + /// + /// Expand any wild-card patterns into known property names. + /// + /// + /// List of known property names + /// + /// + /// The wild-card pattern used to perform globbing + /// + /// + private static List ExpandWildcardPropertyNames(List propertyNames, string pattern) + { + var rv = new List(); + + var wcp = new WildcardPattern(pattern, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); + + foreach (var name in propertyNames) + if (wcp.IsMatch(name)) + rv.Add(name); + + return rv; + } + + /// + /// Produce a list of known, valid property names from property-name + /// parameters. These parameter may use wild-card patterns and may + /// contain invalid property names. This method expands wild-card + /// patterns and filter out any invalid property names. + /// + /// + /// + /// + private static List CollectPropertyNames(string[] requestedProperties) + { + // A quick scan through the requested properties to make sure + // we want to use user-specified properties + foreach (var name in requestedProperties) + { + if (WildcardPattern.ContainsWildcardCharacters(name)) + { + if (name == "*") + return null; // we treat a wild-card pattern of "*" as if no properties were named + } + } + + var availableProperties = GetComputerInfoPropertyNames(); + var rv = new List(); + + // walk though the requested properties again, expanding and collecting property names + foreach (var name in requestedProperties) + { + if (WildcardPattern.ContainsWildcardCharacters(name)) + { + foreach (var matchedName in ExpandWildcardPropertyNames(availableProperties, name)) + if (!rv.Contains(matchedName)) + rv.Add(matchedName); + } + else + { + // find a matching property name via case-insensitive string comparison + Predicate pred = (s) => + { + return string.Equals(s, + name, + StringComparison.OrdinalIgnoreCase); + }; + var propertyName = availableProperties.Find(pred); + + // add the properly-cased name, if found, to the list + if (propertyName != null && !rv.Contains(propertyName)) + rv.Add(propertyName); + } + } + + return rv; + } + #endregion Private Methods + } + #endregion GetComputerInfoCommand cmdlet implementation + + #region Helper classes + internal static class Conversion + { + /// + /// Attempt to convert a string representation of a base-16 value + /// into an integer. + /// + /// + /// A string containing the text to be parsed. + /// + /// + /// An integer into which the parsed value is stored. If the string + /// cannot be converted, this parameter is set to 0. + /// + /// + /// Returns true if the conversion was successful, false otherwise. + /// + /// + /// The hexString parameter must contain a hexadecimal value, with no + /// base-indication prefix. For example, the string "0409" will be + /// parsed into the base-10 integer value 1033, while the string "0x0409" + /// will fail to parse due to the "0x" base-indication prefix. + /// + internal static bool TryParseHex(string hexString, out uint value) + { + try + { + value = Convert.ToUInt32(hexString, 16); + return true; + } + catch (Exception) + { + value = 0; + return false; + } + } + + /// + /// Attempt to create a + /// object from a locale string as retrieved from WMI. + /// + /// + /// A string containing WMI's notion (usually) of a locale. + /// + /// + /// A CultureInfo object if successful, null otherwise. + /// + /// + /// This method first tries to convert the string to a hex value + /// and get the CultureInfo object from that value. + /// Failing that it attempts to retrieve the CultureInfo object + /// using the locale string as passed. + /// + internal static string GetLocaleName(string locale) + { + CultureInfo culture = null; + + if (locale != null) + { + try + { + // The "locale" must contain a hexadecimal value, with no + // base-indication prefix. For example, the string "0409" will be + // parsed into the base-10 integer value 1033, while the string "0x0409" + // will fail to parse due to the "0x" base-indication prefix. + if (uint.TryParse(locale, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint localeNum)) + { + culture = CultureInfo.GetCultureInfo((int)localeNum); + } + + // If TryParse failed we'll try using the original string as culture name + culture ??= CultureInfo.GetCultureInfo(locale); + } + catch (Exception) + { + culture = null; + } + } + + return culture?.Name; + } + + /// + /// Convert a Unix time, expressed in seconds, to a . + /// + /// Number of seconds since the Unix epoch. + /// + /// A DateTime object representing the date and time represented by the + /// parameter. + /// + internal static DateTime UnixSecondsToDateTime(long seconds) + { +#if false // requires .NET 4.6 or higher + return DateTimeOffset.FromUnixTimeSeconds(seconds).DateTime; +#else + const int DaysPerYear = 365; + const int DaysPer4Years = DaysPerYear * 4 + 1; + const int DaysPer100Years = DaysPer4Years * 25 - 1; + const int DaysPer400Years = DaysPer100Years * 4 + 1; + const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; + const long UnixEpochTicks = TimeSpan.TicksPerDay * DaysTo1970; + + long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks; + + return new DateTimeOffset(ticks, TimeSpan.Zero).DateTime; +#endif + } + } + + /// + /// The EnumConverter class contains a method + /// for converting an integer to a nullable enum of the type specified + /// in T. + /// + /// + /// The type of enum to be the destination of the conversion. + /// + internal static class EnumConverter where T : struct, IConvertible + { + // The converter object + private static readonly Func s_convert = MakeConverter(); + + /// + /// Convert an integer to a Nullable enum of type T. + /// + /// + /// The integer value to be converted to the specified enum type. + /// + /// + /// A Nullable enum object. If the value + /// is convertible to a valid enum value, the returned object's + /// value will contain the converted value, otherwise the returned + /// object will be null. + /// + internal static T? Convert(int? value) + { + try + { + if (value.HasValue) + return s_convert(value.Value); + } + catch (Exception) + { + // nothing should go wrong, but just in case + // fall through to the return null below + } + + return (T?)null; + } + + /// + /// Create a converter using Linq Expression classes. + /// + /// + /// A generic Func{} object to convert an int to the specified enum type. + /// + internal static Func MakeConverter() + { + var param = Expression.Parameter(typeof(int)); + var method = Expression.Lambda> + (Expression.Convert(param, typeof(T?)), param); + + return method.Compile(); + } + } + + internal static class RegistryInfo + { + public static Dictionary GetServerLevels() + { + const string keyPath = @"Software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels"; + + var rv = new Dictionary(); + + using (var key = Registry.LocalMachine.OpenSubKey(keyPath)) + { + if (key != null) + { + foreach (var name in key.GetValueNames()) + { + if (key.GetValueKind(name) == RegistryValueKind.DWord) + { + var val = key.GetValue(name); + rv.Add(name, Convert.ToUInt32(val)); + } + } + } + } + + return rv; + } + + public static string GetLogonServer() + { + const string valueName = "LOGONSERVER"; + const string keyPath = "Volatile Environment"; + + using (var key = Registry.CurrentUser.OpenSubKey(keyPath)) + { + if (key != null) + return (string)key.GetValue(valueName, null); + } + + return null; + } + + public static RegWinNtCurrentVersion GetWinNtCurrentVersion() + { + using (var key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion")) + { + if (key != null) + { + object temp = key.GetValue("InstallDate"); + + return new RegWinNtCurrentVersion() + { + BuildLabEx = (string)key.GetValue("BuildLabEx"), + CurrentVersion = (string)key.GetValue("CurrentVersion"), + EditionId = (string)key.GetValue("EditionID"), + InstallationType = (string)key.GetValue("InstallationType"), + InstallDate = temp == null ? (DateTime?)null + : Conversion.UnixSecondsToDateTime((long)(int)temp), + ProductId = (string)key.GetValue("ProductId"), + ProductName = (string)key.GetValue("ProductName"), + RegisteredOrganization = (string)key.GetValue("RegisteredOrganization"), + RegisteredOwner = (string)key.GetValue("RegisteredOwner"), + SystemRoot = (string)key.GetValue("SystemRoot"), + ReleaseId = (string)key.GetValue("ReleaseId"), + UBR = (int?)key.GetValue("UBR") + }; + } + } + + return null; + } + } + #endregion Helper classes + + #region Intermediate WMI classes + /// + /// Base class for some of the other Intermediate WMI classes, + /// providing some shared methods. + /// + internal abstract class WmiClassBase + { + /// + /// Get a language name from a language identifier. + /// + /// + /// A nullable integer containing the language ID for the desired language. + /// + /// + /// A string containing the display name of the language identified by + /// the language parameter. If the language parameter is null or has a + /// value that is not a valid language ID, the method returns null. + /// + protected static string GetLanguageName(uint? lcid) + { + if (lcid != null && lcid >= 0) + { + try + { + return CultureInfo.GetCultureInfo((int)lcid.Value).Name; + } + catch + { + } + } + + return null; + } + } + +#pragma warning disable 649 // fields and properties in these class are assigned dynamically + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiBaseBoard + { + public string Caption; + public string[] ConfigOptions; + public float? Depth; + public string Description; + public float? Height; + public bool? HostingBoard; + public bool? HotSwappable; + public DateTime? InstallDate; + public string Manufacturer; + public string Model; + public string Name; + public string OtherIdentifyingInfo; + public string PartNumber; + public bool? PoweredOn; + public string Product; + public bool? Removable; + public bool? Replaceable; + public string RequirementsDescription; + public bool? RequiresDaughterBoard; + public string SerialNumber; + public string SKU; + public string SlotLayout; + public bool? SpecialRequirements; + public string Status; + public string Tag; + public string Version; + public float? Weight; + public float? Width; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiBios : WmiClassBase + { + public ushort[] BiosCharacteristics; + public string[] BIOSVersion; + public string BuildNumber; + public string Caption; + public string CodeSet; + public string CurrentLanguage; + public string Description; + public byte? EmbeddedControllerMajorVersion; + public byte? EmbeddedControllerMinorVersion; + public string IdentificationCode; + public ushort? InstallableLanguages; + public DateTime? InstallDate; + public string LanguageEdition; + public string[] ListOfLanguages; + public string Manufacturer; + public string Name; + public string OtherTargetOS; + public bool? PrimaryBIOS; + public DateTime? ReleaseDate; + public string SerialNumber; + public string SMBIOSBIOSVersion; + public ushort? SMBIOSMajorVersion; + public ushort? SMBIOSMinorVersion; + public bool? SMBIOSPresent; + public ushort? SoftwareElementState; + public string Status; + public byte? SystemBiosMajorVersion; + public byte? SystemBiosMinorVersion; + public ushort? TargetOperatingSystem; + public string Version; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiComputerSystem + { + public ushort? AdminPasswordStatus; + public bool? AutomaticManagedPagefile; + public bool? AutomaticResetBootOption; + public bool? AutomaticResetCapability; + public ushort? BootOptionOnLimit; + public ushort? BootOptionOnWatchDog; + public bool? BootROMSupported; + public string BootupState; + public ushort[] BootStatus; + public string Caption; + public ushort? ChassisBootupState; + public string ChassisSKUNumber; + public short? CurrentTimeZone; + public bool? DaylightInEffect; + public string Description; + public string DNSHostName; + public string Domain; + public ushort? DomainRole; + public bool? EnableDaylightSavingsTime; + public ushort? FrontPanelResetStatus; + public bool? HypervisorPresent; + public bool? InfraredSupported; + public string InitialLoadInfo; + public DateTime? InstallDate; + public ushort? KeyboardPasswordStatus; + public string LastLoadInfo; + public string Manufacturer; + public string Model; + public string Name; + public bool? NetworkServerModeEnabled; + public uint? NumberOfLogicalProcessors; + public uint? NumberOfProcessors; + public string[] OEMStringArray; + public bool? PartOfDomain; + public long? PauseAfterReset; + public ushort? PCSystemType; + public ushort? PCSystemTypeEx; + public ushort[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public ushort? PowerOnPasswordStatus; + public ushort? PowerState; + public ushort? PowerSupplyState; + public string PrimaryOwnerContact; + public string PrimaryOwnerName; + public ushort? ResetCapability; + public short? ResetCount; + public short? ResetLimit; + public string[] Roles; + public string Status; + public string[] SupportContactDescription; + public string SystemFamily; + public string SystemSKUNumber; + public string SystemType; + public ushort? ThermalState; + public ulong? TotalPhysicalMemory; + public string UserName; + public ushort? WakeUpType; + public string Workgroup; + + public PowerManagementCapabilities[] GetPowerManagementCapabilities() + { + if (PowerManagementCapabilities != null) + { + var list = new List(); + + foreach (var cap in PowerManagementCapabilities) + { + var val = EnumConverter.Convert(cap); + + if (val != null) + list.Add(val.Value); + } + + return list.ToArray(); + } + + return null; + } + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiDeviceGuard + { + public uint[] AvailableSecurityProperties; + public uint? CodeIntegrityPolicyEnforcementStatus; + public uint? UsermodeCodeIntegrityPolicyEnforcementStatus; + public uint[] RequiredSecurityProperties; + public uint[] SecurityServicesConfigured; + public uint[] SecurityServicesRunning; + public uint? VirtualizationBasedSecurityStatus; + + public DeviceGuard AsOutputType + { + get + { + var guard = new DeviceGuard(); + + var status = EnumConverter.Convert((int?)VirtualizationBasedSecurityStatus); + if (status != null && status != DeviceGuardSmartStatus.Off) + { + var listHardware = new List(); + for (int i = 0; i < RequiredSecurityProperties.Length; i++) + { + var temp = EnumConverter.Convert((int?)RequiredSecurityProperties[i]); + + if (temp != null) + listHardware.Add(temp.Value); + } + + guard.RequiredSecurityProperties = listHardware.ToArray(); + + listHardware.Clear(); + for (int i = 0; i < AvailableSecurityProperties.Length; i++) + { + var temp = EnumConverter.Convert((int?)AvailableSecurityProperties[i]); + + if (temp != null) + listHardware.Add(temp.Value); + } + + guard.AvailableSecurityProperties = listHardware.ToArray(); + + var listSoftware = new List(); + for (int i = 0; i < SecurityServicesConfigured.Length; i++) + { + var temp = EnumConverter.Convert((int?)SecurityServicesConfigured[i]); + + if (temp != null) + listSoftware.Add(temp.Value); + } + + guard.SecurityServicesConfigured = listSoftware.ToArray(); + + listSoftware.Clear(); + for (int i = 0; i < SecurityServicesRunning.Length; i++) + { + var temp = EnumConverter.Convert((int?)SecurityServicesRunning[i]); + + if (temp != null) + listSoftware.Add(temp.Value); + } + + guard.SecurityServicesRunning = listSoftware.ToArray(); + } + + var configCiStatus = EnumConverter.Convert((int?)CodeIntegrityPolicyEnforcementStatus); + var userModeCiStatus = EnumConverter.Convert((int?)UsermodeCodeIntegrityPolicyEnforcementStatus); + guard.CodeIntegrityPolicyEnforcementStatus = configCiStatus; + guard.UserModeCodeIntegrityPolicyEnforcementStatus = userModeCiStatus; + + return guard; + } + } + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiKeyboard + { + public ushort? Availability; + public string Caption; + public uint? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public string Description; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public DateTime? InstallDate; + public bool? IsLocked; + public uint? LastErrorCode; + public string Layout; + public string Name; + public ushort? NumberOfFunctionKeys; + public ushort? Password; + public string PNPDeviceID; + public ushort[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public string Status; + public ushort? StatusInfo; + public string SystemCreationClassName; + public string SystemName; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WMiLogicalMemory + { + // TODO: fill this in!!! + public uint? TotalPhysicalMemory; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiMsftNetAdapter + { + public string Caption; + public string Description; + public DateTime? InstallDate; + public string Name; + public string Status; + public ushort? Availability; + public uint? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public uint? LastErrorCode; + public string PNPDeviceID; + public ushort[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public ushort? StatusInfo; + public string SystemCreationClassName; + public string SystemName; + public ulong? Speed; + public ulong? MaxSpeed; + public ulong? RequestedSpeed; + public ushort? UsageRestriction; + public ushort? PortType; + public string OtherPortType; + public string OtherNetworkPortType; + public ushort? PortNumber; + public ushort? LinkTechnology; + public string OtherLinkTechnology; + public string PermanentAddress; + public string[] NetworkAddresses; + public bool? FullDuplex; + public bool? AutoSense; + public ulong? SupportedMaximumTransmissionUnit; + public ulong? ActiveMaximumTransmissionUnit; + public string InterfaceDescription; + public string InterfaceName; + public ulong? NetLuid; + public string InterfaceGuid; + public uint? InterfaceIndex; + public string DeviceName; + public uint? NetLuidIndex; + public bool? Virtual; + public bool? Hidden; + public bool? NotUserRemovable; + public bool? IMFilter; + public uint? InterfaceType; + public bool? HardwareInterface; + public bool? WdmInterface; + public bool? EndPointInterface; + public bool? iSCSIInterface; + public uint? State; + public uint? NdisMedium; + public uint? NdisPhysicalMedium; + public uint? InterfaceOperationalStatus; + public bool? OperationalStatusDownDefaultPortNotAuthenticated; + public bool? OperationalStatusDownMediaDisconnected; + public bool? OperationalStatusDownInterfacePaused; + public bool? OperationalStatusDownLowPowerState; + public uint? InterfaceAdminStatus; + public uint? MediaConnectState; + public uint? MtuSize; + public ushort? VlanID; + public ulong? TransmitLinkSpeed; + public ulong? ReceiveLinkSpeed; + public bool? PromiscuousMode; + public bool? DeviceWakeUpEnable; + public bool? ConnectorPresent; + public uint? MediaDuplexState; + public string DriverDate; + public ulong? DriverDateData; + public string DriverVersionString; + public string DriverName; + public string DriverDescription; + public ushort? MajorDriverVersion; + public ushort? MinorDriverVersion; + public byte? DriverMajorNdisVersion; + public byte? DriverMinorNdisVersion; + public string PnPDeviceID; + public string DriverProvider; + public string ComponentID; + public uint[] LowerLayerInterfaceIndices; + public uint[] HigherLayerInterfaceIndices; + public bool? AdminLocked; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiNetworkAdapter + { + public string AdapterType; + public ushort? AdapterTypeID; + public bool? AutoSense; + public ushort? Availability; + public string Caption; + public uint? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public string Description; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public string GUID; + public uint? Index; + public DateTime? InstallDate; + public bool? Installed; + public uint? InterfaceIndex; + public uint? LastErrorCode; + public string MACAddress; + public string Manufacturer; + public uint? MaxNumberControlled; + public ulong? MaxSpeed; + public string Name; + public string NetConnectionID; + public ushort? NetConnectionStatus; + public bool? NetEnabled; + public string[] NetworkAddresses; + public string PermanentAddress; + public bool? PhysicalAdapter; + public string PNPDeviceID; + public ushort[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public string ProductName; + public string ServiceName; + public ulong? Speed; + public string Status; + public ushort? StatusInfo; + public string SystemCreationClassName; + public string SystemName; + public DateTime? TimeOfLastReset; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiNetworkAdapterConfiguration + { + public bool? ArpAlwaysSourceRoute; + public bool? ArpUseEtherSNAP; + public string Caption; + public string DatabasePath; + public bool? DeadGWDetectEnabled; + public string[] DefaultIPGateway; + public byte? DefaultTOS; + public byte? DefaultTTL; + public string Description; + public bool? DHCPEnabled; + public DateTime? DHCPLeaseExpires; + public DateTime? DHCPLeaseObtained; + public string DHCPServer; + public string DNSDomain; + public string[] DNSDomainSuffixSearchOrder; + public bool? DNSEnabledForWINSResolution; + public string DNSHostName; + public string[] DNSServerSearchOrder; + public bool? DomainDNSRegistrationEnabled; + public uint? ForwardBufferMemory; + public bool? FullDNSRegistrationEnabled; + public ushort[] GatewayCostMetric; + public byte? IGMPLevel; + public uint? Index; + public uint? InterfaceIndex; + public string[] IPAddress; + public uint? IPConnectionMetric; + public bool? IPEnabled; + public bool? IPFilterSecurityEnabled; + public bool? IPPortSecurityEnabled; + public string[] IPSecPermitIPProtocols; + public string[] IPSecPermitTCPPorts; + public string[] IPSecPermitUDPPorts; + public string[] IPSubnet; + public bool? IPUseZeroBroadcast; + public string IPXAddress; + public bool? IPXEnabled; + public uint[] IPXFrameType; + public uint? IPXMediaType; + public string[] IPXNetworkNumber; + public string IPXVirtualNetNumber; + public uint? KeepAliveInterval; + public uint? KeepAliveTime; + public string MACAddress; + public uint? MTU; + public uint? NumForwardPackets; + public bool? PMTUBHDetectEnabled; + public bool? PMTUDiscoveryEnabled; + public string ServiceName; + public string SettingID; + public uint? TcpipNetbiosOptions; + public uint? TcpMaxConnectRetransmissions; + public uint? TcpMaxDataRetransmissions; + public uint? TcpNumConnections; + public bool? TcpUseRFC1122UrgentPointer; + public ushort? TcpWindowSize; + public bool? WINSEnableLMHostsLookup; + public string WINSHostLookupFile; + public string WINSPrimaryServer; + public string WINSScopeID; + public string WINSSecondaryServer; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiOperatingSystem : WmiClassBase + { + #region Fields + public string BootDevice; + public string BuildNumber; + public string BuildType; + public string Caption; + public string CodeSet; + public string CountryCode; + public string CSDVersion; + public string CSName; + public short? CurrentTimeZone; + public bool? DataExecutionPrevention_Available; + public bool? DataExecutionPrevention_32BitApplications; + public bool? DataExecutionPrevention_Drivers; + public byte? DataExecutionPrevention_SupportPolicy; + public bool? Debug; + public string Description; + public bool? Distributed; + public uint? EncryptionLevel; + public byte? ForegroundApplicationBoost; + public ulong? FreePhysicalMemory; + public ulong? FreeSpaceInPagingFiles; + public ulong? FreeVirtualMemory; + public DateTime? InstallDate; + public DateTime? LastBootUpTime; + public DateTime? LocalDateTime; + public string Locale; + public string Manufacturer; + public uint? MaxNumberOfProcesses; + public ulong? MaxProcessMemorySize; + public string[] MUILanguages; + public string Name; + public uint? NumberOfLicensedUsers; + public uint? NumberOfProcesses; + public uint? NumberOfUsers; + public uint? OperatingSystemSKU; + public string Organization; + public string OSArchitecture; + public uint? OSLanguage; + public uint? OSProductSuite; + public ushort? OSType; + public string OtherTypeDescription; + public bool? PAEEnabled; + public bool? PortableOperatingSystem; + public bool? Primary; + public uint? ProductType; + public string RegisteredUser; + public string SerialNumber; + public ushort? ServicePackMajorVersion; + public ushort? ServicePackMinorVersion; + public ulong? SizeStoredInPagingFiles; + public string Status; + public uint? SuiteMask; + public string SystemDevice; + public string SystemDirectory; + public string SystemDrive; + public ulong? TotalSwapSpaceSize; + public ulong? TotalVirtualMemorySize; + public ulong? TotalVisibleMemorySize; + public string Version; + public string WindowsDirectory; + #endregion Fields + + #region Public Properties + public string LanguageName + { + get { return GetLanguageName(OSLanguage); } + } + + public OSProductSuite[] ProductSuites + { + get { return MakeProductSuites(OSProductSuite); } + } + + public OSProductSuite[] Suites + { + get { return MakeProductSuites(SuiteMask); } + } + #endregion Public Properties + + #region Public Methods + public string GetLocale() + { + return Conversion.GetLocaleName(Locale); + } + #endregion Public Methods + + #region Private Methods + private static OSProductSuite[] MakeProductSuites(uint? suiteMask) + { + if (suiteMask == null) + return null; + + var mask = suiteMask.Value; + var list = new List(); + + foreach (OSProductSuite suite in Enum.GetValues()) + if ((mask & (uint)suite) != 0) + list.Add(suite); + + return list.ToArray(); + } + #endregion Private Methods + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiPageFileUsage + { + public uint? AllocatedBaseSize; + public string Caption; + public uint? CurrentUsage; + public string Description; + public DateTime? InstallDate; + public string Name; + public uint? PeakUsage; + public string Status; + public bool? TempPageFile; + } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] + internal sealed class WmiProcessor + { + public ushort? AddressWidth; + public ushort? Architecture; + public string AssetTag; + public ushort? Availability; + public string Caption; + public uint? Characteristics; + public uint? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public ushort? CpuStatus; + public uint? CurrentClockSpeed; + public ushort? CurrentVoltage; + public ushort? DataWidth; + public string Description; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public uint? ExtClock; + public ushort? Family; + public DateTime? InstallDate; + public uint? L2CacheSize; + public uint? L2CacheSpeed; + public uint? L3CacheSize; + public uint? L3CacheSpeed; + public uint? LastErrorCode; + public ushort? Level; + public ushort? LoadPercentage; + public string Manufacturer; + public uint? MaxClockSpeed; + public string Name; + public uint? NumberOfCores; + public uint? NumberOfEnabledCore; + public uint? NumberOfLogicalProcessors; + public string OtherFamilyDescription; + public string PartNumber; + public string PNPDeviceID; + public ushort[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public string ProcessorId; + public ushort? ProcessorType; + public ushort? Revision; + public string Role; + public bool? SecondLevelAddressTranslationExtensions; + public string SerialNumber; + public string SocketDesignation; + public string Status; + public ushort? StatusInfo; + public string Stepping; + public string SystemName; + public uint? ThreadCount; + public string UniqueId; + public ushort? UpgradeMethod; + public string Version; + public bool? VirtualizationFirmwareEnabled; + public bool? VMMonitorModeExtensions; + public uint? VoltageCaps; + } + +#pragma warning restore 649 + #endregion Intermediate WMI classes + + #region Other Intermediate classes + internal sealed class RegWinNtCurrentVersion + { + public string BuildLabEx; + public string CurrentVersion; + public string EditionId; + public string InstallationType; + public DateTime? InstallDate; + public string ProductId; + public string ProductName; + public string RegisteredOrganization; + public string RegisteredOwner; + public string SystemRoot; + public string ReleaseId; + public int? UBR; + } + #endregion Other Intermediate classes + + #region Output components + #region Classes comprising the output object + /// + /// Provides information about Device Guard. + /// + public class DeviceGuard + { + /// + /// Array of required security properties. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardHardwareSecure[] RequiredSecurityProperties { get; internal set; } + /// + /// Array of available security properties. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardHardwareSecure[] AvailableSecurityProperties { get; internal set; } + /// + /// Indicates which security services have been configured. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardSoftwareSecure[] SecurityServicesConfigured { get; internal set; } + /// + /// Indicates which security services are running. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardSoftwareSecure[] SecurityServicesRunning { get; internal set; } + /// + /// Indicates the status of the Device Guard Code Integrity policy. + /// + public DeviceGuardConfigCodeIntegrityStatus? CodeIntegrityPolicyEnforcementStatus { get; internal set; } + + /// + /// Indicates the status of the Device Guard user mode Code Integrity policy. + /// + public DeviceGuardConfigCodeIntegrityStatus? UserModeCodeIntegrityPolicyEnforcementStatus { get; internal set; } + } + + /// + /// Describes a Quick-Fix Engineering update. + /// + public class HotFix + { + /// + /// Unique identifier associated with a particular update. + /// + public string HotFixID + { + get; + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")] + internal set; + } + + /// + /// Description of the update. + /// + public string Description + { + get; + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")] + internal set; + } + + /// + /// String containing the date that the update was installed. + /// + public string InstalledOn + { + get; + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")] + internal set; + } + + /// + /// Additional comments that relate to the update. + /// + public string FixComments + { + get; + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")] + internal set; + } + } + + /// + /// Provides information about a network adapter. + /// + public class NetworkAdapter + { + /// + /// Description of the network adapter. + /// + public string Description { get; internal set; } + /// + /// Name of the network connection as it appears in the Network + /// Connections Control Panel program. + /// + public string ConnectionID { get; internal set; } + /// + /// Indicates whether the DHCP server automatically assigns an IP address + /// to the computer system when establishing a network connection. + /// + public bool? DHCPEnabled { get; internal set; } + /// + /// IP Address of the DHCP server. + /// + public string DHCPServer { get; internal set; } + /// + /// State of the network adapter connection to the network. + /// + public NetConnectionStatus ConnectionStatus { get; internal set; } + /// + /// Array of all of the IP addresses associated with the current network adapter. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] IPAddresses { get; internal set; } + } + + /// + /// Describes a processor on the computer. + /// + public class Processor + { + /// + /// Name of the processor. + /// + public string Name { get; internal set; } + /// + /// Name of the processor manufacturer. + /// + public string Manufacturer { get; internal set; } + /// + /// Description of the processor. + /// + public string Description { get; internal set; } + /// + /// Processor architecture used by the platform. + /// + public CpuArchitecture? Architecture { get; internal set; } + /// + /// Address width of the processor. + /// + public ushort? AddressWidth { get; internal set; } + /// + /// Data width of the processor. + /// + public ushort? DataWidth { get; internal set; } + /// + /// Maximum speed of the processor, in MHz. + /// + public uint? MaxClockSpeed { get; internal set; } + /// + /// Current speed of the processor, in MHz. + /// + public uint? CurrentClockSpeed { get; internal set; } + /// + /// Number of cores for the current instance of the processor. + /// + /// + /// A core is a physical processor on the integrated circuit + /// + public uint? NumberOfCores { get; internal set; } + /// + /// Number of logical processors for the current instance of the processor. + /// + /// + /// For processors capable of hyperthreading, this value includes only the + /// processors which have hyperthreading enabled + /// + public uint? NumberOfLogicalProcessors { get; internal set; } + /// + /// Processor information that describes the processor features. + /// + /// + /// For an x86 class CPU, the field format depends on the processor support + /// of the CPUID instruction. If the instruction is supported, the property + /// contains 2 (two) DWORD formatted values. The first is an offset of 08h-0Bh, + /// which is the EAX value that a CPUID instruction returns with input EAX set + /// to 1. The second is an offset of 0Ch-0Fh, which is the EDX value that the + /// instruction returns. Only the first two bytes of the property are significant + /// and contain the contents of the DX register at CPU reset—all others are set + /// to 0 (zero), and the contents are in DWORD format + /// + public string ProcessorID { get; internal set; } + /// + /// Type of chip socket used on the circuit. + /// + public string SocketDesignation { get; internal set; } + /// + /// Primary function of the processor. + /// + public ProcessorType? ProcessorType { get; internal set; } + /// + /// Role of the processor. + /// + public string Role { get; internal set; } + /// + /// Current status of the processor. + /// + public string Status { get; internal set; } + /// + /// Current status of the processor. + /// Status changes indicate processor usage, but not the physical + /// condition of the processor. + /// + public CpuStatus? CpuStatus { get; internal set; } + /// + /// Availability and status of the processor. + /// + public CpuAvailability? Availability { get; internal set; } + } + + /// + /// The ComputerInfo class is output to the PowerShell pipeline. + /// + public class ComputerInfo + { + #region Registry + /// + /// Windows build lab information, from the Windows Registry. + /// + public string WindowsBuildLabEx { get; internal set; } + + /// + /// Windows version number, from the Windows Registry. + /// + public string WindowsCurrentVersion { get; internal set; } + + /// + /// Windows edition, from the Windows Registry. + /// + public string WindowsEditionId { get; internal set; } + + /// + /// Windows installation type, from the Windows Registry. + /// + public string WindowsInstallationType { get; internal set; } + + /// + /// The data Windows was installed, from the Windows Registry. + /// + public DateTime? WindowsInstallDateFromRegistry { get; internal set; } + + /// + /// The Windows product ID, from the Windows Registry. + /// + public string WindowsProductId { get; internal set; } + + /// + /// The Windows product name, from the Windows Registry. + /// + public string WindowsProductName { get; internal set; } + + /// + /// Name of the organization that this installation of Windows is registered to, from the Windows Registry. + /// + public string WindowsRegisteredOrganization { get; internal set; } + + /// + /// Name of the registered owner of this installation of Windows, from the Windows Registry. + /// + public string WindowsRegisteredOwner { get; internal set; } + + /// + /// Path to the operating system's root directory, from the Windows Registry. + /// + public string WindowsSystemRoot { get; internal set; } + + /// + /// The Windows ReleaseId, from the Windows Registry. + /// + public string WindowsVersion { get; internal set; } + + /// + /// The Windows Update Build Revision (UBR), from the Windows Registry. + /// + public int? WindowsUBR { get; internal set; } + #endregion Registry + + #region BIOS + /// + /// Array of BIOS characteristics supported by the system as defined by + /// the System Management BIOS Reference Specification. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public ushort[] BiosCharacteristics { get; internal set; } + + /// + /// Array of the complete system BIOS information. In many computers + /// there can be several version strings that are stored in the registry + /// and represent the system BIOS information. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] BiosBIOSVersion { get; internal set; } + + /// + /// Internal identifier for this compilation of the BIOS firmware. + /// + public string BiosBuildNumber { get; internal set; } + + /// + /// Short description of the BIOS. + /// + public string BiosCaption { get; internal set; } + + /// + /// Code set used by the BIOS. + /// + public string BiosCodeSet { get; internal set; } + + /// + /// Name of the current BIOS language. + /// + public string BiosCurrentLanguage { get; internal set; } + + /// + /// Description of the BIOS. + /// + public string BiosDescription { get; internal set; } + + /// + /// Major version of the embedded controller firmware. + /// + public short? BiosEmbeddedControllerMajorVersion { get; internal set; } + + /// + /// Minor version of the embedded controller firmware. + /// + public short? BiosEmbeddedControllerMinorVersion { get; internal set; } + + /// + /// Firmware type of the local computer. + /// + /// + /// This is acquired via the GetFirmwareType Windows API function + /// + public FirmwareType? BiosFirmwareType { get; internal set; } + + /// + /// Manufacturer's identifier for this software element. + /// Often this will be a stock keeping unit (SKU) or a part number. + /// + public string BiosIdentificationCode { get; internal set; } + + /// + /// Number of languages available for installation on this system. + /// Language may determine properties such as the need for Unicode and bidirectional text. + /// + public ushort? BiosInstallableLanguages { get; internal set; } + + /// + /// Date and time the object was installed. + /// + // TODO: do we want this? On my system this is null + public DateTime? BiosInstallDate { get; internal set; } + + /// + /// Language edition of the BIOS firmware. + /// The language codes defined in ISO 639 should be used. + /// Where the software element represents a multilingual or international + /// version of a product, the string "multilingual" should be used. + /// + public string BiosLanguageEdition { get; internal set; } + + /// + /// Array of names of available BIOS-installable languages. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] BiosListOfLanguages { get; internal set; } + + /// + /// Manufacturer of the BIOS. + /// + public string BiosManufacturer { get; internal set; } + + /// + /// Name used to identify the BIOS. + /// + public string BiosName { get; internal set; } + + /// + /// Records the manufacturer and operating system type for the BIOS when + /// the BiosTargetOperatingSystem property has a value of 1 (Other). + /// When TargetOperatingSystem has a value of 1, BiosOtherTargetOS must + /// have a nonnull value. For all other values of BiosTargetOperatingSystem, + /// BiosOtherTargetOS is NULL. + /// + public string BiosOtherTargetOS { get; internal set; } + + /// + /// If true, this is the primary BIOS of the computer system. + /// + public bool? BiosPrimaryBIOS { get; internal set; } + + /// + /// Release date of the Windows BIOS. + /// + public DateTime? BiosReleaseDate { get; internal set; } + + /// + /// Assigned serial number of the BIOS. + /// + public string BiosSerialNumber { get; internal set; } + + /// + /// BIOS version as reported by SMBIOS. + /// + public string BiosSMBIOSBIOSVersion { get; internal set; } + + /// + /// SMBIOS major version number. This property is null if SMBIOS is not found. + /// + public ushort? BiosSMBIOSMajorVersion { get; internal set; } + + /// + /// SMBIOS minor version number. This property is null if SMBIOS is not found. + /// + public ushort? BiosSMBIOSMinorVersion { get; internal set; } + + /// + /// If true, the SMBIOS is available on this computer system. + /// + public bool? BiosSMBIOSPresent { get; internal set; } + + /// + /// State of a BIOS software element. + /// + public SoftwareElementState? BiosSoftwareElementState { get; internal set; } + + /// + /// Status of the BIOS. + /// + public string BiosStatus { get; internal set; } + + /// + /// Major elease of the System BIOS. + /// + public ushort? BiosSystemBiosMajorVersion { get; internal set; } + + /// + /// Minor release of the System BIOS. + /// + public ushort? BiosSystemBiosMinorVersion { get; internal set; } + + /// + /// Target operating system. + /// + public ushort? BiosTargetOperatingSystem { get; internal set; } + + /// + /// Version of the BIOS. + /// This string is created by the BIOS manufacturer. + /// + public string BiosVersion { get; internal set; } + #endregion BIOS + + #region Computer System + /// + /// System hardware security settings for administrator password status. + /// + // public AdminPasswordStatus? CsAdminPasswordStatus { get; internal set; } + + public HardwareSecurity? CsAdminPasswordStatus { get; internal set; } + + /// + /// If true, the system manages the page file. + /// + public bool? CsAutomaticManagedPagefile { get; internal set; } + + /// + /// If True, the automatic reset boot option is enabled. + /// + public bool? CsAutomaticResetBootOption { get; internal set; } + + /// + /// If True, the automatic reset is enabled. + /// + public bool? CsAutomaticResetCapability { get; internal set; } + + /// + /// Boot option limit is ON. Identifies the system action when the + /// CsResetLimit value is reached. + /// + public BootOptionAction? CsBootOptionOnLimit { get; internal set; } + + /// + /// Type of reboot action after the time on the watchdog timer is elapsed. + /// + public BootOptionAction? CsBootOptionOnWatchDog { get; internal set; } + + /// + /// If true, indicates whether a boot ROM is supported. + /// + public bool? CsBootROMSupported { get; internal set; } + + /// + /// Status and Additional Data fields that identify the boot status. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public ushort[] CsBootStatus { get; internal set; } + + /// + /// System is started. Fail-safe boot bypasses the user startup files—also called SafeBoot. + /// + public string CsBootupState { get; internal set; } + + /// + /// The name of this computer. + /// + public string CsCaption { get; internal set; } // TODO: remove this? Same as CsName??? + + /// + /// Boot up state of the chassis. + /// + // public ChassisBootupState? CsChassisBootupState { get; internal set; } + + public SystemElementState? CsChassisBootupState { get; internal set; } + + /// + /// The chassis or enclosure SKU number as a string. + /// + public string CsChassisSKUNumber { get; internal set; } + + /// + /// Amount of time the unitary computer system is offset from Coordinated + /// Universal Time (UTC). + /// + public short? CsCurrentTimeZone { get; internal set; } + + /// + /// If True, the daylight savings mode is ON. + /// + public bool? CsDaylightInEffect { get; internal set; } + + /// + /// Description of the computer system. + /// + public string CsDescription { get; internal set; } + + /// + /// Name of local computer according to the domain name server. + /// + public string CsDNSHostName { get; internal set; } + + /// + /// Name of the domain to which a computer belongs. + /// + /// + /// If the computer is not part of a domain, then the name of the workgroup is returned + /// + public string CsDomain { get; internal set; } + + /// + /// Role of a computer in an assigned domain workgroup. A domain workgroup + /// is a collection of computers on the same network. For example, + /// a DomainRole property may show that a computer is a member workstation. + /// + public DomainRole? CsDomainRole { get; internal set; } + + /// + /// Enables daylight savings time on a computer. A value of True indicates + /// that the system time changes to an hour ahead or behind when DST starts + /// or ends. A value of False indicates that the system time does not change + /// to an hour ahead or behind when DST starts or ends. A value of NULL + /// indicates that the DST status is unknown on a system. + /// + public bool? CsEnableDaylightSavingsTime { get; internal set; } + + /// + /// Hardware security setting for the reset button on a computer. + /// + // public FrontPanelResetStatus? CsFrontPanelResetStatus { get; internal set; } + + public HardwareSecurity? CsFrontPanelResetStatus { get; internal set; } + + /// + /// If True, a hypervisor is present. + /// + public bool? CsHypervisorPresent { get; internal set; } + + /// + /// If True, an infrared port exists on a computer system. + /// + public bool? CsInfraredSupported { get; internal set; } + + /// + /// Data required to find the initial load device or boot service to request that the operating system start up. + /// + public string CsInitialLoadInfo { get; internal set; } + + /// + /// Object is installed. An object does not need a value to indicate that it is installed. + /// + public DateTime? CsInstallDate { get; internal set; } + + /// + /// System hardware security setting for Keyboard Password Status. + /// + // public KeyboardPasswordStatus? CsKeyboardPasswordStatus { get; internal set; } + + public HardwareSecurity? CsKeyboardPasswordStatus { get; internal set; } + + /// + /// Array entry of the CsInitialLoadInfo property that contains the data + /// to start the loaded operating system. + /// + public string CsLastLoadInfo { get; internal set; } + + /// + /// Name of the computer manufacturer. + /// + public string CsManufacturer { get; internal set; } + + /// + /// Product name that a manufacturer gives to a computer. + /// + public string CsModel { get; internal set; } + + /// + /// Key of a CIM_System instance in an enterprise environment. + /// + public string CsName { get; internal set; } + + /// + /// An array of objects describing any + /// network adapters on the system. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public NetworkAdapter[] CsNetworkAdapters { get; internal set; } + + /// + /// If True, the network Server Mode is enabled. + /// + public bool? CsNetworkServerModeEnabled { get; internal set; } + + /// + /// Number of logical processors available on the computer. + /// + public uint? CsNumberOfLogicalProcessors { get; internal set; } + + /// + /// Number of physical processors currently available on a system. + /// + /// + /// This is the number of enabled processors for a system, which + /// does not include the disabled processors. If a computer system + /// has two physical processors each containing two logical processors, + /// then the value of CsNumberOfProcessors is 2 and CsNumberOfLogicalProcessors + /// is 4. The processors may be multicore or they may be hyperthreading processors + /// + public uint? CsNumberOfProcessors { get; internal set; } + + /// + /// Array of objects describing each processor on the system. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Processor[] CsProcessors { get; internal set; } + + /// + /// Array of free-form strings that an OEM defines. + /// For example, an OEM defines the part numbers for system reference + /// documents, manufacturer contact information, and so on. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] CsOEMStringArray { get; internal set; } + + /// + /// If True, the computer is part of a domain. + /// If the value is NULL, the computer is not in a domain or the status is unknown. + /// + public bool? CsPartOfDomain { get; internal set; } + + /// + /// Time delay before a reboot is initiated, in milliseconds. + /// It is used after a system power cycle, local or remote system reset, + /// and automatic system reset. A value of –1 (minus one) indicates that + /// the pause value is unknown. + /// + public long? CsPauseAfterReset { get; internal set; } + + /// + /// Type of the computer in use, such as laptop, desktop, or tablet. + /// + public PCSystemType? CsPCSystemType { get; internal set; } + + /// + /// Type of the computer in use, such as laptop, desktop, or tablet. + /// + public PCSystemTypeEx? CsPCSystemTypeEx { get; internal set; } + + /// + /// Array of the specific power-related capabilities of a logical device. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public PowerManagementCapabilities[] CsPowerManagementCapabilities { get; internal set; } + + /// + /// If True, device can be power-managed, for example, a device can be + /// put into suspend mode, and so on. + /// + /// + /// This property does not indicate that power management features are + /// enabled currently, but it does indicate that the logical device is + /// capable of power management + /// + public bool? CsPowerManagementSupported { get; internal set; } + + /// + /// System hardware security setting for Power-On Password Status. + /// + // public PowerOnPasswordStatus? CsPowerOnPasswordStatus { get; internal set; } + + public HardwareSecurity? CsPowerOnPasswordStatus { get; internal set; } + + /// + /// Current power state of a computer and its associated operating system. + /// + public PowerState? CsPowerState { get; internal set; } + + /// + /// State of the power supply or supplies when last booted. + /// + // public PowerSupplyState? CsPowerSupplyState { get; internal set; } + + public SystemElementState? CsPowerSupplyState { get; internal set; } + + /// + /// Contact information for the primary system owner. + /// For example, phone number, email address, and so on. + /// + public string CsPrimaryOwnerContact { get; internal set; } + + /// + /// Name of the primary system owner. + /// + public string CsPrimaryOwnerName { get; internal set; } + + /// + /// Indicates if the computer system can be reset. + /// + public ResetCapability? CsResetCapability { get; internal set; } + + /// + /// Number of automatic resets since the last reset. + /// A value of –1 (minus one) indicates that the count is unknown. + /// + public short? CsResetCount { get; internal set; } + + /// + /// Number of consecutive times a system reset is attempted. + /// A value of –1 (minus one) indicates that the limit is unknown. + /// + public short? CsResetLimit { get; internal set; } + + /// + /// Array that specifies the roles of a system in the information + /// technology environment. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] CsRoles { get; internal set; } + + /// + /// Statis pf the computer system. + /// + public string CsStatus { get; internal set; } + + /// + /// Array of the support contact information for the Windows operating system. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] CsSupportContactDescription { get; internal set; } + + /// + /// The family to which a particular computer belongs. + /// A family refers to a set of computers that are similar but not + /// identical from a hardware or software point of view. + /// + public string CsSystemFamily { get; internal set; } + + /// + /// Identifies a particular computer configuration for sale. + /// It is sometimes also called a product ID or purchase order number. + /// + public string CsSystemSKUNumber { get; internal set; } + + /// + /// System running on the Windows-based computer. + /// + public string CsSystemType { get; internal set; } + + /// + /// Thermal state of the system when last booted. + /// + // public ThermalState? CsThermalState { get; internal set; } + + public SystemElementState? CsThermalState { get; internal set; } + + /// + /// Total size of physical memory. + /// + /// + /// Be aware that, under some circumstances, this property may not + /// return an accurate value for the physical memory. For example, + /// it is not accurate if the BIOS is using some of the physical memory + /// + public ulong? CsTotalPhysicalMemory { get; internal set; } + + /// + /// Size of physically installed memory, as reported by the Windows API + /// function GetPhysicallyInstalledSystemMemory. + /// + public ulong? CsPhysicallyInstalledMemory { get; internal set; } + + /// + /// Name of a user that is logged on currently. + /// + /// + /// In a terminal services session, CsUserName is the name of the user + /// that is logged on to the console—not the user logged on during the + /// terminal service session + /// + public string CsUserName { get; internal set; } + + /// + /// Event that causes the system to power up. + /// + public WakeUpType? CsWakeUpType { get; internal set; } + + /// + /// Name of the workgroup for this computer. + /// + public string CsWorkgroup { get; internal set; } + #endregion Computer System + + #region Operating System + /// + /// Name of the operating system. + /// + public string OsName { get; internal set; } + + /// + /// Type of operating system. + /// + public OSType? OsType { get; internal set; } + + /// + /// SKU number for the operating system. + /// + public OperatingSystemSKU? OsOperatingSystemSKU { get; internal set; } + + /// + /// Version number of the operating system. + /// + public string OsVersion { get; internal set; } + + /// + /// String that indicates the latest service pack installed on a computer. + /// If no service pack is installed, the string is NULL. + /// + public string OsCSDVersion { get; internal set; } + + /// + /// Build number of the operating system. + /// + public string OsBuildNumber { get; internal set; } + + /// + /// Array of objects containing information about + /// any Quick-Fix Engineering patches (Hot Fixes) applied to the operating + /// system. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public HotFix[] OsHotFixes { get; internal set; } + + /// + /// Name of the disk drive from which the Windows operating system starts. + /// + public string OsBootDevice { get; internal set; } + + /// + /// Physical disk partition on which the operating system is installed. + /// + public string OsSystemDevice { get; internal set; } + + /// + /// System directory of the operating system. + /// + public string OsSystemDirectory { get; internal set; } + + /// + /// Letter of the disk drive on which the operating system resides. + /// + public string OsSystemDrive { get; internal set; } + + /// + /// Windows directory of the operating system. + /// + public string OsWindowsDirectory { get; internal set; } + + /// + /// Code for the country/region that an operating system uses. + /// + /// + /// Values are based on international phone dialing prefixes—also + /// referred to as IBM country/region codes + /// + public string OsCountryCode { get; internal set; } + + /// + /// Number, in minutes, an operating system is offset from Greenwich + /// mean time (GMT). The number is positive, negative, or zero. + /// + public short? OsCurrentTimeZone { get; internal set; } + + /// + /// Language identifier used by the operating system. + /// + /// + /// A language identifier is a standard international numeric abbreviation + /// for a country/region. Each language has a unique language identifier (LANGID), + /// a 16-bit value that consists of a primary language identifier and a secondary + /// language identifier + /// + public string OsLocaleID { get; internal set; } // From Win32_OperatingSystem.Locale + + /// + /// The culture name, such as "en-US", derived from the property. + /// + public string OsLocale { get; internal set; } + + /// + /// Operating system version of the local date and time-of-day. + /// + public DateTime? OsLocalDateTime { get; internal set; } + + /// + /// Date and time the operating system was last restarted. + /// + public DateTime? OsLastBootUpTime { get; internal set; } + + /// + /// The interval between the time the operating system was last + /// restarted and the current time. + /// + public TimeSpan? OsUptime { get; internal set; } + + /// + /// Type of build used for the operating system. + /// + public string OsBuildType { get; internal set; } + + /// + /// Code page value the operating system uses. + /// + public string OsCodeSet { get; internal set; } + + /// + /// If true, then the data execution prevention hardware feature is available. + /// + public bool? OsDataExecutionPreventionAvailable { get; internal set; } + + /// + /// When the data execution prevention hardware feature is available, + /// this property indicates that the feature is set to work for 32-bit + /// applications if true. + /// + public bool? OsDataExecutionPrevention32BitApplications { get; internal set; } + + /// + /// When the data execution prevention hardware feature is available, + /// this property indicates that the feature is set to work for drivers + /// if true. + /// + public bool? OsDataExecutionPreventionDrivers { get; internal set; } + + /// + /// Indicates which Data Execution Prevention (DEP) setting is applied. + /// The DEP setting specifies the extent to which DEP applies to 32-bit + /// applications on the system. DEP is always applied to the Windows kernel. + /// + public DataExecutionPreventionSupportPolicy? OsDataExecutionPreventionSupportPolicy { get; internal set; } + + /// + /// If true, the operating system is a checked (debug) build. + /// + public bool? OsDebug { get; internal set; } + + /// + /// If True, the operating system is distributed across several computer + /// system nodes. If so, these nodes should be grouped as a cluster. + /// + public bool? OsDistributed { get; internal set; } + + /// + /// Encryption level for secure transactions: 40-bit, 128-bit, or n-bit. + /// + public OSEncryptionLevel? OsEncryptionLevel { get; internal set; } + + /// + /// Increased priority given to the foreground application. + /// + public ForegroundApplicationBoost? OsForegroundApplicationBoost { get; internal set; } + + /// + /// Total amount, in kilobytes, of physical memory available to the + /// operating system. + /// + /// + /// This value does not necessarily indicate the true amount of + /// physical memory, but what is reported to the operating system + /// as available to it. + /// + public ulong? OsTotalVisibleMemorySize { get; internal set; } + + /// + /// Number, in kilobytes, of physical memory currently unused and available. + /// + public ulong? OsFreePhysicalMemory { get; internal set; } + + /// + /// Number, in kilobytes, of virtual memory. + /// + public ulong? OsTotalVirtualMemorySize { get; internal set; } + + /// + /// Number, in kilobytes, of virtual memory currently unused and available. + /// + public ulong? OsFreeVirtualMemory { get; internal set; } + + /// + /// Number, in kilobytes, of virtual memory currently in use. + /// + public ulong? OsInUseVirtualMemory { get; internal set; } + + /// + /// Total swap space in kilobytes. + /// + /// + /// This value may be NULL (unspecified) if the swap space is not + /// distinguished from page files. However, some operating systems + /// distinguish these concepts. For example, in UNIX, whole processes + /// can be swapped out when the free page list falls and remains below + /// a specified amount + /// + public ulong? OsTotalSwapSpaceSize { get; internal set; } + + /// + /// Total number of kilobytes that can be stored in the operating system + /// paging files—0 (zero) indicates that there are no paging files. + /// Be aware that this number does not represent the actual physical + /// size of the paging file on disk. + /// + public ulong? OsSizeStoredInPagingFiles { get; internal set; } + + /// + /// Number, in kilobytes, that can be mapped into the operating system + /// paging files without causing any other pages to be swapped out. + /// + public ulong? OsFreeSpaceInPagingFiles { get; internal set; } + + /// + /// Array of file paths to the operating system's paging files. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] OsPagingFiles { get; internal set; } + + /// + /// Version of the operating system's Hardware Abstraction Layer (HAL) + /// + public string OsHardwareAbstractionLayer { get; internal set; } + + /// + /// Indicates the install date. + /// + public DateTime? OsInstallDate { get; internal set; } + + /// + /// Name of the operating system manufacturer. + /// For Windows-based systems, this value is "Microsoft Corporation" + /// + public string OsManufacturer { get; internal set; } + + /// + /// Maximum number of process contexts the operating system can support. + /// + public uint? OsMaxNumberOfProcesses { get; internal set; } + + /// + /// Maximum number, in kilobytes, of memory that can be allocated to a process. + /// + public ulong? OsMaxProcessMemorySize { get; internal set; } + + /// + /// Array of Multilingual User Interface Pack (MUI Pack) languages installed + /// on the computer. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] OsMuiLanguages { get; internal set; } + + /// + /// Number of user licenses for the operating system. + /// + public uint? OsNumberOfLicensedUsers { get; internal set; } + + /// + /// Number of process contexts currently loaded or running on the operating system. + /// + public uint? OsNumberOfProcesses { get; internal set; } + + /// + /// Number of user sessions for which the operating system is storing + /// state information currently. + /// + public uint? OsNumberOfUsers { get; internal set; } + + /// + /// Company name for the registered user of the operating system. + /// + public string OsOrganization { get; internal set; } + + /// + /// Architecture of the operating system, as opposed to the processor. + /// + public string OsArchitecture { get; internal set; } + + /// + /// Language version of the operating system installed. + /// + public string OsLanguage { get; internal set; } + + /// + /// Array of objects indicating installed + /// and licensed product additions to the operating system. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public OSProductSuite[] OsProductSuites { get; internal set; } + + /// + /// Additional description for the current operating system version. + /// + public string OsOtherTypeDescription { get; internal set; } + + /// + /// If True, the physical address extensions (PAE) are enabled by the + /// operating system running on Intel processors. + /// + public bool? OsPAEEnabled { get; internal set; } + + /// + /// Specifies whether the operating system booted from an external USB device. + /// If true, the operating system has detected it is booting on a supported + /// locally connected storage device. + /// + public bool? OsPortableOperatingSystem { get; internal set; } + + /// + /// Specifies whether this is the primary operating system. + /// + public bool? OsPrimary { get; internal set; } + + /// + /// Additional system information. + /// + public ProductType? OsProductType { get; internal set; } + + /// + /// Name of the registered user of the operating system. + /// + public string OsRegisteredUser { get; internal set; } + + /// + /// Operating system product serial identification number. + /// + public string OsSerialNumber { get; internal set; } + + /// + /// Major version of the service pack installed on the computer system. + /// + public ushort? OsServicePackMajorVersion { get; internal set; } + + /// + /// Minor version of the service pack installed on the computer system. + /// + public ushort? OsServicePackMinorVersion { get; internal set; } + + /// + /// Current status. + /// + public string OsStatus { get; internal set; } + + /// + /// Product suites available on the operating system. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public OSProductSuite[] OsSuites { get; internal set; } + + /// + /// Server level of the operating system, if the operating system is a server. + /// + public ServerLevel? OsServerLevel { get; internal set; } + #endregion Operating System + + #region Misc Info + /// + /// Layout of the (first) keyboard attached to the system. + /// + public string KeyboardLayout { get; internal set; } + + /// + /// Name of the system's current time zone. + /// + public string TimeZone { get; internal set; } + + /// + /// Path to the system's logon server. + /// + public string LogonServer { get; internal set; } + + /// + /// Power platform role. + /// + public PowerPlatformRole? PowerPlatformRole { get; internal set; } + + /// + /// If true, a HyperVisor was detected. + /// + public bool? HyperVisorPresent { get; internal set; } + + /// + /// If a HyperVisor is not present, indicates the state of the + /// requirement that the Data Execution Prevention feature is available. + /// + public bool? HyperVRequirementDataExecutionPreventionAvailable { get; internal set; } + + /// + /// If a HyperVisor is not present, indicates the state of the + /// requirement that the processor supports address translation + /// extensions used for virtualization. + /// + public bool? HyperVRequirementSecondLevelAddressTranslation { get; internal set; } + + /// + /// If a HyperVisor is not present, indicates the state of the + /// requirement that the firmware has enabled virtualization + /// extensions. + /// + public bool? HyperVRequirementVirtualizationFirmwareEnabled { get; internal set; } + + /// + /// If a HyperVisor is not present, indicates the state of the + /// requirement that the processor supports Intel or AMD Virtual + /// Machine Monitor extensions. + /// + public bool? HyperVRequirementVMMonitorModeExtensions { get; internal set; } + + /// + /// Indicates the status of the Device Guard features. + /// + public DeviceGuardSmartStatus? DeviceGuardSmartStatus { get; internal set; } + + /// + /// Required Device Guard security properties. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardHardwareSecure[] DeviceGuardRequiredSecurityProperties { get; internal set; } + + /// + /// Available Device Guard security properties. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardHardwareSecure[] DeviceGuardAvailableSecurityProperties { get; internal set; } + + /// + /// Configured Device Guard security services. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardSoftwareSecure[] DeviceGuardSecurityServicesConfigured { get; internal set; } + + /// + /// Running Device Guard security services. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public DeviceGuardSoftwareSecure[] DeviceGuardSecurityServicesRunning { get; internal set; } + + /// + /// Status of the Device Guard Code Integrity policy enforcement. + /// + public DeviceGuardConfigCodeIntegrityStatus? DeviceGuardCodeIntegrityPolicyEnforcementStatus { get; internal set; } + + /// + /// Status of the Device Guard user mode Code Integrity policy enforcement. + /// + public DeviceGuardConfigCodeIntegrityStatus? DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus { get; internal set; } + #endregion Misc Info + } + #endregion Classes comprising the output object + + #region Enums used in the output objects + /// + /// System hardware security settings for administrator password status. + /// + public enum AdminPasswordStatus + { + /// + /// Feature is disabled. + /// + Disabled = 0, + + /// + /// Feature is Enabled. + /// + Enabled = 1, + + /// + /// Feature is not implemented. + /// + NotImplemented = 2, + + /// + /// Status is unknown. + /// + Unknown = 3 + } + + /// + /// Actions related to the BootOptionOn* properties of the Win32_ComputerSystem + /// CIM class. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum BootOptionAction + { + // + // This value is reserved + // + // Reserved = 0, + + /// + /// Boot into operating system. + /// + OperatingSystem = 1, + + /// + /// Boot into system utilities. + /// + SystemUtilities = 2, + + /// + /// Do not reboot. + /// + DoNotReboot = 3 + } + + /// + /// Indicates the state of a system element. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum SystemElementState + { + /// + /// The element state is something other than those in this Enum. + /// + Other = 1, + + /// + /// The element state is unknown. + /// + Unknown = 2, + + /// + /// The element is in Safe state. + /// + Safe = 3, + + /// + /// The element is in Warning state. + /// + Warning = 4, + + /// + /// The element is in Critical state. + /// + Critical = 5, + + /// + /// The element is in Non-Recoverable state. + /// + NonRecoverable = 6 + } + + /// + /// Specifies the processor architecture. + /// + public enum CpuArchitecture + { + /// + /// Architecture is Intel x86. + /// + x86 = 0, + + /// + /// Architecture is MIPS. + /// + MIPs = 1, + + /// + /// Architecture is DEC Alpha. + /// + Alpha = 2, + + /// + /// Architecture is Motorola PowerPC. + /// + PowerPC = 3, + + /// + /// Architecture is ARM. + /// + ARM = 5, + + /// + /// Architecture is Itanium-based 64-bit. + /// + ia64 = 6, + + /// + /// Architecture is Intel 64-bit. + /// + x64 = 9 + } + + /// + /// Specifies a CPU's availability and status. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum CpuAvailability + { + /// + /// A state other than those specified in CpuAvailability. + /// + Other = 1, + + /// + /// Availability status is unknown. + /// + Unknown = 2, + + /// + /// The device is running or at full power. + /// + RunningOrFullPower = 3, + + /// + /// Device is in a Warning state. + /// + Warning = 4, + + /// + /// Availability status is In Test. + /// + InTest = 5, + + /// + /// Status is not applicable to this device. + /// + NotApplicable = 6, + + /// + /// The device is powered off. + /// + PowerOff = 7, + + /// + /// Availability status is Offline. + /// + OffLine = 8, + + /// + /// Availability status is Off-Duty. + /// + OffDuty = 9, + + /// + /// Availability status is Degraded. + /// + Degraded = 10, + + /// + /// Availability status is Not Installed. + /// + NotInstalled = 11, + + /// + /// Availability status is Install Error. + /// + InstallError = 12, + + /// + /// The device is known to be in a power save state, but its exact status is unknown. + /// + PowerSaveUnknown = 13, + + /// + /// The device is in a power save state, but is still functioning, + /// and may exhibit decreased performance. + /// + PowerSaveLowPowerMode = 14, + + /// + /// The device is not functioning, but can be brought to full power quickly. + /// + PowerSaveStandby = 15, + + /// + /// The device is in a power-cycle state. + /// + PowerCycle = 16, + + /// + /// The device is in a warning state, though also in a power save state. + /// + PowerSaveWarning = 17, + + /// + /// The device is paused. + /// + Paused = 18, + + /// + /// The device is not ready. + /// + NotReady = 19, + + /// + /// The device is not configured. + /// + NotConfigured = 20, + + /// + /// The device is quiet. + /// + Quiesced = 21 + } + + /// + /// Specifies that current status of the processor. + /// + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags", Justification = "The underlying MOF definition is not a bit field.")] + public enum CpuStatus + { + /// + /// CPU status is Unknown. + /// + Unknown = 0, + + /// + /// CPU status is Enabled. + /// + Enabled = 1, + + /// + /// CPU status is Disabled by User via BIOS Setup. + /// + DisabledByUser = 2, + + /// + /// CPU status is Disabled by BIOS. + /// + DisabledByBIOS = 3, + + /// + /// CPU is Idle. + /// + Idle = 4, + + // + // This value is reserved + // + // Reserved_5 = 5, + + // + // This value is reserved + // + // Reserved_6 = 6, + + /// + /// CPU is in another state. + /// + Other = 7 + } + + /// + /// Data Execution Prevention (DEP) settings. + /// + public enum DataExecutionPreventionSupportPolicy + { + // Unknown = -1, + + /// + /// DEP is turned off for all 32-bit applications on the computer with no exceptions. + /// + AlwaysOff = 0, + + /// + /// DEP is enabled for all 32-bit applications on the computer. + /// + AlwaysOn = 1, + + /// + /// DEP is enabled for a limited number of binaries, the kernel, and all + /// Windows-based services. However, it is off by default for all 32-bit + /// applications. A user or administrator must explicitly choose either + /// the Always On or the Opt Out setting before DEP can be applied to + /// 32-bit applications. + /// + OptIn = 2, + + /// + /// DEP is enabled by default for all 32-bit applications. A user or + /// administrator can explicitly remove support for a 32-bit + /// application by adding the application to an exceptions list. + /// + OptOut = 3 + } + + /// + /// Status of the Device Guard feature. + /// + public enum DeviceGuardSmartStatus + { + /// + /// Device Guard is off. + /// + Off = 0, + + /// + /// Device Guard is Configured. + /// + Configured = 1, + + /// + /// Device Guard is Running. + /// + Running = 2 + } + + /// + /// Configuration status of the Device Guard Code Integrity. + /// + public enum DeviceGuardConfigCodeIntegrityStatus + { + /// + /// Code Integrity is off. + /// + Off = 0, + + /// + /// Code Integrity uses Audit mode. + /// + AuditMode = 1, + + /// + /// Code Integrity uses Enforcement mode. + /// + EnforcementMode = 2 + } + + /// + /// Device Guard hardware security properties. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum DeviceGuardHardwareSecure + { + /// + /// Base Virtualization Support. + /// + BaseVirtualizationSupport = 1, + + /// + /// Secure Boot. + /// + SecureBoot = 2, + + /// + /// DMA Protection. + /// + DMAProtection = 3, + + /// + /// Secure Memory Overwrite. + /// + SecureMemoryOverwrite = 4, + + /// + /// UEFI Code Readonly. + /// + UEFICodeReadonly = 5, + + /// + /// SMM Security Mitigations 1.0. + /// + SMMSecurityMitigations = 6, + + /// + /// Mode Based Execution Control. + /// + ModeBasedExecutionControl = 7 + } + + /// + /// Device Guard software security properties. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum DeviceGuardSoftwareSecure + { + /// + /// Credential Guard. + /// + CredentialGuard = 1, + + /// + /// Hypervisor enforced Code Integrity. + /// + HypervisorEnforcedCodeIntegrity = 2 + } + + /// + /// Role of a computer in an assigned domain workgroup. + /// + public enum DomainRole + { + /// + /// Standalone Workstation. + /// + StandaloneWorkstation = 0, + + /// + /// Member Workstation. + /// + MemberWorkstation = 1, + + /// + /// Standalone Server. + /// + StandaloneServer = 2, + + /// + /// Member Server. + /// + MemberServer = 3, + + /// + /// Backup Domain Controller. + /// + BackupDomainController = 4, + + /// + /// Primary Domain Controller. + /// + PrimaryDomainController = 5 + } + + /// + /// Specifies a firmware type. + /// + public enum FirmwareType + { + /// + /// The firmware type is unknown. + /// + Unknown = 0, + + /// + /// The computer booted in legacy BIOS mode. + /// + Bios = 1, + + /// + /// The computer booted in UEFI mode. + /// + Uefi = 2, + + /// + /// Not implemented. + /// + Max = 3 + } + + /// + /// Increase in priority given to the foreground application. + /// + public enum ForegroundApplicationBoost + { + /// + /// The system boosts the quantum length by 6. + /// + None = 0, + + /// + /// The system boosts the quantum length by 12. + /// + Minimum = 1, + + /// + /// The system boosts the quantum length by 18. + /// + Maximum = 2 + } + + /// + /// Hardware security settings for the reset button on a computer. + /// + public enum FrontPanelResetStatus + { + /// + /// Reset button is disabled. + /// + Disabled = 0, + + /// + /// Reset button is enabled. + /// + Enabled = 1, + + /// + /// Hardware security settings are not implement. + /// + NotImplemented = 2, + + /// + /// Unknown security setting. + /// + Unknown = 3 + } + + /// + /// Indicates a hardware security setting. + /// + public enum HardwareSecurity + { + /// + /// Hardware security is disabled. + /// + Disabled = 0, + + /// + /// Hardware security is enabled. + /// + Enabled = 1, + + /// + /// Hardware security is not implemented. + /// + NotImplemented = 2, + + /// + /// Hardware security setting is unknown. + /// + Unknown = 3 + } + + /// + /// State of the network adapter connection to the network. + /// + public enum NetConnectionStatus + { + /// + /// Adapter is disconnected. + /// + Disconnected = 0, + + /// + /// Adapter is connecting. + /// + Connecting = 1, + + /// + /// Adapter is connected. + /// + Connected = 2, + + /// + /// Adapter is disconnecting. + /// + Disconnecting = 3, + + /// + /// Adapter hardware is not present. + /// + HardwareNotPresent = 4, + + /// + /// Adapter hardware is disabled. + /// + HardwareDisabled = 5, + + /// + /// Adapter has a hardware malfunction. + /// + HardwareMalfunction = 6, + + /// + /// Media is disconnected. + /// + MediaDisconnected = 7, + + /// + /// Adapter is authenticating. + /// + Authenticating = 8, + + /// + /// Authentication has succeeded. + /// + AuthenticationSucceeded = 9, + + /// + /// Authentication has failed. + /// + AuthenticationFailed = 10, + + /// + /// Address is invalid. + /// + InvalidAddress = 11, + + /// + /// Credentials are required. + /// + CredentialsRequired = 12, + + /// + /// Other unspecified state. + /// + Other = 13 + } + + /// + /// Encryption level for secure transactions: 40-bit, 128-bit, or n-bit. + /// + public enum OSEncryptionLevel + { + /// + /// 40-bit encryption. + /// + Encrypt40Bits = 0, + + /// + /// 128-bit encryption. + /// + Encrypt128Bits = 1, + + /// + /// N-bit encryption. + /// + EncryptNBits = 2 + } + + /// + /// Indicates installed and licensed system product additions to the operating system. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + [FlagsAttribute] + public enum OSProductSuite + { + /// + /// Microsoft Small Business Server was once installed, but may have + /// been upgraded to another version of Windows. + /// + SmallBusinessServer = 0x0001, + + /// + /// Windows Server 2008 Enterprise is installed. + /// + Server2008Enterprise = 0x0002, + + /// + /// Windows BackOffice components are installed. + /// + BackOfficeComponents = 0x0004, + + /// + /// Communication Server is installed. + /// + CommunicationsServer = 0x0008, + + /// + /// Terminal Services is installed. + /// + TerminalServices = 0x0010, + + /// + /// Microsoft Small Business Server is installed with the restrictive + /// client license. + /// + SmallBusinessServerRestricted = 0x0020, + + /// + /// Windows Embedded is installed. + /// + WindowsEmbedded = 0x0040, + + /// + /// A Datacenter edition is installed. + /// + DatacenterEdition = 0x0080, + + /// + /// Terminal Services is installed, but only one interactive session is supported. + /// + TerminalServicesSingleSession = 0x0100, + + /// + /// Windows Home Edition is installed. + /// + HomeEdition = 0x0200, + + /// + /// Web Server Edition is installed. + /// + WebServerEdition = 0x0400, + + /// + /// Storage Server Edition is installed. + /// + StorageServerEdition = 0x2000, + + /// + /// Compute Cluster Edition is installed. + /// + ComputeClusterEdition = 0x4000 + } + + /// + /// Indicates the operating system Stock Keeping Unit (SKU) + /// + public enum OperatingSystemSKU + { + /// + /// The SKU is undefined. + /// + Undefined = 0, + + /// + /// SKU is Ultimate Edition. + /// + UltimateEdition = 1, + + /// + /// SKU is Home Basic Edition. + /// + HomeBasicEdition = 2, + + /// + /// SKU is Home Premium Edition. + /// + HomePremiumEdition = 3, + + /// + /// SKU is Enterprise Edition. + /// + EnterpriseEdition = 4, + + /// + /// SKU is Home Basic N Edition. + /// + HomeBasicNEdition = 5, + + /// + /// SKU is Business Edition. + /// + BusinessEdition = 6, + + /// + /// SKU is Standard Server Edition. + /// + StandardServerEdition = 7, + + /// + /// SKU is Datacenter Server Edition. + /// + DatacenterServerEdition = 8, + + /// + /// SKU is Small Business Server Edition. + /// + SmallBusinessServerEdition = 9, + + /// + /// SKU is Enterprise Server Edition. + /// + EnterpriseServerEdition = 10, + + /// + /// SKU is Starter Edition. + /// + StarterEdition = 11, + + /// + /// SKU is Datacenter Server Core Edition. + /// + DatacenterServerCoreEdition = 12, + + /// + /// SKU is Standard Server Core Edition. + /// + StandardServerCoreEdition = 13, + + /// + /// SKU is Enterprise Server Core Edition. + /// + EnterpriseServerCoreEdition = 14, + + /// + /// SKU is Enterprise Server IA64 Edition. + /// + EnterpriseServerIA64Edition = 15, + + /// + /// SKU is Business N Edition. + /// + BusinessNEdition = 16, + + /// + /// SKU is Web Server Edition. + /// + WebServerEdition = 17, + + /// + /// SKU is Cluster Server Edition. + /// + ClusterServerEdition = 18, + + /// + /// SKU is Home Server Edition. + /// + HomeServerEdition = 19, + + /// + /// SKU is Storage Express Server Edition. + /// + StorageExpressServerEdition = 20, + + /// + /// SKU is Storage Standard Server Edition. + /// + StorageStandardServerEdition = 21, + + /// + /// SKU is Storage Workgroup Server Edition. + /// + StorageWorkgroupServerEdition = 22, + + /// + /// SKU is Storage Enterprise Server Edition. + /// + StorageEnterpriseServerEdition = 23, + + /// + /// SKU is Server For Small Business Edition. + /// + ServerForSmallBusinessEdition = 24, + + /// + /// SKU is Small Business Server Premium Edition. + /// + SmallBusinessServerPremiumEdition = 25, + + /// + /// SKU is to be determined. + /// + TBD = 26, + + /// + /// SKU is Windows Enterprise. + /// + WindowsEnterprise = 27, + + /// + /// SKU is Windows Ultimate. + /// + WindowsUltimate = 28, + + /// + /// SKU is Web Server (core installation) + /// + WebServerCore = 29, + + /// + /// SKU is Server Foundation. + /// + ServerFoundation = 33, + + /// + /// SKU is Windows Home Server. + /// + WindowsHomeServer = 34, + + /// + /// SKU is Windows Server Standard without Hyper-V. + /// + WindowsServerStandardNoHyperVFull = 36, + + /// + /// SKU is Windows Server Datacenter without Hyper-V (full installation) + /// + WindowsServerDatacenterNoHyperVFull = 37, + + /// + /// SKU is Windows Server Enterprise without Hyper-V (full installation) + /// + WindowsServerEnterpriseNoHyperVFull = 38, + + /// + /// SKU is Windows Server Datacenter without Hyper-V (core installation) + /// + WindowsServerDatacenterNoHyperVCore = 39, + + /// + /// SKU is Windows Server Standard without Hyper-V (core installation) + /// + WindowsServerStandardNoHyperVCore = 40, + + /// + /// SKU is Windows Server Enterprise without Hyper-V (core installation) + /// + WindowsServerEnterpriseNoHyperVCore = 41, + + /// + /// SKU is Microsoft Hyper-V Server. + /// + MicrosoftHyperVServer = 42, + + /// + /// SKU is Storage Server Express (core installation) + /// + StorageServerExpressCore = 43, + + /// + /// SKU is Storage Server Standard (core installation) + /// + StorageServerStandardCore = 44, + + /// + /// SKU is Storage Server Workgroup (core installation) + /// + StorageServerWorkgroupCore = 45, + + /// + /// SKU is Storage Server Enterprise (core installation) + /// + StorageServerEnterpriseCore = 46, + + /// + /// SKU is Windows Small Business Server 2011 Essentials. + /// + WindowsSmallBusinessServer2011Essentials = 50, + + /// + /// SKU is Small Business Server Premium (core installation) + /// + SmallBusinessServerPremiumCore = 63, + + /// + /// SKU is Windows Server Hyper Core V. + /// + WindowsServerHyperCoreV = 64, + + /// + /// SKU is Windows Thin PC. + /// + WindowsThinPC = 87, + + /// + /// SKU is Windows Embedded Industry. + /// + WindowsEmbeddedIndustry = 89, + + /// + /// SKU is Windows RT. + /// + WindowsRT = 97, + + /// + /// SKU is Windows Home. + /// + WindowsHome = 101, + + /// + /// SKU is Windows Professional with Media Center. + /// + WindowsProfessionalWithMediaCenter = 103, + + /// + /// SKU is Windows Mobile. + /// + WindowsMobile = 104, + + /// + /// SKU is Windows Embedded Handheld. + /// + WindowsEmbeddedHandheld = 118, + + /// + /// SKU is Windows IoT (Internet of Things) Core. + /// + WindowsIotCore = 123 + } + + /// + /// Type of operating system. + /// + public enum OSType + { + /// + /// OS is unknown. + /// + Unknown = 0, + + /// + /// OS is one other than covered by this Enum. + /// + Other = 1, + + /// + /// OS is MacOS. + /// + MACROS = 2, + + /// + /// OS is AT&T UNIX. + /// + ATTUNIX = 3, + + /// + /// OS is DG/UX. + /// + DGUX = 4, + + /// + /// OS is DECNT. + /// + DECNT = 5, + + /// + /// OS is Digital UNIX. + /// + DigitalUNIX = 6, + + /// + /// OS is OpenVMS. + /// + OpenVMS = 7, + + /// + /// OS is HP-UX. + /// + HPUX = 8, + + /// + /// OS is AIX. + /// + AIX = 9, + + /// + /// OS is MVS. + /// + MVS = 10, + + /// + /// OS is OS/400. + /// + OS400 = 11, + + /// + /// OS is OS/2. + /// + OS2 = 12, + + /// + /// OS is Java Virtual Machine. + /// + JavaVM = 13, + + /// + /// OS is MS-DOS. + /// + MSDOS = 14, + + /// + /// OS is Windows 3x. + /// + WIN3x = 15, + + /// + /// OS is Windows 95. + /// + WIN95 = 16, + + /// + /// OS is Windows 98. + /// + WIN98 = 17, + + /// + /// OS is Windows NT. + /// + WINNT = 18, + + /// + /// OS is Windows CE. + /// + WINCE = 19, + + /// + /// OS is NCR System 3000. + /// + NCR3000 = 20, + + /// + /// OS is NetWare. + /// + NetWare = 21, + + /// + /// OS is OSF. + /// + OSF = 22, + + /// + /// OS is DC/OS. + /// + DC_OS = 23, + + /// + /// OS is Reliant UNIX. + /// + ReliantUNIX = 24, + + /// + /// OS is SCO UnixWare. + /// + SCOUnixWare = 25, + + /// + /// OS is SCO OpenServer. + /// + SCOOpenServer = 26, + + /// + /// OS is Sequent. + /// + Sequent = 27, + + /// + /// OS is IRIX. + /// + IRIX = 28, + + /// + /// OS is Solaris. + /// + Solaris = 29, + + /// + /// OS is SunOS. + /// + SunOS = 30, + + /// + /// OS is U6000. + /// + U6000 = 31, + + /// + /// OS is ASERIES. + /// + ASERIES = 32, + + /// + /// OS is Tandem NSK. + /// + TandemNSK = 33, + + /// + /// OS is Tandem NT. + /// + TandemNT = 34, + + /// + /// OS is BS2000. + /// + BS2000 = 35, + + /// + /// OS is Linux. + /// + LINUX = 36, + + /// + /// OS is Lynx. + /// + Lynx = 37, + + /// + /// OS is XENIX. + /// + XENIX = 38, + + /// + /// OS is VM/ESA. + /// + VM_ESA = 39, + + /// + /// OS is Interactive UNIX. + /// + InteractiveUNIX = 40, + + /// + /// OS is BSD UNIX. + /// + BSDUNIX = 41, + + /// + /// OS is FreeBSD. + /// + FreeBSD = 42, + + /// + /// OS is NetBSD. + /// + NetBSD = 43, + + /// + /// OS is GNU Hurd. + /// + GNUHurd = 44, + + /// + /// OS is OS 9. + /// + OS9 = 45, + + /// + /// OS is Mach Kernel. + /// + MACHKernel = 46, + + /// + /// OS is Inferno. + /// + Inferno = 47, + + /// + /// OS is QNX. + /// + QNX = 48, + + /// + /// OS is EPOC. + /// + EPOC = 49, + + /// + /// OS is IxWorks. + /// + IxWorks = 50, + + /// + /// OS is VxWorks. + /// + VxWorks = 51, + + /// + /// OS is MiNT. + /// + MiNT = 52, + + /// + /// OS is BeOS. + /// + BeOS = 53, + + /// + /// OS is HP MPE. + /// + HP_MPE = 54, + + /// + /// OS is NextStep. + /// + NextStep = 55, + + /// + /// OS is PalmPilot. + /// + PalmPilot = 56, + + /// + /// OS is Rhapsody. + /// + Rhapsody = 57, + + /// + /// OS is Windows 2000. + /// + Windows2000 = 58, + + /// + /// OS is Dedicated. + /// + Dedicated = 59, + + /// + /// OS is OS/390. + /// + OS_390 = 60, + + /// + /// OS is VSE. + /// + VSE = 61, + + /// + /// OS is TPF. + /// + TPF = 62 + } + + /// + /// Specifies the type of the computer in use, such as laptop, desktop, or Tablet. + /// + public enum PCSystemType + { + /// + /// System type is unspecified. + /// + Unspecified = 0, + + /// + /// System is a desktop. + /// + Desktop = 1, + + /// + /// System is a mobile device. + /// + Mobile = 2, + + /// + /// System is a workstation. + /// + Workstation = 3, + + /// + /// System is an Enterprise Server. + /// + EnterpriseServer = 4, + + /// + /// System is a Small Office and Home Office (SOHO) Server. + /// + SOHOServer = 5, + + /// + /// System is an appliance PC. + /// + AppliancePC = 6, + + /// + /// System is a performance server. + /// + PerformanceServer = 7, + + /// + /// Maximum enum value. + /// + Maximum = 8 + } + + /// + /// Specifies the type of the computer in use, such as laptop, desktop, or Tablet. + /// This is an extended version of PCSystemType. + /// + // TODO: conflate these two enums??? + public enum PCSystemTypeEx + { + /// + /// System type is unspecified. + /// + Unspecified = 0, + + /// + /// System is a desktop. + /// + Desktop = 1, + + /// + /// System is a mobile device. + /// + Mobile = 2, + + /// + /// System is a workstation. + /// + Workstation = 3, + + /// + /// System is an Enterprise Server. + /// + EnterpriseServer = 4, + + /// + /// System is a Small Office and Home Office (SOHO) Server. + /// + SOHOServer = 5, + + /// + /// System is an appliance PC. + /// + AppliancePC = 6, + + /// + /// System is a performance server. + /// + PerformanceServer = 7, + + /// + /// System is a Slate. + /// + Slate = 8, + + /// + /// Maximum enum value. + /// + Maximum = 9 + } + + /// + /// Specifies power-related capabilities of a logical device. + /// + public enum PowerManagementCapabilities + { + /// + /// Unknown capability. + /// + Unknown = 0, + + /// + /// Power management not supported. + /// + NotSupported = 1, + + /// + /// Power management features are currently disabled. + /// + Disabled = 2, + + /// + /// The power management features are currently enabled, + /// but the exact feature set is unknown or the information is unavailable. + /// + Enabled = 3, + + /// + /// The device can change its power state based on usage or other criteria. + /// + PowerSavingModesEnteredAutomatically = 4, + + /// + /// The power state may be set through the Win32_LogicalDevice class. + /// + PowerStateSettable = 5, + + /// + /// Power may be done through the Win32_LogicalDevice class. + /// + PowerCyclingSupported = 6, + + /// + /// Timed power-on is supported. + /// + TimedPowerOnSupported = 7 + } + + /// + /// Specified power states. + /// + public enum PowerState + { + /// + /// Power state is unknown. + /// + Unknown = 0, + + /// + /// Full power. + /// + FullPower = 1, + + /// + /// Power Save - Low Power mode. + /// + PowerSaveLowPowerMode = 2, + + /// + /// Power Save - Standby. + /// + PowerSaveStandby = 3, + + /// + /// Unknown Power Save mode. + /// + PowerSaveUnknown = 4, + + /// + /// Power Cycle. + /// + PowerCycle = 5, + + /// + /// Power Off. + /// + PowerOff = 6, + + /// + /// Power Save - Warning. + /// + PowerSaveWarning = 7, + + /// + /// Power Save - Hibernate. + /// + PowerSaveHibernate = 8, + + /// + /// Power Save - Soft off. + /// + PowerSaveSoftOff = 9 + } + + /// + /// Specifies the primary function of a processor. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum ProcessorType + { + /// + /// Processor ype is other than provided in these enumeration values. + /// + Other = 1, + + /// + /// Processor type is. + /// + Unknown = 2, + + /// + /// Processor is a Central Processing Unit (CPU) + /// + CentralProcessor = 3, + + /// + /// Processor is a Math processor. + /// + MathProcessor = 4, + + /// + /// Processor is a Digital Signal processor (DSP) + /// + DSPProcessor = 5, + + /// + /// Processor is a Video processor. + /// + VideoProcessor = 6 + } + + /// + /// Specifies a computer's reset capability. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum ResetCapability + { + /// + /// Capability is a value other than provided in these enumerated values. + /// + Other = 1, + + /// + /// Reset capability is unknown. + /// + Unknown = 2, + + /// + /// Capability is disabled. + /// + Disabled = 3, + + /// + /// Capability is enabled. + /// + Enabled = 4, + + /// + /// Capability is not implemented. + /// + NotImplemented = 5 + } + + /// + /// Specifies the kind of event that causes a computer to power up. + /// + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] + public enum WakeUpType + { + // + // This value is reserved + // + // Reserved = 0, + + /// + /// An event other than specified in this enumeration. + /// + Other = 1, + + /// + /// Event type is unknown. + /// + Unknown = 2, + + /// + /// Event is APM timer. + /// + APMTimer = 3, + + /// + /// Event is a Modem Ring. + /// + ModemRing = 4, + + /// + /// Event is a LAN Remove. + /// + LANRemote = 5, + + /// + /// Event is a power switch. + /// + PowerSwitch = 6, + + /// + /// Event is a PCI PME# signal. + /// + PCIPME = 7, + + /// + /// AC power was restored. + /// + ACPowerRestored = 8 + } + + /// + /// Indicates the OEM's preferred power management profile. + /// + public enum PowerPlatformRole + { + /// + /// The OEM did not specify a specific role. + /// + Unspecified = 0, + + /// + /// The OEM specified a desktop role. + /// + Desktop = 1, + + /// + /// The OEM specified a mobile role (for example, a laptop) + /// + Mobile = 2, + + /// + /// The OEM specified a workstation role. + /// + Workstation = 3, + + /// + /// The OEM specified an enterprise server role. + /// + EnterpriseServer = 4, + + /// + /// The OEM specified a single office/home office (SOHO) server role. + /// + SOHOServer = 5, + + /// + /// The OEM specified an appliance PC role. + /// + AppliancePC = 6, + + /// + /// The OEM specified a performance server role. + /// + PerformanceServer = 7, // v1 last supported + + /// + /// The OEM specified a tablet form factor role. + /// + Slate = 8, // v2 last supported + + /// + /// Max enum value. + /// + MaximumEnumValue + } + + /// + /// Additional system information, from Win32_OperatingSystem. + /// + public enum ProductType + { + /// + /// Product type is unknown. + /// + Unknown = 0, // this value is not specified in Win32_OperatingSystem, but may prove useful + + /// + /// System is a workstation. + /// + WorkStation = 1, + + /// + /// System is a domain controller. + /// + DomainController = 2, + + /// + /// System is a server. + /// + Server = 3 + } + + /// + /// Specifies the system server level. + /// + public enum ServerLevel + { + /// + /// An unknown or unrecognized level was detected. + /// + Unknown = 0, + + /// + /// Nano server. + /// + NanoServer, + + /// + /// Server core. + /// + ServerCore, + + /// + /// Server core with management tools. + /// + ServerCoreWithManagementTools, + + /// + /// Full server. + /// + FullServer + } + + /// + /// State of a software element. + /// + public enum SoftwareElementState + { + /// + /// Software element is deployable. + /// + Deployable = 0, + + /// + /// Software element is installable. + /// + Installable = 1, + + /// + /// Software element is executable. + /// + Executable = 2, + + /// + /// Software element is running. + /// + Running = 3 + } + #endregion Enums used in the output objects + #endregion Output components + + #region Native + internal static partial class Native + { + private static class PInvokeDllNames + { + public const string GetPhysicallyInstalledSystemMemoryDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; + public const string PowerDeterminePlatformRoleExDllName = "api-ms-win-power-base-l1-1-0.dll"; + public const string GetFirmwareTypeDllName = "api-ms-win-core-kernel32-legacy-l1-1-1"; + } + + public const int LOCALE_NAME_MAX_LENGTH = 85; + public const uint POWER_PLATFORM_ROLE_V1 = 0x1; + public const uint POWER_PLATFORM_ROLE_V2 = 0x2; + + public const uint S_OK = 0; + + /// + /// Import WINAPI function PowerDeterminePlatformRoleEx. + /// + /// The version of the POWER_PLATFORM_ROLE enumeration for the platform. + /// POWER_PLATFORM_ROLE enumeration. + [LibraryImport(PInvokeDllNames.PowerDeterminePlatformRoleExDllName, EntryPoint = "PowerDeterminePlatformRoleEx")] + public static partial uint PowerDeterminePlatformRoleEx(uint version); + + /// + /// Retrieve the amount of RAM physically installed in the computer. + /// + /// + /// + [LibraryImport(PInvokeDllNames.GetPhysicallyInstalledSystemMemoryDllName)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetPhysicallyInstalledSystemMemory(out ulong MemoryInKilobytes); + + /// + /// Retrieve the firmware type of the local computer. + /// + /// + /// A reference to a enumeration to contain + /// the resultant firmware type + /// + /// + [LibraryImport(PInvokeDllNames.GetFirmwareTypeDllName)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetFirmwareType(out FirmwareType firmwareType); + + /// + /// Gets the data specified for the passed in property name from the + /// Software Licensing API. + /// + /// Name of the licensing property to get. + /// Out parameter for the value. + /// An hresult indicating success or failure. + [LibraryImport("slc.dll", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int SLGetWindowsInformationDWORD(string licenseProperty, out int propertyValue); + } + #endregion Native +} + +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..a9d8772a5fc8fda657ff22c8401b10c0ca9c763e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -0,0 +1,378 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Provider; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to get the content of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Get, "Content", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096490")] + public class GetContentCommand : ContentCommandBase + { + #region Parameters + + /// + /// The number of content items to retrieve per block. + /// By default this value is 1 which means read one block + /// at a time. To read all blocks at once, set this value + /// to a negative number. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public long ReadCount { get; set; } = 1; + + /// + /// The number of content items to retrieve. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, long.MaxValue)] + [Alias("First", "Head")] + public long TotalCount { get; set; } = -1; + + /// + /// The number of content items to retrieve from the back of the file. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, int.MaxValue)] + [Alias("Last")] + public int Tail { get; set; } = -1; + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Content.GetContentReaderDynamicParameters(Path[0], context); + } + + return InvokeProvider.Content.GetContentReaderDynamicParameters(".", context); + } + + #endregion Parameters + + #region Command code + + /// + /// Gets the content of an item at the specified path. + /// + protected override void ProcessRecord() + { + // TotalCount and Tail should not be specified at the same time. + // Throw out terminating error if this is the case. + if (TotalCount != -1 && Tail != -1) + { + string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); + ErrorRecord error = new(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); + WriteError(error); + return; + } + + if (TotalCount == 0) + { + // Don't read anything + return; + } + + // Get the content readers + CmdletProviderContext currentContext = CmdletProviderContext; + contentStreams = this.GetContentReaders(Path, currentContext); + + try + { + // Iterate through the content holders reading the content + foreach (ContentHolder holder in contentStreams) + { + long countRead = 0; + + Dbg.Diagnostics.Assert(holder.Reader != null, "All holders should have a reader assigned"); + + if (Tail != -1 && holder.Reader is not FileSystemContentReaderWriter) + { + string errMsg = SessionStateStrings.GetContent_TailNotSupported; + ErrorRecord error = new(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); + WriteError(error); + continue; + } + + // If Tail is -1, we are supposed to read all content out. This is same + // as reading forwards. So we read forwards in this case. + // If Tail is positive, we seek the right position. Or, if the seek failed + // because of an unsupported encoding, we scan forward to get the tail content. + if (Tail >= 0) + { + bool seekSuccess = false; + + try + { + seekSuccess = SeekPositionForTail(holder.Reader); + } + catch (Exception e) + { + ProviderInvocationException providerException = + new( + "ProviderContentReadError", + SessionStateStrings.ProviderContentReadError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + MshLog.LogProviderHealthEvent( + this.Context, + holder.PathInfo.Provider.Name, + providerException, + Severity.Warning); + + WriteError(new ErrorRecord( + providerException.ErrorRecord, + providerException)); + + continue; + } + + // If the seek was successful, we start to read forwards from that + // point. Otherwise, we need to scan forwards to get the tail content. + if (!seekSuccess && !ScanForwardsForTail(holder, currentContext)) + { + continue; + } + } + + IList results = null; + + do + { + long countToRead = ReadCount; + + // Make sure we only ask for the amount the user wanted + // I am using TotalCount - countToRead so that I don't + // have to worry about overflow + if (TotalCount > 0 && (countToRead == 0 || TotalCount - countToRead < countRead)) + { + countToRead = TotalCount - countRead; + } + + try + { + results = holder.Reader.Read(countToRead); + } + catch (Exception e) // Catch-all OK. 3rd party callout + { + ProviderInvocationException providerException = + new( + "ProviderContentReadError", + SessionStateStrings.ProviderContentReadError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + MshLog.LogProviderHealthEvent(this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); + WriteError(new ErrorRecord(providerException.ErrorRecord, providerException)); + + break; + } + + if (results != null && results.Count > 0) + { + countRead += results.Count; + if (ReadCount == 1) + { + // Write out the content as a single object + WriteContentObject(results[0], countRead, holder.PathInfo, currentContext); + } + else + { + // Write out the content as an array of objects + WriteContentObject(results, countRead, holder.PathInfo, currentContext); + } + } + } while (results != null && results.Count > 0 && (TotalCount == -1 || countRead < TotalCount)); + } + } + finally + { + // Close all the content readers + + CloseContent(contentStreams, false); + + // Empty the content holder array + contentStreams = new List(); + } + } + + /// + /// Scan forwards to get the tail content. + /// + /// + /// + /// + /// true if no error occurred + /// false if there was an error + /// + private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext currentContext) + { + var fsReader = holder.Reader as FileSystemContentReaderWriter; + Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); + Queue tailResultQueue = new(); + IList results = null; + ErrorRecord error = null; + + do + { + try + { + results = fsReader.ReadWithoutWaitingChanges(ReadCount); + } + catch (Exception e) + { + ProviderInvocationException providerException = + new( + "ProviderContentReadError", + SessionStateStrings.ProviderContentReadError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + MshLog.LogProviderHealthEvent( + this.Context, + holder.PathInfo.Provider.Name, + providerException, + Severity.Warning); + + // Create and save the error record. The error record + // will be written outside the while loop. + // This is to make sure the accumulated results get written + // out before the error record when the 'scanForwardForTail' is true. + error = new ErrorRecord( + providerException.ErrorRecord, + providerException); + + break; + } + + if (results != null && results.Count > 0) + { + foreach (object entry in results) + { + if (tailResultQueue.Count == Tail) + { + tailResultQueue.Dequeue(); + } + + tailResultQueue.Enqueue(entry); + } + } + } while (results != null && results.Count > 0); + + if (tailResultQueue.Count > 0) + { + // Respect the ReadCount parameter. + // Output single object when ReadCount == 1; Output array otherwise + int count = 0; + if (ReadCount <= 0 || (ReadCount >= tailResultQueue.Count && ReadCount != 1)) + { + count = tailResultQueue.Count; + + // Write out the content as an array of objects + WriteContentObject(tailResultQueue.ToArray(), count, holder.PathInfo, currentContext); + } + else if (ReadCount == 1) + { + // Write out the content as single object + while (tailResultQueue.Count > 0) + { + WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext); + } + } + else // ReadCount < Queue.Count + { + while (tailResultQueue.Count >= ReadCount) + { + List outputList = new((int)ReadCount); + for (int idx = 0; idx < ReadCount; idx++, count++) + { + outputList.Add(tailResultQueue.Dequeue()); + } + + // Write out the content as an array of objects + WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); + } + + if (tailResultQueue.Count > 0) + { + // Write out the content as an array of objects + WriteContentObject(tailResultQueue.ToArray(), count, holder.PathInfo, currentContext); + } + } + } + + if (error != null) + { + WriteError(error); + return false; + } + + return true; + } + + /// + /// Seek position to the right place. + /// + /// + /// reader should be able to be casted to FileSystemContentReader + /// + /// + /// true if the stream pointer is moved to the right place + /// false if we cannot seek + /// + private bool SeekPositionForTail(IContentReader reader) + { + var fsReader = reader as FileSystemContentReaderWriter; + Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); + + try + { + fsReader.SeekItemsBackward(Tail); + return true; + } + catch (BackReaderEncodingNotSupportedException) + { + // Move to the head + fsReader.Seek(0, SeekOrigin.Begin); + return false; + } + } + + /// + /// Be sure to clean up. + /// + protected override void EndProcessing() + { + Dispose(true); + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..7523a4973907c24def541d150cf28c82d5eb9964 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs @@ -0,0 +1,345 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to get the property of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Get, "ItemProperty", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096493")] + public class GetItemPropertyCommand : ItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return paths; + } + + set + { + paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The properties to retrieve from the item. + /// + [Parameter(Position = 1)] + [Alias("PSProperty")] + public string[] Name + { + get + { + return _property; + } + + set + { + _property = value; + } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.GetPropertyDynamicParameters( + Path[0], + SessionStateUtilities.ConvertArrayToCollection(_property), context); + } + + return InvokeProvider.Property.GetPropertyDynamicParameters( + ".", + SessionStateUtilities.ConvertArrayToCollection(_property), context); + } + + #endregion Parameters + + #region parameter data + + /// + /// The properties to be retrieved. + /// + private string[] _property; + + #endregion parameter data + + #region Command code + + /// + /// Gets the properties of an item at the specified path. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + try + { + InvokeProvider.Property.Get( + path, + SessionStateUtilities.ConvertArrayToCollection(_property), + CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + + #endregion Command code + } + + /// + /// A command to get the property value of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Get, "ItemPropertyValue", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096906")] + public sealed class GetItemPropertyValueCommand : ItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = false, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Path + { + get + { + return paths; + } + + set + { + paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The properties to retrieve from the item. + /// + [Parameter(Position = 1, Mandatory = true)] + [Alias("PSProperty")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get + { + return _property; + } + + set + { + _property = value; + } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.GetPropertyDynamicParameters( + Path[0], + SessionStateUtilities.ConvertArrayToCollection(_property), context); + } + + return InvokeProvider.Property.GetPropertyDynamicParameters( + ".", + SessionStateUtilities.ConvertArrayToCollection(_property), context); + } + + #endregion Parameters + + #region parameter data + + /// + /// The properties to be retrieved. + /// + private string[] _property; + + #endregion parameter data + + #region Command code + + /// + /// Gets the values of the properties of an item at the specified path. + /// + protected override void ProcessRecord() + { + if (Path == null || Path.Length == 0) + { + paths = new string[] { "." }; + } + + foreach (string path in Path) + { + try + { + Collection itemProperties = InvokeProvider.Property.Get( + new string[] { path }, + SessionStateUtilities.ConvertArrayToCollection(_property), + base.SuppressWildcardExpansion); + + if (itemProperties != null) + { + foreach (PSObject currentItem in itemProperties) + { + if (this.Name != null) + { + foreach (string currentPropertyName in this.Name) + { + if (currentItem.Properties != null && + currentItem.Properties[currentPropertyName] != null && + currentItem.Properties[currentPropertyName].Value != null) + { + CmdletProviderContext.WriteObject(currentItem.Properties[currentPropertyName].Value); + } + } + } + } + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..6b6551619f124f888fa0ec17a53b5823df4a355d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that gets the active transaction. + /// + [Cmdlet(VerbsCommon.Get, "Transaction", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135220")] + [OutputType(typeof(PSTransaction))] + public class GetTransactionCommand : PSCmdlet + { + /// + /// Creates a new transaction. + /// + protected override void EndProcessing() + { + WriteObject(this.Context.TransactionManager.GetCurrent()); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..27f812c7a80432e15c744302f6e74b32066f65bf --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Globalization; +using System.Management; +using System.Management.Automation; +using System.Text; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to get WMI Objects. + /// + [Cmdlet(VerbsCommon.Get, "WmiObject", DefaultParameterSetName = "query", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113337", RemotingCapability = RemotingCapability.OwnedByCommand)] + public class GetWmiObjectCommand : WmiBaseCmdlet + { + #region Parameters + + /// + /// The WMI class to query. + /// + [Alias("ClassName")] + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")] + [Parameter(Position = 1, ParameterSetName = "list")] + [ValidateNotNullOrEmpty] + public string Class { get; set; } + + /// + /// To specify whether to get the results recursively. + /// + [Parameter(ParameterSetName = "list")] + public SwitchParameter Recurse { get; set; } = false; + + /// + /// The WMI properties to retrieve. + /// + [Parameter(Position = 1, ParameterSetName = "query")] + [ValidateNotNullOrEmpty] + public string[] Property + { + get { return (string[])_property.Clone(); } + + set { _property = value; } + } + + /// + /// The filter to be used in the search. + /// + [Parameter(ParameterSetName = "query")] + public string Filter { get; set; } + + /// + /// If Amended qualifier to use. + /// + [Parameter] + public SwitchParameter Amended { get; set; } + + /// + /// If Enumerate Deep flag to use. When 'list' parameter is specified 'EnumerateDeep' parameter is ignored. + /// + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + public SwitchParameter DirectRead { get; set; } + + /// + /// The list of classes. + /// + [Parameter(ParameterSetName = "list")] + public SwitchParameter List { get; set; } = false; + + /// + /// The query string to search for objects. + /// + [Parameter(Mandatory = true, ParameterSetName = "WQLQuery")] + public string Query { get; set; } + + #endregion Parameters + + #region parameter data + + private string[] _property = new string[] { "*" }; + + #endregion parameter data + + #region Command code + + /// + /// Uses this.filter, this.wmiClass and this.property to retrieve the filter. + /// + internal string GetQueryString() + { + StringBuilder returnValue = new StringBuilder("select "); + returnValue.Append(string.Join(", ", _property)); + returnValue.Append(" from "); + returnValue.Append(Class); + if (!string.IsNullOrEmpty(Filter)) + { + returnValue.Append(" where "); + returnValue.Append(Filter); + } + + return returnValue.ToString(); + } + /// + /// Uses filter table to convert the class into WMI understandable language. + /// Character Description Example Match Comment + /// * Matches zero or more characters starting at the specified position A* A,ag,Apple Supported by PowerShell. + /// ? Matches any character at the specified position ?n An,in,on (does not match ran) Supported by PowerShell. + /// _ Matches any character at the specified position _n An,in,on (does not match ran) Supported by WMI + /// % Matches zero or more characters starting at the specified position A% A,ag,Apple Supported by WMI + /// [] Matches a range of characters [a-l]ook Book,cook,look (does not match took) Supported by WMI and powershell + /// [] Matches specified characters [bc]ook Book,cook, (does not match look) Supported by WMI and powershell + /// ^ Does not Match specified characters. [^bc]ook Look, took (does not match book, cook) Supported by WMI. + /// + + internal string GetFilterClassName() + { + if (string.IsNullOrEmpty(this.Class)) + return string.Empty; + string filterClass = string.Copy(this.Class); + filterClass = filterClass.Replace('*', '%'); + filterClass = filterClass.Replace('?', '_'); + return filterClass; + } + + internal bool IsLocalizedNamespace(string sNamespace) + { + bool toReturn = false; + if (sNamespace.StartsWith("ms_", StringComparison.OrdinalIgnoreCase)) + { + toReturn = true; + } + + return toReturn; + } + + internal bool ValidateClassFormat() + { + string filterClass = this.Class; + if (string.IsNullOrEmpty(filterClass)) + return true; + StringBuilder newClassName = new StringBuilder(); + for (int i = 0; i < filterClass.Length; i++) + { + if (char.IsLetterOrDigit(filterClass[i]) || + filterClass[i].Equals('[') || filterClass[i].Equals(']') || + filterClass[i].Equals('*') || filterClass[i].Equals('?') || + filterClass[i].Equals('-')) + { + newClassName.Append(filterClass[i]); + continue; + } + else if (filterClass[i].Equals('_')) + { + newClassName.Append('['); + newClassName.Append(filterClass[i]); + newClassName.Append(']'); + continue; + } + + return false; + } + + this.Class = newClassName.ToString(); + return true; + } + + /// + /// Gets the ManagementObjectSearcher object. + /// + internal ManagementObjectSearcher GetObjectList(ManagementScope scope) + { + StringBuilder queryStringBuilder = new StringBuilder(); + if (string.IsNullOrEmpty(this.Class)) + { + queryStringBuilder.Append("select * from meta_class"); + } + else + { + string filterClass = GetFilterClassName(); + if (filterClass == null) + return null; + queryStringBuilder.Append("select * from meta_class where __class like '"); + queryStringBuilder.Append(filterClass); + queryStringBuilder.Append("'"); + } + + ObjectQuery classQuery = new ObjectQuery(queryStringBuilder.ToString()); + + EnumerationOptions enumOptions = new EnumerationOptions(); + enumOptions.EnumerateDeep = true; + enumOptions.UseAmendedQualifiers = this.Amended; + var searcher = new ManagementObjectSearcher(scope, classQuery, enumOptions); + return searcher; + } + /// + /// Gets the properties of an item at the specified path. + /// + protected override void BeginProcessing() + { + ConnectionOptions options = GetConnectionOption(); + if (this.AsJob) + { + RunAsJob("Get-WMIObject"); + return; + } + else + { + if (List.IsPresent) + { + if (!this.ValidateClassFormat()) + { + ErrorRecord errorRecord = new ErrorRecord( + new ArgumentException( + string.Format( + Thread.CurrentThread.CurrentCulture, + "Class", this.Class)), + "INVALID_QUERY_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiFilterInvalidClass", this.Class); + + WriteError(errorRecord); + return; + } + + foreach (string name in ComputerName) + { + if (this.Recurse.IsPresent) + { + Queue namespaceElement = new Queue(); + namespaceElement.Enqueue(this.Namespace); + while (namespaceElement.Count > 0) + { + string connectNamespace = (string)namespaceElement.Dequeue(); + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, connectNamespace), options); + try + { + scope.Connect(); + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "INVALID_NAMESPACE_IDENTIFIER", + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); + WriteError(errorRecord); + continue; + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "INVALID_NAMESPACE_IDENTIFIER", + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); + WriteError(errorRecord); + continue; + } + catch (System.UnauthorizedAccessException e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "INVALID_NAMESPACE_IDENTIFIER", + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); + WriteError(errorRecord); + continue; + } + + ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); + foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) + { + if (!IsLocalizedNamespace((string)obj["Name"])) + { + namespaceElement.Enqueue(connectNamespace + "\\" + obj["Name"]); + } + } + + ManagementObjectSearcher searcher = this.GetObjectList(scope); + if (searcher == null) + continue; + foreach (ManagementBaseObject obj in searcher.Get()) + { + WriteObject(obj); + } + } + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); + try + { + scope.Connect(); + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "INVALID_NAMESPACE_IDENTIFIER", + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); + WriteError(errorRecord); + continue; + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "INVALID_NAMESPACE_IDENTIFIER", + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); + WriteError(errorRecord); + continue; + } + catch (System.UnauthorizedAccessException e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "INVALID_NAMESPACE_IDENTIFIER", + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); + WriteError(errorRecord); + continue; + } + + ManagementObjectSearcher searcher = this.GetObjectList(scope); + if (searcher == null) + continue; + foreach (ManagementBaseObject obj in searcher.Get()) + { + WriteObject(obj); + } + } + } + + return; + } + + // When -List is not specified and -Recurse is specified, we need the -Class parameter to compose the right query string + if (this.Recurse.IsPresent && string.IsNullOrEmpty(Class)) + { + string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, "-Class"); + ErrorRecord er = new ErrorRecord(new InvalidOperationException(errorMsg), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + string queryString = string.IsNullOrEmpty(this.Query) ? GetQueryString() : this.Query; + ObjectQuery query = new ObjectQuery(queryString.ToString()); + + foreach (string name in ComputerName) + { + try + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); + EnumerationOptions enumOptions = new EnumerationOptions(); + enumOptions.UseAmendedQualifiers = Amended; + enumOptions.DirectRead = DirectRead; + ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); + foreach (ManagementBaseObject obj in searcher.Get()) + { + WriteObject(obj); + } + } + catch (ManagementException e) + { + ErrorRecord errorRecord = null; + if (e.ErrorCode.Equals(ManagementStatus.InvalidClass)) + { + string className = GetClassNameFromQuery(queryString); + string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, + e.Message, className); + errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidType, null); + } + else if (e.ErrorCode.Equals(ManagementStatus.InvalidQuery)) + { + string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, + e.Message, queryString); + errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); + } + else if (e.ErrorCode.Equals(ManagementStatus.InvalidNamespace)) + { + string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, + e.Message, this.Namespace); + errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); + } + else + { + errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); + } + + WriteError(errorRecord); + continue; + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "GetWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + continue; + } + } + } + } + + /// + /// Get the class name from a query string. + /// + /// + /// + private string GetClassNameFromQuery(string query) + { + System.Management.Automation.Diagnostics.Assert(query.Contains("from"), + "Only get called when ErrorCode is InvalidClass, which means the query string contains 'from' and the class name"); + + if (Class != null) + { + return Class; + } + + int fromIndex = query.IndexOf(" from ", StringComparison.OrdinalIgnoreCase); + string subQuery = query.Substring(fromIndex + " from ".Length); + string className = subQuery.Split(' ')[0]; + return className; + } + + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs new file mode 100644 index 0000000000000000000000000000000000000000..d0f15346396920f389ce1eeebd684eeb009f7dec --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Management; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security.Principal; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + #region Get-HotFix + + /// + /// Cmdlet for Get-Hotfix Proxy. + /// + [Cmdlet(VerbsCommon.Get, "HotFix", DefaultParameterSetName = "Default", + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2109716", RemotingCapability = RemotingCapability.SupportedByCommand)] + [OutputType(@"System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering")] + public sealed class GetHotFixCommand : PSCmdlet, IDisposable + { + #region Parameters + + /// + /// Specifies the HotFixID. Unique identifier associated with a particular update. + /// + [Parameter(Position = 0, ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + [Alias("HFID")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Id { get; set; } + + /// + /// To search on description of Hotfixes. + /// + [Parameter(ParameterSetName = "Description")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Description { get; set; } + + /// + /// Parameter to pass the Computer Name. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("CN", "__Server", "IPAddress")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName { get; set; } = new string[] { "localhost" }; + + /// + /// Parameter to pass the Credentials. + /// + [Parameter] + [Credential] + [ValidateNotNullOrEmpty] + public PSCredential Credential { get; set; } + + #endregion Parameters + + #region Overrides + + private ManagementObjectSearcher _searchProcess; + + private bool _inputContainsWildcard = false; + private readonly ConnectionOptions _connectionOptions = new(); + + /// + /// Sets connection options. + /// + protected override void BeginProcessing() + { + _connectionOptions.Authentication = AuthenticationLevel.Packet; + _connectionOptions.Impersonation = ImpersonationLevel.Impersonate; + _connectionOptions.Username = Credential?.UserName; + _connectionOptions.SecurePassword = Credential?.Password; + } + + /// + /// Get the List of HotFixes installed on the Local Machine. + /// + protected override void ProcessRecord() + { + foreach (string computer in ComputerName) + { + bool foundRecord = false; + StringBuilder queryString = new(); + ManagementScope scope = new(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), _connectionOptions); + scope.Connect(); + if (Id != null) + { + queryString.Append("Select * from Win32_QuickFixEngineering where ("); + for (int i = 0; i <= Id.Length - 1; i++) + { + queryString.Append("HotFixID= '"); + queryString.Append(Id[i].Replace("'", "\\'")); + queryString.Append('\''); + if (i < Id.Length - 1) + { + queryString.Append(" Or "); + } + } + + queryString.Append(')'); + } + else + { + queryString.Append("Select * from Win32_QuickFixEngineering"); + foundRecord = true; + } + + _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(queryString.ToString())); + foreach (ManagementObject obj in _searchProcess.Get()) + { + if (Description != null) + { + if (!FilterMatch(obj)) + { + continue; + } + } + else + { + _inputContainsWildcard = true; + } + + // try to translate the SID to a more friendly username + // just stick with the SID if anything goes wrong + string installed = (string)obj["InstalledBy"]; + if (!string.IsNullOrEmpty(installed)) + { + try + { + SecurityIdentifier secObj = new(installed); + obj["InstalledBy"] = secObj.Translate(typeof(NTAccount)); + } + catch (IdentityNotMappedException) + { + // thrown by SecurityIdentifier.Translate + } + catch (SystemException) + { + // thrown by SecurityIdentifier.constr + } + } + + WriteObject(obj); + foundRecord = true; + } + + if (!foundRecord && !_inputContainsWildcard) + { + Exception ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer)); + WriteError(new ErrorRecord(ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null)); + } + + if (_searchProcess != null) + { + this.Dispose(); + } + } + } + + /// + /// To implement ^C. + /// + protected override void StopProcessing() + { + _searchProcess?.Dispose(); + } + #endregion Overrides + + #region "Private Methods" + + private bool FilterMatch(ManagementObject obj) + { + try + { + foreach (string desc in Description) + { + WildcardPattern wildcardpattern = WildcardPattern.Get(desc, WildcardOptions.IgnoreCase); + if (wildcardpattern.IsMatch((string)obj["Description"])) + { + return true; + } + + if (WildcardPattern.ContainsWildcardCharacters(desc)) + { + _inputContainsWildcard = true; + } + } + } + catch (Exception) + { + return false; + } + + return false; + } + + #endregion "Private Methods" + + #region "IDisposable Members" + + /// + /// Release all resources. + /// + public void Dispose() + { + _searchProcess?.Dispose(); + } + + #endregion "IDisposable Members" + } + #endregion +} + +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..df0c5775ca1fc33ba1c674d3348bc7f39f1c7388 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs @@ -0,0 +1,318 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Management; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Provider; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to Invoke WMI Method. + /// + [Cmdlet(VerbsLifecycle.Invoke, "WmiMethod", DefaultParameterSetName = "class", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113346", RemotingCapability = RemotingCapability.OwnedByCommand)] + public sealed class InvokeWmiMethod : WmiBaseCmdlet + { + #region Parameters + /// + /// The WMI Object to use. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] + public ManagementObject InputObject + { + get { return _inputObject; } + + set { _inputObject = value; } + } + /// + /// The WMI Path to use. + /// + [Parameter(ParameterSetName = "path", Mandatory = true)] + public string Path + { + get { return _path; } + + set { _path = value; } + } + /// + /// The WMI class to use. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] + public string Class + { + get { return _className; } + + set { _className = value; } + } + /// + /// The WMI Method to execute. + /// + [Parameter(Position = 1, Mandatory = true)] + public string Name + { + get { return _methodName; } + + set { _methodName = value; } + } + + /// + /// The parameters to the method specified by MethodName. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(Position = 2, ParameterSetName = "class")] + [Parameter(ParameterSetName = "object")] + [Alias("Args")] + public object[] ArgumentList + { + get { return _argumentList; } + + set { _argumentList = value; } + } + + #endregion Parameters + + #region parameter data + private string _path = null; + private string _className = null; + private string _methodName = null; + private ManagementObject _inputObject = null; + private object[] _argumentList = null; + + #endregion parameter data + #region Command code + /// + /// Invoke WMI method given either path,class name or pipeline input. + /// + protected override void ProcessRecord() + { + if (this.AsJob) + { + RunAsJob("Invoke-WMIMethod"); + return; + } + + if (_inputObject != null) + { + object result = null; + ManagementBaseObject inputParameters = null; + try + { + inputParameters = _inputObject.GetMethodParameters(_methodName); + if (_argumentList != null) + { + int inParamCount = _argumentList.Length; + foreach (PropertyData property in inputParameters.Properties) + { + if (inParamCount == 0) + break; + property.Value = _argumentList[_argumentList.Length - inParamCount]; + inParamCount--; + } + } + + if (!ShouldProcess( + StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, + _inputObject["__CLASS"].ToString(), + this.Name) + )) + { + return; + } + + result = _inputObject.InvokeMethod(_methodName, inputParameters, null); + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMIManagementException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + + if (result != null) + { + WriteObject(result); + } + + return; + } + else + { + ConnectionOptions options = GetConnectionOption(); + ManagementPath mPath = null; + object result = null; + ManagementObject mObject = null; + if (_path != null) + { + mPath = new ManagementPath(_path); + if (string.IsNullOrEmpty(mPath.NamespacePath)) + { + mPath.NamespacePath = this.Namespace; + } + else if (namespaceSpecified) + { + // ThrowTerminatingError + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "NamespaceSpecifiedWithPath", + ErrorCategory.InvalidOperation, + this.Namespace)); + } + + if (mPath.Server != "." && serverNameSpecified) + { + // ThrowTerminatingError + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "ComputerNameSpecifiedWithPath", + ErrorCategory.InvalidOperation, + ComputerName)); + } + // If server name is specified loop through it. + if (!(mPath.Server == "." && serverNameSpecified)) + { + string[] serverName = new string[] { mPath.Server }; + ComputerName = serverName; + } + } + + foreach (string name in ComputerName) + { + result = null; + try + { + if (_path != null) + { + mPath.Server = name; + if (mPath.IsClass) + { + ManagementClass mClass = new ManagementClass(mPath); + mObject = mClass; + } + else + { + ManagementObject mInstance = new ManagementObject(mPath); + mObject = mInstance; + } + + ManagementScope mScope = new ManagementScope(mPath, options); + mObject.Scope = mScope; + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); + ManagementClass mClass = new ManagementClass(_className); + mObject = mClass; + mObject.Scope = scope; + } + + ManagementBaseObject inputParameters = mObject.GetMethodParameters(_methodName); + if (_argumentList != null) + { + int inParamCount = _argumentList.Length; + foreach (PropertyData property in inputParameters.Properties) + { + if (inParamCount == 0) + break; + object argument = PSObject.Base(_argumentList[_argumentList.Length - inParamCount]); + if (property.IsArray) + { + property.Value = MakeBaseObjectArray(argument); + } + else + { + property.Value = argument; + } + + inParamCount--; + } + } + + if (!ShouldProcess( + StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, + mObject["__CLASS"].ToString(), + this.Name) + )) + { + return; + } + + result = mObject.InvokeMethod(_methodName, inputParameters, null); + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMIManagementException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + + if (result != null) + { + WriteObject(result); + } + } + } + } + + /// + /// Ensure that the argument is a collection containing no PSObjects. + /// + /// + /// + private static object MakeBaseObjectArray(object argument) + { + if (argument == null) + return null; + + IList listArgument = argument as IList; + if (listArgument == null) + { + return new object[] { argument }; + } + + bool needCopy = false; + foreach (object argElement in listArgument) + { + if (argElement is PSObject) + { + needCopy = true; + break; + } + } + + if (needCopy) + { + var copiedArgument = new object[listArgument.Count]; + int index = 0; + foreach (object argElement in listArgument) + { + copiedArgument[index++] = argElement != null ? PSObject.Base(argElement) : null; + } + + return copiedArgument; + } + else + { + return argument; + } + } + + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/JobProcessCollection.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/JobProcessCollection.cs new file mode 100644 index 0000000000000000000000000000000000000000..78560543939262f8b9e300b8350d77593d2614e4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/JobProcessCollection.cs @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable +#if !UNIX +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.Win32.SafeHandles; + +namespace Microsoft.PowerShell.Commands; + +/// +/// JobProcessCollection is a helper class used by Start-Process -Wait cmdlet to monitor the +/// child processes created by the main process hosted by the Start-process cmdlet. +/// +internal sealed class JobProcessCollection : IDisposable +{ + /// + /// Stores the initialisation state of the job and completion port. + /// + private bool? _initStatus; + + /// + /// JobObjectHandle is a reference to the job object used to track + /// the child processes created by the main process hosted by the Start-Process cmdlet. + /// + private Interop.Windows.SafeJobHandle? _jobObject; + + /// + /// The completion port handle that is used to monitor job events. + /// + private Interop.Windows.SafeIoCompletionPort? _completionPort; + + /// + /// Initializes a new instance of the class. + /// + public JobProcessCollection() + { } + + /// + /// Initializes the job and IO completion port and adds the process to the + /// job object. + /// + /// The process to add to the job. + /// Whether the job creation and assignment worked or not. + public bool AssignProcessToJobObject(SafeProcessHandle process) + => InitializeJob() && Interop.Windows.AssignProcessToJobObject(_jobObject, process); + + /// + /// Blocks the current thread until all processes in the job have exited. + /// + /// A token to cancel the operation. + public void WaitForExit(CancellationToken cancellationToken) + { + if (_completionPort is null) + { + return; + } + + using var cancellationRegistration = cancellationToken.Register(() => + { + Interop.Windows.PostQueuedCompletionStatus( + _completionPort, + Interop.Windows.JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO); + }); + + int completionCode = 0; + do + { + Interop.Windows.GetQueuedCompletionStatus( + _completionPort, + Interop.Windows.INFINITE, + out completionCode); + } + while (completionCode != Interop.Windows.JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO); + cancellationToken.ThrowIfCancellationRequested(); + } + + [MemberNotNullWhen(true, [nameof(_jobObject), nameof(_completionPort)])] + private bool InitializeJob() + { + if (_initStatus.HasValue) + { + return _initStatus.Value; + } + + if (_jobObject is null) + { + _jobObject = Interop.Windows.CreateJobObject(); + if (_jobObject.IsInvalid) + { + _initStatus = false; + _jobObject.Dispose(); + _jobObject = null; + return false; + } + } + + if (_completionPort is null) + { + _completionPort = Interop.Windows.CreateIoCompletionPort(); + if (_completionPort.IsInvalid) + { + _initStatus = false; + _completionPort.Dispose(); + _completionPort = null; + return false; + } + } + + _initStatus = Interop.Windows.SetInformationJobObject( + _jobObject, + _completionPort); + + return _initStatus.Value; + } + + public void Dispose() + { + _jobObject?.Dispose(); + _completionPort?.Dispose(); + } +} +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..a40cae64b9f25e8b4082c75e6366850d06ae986f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to move a property on an item to another item. + /// + [Cmdlet(VerbsCommon.Move, "ItemProperty", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096817")] + public class MoveItemPropertyCommand : PassThroughItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get { return paths; } + + set { paths = value; } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The name of the property to create on the item. + /// + [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Alias("PSProperty")] + public string[] Name + { + get + { + return _property; + } + + set + { + value ??= Array.Empty(); + + _property = value; + } + } + + /// + /// The path to the destination item to copy the property to. + /// + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] + public string Destination { get; set; } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + string propertyName = string.Empty; + if (Name != null && Name.Length > 0) + { + propertyName = Name[0]; + } + + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.MovePropertyDynamicParameters(Path[0], propertyName, Destination, propertyName, context); + } + + return InvokeProvider.Property.MovePropertyDynamicParameters( + ".", + propertyName, + Destination, + propertyName, + context); + } + + #endregion Parameters + + #region parameter data + + /// + /// The property to be created. + /// + private string[] _property = Array.Empty(); + + #endregion parameter data + + #region Command code + + /// + /// Creates the property on the item. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + foreach (string propertyName in Name) + { + try + { + InvokeProvider.Property.Move(path, propertyName, Destination, propertyName, GetCurrentContext()); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs new file mode 100644 index 0000000000000000000000000000000000000000..6ab8f1d652d60a34127816878d57d78437425641 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -0,0 +1,4224 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Provider; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + #region CoreCommandBase + + /// + /// The base command for the core commands. + /// + public abstract class CoreCommandBase : PSCmdlet, IDynamicParameters + { + #region Tracer + + /// + /// An instance of the PSTraceSource class used for trace output + /// using "NavigationCommands" as the category. + /// + [Dbg.TraceSource("NavigationCommands", "The namespace navigation tracer")] + internal static readonly Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); + + #endregion Tracer + + #region Protected members + + /// + /// The context for the command that is passed to the core command providers. + /// + internal virtual CmdletProviderContext CmdletProviderContext + { + get + { + CmdletProviderContext coreCommandContext = new(this); + + coreCommandContext.Force = Force; + + Collection includeFilter = + SessionStateUtilities.ConvertArrayToCollection(Include); + + Collection excludeFilter = + SessionStateUtilities.ConvertArrayToCollection(Exclude); + + coreCommandContext.SetFilters(includeFilter, excludeFilter, Filter); + coreCommandContext.SuppressWildcardExpansion = SuppressWildcardExpansion; + coreCommandContext.DynamicParameters = RetrievedDynamicParameters; + stopContextCollection.Add(coreCommandContext); + + return coreCommandContext; + } + } + + internal virtual SwitchParameter SuppressWildcardExpansion + { + get => _suppressWildcardExpansion; + set => _suppressWildcardExpansion = value; + } + + private bool _suppressWildcardExpansion; + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal virtual object GetDynamicParameters(CmdletProviderContext context) => null; + + /// + /// Called by the base implementation that checks the SupportShouldProcess provider + /// capability. This virtual method gives the + /// derived cmdlet a chance query the CmdletProvider capabilities to determine + /// if the provider supports ShouldProcess. + /// + /// + protected virtual bool ProviderSupportsShouldProcess => true; + + /// + /// A helper for derived classes to call to determine if the paths specified + /// are for a provider that supports ShouldProcess. + /// + /// + /// The paths to check to see if the providers support ShouldProcess. + /// + /// + /// If the paths are to different providers, and any don't support + /// ShouldProcess, then the return value is false. If they all + /// support ShouldProcess then the return value is true. + /// + protected bool DoesProviderSupportShouldProcess(string[] paths) + { + // If no paths are specified, then default to true as the paths + // may be getting piped in. + bool result = true; + + if (paths != null) + { + foreach (string path in paths) + { + ProviderInfo provider = null; + PSDriveInfo drive = null; + + // I don't really care about the returned path, just the provider name + SessionState.Path.GetUnresolvedProviderPathFromPSPath( + path, + this.CmdletProviderContext, + out provider, + out drive); + + // Check the provider's capabilities + + if (!CmdletProviderManagementIntrinsics.CheckProviderCapabilities( + ProviderCapabilities.ShouldProcess, + provider)) + { + result = false; + break; + } + } + } + + return result; + } + + /// + /// The dynamic parameters which have already been retrieved from the provider + /// and bound by the command processor. + /// + protected internal object RetrievedDynamicParameters => _dynamicParameters; + /// + /// The dynamic parameters for the command. They are retrieved using the + /// GetDynamicParameters virtual method. + /// + private object _dynamicParameters; + + #endregion Protected members + + #region Public members + + /// + /// Stops the processing of the provider by using the + /// CmdletProviderContext to tunnel the stop message to + /// the provider instance. + /// + protected override void StopProcessing() + { + foreach (CmdletProviderContext stopContext in stopContextCollection) + { + stopContext.StopProcessing(); + } + } + + internal Collection stopContextCollection = + new(); + + /// + /// Gets or sets the filter property. + /// + /// + /// This is meant to be overridden by derived classes if + /// they support the Filter parameter. This property is on + /// the base class to simplify the creation of the CmdletProviderContext. + /// + public virtual string Filter { get; set; } + + /// + /// Gets or sets the include property. + /// + /// + /// This is meant to be overridden by derived classes if + /// they support the Include parameter. This property is on + /// the base class to simplify the creation of the CmdletProviderContext. + /// + public virtual string[] Include + { + get; + set; + } = Array.Empty(); + + /// + /// Gets or sets the exclude property. + /// + /// + /// This is meant to be overridden by derived classes if + /// they support the Exclude parameter. This property is on + /// the base class to simplify the creation of the CmdletProviderContext. + /// + public virtual string[] Exclude + { + get; + set; + } = Array.Empty(); + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + /// This is meant to be overridden by derived classes if + /// they support the Force parameter. This property is on + /// the base class to simplify the creation of the CmdletProviderContext. + /// + public virtual SwitchParameter Force + { + get => _force; + set => _force = value; + } + + private bool _force; + + /// + /// Retrieves the dynamic parameters for the command from + /// the provider. + /// + public object GetDynamicParameters() + { + // Don't stream errors or Write* to the pipeline. + CmdletProviderContext context = CmdletProviderContext; + context.PassThru = false; + + try + { + _dynamicParameters = GetDynamicParameters(context); + } + catch (ItemNotFoundException) + { + _dynamicParameters = null; + } + catch (ProviderNotFoundException) + { + _dynamicParameters = null; + } + catch (DriveNotFoundException) + { + _dynamicParameters = null; + } + + return _dynamicParameters; + } + + /// + /// Determines if the cmdlet and CmdletProvider supports ShouldProcess. + /// + public bool SupportsShouldProcess => ProviderSupportsShouldProcess; + + #endregion Public members + } + + #endregion CoreCommandBase + + #region CoreCommandWithCredentialsBase + + /// + /// The base class for core commands to extend when they require credentials + /// to be passed as parameters. + /// + public class CoreCommandWithCredentialsBase : CoreCommandBase + { + #region Parameters + + /// + /// Gets or sets the credential parameter. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Credential] + public PSCredential Credential { get; set; } + + #endregion Parameters + + #region parameter data + + #endregion parameter data + + #region Protected members + + /// + /// The context for the command that is passed to the core command providers. + /// + internal override CmdletProviderContext CmdletProviderContext + { + get + { + CmdletProviderContext coreCommandContext = new(this, Credential); + coreCommandContext.Force = Force; + + Collection includeFilter = + SessionStateUtilities.ConvertArrayToCollection(Include); + + Collection excludeFilter = + SessionStateUtilities.ConvertArrayToCollection(Exclude); + + coreCommandContext.SetFilters(includeFilter, excludeFilter, Filter); + coreCommandContext.SuppressWildcardExpansion = SuppressWildcardExpansion; + coreCommandContext.DynamicParameters = RetrievedDynamicParameters; + stopContextCollection.Add(coreCommandContext); + + return coreCommandContext; + } + } + + #endregion Protected members + } + + #endregion CoreCommandWithCredentialsBase + + #region GetLocationCommand + + /// + /// The get-location command class. + /// This command does things like list the contents of a container, get + /// an item at a given path, get the current working directory, etc. + /// + /// + /// + [Cmdlet(VerbsCommon.Get, "Location", DefaultParameterSetName = LocationParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096495")] + [OutputType(typeof(PathInfo), ParameterSetName = new string[] { LocationParameterSet })] + [OutputType(typeof(PathInfoStack), ParameterSetName = new string[] { StackParameterSet })] + public class GetLocationCommand : DriveMatchingCoreCommandBase + { + private const string LocationParameterSet = "Location"; + private const string StackParameterSet = "Stack"; + + #region Command parameters + + #region Location parameter set parameters + + /// + /// Gets or sets the provider from which to get the current location. + /// + [Parameter(ParameterSetName = LocationParameterSet, ValueFromPipelineByPropertyName = true)] + public string[] PSProvider + { + get => _provider; + set => _provider = value ?? Array.Empty(); + } + + /// + /// Gets or sets the drive from which to get the current location. + /// + [Parameter(ParameterSetName = LocationParameterSet, ValueFromPipelineByPropertyName = true)] + public string[] PSDrive { get; set; } + + #endregion Location parameter set parameters + + #region Stack parameter set parameters + + /// + /// Gets or sets the Stack switch parameter which is used + /// to disambiguate parameter sets. + /// + /// + [Parameter(ParameterSetName = StackParameterSet)] + public SwitchParameter Stack + { + get => _stackSwitch; + set => _stackSwitch = value; + } + + private bool _stackSwitch; + + /// + /// Gets or sets the stack ID for the location stack that will + /// be retrieved. + /// + [Parameter(ParameterSetName = StackParameterSet, ValueFromPipelineByPropertyName = true)] + public string[] StackName + { + get => _stackNames; + + set => _stackNames = value; + } + + #endregion Stack parameter set parameters + + #endregion Command parameters + + #region command data + + #region Location parameter set data + + /// + /// The name of the provider from which to return the current location. + /// + private string[] _provider = Array.Empty(); + + #endregion Location parameter set data + + #region Stack parameter set data + + /// + /// The name of the location stack from which to return the stack. + /// + private string[] _stackNames; + + #endregion Stack parameter set data + + #endregion command data + + #region command code + + /// + /// The main execution method for the get-location command. Depending on + /// the parameter set that is specified, the command can do many things. + /// -locationSet gets the current working directory as a Monad path + /// -stackSet gets the directory stack of directories that have been + /// pushed by the push-location command. + /// + protected override void ProcessRecord() + { + // It is OK to use a switch for string comparison here because we + // want a case sensitive comparison in the current culture. + switch (ParameterSetName) + { + case LocationParameterSet: + PathInfo result = null; + + if (PSDrive != null && PSDrive.Length > 0) + { + foreach (string drive in PSDrive) + { + List foundDrives = null; + try + { + foundDrives = GetMatchingDrives(drive, PSProvider, null); + } + catch (DriveNotFoundException e) + { + ErrorRecord errorRecord = + new( + e, + "GetLocationNoMatchingDrive", + ErrorCategory.ObjectNotFound, + drive); + WriteError(errorRecord); + continue; + } + catch (ProviderNotFoundException e) + { + ErrorRecord errorRecord = + new( + e, + "GetLocationNoMatchingProvider", + ErrorCategory.ObjectNotFound, + PSProvider); + WriteError(errorRecord); + continue; + } + catch (ArgumentException argException) + { + ErrorRecord errorRecord = + new( + argException, + "GetLocationNoMatchingDrive", + ErrorCategory.ObjectNotFound, + drive); + WriteError(errorRecord); + continue; + } + + // Get the current location for a specific drive and provider + + foreach (PSDriveInfo workingDrive in foundDrives) + { + try + { + string path = + LocationGlobber.GetDriveQualifiedPath( + workingDrive.CurrentLocation, + workingDrive); + + result = new PathInfo(workingDrive, workingDrive.Provider, path, SessionState); + + WriteObject(result); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + } + } + } + // If the drive wasn't specified but the provider was + else if ((PSDrive == null || PSDrive.Length == 0) && + (PSProvider != null && PSProvider.Length > 0)) + { + foreach (string providerName in PSProvider) + { + bool providerContainsWildcard = WildcardPattern.ContainsWildcardCharacters(providerName); + if (!providerContainsWildcard) + { + // Since the Provider was specified and doesn't contain + // wildcard characters, make sure it exists. + + try + { + SessionState.Provider.GetOne(providerName); + } + catch (ProviderNotFoundException e) + { + ErrorRecord errorRecord = + new( + e, + "GetLocationNoMatchingProvider", + ErrorCategory.ObjectNotFound, + providerName); + WriteError(errorRecord); + continue; + } + } + + // Match the providers + + foreach (ProviderInfo providerInfo in SessionState.Provider.GetAll()) + { + if (providerInfo.IsMatch(providerName)) + { + try + { + WriteObject(SessionState.Path.CurrentProviderLocation(providerInfo.FullName)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + if (providerContainsWildcard) + { + // NTRAID#Windows Out Of Band Releases-923607-2005/11/02-JeffJon + // This exception is ignored, because it just means we didn't find + // an active drive for the provider. + continue; + } + else + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + } + } + } + } + } + else + { + // Get the current working directory using the core command API. + WriteObject(SessionState.Path.CurrentLocation); + } + + break; + + case StackParameterSet: + if (_stackNames != null) + { + foreach (string stackName in _stackNames) + { + try + { + // Get the directory stack. This is similar to the "dirs" command + WriteObject(SessionState.Path.LocationStack(stackName), false); + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + continue; + } + } + } + else + { + try + { + WriteObject(SessionState.Path.LocationStack(null), false); + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + } + } + + break; + + default: + Dbg.Diagnostics.Assert(false, string.Create(System.Globalization.CultureInfo.InvariantCulture, $"One of the predefined parameter sets should have been specified, instead we got: {ParameterSetName}")); + break; + } + } + + #endregion command code + } + #endregion GetLocationCommand + + #region SetLocationCommand + + /// + /// The core command for setting/changing location. + /// This is the equivalent of cd command. + /// + [Cmdlet(VerbsCommon.Set, "Location", DefaultParameterSetName = PathParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097049")] + [OutputType(typeof(PathInfo), typeof(PathInfoStack))] + public class SetLocationCommand : CoreCommandBase + { + #region Command parameters + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + private const string StackParameterSet = "Stack"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string Path + { + get => _path; + set => _path = value; + } + + /// + /// Gets or sets the path property, when bound from the pipeline. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get => _path; + set + { + _path = value; + base.SuppressWildcardExpansion = true; + } + } + + /// + /// Gets or sets the parameter -passThru which states output from + /// the command should be placed in the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets or sets the StackName parameter which determines which location stack + /// to use for the push. If the parameter is missing or empty the default + /// location stack is used. + /// + [Parameter(ParameterSetName = StackParameterSet, ValueFromPipelineByPropertyName = true)] + public string StackName { get; set; } + + #endregion Command parameters + + #region Command data + + /// + /// The filter used when doing a dir. + /// + private string _path = string.Empty; + + /// + /// Determines if output should be passed through for + /// set-location. + /// + private bool _passThrough; + + #endregion Command data + + #region Command code + + /// + /// The functional part of the code that does the changing of the current + /// working directory. + /// + protected override void ProcessRecord() + { + object result = null; + + switch (ParameterSetName) + { + case PathParameterSet: + case LiteralPathParameterSet: + try + { + // Change the current working directory + if (string.IsNullOrEmpty(Path)) + { + // If user just typed 'cd', go to FileSystem provider home directory + Path = SessionState.Internal.GetSingleProvider(Commands.FileSystemProvider.ProviderName).Home; + } + + result = SessionState.Path.SetLocation(Path, CmdletProviderContext, ParameterSetName == LiteralPathParameterSet); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + } + + break; + + case StackParameterSet: + + try + { + // Change the default location stack + result = SessionState.Path.SetDefaultLocationStack(StackName); + } + catch (ItemNotFoundException itemNotFound) + { + WriteError( + new ErrorRecord( + itemNotFound.ErrorRecord, + itemNotFound)); + } + + break; + + default: + Dbg.Diagnostics.Assert( + false, + "One of the specified parameter sets should have been called"); + break; + } + + if (_passThrough && result != null) + { + WriteObject(result); + } + } + + #endregion Command code + } + + #endregion SetLocationCommand + + #region PushLocationCommand + + /// + /// The core command for setting/changing location and pushing it onto a location stack. + /// This is the equivalent of the pushd command. + /// + [Cmdlet(VerbsCommon.Push, "Location", DefaultParameterSetName = PathParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097105")] + public class PushLocationCommand : CoreCommandBase + { + #region Command parameters + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string Path + { + get => _path; + set => _path = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get => _path; + set + { + base.SuppressWildcardExpansion = true; + _path = value; + } + } + + /// + /// Gets or sets the parameter -passThru which states output from + /// the command should be placed in the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets or sets the StackName parameter which determines which location stack + /// to use for the push. If the parameter is missing or empty the default + /// location stack is used. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string StackName + { + get => _stackName; + set => _stackName = value; + } + + #endregion Command parameters + + #region Command data + + /// + /// The filter used when doing a dir. + /// + private string _path = string.Empty; + + /// + /// Determines if output should be passed through for + /// push-location. + /// + private bool _passThrough; + + /// + /// The ID of the stack to use for the pop. + /// + private string _stackName; + + #endregion Command data + + #region Command code + + /// + /// The functional part of the code that does the changing of the current + /// working directory and pushes the container onto the stack. + /// + protected override void ProcessRecord() + { + // Push the current working directory onto the + // working directory stack + SessionState.Path.PushCurrentLocation(_stackName); + + if (Path != null) + { + try + { + // Now change the directory to the one specified + // in the command + PathInfo result = SessionState.Path.SetLocation(Path, CmdletProviderContext); + + if (PassThru) + { + WriteObject(result); + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + return; + } + } + } + + #endregion Command code + } + + #endregion PushLocationCommand + + #region PopLocationCommand + + /// + /// The core command for pop-location. This is the equivalent of the popd command. + /// It pops a container from the stack and sets the current location to that container. + /// + [Cmdlet(VerbsCommon.Pop, "Location", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096907")] + public class PopLocationCommand : CoreCommandBase + { + #region Command parameters + + /// + /// Gets or sets the parameter -passThru which states output from + /// the command should be placed in the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets or sets the StackName parameter which determines which location stack + /// to use for the pop. If the parameter is missing or empty the default + /// location stack is used. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string StackName + { + get => _stackName; + set => _stackName = value; + } + + #endregion Command parameters + + #region Command data + + /// + /// Determines if output should be passed through for + /// pop-location. + /// + private bool _passThrough; + + /// + /// The ID of the stack to use for the pop. + /// + private string _stackName; + + #endregion Command data + + #region Command code + + /// + /// Gets the top container from the location stack and sets the + /// location to it. + /// + protected override void ProcessRecord() + { + try + { + // Pop the top of the location stack. + + PathInfo result = SessionState.Path.PopLocation(_stackName); + + if (PassThru) + { + WriteObject(result); + } + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + return; + } + catch (ItemNotFoundException itemNotFound) + { + WriteError( + new ErrorRecord( + itemNotFound.ErrorRecord, + itemNotFound)); + return; + } + } + + #endregion Command code + } + + #endregion PopLocationCommand + + #region Drive commands + + #region NewPSDriveCommand + + /// + /// Mounts a drive in PowerShell runspace. + /// + [Cmdlet(VerbsCommon.New, "PSDrive", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, + SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096815")] + public class NewPSDriveCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + /// + /// Gets or sets the name of the drive. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string Name + { + get => _name; + set => _name = value ?? throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + /// + /// Gets or sets the provider ID. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string PSProvider + { + get => _provider; + set => _provider = value ?? throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + /// + /// Gets or sets the root of the drive. This path should be + /// a namespace specific path. + /// + [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [AllowEmptyString] + public string Root + { + get => _root; + set => _root = value ?? throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + /// + /// Gets or sets the description of the drive. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string Description + { + get => _description; + set => _description = value ?? throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + /// + /// Gets or sets the scope identifier for the drive being created. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + +#if !UNIX + /// + /// Gets or sets the Persist Switch parameter. + /// If this switch parameter is set then the created PSDrive + /// would be persisted across PowerShell sessions. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public SwitchParameter Persist + { + get => _persist; + set => _persist = value; + } + + private bool _persist = false; +#endif + /// + /// Gets the dynamic parameters for the new-psdrive cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + return SessionState.Drive.NewDriveDynamicParameters(PSProvider, context); + } + + /// + /// New-psdrive always supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => true; + + #endregion Command parameters + + #region Command data + + /// + /// The name of the drive. + /// + private string _name; + + /// + /// The provider ID for the drive. + /// + private string _provider; + + /// + /// The namespace specific path of the root of the drive. + /// + private string _root; + + /// + /// A description for the drive. + /// + private string _description; + + #endregion Command data + + #region Command code + + /// + /// Adds a new drive to the Monad namespace. + /// + protected override void ProcessRecord() + { + ProviderInfo provider = null; + + try + { + provider = SessionState.Internal.GetSingleProvider(PSProvider); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + + // Check to see if the provider exists + if (provider != null) + { + // Get the confirmation strings + + string action = NavigationResources.NewDriveConfirmAction; + string resourceTemplate = NavigationResources.NewDriveConfirmResourceTemplate; + + string resource = + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + resourceTemplate, + Name, + provider.FullName, + Root); + + if (ShouldProcess(resource, action)) + { +#if !UNIX + // -Persist switch parameter is supported only for FileSystem provider. + if (Persist && !provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + { + ErrorRecord er = new(new NotSupportedException(FileSystemProviderStrings.PersistNotSupported), "DriveRootNotNetworkPath", ErrorCategory.InvalidArgument, this); + ThrowTerminatingError(er); + } + + // Trimming forward and backward slash for FileSystem provider when -Persist is used. + if (Persist && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + { + Root = Root.TrimEnd('/', '\\'); + } + + // Create the new drive + PSDriveInfo newDrive = + new( + Name, + provider, + Root, + Description, + Credential, + Persist); +#else + // Create the new drive + PSDriveInfo newDrive = + new PSDriveInfo( + Name, + provider, + Root, + Description, + Credential, + persist: false); +#endif + try + { + SessionState.Drive.New(newDrive, Scope, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + return; + } + } + } + } + #endregion Command code + + } + + #endregion NewPSDriveCommand + + #region DriveMatchingCoreCommandBase + + /// + /// Base class for Drive commands that need to glob drives on both the drive name + /// and the provider name. + /// + public class DriveMatchingCoreCommandBase : CoreCommandBase + { + /// + /// Globs on both the drive name and the provider name to get a list of Drives + /// that match the glob filters. + /// + /// + /// The name of the drive(s) to returned. The name can contain glob characters. + /// + /// + /// The name of the provider(s) to return. The name can contain glob characters. + /// + /// + /// The scope to get the drives from. If this parameter is null or empty all drives + /// will be retrieved. + /// + /// + /// A collection of the drives that match the filters. + /// + /// + /// + /// + /// If is less than zero, or not + /// a number and not "script", "global", "local", or "private" + /// + /// + /// If is less than zero or greater than the number of currently + /// active scopes. + /// + internal List GetMatchingDrives( + string driveName, + string[] providerNames, + string scope) + { + List results = new(); + + if (providerNames == null || providerNames.Length == 0) + { + providerNames = new string[] { "*" }; + } + + foreach (string providerName in providerNames) + { + tracer.WriteLine("ProviderName: {0}", providerName); + + bool providerNameEmpty = string.IsNullOrEmpty(providerName); + bool providerNameContainsWildcardCharacters = + WildcardPattern.ContainsWildcardCharacters(providerName); + + bool driveNameEmpty = string.IsNullOrEmpty(driveName); + bool driveNameContainsWildcardCharacters = + WildcardPattern.ContainsWildcardCharacters(driveName); + + // This is just a simple check to see if the provider exists + // if the provider name is specified without glob characters. + // The call will throw an exception if the provider doesn't + // exist. + if (!providerNameEmpty && !providerNameContainsWildcardCharacters) + { + SessionState.Provider.Get(providerName); + } + + // This is just a simple check to see if the drive exists + // if the drive name is specified without glob characters. + // The call will throw an exception if the drive doesn't + // exist. + if (!driveNameEmpty && !driveNameContainsWildcardCharacters) + { + if (string.IsNullOrEmpty(scope)) + { + SessionState.Drive.Get(driveName); + } + else + { + SessionState.Drive.GetAtScope(driveName, scope); + } + } + + WildcardPattern providerMatcher = null; + PSSnapinQualifiedName pssnapinQualifiedProviderName = null; + + if (!providerNameEmpty) + { + pssnapinQualifiedProviderName = PSSnapinQualifiedName.GetInstance(providerName); + + if (pssnapinQualifiedProviderName == null) + { + // This is a malformed pssnapin-qualified name so there is no chances for a match. + continue; + } + + providerMatcher = + WildcardPattern.Get( + pssnapinQualifiedProviderName.ShortName, + WildcardOptions.IgnoreCase); + } + + WildcardPattern nameMatcher = null; + + if (!driveNameEmpty) + { + nameMatcher = + WildcardPattern.Get( + driveName, + WildcardOptions.IgnoreCase); + } + + foreach (PSDriveInfo drive in SessionState.Drive.GetAllAtScope(scope)) + { + bool addDrive = driveNameEmpty; + + if (base.SuppressWildcardExpansion) + { + if (string.Equals(drive.Name, driveName, StringComparison.OrdinalIgnoreCase)) + addDrive = true; + } + else + { + if (nameMatcher != null && nameMatcher.IsMatch(drive.Name)) + addDrive = true; + } + + if (addDrive) + { + // Now check to see if it matches the provider + if (providerNameEmpty || drive.Provider.IsMatch(providerMatcher, pssnapinQualifiedProviderName)) + { + results.Add(drive); + } + } + } + } + + results.Sort(); + return results; + } + } + + #endregion DriveMatchingCoreCommandBase + + #region RemovePSDriveCommand + + /// + /// Removes a drive that is mounted in the PowerShell runspace. + /// + [Cmdlet(VerbsCommon.Remove, "PSDrive", DefaultParameterSetName = NameParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097050")] + public class RemovePSDriveCommand : DriveMatchingCoreCommandBase + { + #region Command parameters + + private const string NameParameterSet = "Name"; + private const string LiteralNameParameterSet = "LiteralName"; + + /// + /// Gets or sets the name of the drive to remove. + /// + [Parameter(Position = 0, ParameterSetName = NameParameterSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [AllowNull] + [AllowEmptyCollection] + public string[] Name + { + get => _names; + set => _names = value; + } + + /// + /// Gets or sets the literal name parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = LiteralNameParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + public string[] LiteralName + { + get => _names; + set + { + base.SuppressWildcardExpansion = true; + _names = value; + } + } + + /// + /// Gets or sets the name provider(s) for which the drives should be removed. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string[] PSProvider + { + get => _provider; + set => _provider = value ?? Array.Empty(); + } + + /// + /// Gets or sets the scope identifier from which to remove the drive. + /// If the scope is null or empty, the scope hierarchy will be searched + /// starting at the current scope through all the parent scopes to the + /// global scope until a drive of the given name is found to remove. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + /// + /// Gets or sets the force property which determines if the drive + /// should be removed even if there were errors. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => true; + + #endregion Command parameters + + #region Command data + + /// + /// The name of the drive to remove. + /// + private string[] _names; + + /// + /// The name of the provider(s) for which to remove all drives. + /// + private string[] _provider = Array.Empty(); + + #endregion Command data + + #region Command code + + /// + /// Removes the specified drive from the Monad namespace using the name + /// of the drive. + /// + protected override void ProcessRecord() + { + // Get the confirmation strings + + string action = NavigationResources.RemoveDriveConfirmAction; + string resourceTemplate = NavigationResources.RemoveDriveConfirmResourceTemplate; + + bool verifyMatch = true; + if (_names == null) + { + _names = new string[] { string.Empty }; + verifyMatch = false; + } + + foreach (string driveName in _names) + { + bool foundMatch = false; + try + { + foreach (PSDriveInfo drive in GetMatchingDrives(driveName, PSProvider, Scope)) + { + string resource = + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + resourceTemplate, + drive.Name, + drive.Provider, + drive.Root); + + foundMatch = true; + if (ShouldProcess(resource, action)) + { + if (!Force && drive == SessionState.Drive.Current) + { + PSInvalidOperationException invalidOperation = + (PSInvalidOperationException)PSTraceSource.NewInvalidOperationException( + NavigationResources.RemoveDriveInUse, + drive.Name); + + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, + invalidOperation)); + continue; + } + + SessionState.Drive.Remove(drive.Name, Force, Scope, CmdletProviderContext); + } + } + } + catch (DriveNotFoundException) + { + } + catch (ProviderNotFoundException) + { + } + + // If a name was specified explicitly write an error if the drive wasn't + // found + + if (verifyMatch && !foundMatch) + { + DriveNotFoundException e = new( + driveName, + "DriveNotFound", + SessionStateStrings.DriveNotFound); + WriteError(new ErrorRecord(e.ErrorRecord, e)); + } + } + } + + #endregion Command code + } + + #endregion RemovePSDriveCommand + + #region GetPSDriveCommand + + /// + /// Gets a specified or listing of drives that are mounted in PowerShell + /// namespace. + /// + [Cmdlet(VerbsCommon.Get, "PSDrive", DefaultParameterSetName = NameParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096494")] + [OutputType(typeof(PSDriveInfo))] + public class GetPSDriveCommand : DriveMatchingCoreCommandBase + { + #region Command parameters + + private const string NameParameterSet = "Name"; + private const string LiteralNameParameterSet = "LiteralName"; + + /// + /// Gets or sets the drive name the user is looking for. + /// + /// + /// If the drive name is left empty, all drives will be + /// returned. A globing or regular expression can also be + /// supplied and any drive names that match the expression + /// will be returned. + /// + [Parameter(Position = 0, ParameterSetName = NameParameterSet, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string[] Name + { + get => _name; + set => _name = value ?? new string[] { "*" }; + } + + /// + /// Gets or sets the literal name parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = LiteralNameParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + public string[] LiteralName + { + get => _name; + set + { + base.SuppressWildcardExpansion = true; + _name = value; + } + } + + /// + /// Gets or sets the scope parameter to the command. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + /// + /// Gets or sets the provider name for the + /// drives that should be retrieved. + /// + /// + /// If the provider is left empty, all drives will be + /// returned. A globing or regular expression can also be + /// supplied and any drive with providers that match the expression + /// will be returned. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string[] PSProvider + { + get => _provider; + set => _provider = value ?? Array.Empty(); + } + + #endregion Command parameters + + #region Command data + + /// + /// The name of the drive to be retrieved. + /// + private string[] _name = new string[] { "*" }; + + /// + /// The provider ID for the drives you want to see. + /// + private string[] _provider = Array.Empty(); + + #endregion Command data + + #region Command code + + /// + /// Prepare the session for the Get-PSDrive command. + /// Currently, auto-loads the core modules that define drives. Ideally, + /// we could discover fake PSDriveInfo objects here based on drives exported + /// from modules. + /// + protected override void BeginProcessing() + { + SessionStateInternal.MountDefaultDrive("Cert", Context); + SessionStateInternal.MountDefaultDrive("WSMan", Context); + } + + /// + /// Retrieves the drives specified by the parameters. If the name is empty, all drives + /// will be retrieved. If the provider is specified, only drives for that provider + /// will be retrieved. + /// + protected override void ProcessRecord() + { + foreach (string driveName in Name) + { + try + { + List foundDrives = GetMatchingDrives(driveName, PSProvider, Scope); + + if (foundDrives.Count > 0) + { + WriteObject(foundDrives, true); + } + else + { + // If no drives were found and the user was asking for a specific + // drive (no wildcards) then write an error + + if (!WildcardPattern.ContainsWildcardCharacters(driveName)) + { + DriveNotFoundException driveNotFound = + new( + driveName, + "DriveNotFound", + SessionStateStrings.DriveNotFound); + + WriteError( + new ErrorRecord( + driveNotFound, + "GetDriveNoMatchingDrive", + ErrorCategory.ObjectNotFound, + driveName)); + } + } + } + catch (DriveNotFoundException driveNotFound) + { + ErrorRecord errorRecord = + new( + driveNotFound, + "GetLocationNoMatchingDrive", + ErrorCategory.ObjectNotFound, + driveName); + WriteError(errorRecord); + } + catch (ProviderNotFoundException providerNotFound) + { + ErrorRecord errorRecord = + new( + providerNotFound, + "GetLocationNoMatchingDrive", + ErrorCategory.ObjectNotFound, + PSProvider); + WriteError(errorRecord); + } + catch (PSArgumentOutOfRangeException outOfRange) + { + WriteError( + new ErrorRecord( + outOfRange.ErrorRecord, + outOfRange)); + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + } + } + } + + #endregion Command code + } + + #endregion GetPSDriveCommand + + #endregion Drive commands + + #region Item commands + + #region GetItemCommand + + /// + /// Gets the specified item using the namespace providers. + /// + [Cmdlet(VerbsCommon.Get, "Item", DefaultParameterSetName = PathParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096812")] + public class GetItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path to item to get. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets the dynamic parameters for the get-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.GetItemDynamicParameters(Path[0], context); + } + + return InvokeProvider.Item.GetItemDynamicParameters(".", context); + } + + #endregion Command parameters + + #region Command data + /// + /// The path of the item to get. + /// + private string[] _paths; + + #endregion Command data + + #region Command code + + /// + /// Gets the specified item. + /// + protected override void ProcessRecord() + { + foreach (string path in _paths) + { + try + { + InvokeProvider.Item.Get(path, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + } + } + + #endregion Command code + } + + #endregion GetItemCommand + + #region NewItemCommand + + /// + /// Creates the specified item using the namespace providers. + /// + [Cmdlet(VerbsCommon.New, "Item", DefaultParameterSetName = PathParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096592")] + public class NewItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string NameParameterSet = "nameSet"; + private const string PathParameterSet = "pathSet"; + + /// + /// Gets or sets the container path to create the item in. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = NameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true)] + public string[] Path { get; set; } + + /// + /// Gets or sets the name of the item to create. + /// + [Parameter(ParameterSetName = NameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [AllowNull] + [AllowEmptyString] + public string Name { get; set; } + + /// + /// Gets or sets the type of the item to create. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Alias("Type")] + public string ItemType { get; set; } + + /// + /// Gets or sets the content of the item to create. + /// + [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Alias("Target")] + public object Value { get; set; } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets the dynamic parameters for the new-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + // Path is only globbed if Name is specified. + if (string.IsNullOrEmpty(Name)) + return InvokeProvider.Item.NewItemDynamicParameters(WildcardPattern.Escape(Path[0]), ItemType, Value, context); + else + return InvokeProvider.Item.NewItemDynamicParameters(Path[0], ItemType, Value, context); + } + + return InvokeProvider.Item.NewItemDynamicParameters(".", ItemType, Value, context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(Path); + + #endregion Command parameters + + #region Command data + + #endregion Command Data + + #region Command code + + /// + /// Creates the specified item. + /// + protected override void ProcessRecord() + { + if (Path == null || Path.Length == 0) + { + Path = new string[] { string.Empty }; + } + + foreach (string path in Path) + { + try + { + InvokeProvider.Item.New(path, Name, ItemType, Value, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + } + } + + #endregion Command code + } + + #endregion NewItemCommand + + #region SetItemCommand + + /// + /// Sets the specified item using the namespace providers. + /// + [Cmdlet(VerbsCommon.Set, "Item", SupportsShouldProcess = true, DefaultParameterSetName = PathParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097055")] + public class SetItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path to item to set. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the value of the item to be set. + /// + [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public object Value { get; set; } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets or sets the pass through property which determines + /// if the object that is set should be written to the pipeline. + /// Defaults to false. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets the dynamic parameters for the set-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.SetItemDynamicParameters(Path[0], Value, context); + } + + return InvokeProvider.Item.SetItemDynamicParameters(".", Value, context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(_paths); + #endregion Command parameters + + #region Command data + /// + /// The path of the item to set. + /// + private string[] _paths; + + /// + /// Determines if the object being set should be written to the pipeline. + /// Defaults to false. + /// + private bool _passThrough; + + #endregion Command data + + #region Command code + + /// + /// Sets the specified item. + /// + protected override void ProcessRecord() + { + // Default to the CmdletProviderContext that will direct output to + // the pipeline. + + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = _passThrough; + + foreach (string path in _paths) + { + try + { + InvokeProvider.Item.Set(path, Value, currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + } + } + + #endregion Command code + } + + #endregion SetItemCommand + + #region RemoveItemCommand + + /// + /// Removes the specified item using the namespace providers. + /// + [Cmdlet(VerbsCommon.Remove, "Item", SupportsShouldProcess = true, DefaultParameterSetName = PathParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097103")] + public class RemoveItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets or sets the recurse property. + /// + [Parameter] + public SwitchParameter Recurse + { + get => _recurse; + set => _recurse = value; + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets the dynamic parameters for the remove-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.RemoveItemDynamicParameters(Path[0], Recurse, context); + } + + return InvokeProvider.Item.RemoveItemDynamicParameters(".", Recurse, context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(_paths); + #endregion Command parameters + + #region Command data + + /// + /// The path used when doing a delete. + /// + private string[] _paths; + + /// + /// Determines if the remove command should recurse into + /// sub-containers. + /// + private bool _recurse; + + #endregion Command data + + #region Command code + + /// + /// Removes the specified items. + /// + protected override void ProcessRecord() + { + CmdletProviderContext currentContext = CmdletProviderContext; + + bool yesToAll = false; + bool noToAll = false; + + foreach (string path in Path) + { + // Resolve the path in case it contains any glob characters + Collection resolvedPSPaths = null; + + try + { + // Save the include and exclude filters so that we can ignore + // them when doing recursion + Collection include = currentContext.Include; + Collection exclude = currentContext.Exclude; + string filter = currentContext.Filter; + + if (_recurse) + { + currentContext.SetFilters( + new Collection(), + new Collection(), + null); + } + + try + { + resolvedPSPaths = SessionState.Path.GetResolvedPSPathFromPSPath(path, currentContext); + if (SuppressWildcardExpansion == true && resolvedPSPaths.Count == 0) + { + ItemNotFoundException pathNotFound = + new( + path, + "PathNotFound", + SessionStateStrings.PathNotFound); + WriteError(new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + finally + { + // Reset the include and exclude filters + currentContext.SetFilters( + include, + exclude, + filter); + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + foreach (PathInfo resolvedPath in resolvedPSPaths) + { + // Check each path to make sure it isn't a parent of the current working location + + bool isCurrentLocationOrAncestor = false; + + try + { + isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor(resolvedPath.Path, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + if (isCurrentLocationOrAncestor) + { + PSInvalidOperationException invalidOperation = + (PSInvalidOperationException)PSTraceSource.NewInvalidOperationException( + NavigationResources.RemoveItemInUse, + resolvedPath.Path); + + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, + invalidOperation)); + continue; + } + + bool hasChildren = false; + + string providerPath = GetUnresolvedProviderPathFromPSPath(resolvedPath.Path); + + try + { + hasChildren = SessionState.Internal.HasChildItems(resolvedPath.Provider.Name, providerPath, currentContext); + + currentContext.ThrowFirstErrorOrDoNothing(); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + bool shouldRecurse = Recurse; + bool treatAsFile = false; + + // only check if path is a directory using DirectoryInfo if using FileSystemProvider + if (resolvedPath.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + { + try + { + System.IO.DirectoryInfo di = new(providerPath); + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(di)) + { + shouldRecurse = false; + treatAsFile = true; + } + } + catch (System.IO.FileNotFoundException) + { + // not a directory + } + } + + if (!treatAsFile && !Recurse && hasChildren) + { + // Get the localized prompt string + + string prompt = StringUtil.Format(NavigationResources.RemoveItemWithChildren, providerPath); + + // Confirm the user wants to remove all children and the item even if + // they did not specify -recurse + + if (!ShouldContinue(prompt, null, ref yesToAll, ref noToAll)) + { + continue; + } + + shouldRecurse = true; + } + + // Now do the delete + // This calls the internal method since it is more efficient + // than trying to glob again. It also will prevent problems + // where globbing a second time may not have properly escaped + // wildcard characters in the path. + + try + { + SessionState.Internal.RemoveItem( + resolvedPath.Provider.Name, + providerPath, + shouldRecurse, + currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + } + + #endregion Command code + } + + #endregion RemoveItemCommand + + #region MoveItemCommand + + /// + /// Moves an item from the specified location to the specified destination using + /// the namespace providers. + /// + [Cmdlet(VerbsCommon.Move, "Item", DefaultParameterSetName = PathParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096591")] + public class MoveItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the destination property. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] + public string Destination { get; set; } = "."; + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets or sets the pass through property which determines + /// if the object that is set should be written to the pipeline. + /// Defaults to false. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets the dynamic parameters for the move-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.MoveItemDynamicParameters(Path[0], Destination, context); + } + + return InvokeProvider.Item.MoveItemDynamicParameters(".", Destination, context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(_paths); + + #endregion Command parameters + + #region Command data + /// + /// The path of the item to move. It is set or retrieved via + /// the Path property. + /// + private string[] _paths; + + /// + /// Determines if the object being set should be written to the pipeline. + /// Defaults to false. + /// + private bool _passThrough; + + #endregion Command data + + #region Command code + + private Collection GetResolvedPaths(string path) + { + Collection results = new(); + try + { + results = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + + return results; + } + + /// + /// Moves the specified item to the specified destination. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + if (base.SuppressWildcardExpansion) + { + MoveItem(path, literalPath: true); + } + else + { + Collection resolvedPaths = GetResolvedPaths(path); + + foreach (PathInfo resolvedPathInfo in resolvedPaths) + { + string resolvedPath = resolvedPathInfo.Path; + MoveItem(resolvedPath, literalPath: true); + } + } + } + } + + private void MoveItem(string path, bool literalPath = false) + { + CmdletProviderContext currentContext = CmdletProviderContext; + currentContext.SuppressWildcardExpansion = literalPath; + + try + { + if (!InvokeProvider.Item.Exists(path, currentContext)) + { + PSInvalidOperationException invalidOperation = + (PSInvalidOperationException)PSTraceSource.NewInvalidOperationException( + NavigationResources.MoveItemDoesntExist, + path); + + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, + invalidOperation)); + return; + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + + // See if the item to be moved is in use. + bool isCurrentLocationOrAncestor = false; + try + { + isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor(path, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + + if (isCurrentLocationOrAncestor) + { + PSInvalidOperationException invalidOperation = + (PSInvalidOperationException)PSTraceSource.NewInvalidOperationException( + NavigationResources.MoveItemInUse, + path); + + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, + invalidOperation)); + return; + } + + // Default to the CmdletProviderContext that will direct output to + // the pipeline. + + currentContext.PassThru = PassThru; + + tracer.WriteLine("Moving {0} to {1}", path, Destination); + + try + { + // Now do the move + InvokeProvider.Item.Move(path, Destination, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + } + #endregion Command code + + } + + #endregion MoveItemCommand + + #region RenameItemCommand + + /// + /// Renames a specified item to a new name using the namespace providers. + /// + [Cmdlet(VerbsCommon.Rename, "Item", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = ByPathParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097153")] + public class RenameItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string ByPathParameterSet = "ByPath"; + private const string ByLiteralPathParameterSet = "ByLiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ByPathParameterSet)] + public string Path + { + get => _path; + set => _path = value; + } + + /// + /// Gets or sets the literal path property. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ByLiteralPathParameterSet)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get => _path; + set + { + _path = value; + base.SuppressWildcardExpansion = true; + } + } + + /// + /// Gets or sets the newName property. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string NewName { get; set; } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets or sets the pass through property which determines + /// if the object that is set should be written to the pipeline. + /// Defaults to false. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets the dynamic parameters for the rename-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + return InvokeProvider.Item.RenameItemDynamicParameters(Path, NewName, context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(new string[] { _path }); + + #endregion Command parameters + + #region Command data + /// + /// The path of the item to rename. It is set or retrieved via + /// the Path property. + /// + private string _path; + + /// + /// Determines if the object being set should be written to the pipeline. + /// Defaults to false. + /// + private bool _passThrough; + + #endregion Command data + + #region Command code + + private Collection GetResolvedPaths(string path) + { + Collection results = null; + try + { + results = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + + return results; + } + + /// + /// Moves the specified item to the specified destination. + /// + protected override void ProcessRecord() + { + if (SuppressWildcardExpansion) + { + RenameItem(Path, literalPath: true); + return; + } + + Collection resolvedPaths = GetResolvedPaths(Path); + if (resolvedPaths == null) + { + return; + } + + if (resolvedPaths.Count == 1) + { + RenameItem(resolvedPaths[0].Path, literalPath: true); + } + else + { + RenameItem(WildcardPattern.Unescape(Path), literalPath: true); + } + } + + private void RenameItem(string path, bool literalPath = false) + { + CmdletProviderContext currentContext = CmdletProviderContext; + currentContext.SuppressWildcardExpansion = literalPath; + + try + { + if (!InvokeProvider.Item.Exists(path, currentContext)) + { + PSInvalidOperationException invalidOperation = + (PSInvalidOperationException)PSTraceSource.NewInvalidOperationException( + NavigationResources.RenameItemDoesntExist, + path); + + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, + invalidOperation)); + return; + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + + // See if the item to be moved is in use. + bool isCurrentLocationOrAncestor = false; + try + { + isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor(path, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + + if (isCurrentLocationOrAncestor) + { + PSInvalidOperationException invalidOperation = + (PSInvalidOperationException)PSTraceSource.NewInvalidOperationException( + NavigationResources.RenamedItemInUse, + path); + + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, + invalidOperation)); + return; + } + + // Default to the CmdletProviderContext that will direct output to + // the pipeline. + currentContext.PassThru = PassThru; + + tracer.WriteLine("Rename {0} to {1}", path, NewName); + + try + { + // Now do the rename + InvokeProvider.Item.Rename(path, NewName, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + return; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + return; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + return; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + return; + } + } + #endregion Command code + + } + + #endregion RenameItemCommand + + #region CopyItemCommand + + /// + /// Copies a specified item to a new location using the namespace providers. + /// + [Cmdlet(VerbsCommon.Copy, "Item", DefaultParameterSetName = PathParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096990")] + public class CopyItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the destination property. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] + public string Destination { get; set; } + + /// + /// Gets or sets the container property. + /// + [Parameter] + public SwitchParameter Container + { + get => _container; + set + { + _containerSpecified = true; + _container = value; + } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets or sets the recurse property. + /// + [Parameter] + public SwitchParameter Recurse + { + get => _recurse; + set + { + _recurse = value; + + // is, then -Container takes on the same value + // as -Recurse + + if (!_containerSpecified) + { + _container = _recurse; + } + } + } + + /// + /// Gets or sets the pass through property which determines + /// if the object that is set should be written to the pipeline. + /// Defaults to false. + /// + [Parameter] + public SwitchParameter PassThru + { + get => _passThrough; + set => _passThrough = value; + } + + /// + /// Gets the dynamic parameters for the copy-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.CopyItemDynamicParameters(Path[0], Destination, Recurse, context); + } + + return InvokeProvider.Item.CopyItemDynamicParameters(".", Destination, Recurse, context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(_paths); + + #endregion Command parameters + + #region Command data + /// + /// The path of the item to copy. It is set or retrieved via + /// the Path property. + /// + private string[] _paths; + + /// + /// Determines if the containers should be copied with the items or not. + /// + private bool _container = true; + private bool _containerSpecified; + + /// + /// Determines if the copy command should recurse into + /// sub-containers. + /// + private bool _recurse; + + /// + /// Determines if the object being set should be written to the pipeline. + /// Defaults to false. + /// + private bool _passThrough; + + #endregion Command data + + #region Command code + + /// + /// Copies the specified item(s) to the specified destination. + /// + protected override void ProcessRecord() + { + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = PassThru; + + foreach (string path in _paths) + { + tracer.WriteLine("Copy {0} to {1}", path, Destination); + + try + { + CopyContainers copyContainers = (Container) ? CopyContainers.CopyTargetContainer : CopyContainers.CopyChildrenOfTargetContainer; + + // Now do the copy + InvokeProvider.Item.Copy(path, Destination, Recurse, copyContainers, currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + #endregion Command code + + } + + #endregion CopyItemCommand + + #region ClearItemCommand + + /// + /// Clears an item at the specified location. + /// + [Cmdlet(VerbsCommon.Clear, "Item", DefaultParameterSetName = PathParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096491")] + public class ClearItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets the dynamic parameters for the clear-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.ClearItemDynamicParameters(Path[0], context); + } + + return InvokeProvider.Item.ClearItemDynamicParameters(".", context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(_paths); + + #endregion Command parameters + + #region Command data + /// + /// The path of the item to move. It is set or retrieved via + /// the Path property. + /// + private string[] _paths; + + #endregion Command data + + #region Command code + + /// + /// Clears the specified item. + /// + protected override void ProcessRecord() + { + // Default to the CmdletProviderContext that will direct output to + // the pipeline. + + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = false; + + foreach (string path in _paths) + { + tracer.WriteLine("Clearing {0}", path); + + try + { + // Now do the move + InvokeProvider.Item.Clear(path, currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + + #endregion Command code + } + + #endregion ClearItemCommand + + #region InvokeItemCommand + + /// + /// Invokes an item at the specified location. + /// + [Cmdlet(VerbsLifecycle.Invoke, "Item", DefaultParameterSetName = PathParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096590")] + public class InvokeItemCommand : CoreCommandWithCredentialsBase + { + #region Command parameters + + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + + /// + /// Gets or sets the path property. + /// + [Parameter(Position = 0, ParameterSetName = PathParameterSet, + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get => _paths; + set => _paths = value; + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = LiteralPathParameterSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => _paths; + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get => base.Filter; + set => base.Filter = value; + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get => base.Include; + set => base.Include = value; + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get => base.Exclude; + set => base.Exclude = value; + } + + /// + /// Gets the dynamic parameters for the invoke-item cmdlet. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Item.InvokeItemDynamicParameters(Path[0], context); + } + + return InvokeProvider.Item.InvokeItemDynamicParameters(".", context); + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess => DoesProviderSupportShouldProcess(_paths); + + #endregion Command parameters + + #region Command data + /// + /// The path of the item to move. It is set or retrieved via + /// the Path property. + /// + private string[] _paths; + + #endregion Command data + + #region Command code + + /// + /// Invokes the specified item. + /// + protected override void ProcessRecord() + { + foreach (string path in _paths) + { + tracer.WriteLine("Invoking {0}", path); + + try + { + // Now invoke the action + InvokeProvider.Item.Invoke(path, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + #endregion Command code + + } + + #endregion InvokeItemCommand + + #endregion Item commands + + #region Provider commands + + #region GetProviderCommand + + /// + /// Gets a core command provider by name. + /// + [Cmdlet(VerbsCommon.Get, "PSProvider", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096816")] + [OutputType(typeof(ProviderInfo))] + public class GetPSProviderCommand : CoreCommandBase + { + #region Command parameters + + /// + /// Gets or sets the provider that will be removed. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string[] PSProvider + { + get => _provider; + set => _provider = value ?? Array.Empty(); + } + + #endregion Command parameters + + #region Command data + /// + /// The string ID of the provider to remove. + /// + private string[] _provider = Array.Empty(); + + #endregion Command data + + #region Command code + + /// + /// Gets a provider from the core command namespace. + /// + protected override void ProcessRecord() + { + if (PSProvider == null || PSProvider.Length == 0) + { + // Get all the providers + + WriteObject(SessionState.Provider.GetAll(), true); + } + else + { + foreach (string requestedProvider in PSProvider) + { + PSSnapinQualifiedName pssnapinQualifiedProvider = PSSnapinQualifiedName.GetInstance(requestedProvider); + + if (pssnapinQualifiedProvider != null && WildcardPattern.ContainsWildcardCharacters(pssnapinQualifiedProvider.ShortName)) + { + // The user entered a glob string so use the WildcardPattern to + // compare the glob string to the provider names that exist + // and write out any that match + + WildcardPattern matcher = + WildcardPattern.Get( + pssnapinQualifiedProvider.ShortName, + WildcardOptions.IgnoreCase); + + foreach (ProviderInfo enumeratedProvider in SessionState.Provider.GetAll()) + { + Dbg.Diagnostics.Assert( + enumeratedProvider != null, + "SessionState.Providers should return only ProviderInfo objects"); + + if (enumeratedProvider.IsMatch(matcher, pssnapinQualifiedProvider)) + { + // A match was found + + WriteObject(enumeratedProvider); + } + } + } + else + { + try + { + Collection matchingProviders = + SessionState.Provider.Get(requestedProvider); + + // The provider was found + + WriteObject(matchingProviders, true); + } + catch (ProviderNotFoundException e) + { + WriteError( + new ErrorRecord( + e.ErrorRecord, + e)); + } + } + } + } + } + + #endregion Command code + } + + #endregion GetProviderCommand + + #endregion Provider commands +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..fb134ce7a118d0dd6f14c2b2442aac693fedd3e4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Language; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to create a new property on an object. + /// + [Cmdlet(VerbsCommon.New, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096813")] + public class NewItemPropertyCommand : ItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true)] + public string[] Path + { + get + { + return paths; + } + + set + { + paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The name of the property to create on the item. + /// + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] + [Alias("PSProperty")] + public string Name { get; set; } + + /// + /// The type of the property to create on the item. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Alias("Type")] +#if !UNIX + [ArgumentCompleter(typeof(PropertyTypeArgumentCompleter))] +#endif + public string PropertyType { get; set; } + + /// + /// The value of the property to create on the item. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public object Value { get; set; } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get + { + return base.Force; + } + + set + { + base.Force = value; + } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.NewPropertyDynamicParameters(Path[0], Name, PropertyType, Value, context); + } + + return InvokeProvider.Property.NewPropertyDynamicParameters(".", Name, PropertyType, Value, context); + } + + #endregion Parameters + + #region parameter data + + #endregion parameter data + + #region Command code + + /// + /// Creates the property on the item. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + try + { + InvokeProvider.Property.New(path, Name, PropertyType, Value, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + #endregion Command code + + } + +#if !UNIX + /// + /// Provides argument completion for PropertyType parameter. + /// + public class PropertyTypeArgumentCompleter : IArgumentCompleter + { + private static readonly CompletionHelpers.CompletionDisplayInfoMapper RegistryPropertyTypeDisplayInfoMapper = registryPropertyType => registryPropertyType switch + { + "String" => ( + ToolTip: TabCompletionStrings.RegistryStringToolTip, + ListItemText: "String"), + "ExpandString" => ( + ToolTip: TabCompletionStrings.RegistryExpandStringToolTip, + ListItemText: "ExpandString"), + "Binary" => ( + ToolTip: TabCompletionStrings.RegistryBinaryToolTip, + ListItemText: "Binary"), + "DWord" => ( + ToolTip: TabCompletionStrings.RegistryDWordToolTip, + ListItemText: "DWord"), + "MultiString" => ( + ToolTip: TabCompletionStrings.RegistryMultiStringToolTip, + ListItemText: "MultiString"), + "QWord" => ( + ToolTip: TabCompletionStrings.RegistryQWordToolTip, + ListItemText: "QWord"), + _ => ( + ToolTip: TabCompletionStrings.RegistryUnknownToolTip, + ListItemText: "Unknown"), + }; + + private static readonly IReadOnlyList s_RegistryPropertyTypes = new List(capacity: 7) + { + "String", + "ExpandString", + "Binary", + "DWord", + "MultiString", + "QWord", + "Unknown" + }; + + /// + /// Returns completion results for PropertyType parameter. + /// + /// The command name. + /// The parameter name. + /// The word to complete. + /// The command AST. + /// The fake bound parameters. + /// List of Completion Results. + public IEnumerable CompleteArgument( + string commandName, + string parameterName, + string wordToComplete, + CommandAst commandAst, + IDictionary fakeBoundParameters) + => IsRegistryProvider(fakeBoundParameters) + ? CompletionHelpers.GetMatchingResults( + wordToComplete, + possibleCompletionValues: s_RegistryPropertyTypes, + displayInfoMapper: RegistryPropertyTypeDisplayInfoMapper, + resultType: CompletionResultType.ParameterValue) + : []; + + /// + /// Checks if parameter paths are from Registry provider. + /// + /// The fake bound parameters. + /// Boolean indicating if paths are from Registry Provider. + private static bool IsRegistryProvider(IDictionary fakeBoundParameters) + { + Collection paths; + + if (fakeBoundParameters.Contains("Path")) + { + paths = ResolvePath(fakeBoundParameters["Path"], isLiteralPath: false); + } + else if (fakeBoundParameters.Contains("LiteralPath")) + { + paths = ResolvePath(fakeBoundParameters["LiteralPath"], isLiteralPath: true); + } + else + { + paths = ResolvePath(@".\", isLiteralPath: false); + } + + return paths.Count > 0 && paths[0].Provider.NameEquals("Registry"); + } + + /// + /// Resolve path or literal path using Resolve-Path. + /// + /// The path to resolve. + /// Specifies if path is literal path. + /// Collection of Pathinfo objects. + private static Collection ResolvePath(object path, bool isLiteralPath) + { + using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); + + ps.AddCommand("Microsoft.PowerShell.Management\\Resolve-Path"); + ps.AddParameter(isLiteralPath ? "LiteralPath" : "Path", path); + + Collection output = ps.Invoke(); + + return output; + } + } +#endif +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..ca616301ebbbb1f7d9be9a0f3244c87aa1bd1316 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -0,0 +1,466 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to resolve PowerShell paths containing glob characters to + /// PowerShell paths that match the glob strings. + /// + [Cmdlet(VerbsCommon.Split, "Path", DefaultParameterSetName = "ParentSet", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097149")] + [OutputType(typeof(string), ParameterSetName = new[] { leafSet, + leafBaseSet, + extensionSet, + noQualifierSet, + parentSet, + qualifierSet, + literalPathSet})] + [OutputType(typeof(bool), ParameterSetName = new[] { isAbsoluteSet })] + public class SplitPathCommand : CoreCommandWithCredentialsBase + { + #region Parameters + + /// + /// The parameter set name to get the parent path. + /// + private const string parentSet = "ParentSet"; + + /// + /// The parameter set name to get the leaf name. + /// + private const string leafSet = "LeafSet"; + + /// + /// The parameter set name to get the leaf base name. + /// + private const string leafBaseSet = "LeafBaseSet"; + + /// + /// The parameter set name to get the extension. + /// + private const string extensionSet = "ExtensionSet"; + + /// + /// The parameter set name to get the qualifier set. + /// + private const string qualifierSet = "QualifierSet"; + + /// + /// The parameter set name to get the noqualifier set. + /// + private const string noQualifierSet = "NoQualifierSet"; + + /// + /// The parameter set name to get the IsAbsolute set. + /// + private const string isAbsoluteSet = "IsAbsoluteSet"; + + /// + /// The parameter set name to get the LiteralPath set. + /// + private const string literalPathSet = "LiteralPathSet"; + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = parentSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = leafSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = leafBaseSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = extensionSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = qualifierSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = noQualifierSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = isAbsoluteSet, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path { get; set; } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPathSet", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return Path; + } + + set + { + base.SuppressWildcardExpansion = true; + Path = value; + } + } + + /// + /// Determines if the qualifier should be returned. + /// + /// + /// If true the qualifier of the path will be returned. + /// The qualifier is the drive or provider that is qualifying + /// the PowerShell path. + /// + [Parameter(ParameterSetName = qualifierSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public SwitchParameter Qualifier { get; set; } + + /// + /// Determines if the qualifier should be returned. + /// + /// + /// If true the qualifier of the path will be returned. + /// The qualifier is the drive or provider that is qualifying + /// the PowerShell path. + /// + [Parameter(ParameterSetName = noQualifierSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public SwitchParameter NoQualifier { get; set; } + + /// + /// Determines if the parent path should be returned. + /// + /// + /// If true the parent of the path will be returned. + /// + [Parameter(ParameterSetName = parentSet, Mandatory = false, ValueFromPipelineByPropertyName = true)] + public SwitchParameter Parent { get; set; } = true; + + /// + /// Determines if the leaf name should be returned. + /// + /// + /// If true the leaf name of the path will be returned. + /// + [Parameter(ParameterSetName = leafSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public SwitchParameter Leaf { get; set; } + + /// + /// Determines if the leaf base name (name without extension) should be returned. + /// + /// + /// If true the leaf base name of the path will be returned. + /// + [Parameter(ParameterSetName = leafBaseSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public SwitchParameter LeafBase { get; set; } + + /// + /// Determines if the extension should be returned. + /// + /// + /// If true the extension of the path will be returned. + /// + [Parameter(ParameterSetName = extensionSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public SwitchParameter Extension { get; set; } + + /// + /// Determines if the path should be resolved before being parsed. + /// + /// + [Parameter] + public SwitchParameter Resolve { get; set; } + + /// + /// Determines if the path is an absolute path. + /// + [Parameter(ParameterSetName = isAbsoluteSet, Mandatory = true)] + public SwitchParameter IsAbsolute { get; set; } + + #endregion Parameters + + #region parameter data + + #endregion parameter data + + #region Command code + + /// + /// Parses the specified path and returns the portion determined by the + /// boolean parameters. + /// + protected override void ProcessRecord() + { + StringCollection pathsToParse = new(); + + if (Resolve) + { + CmdletProviderContext currentContext = CmdletProviderContext; + + foreach (string path in Path) + { + // resolve the paths and then parse each one. + + Collection resolvedPaths; + + try + { + resolvedPaths = + SessionState.Path.GetResolvedPSPathFromPSPath(path, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + foreach (PathInfo resolvedPath in resolvedPaths) + { + try + { + if (InvokeProvider.Item.Exists(resolvedPath.Path, currentContext)) + { + pathsToParse.Add(resolvedPath.Path); + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + } + else + { + pathsToParse.AddRange(Path); + } + + // Now parse each path + + for (int index = 0; index < pathsToParse.Count; ++index) + { + string result = null; + + // Check switch parameters in order of specificity + if (IsAbsolute) + { + string ignored; + bool isPathAbsolute = + SessionState.Path.IsPSAbsolute(pathsToParse[index], out ignored); + + WriteObject(isPathAbsolute); + continue; + } + else if (Qualifier) + { + int separatorIndex = pathsToParse[index].IndexOf(':'); + + if (separatorIndex < 0) + { + FormatException e = + new( + StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index])); + WriteError( + new ErrorRecord( + e, + "ParsePathFormatError", // RENAME + ErrorCategory.InvalidArgument, + pathsToParse[index])); + continue; + } + else + { + // Check to see if it is provider or drive qualified + + if (SessionState.Path.IsProviderQualified(pathsToParse[index])) + { + // The plus 2 is for the length of the provider separator + // which is "::" + + result = + pathsToParse[index].Substring( + 0, + separatorIndex + 2); + } + else + { + result = + pathsToParse[index].Substring( + 0, + separatorIndex + 1); + } + } + } + else if (Leaf || LeafBase || Extension) + { + try + { + result = + SessionState.Path.ParseChildName( + pathsToParse[index], + CmdletProviderContext, + true); + if (LeafBase) + { + result = System.IO.Path.GetFileNameWithoutExtension(result); + } + else if (Extension) + { + result = System.IO.Path.GetExtension(result); + } + } + catch (PSNotSupportedException) + { + // Since getting the leaf part of a path is not supported, + // the provider must be a container, item, or drive + // provider. Since the paths for these types of + // providers can't be split, asking for the leaf + // is asking for the specified path back. + result = pathsToParse[index]; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + } + else if (NoQualifier) + { + result = RemoveQualifier(pathsToParse[index]); + } + else + { + // None of the switch parameters are true: default to -Parent behavior + try + { + result = + SessionState.Path.ParseParent( + pathsToParse[index], + string.Empty, + CmdletProviderContext, + true); + } + catch (PSNotSupportedException) + { + // Since getting the parent path is not supported, + // the provider must be a container, item, or drive + // provider. Since the paths for these types of + // providers can't be split, asking for the parent + // is asking for an empty string. + result = string.Empty; + } + } + + if (result != null) + { + WriteObject(result); + } + } + } + #endregion Command code + + /// + /// Removes either the drive or provider qualifier or both from the path. + /// + /// + /// The path to strip the provider qualifier from. + /// + /// + /// The path without the qualifier. + /// + private string RemoveQualifier(string path) + { + Dbg.Diagnostics.Assert( + path != null, + "Path should be verified by the caller"); + + string result = path; + + if (SessionState.Path.IsProviderQualified(path)) + { + int index = path.IndexOf("::", StringComparison.Ordinal); + + if (index != -1) + { + // remove the qualifier + result = path.Substring(index + 2); + } + } + else + { + string driveName = string.Empty; + + if (SessionState.Path.IsPSAbsolute(path, out driveName)) + { + var driveNameLength = driveName.Length; + if (path.Length > (driveNameLength + 1) && path[driveNameLength] == ':') + { + // Remove the drive name and colon + result = path.Substring(driveNameLength + 1); + } + } + } + + return result; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..19bad39785b4b17633784009e57cd2ff4a88e6a4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The base class for the */content commands that also take + /// a passthrough parameter. + /// + public class PassThroughContentCommandBase : ContentCommandBase + { + #region Parameters + + /// + /// Gets or sets the passthrough parameter to the command. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThrough; + } + + set + { + _passThrough = value; + } + } + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess + { + get + { + return base.DoesProviderSupportShouldProcess(base.Path); + } + } + + #endregion Parameters + + #region parameter data + + /// + /// Determines if the content returned from the provider should + /// be passed through to the pipeline. + /// + private bool _passThrough; + + #endregion parameter data + + #region protected members + + /// + /// Initializes a CmdletProviderContext instance to the current context of + /// the command. + /// + /// + /// A CmdletProviderContext instance initialized to the context of the current + /// command. + /// + internal CmdletProviderContext GetCurrentContext() + { + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = PassThru; + return currentCommandContext; + } + + #endregion protected members + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b76ac36786d6004b1d8dd5739a21eeb2b3ae737 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The base class for the */property commands that also take + /// a passthrough parameter. + /// + public class PassThroughItemPropertyCommandBase : ItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the passthrough parameter to the command. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThrough; + } + + set + { + _passThrough = value; + } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get + { + return base.Force; + } + + set + { + base.Force = value; + } + } + + #endregion Parameters + + #region parameter data + + /// + /// Determines if the property returned from the provider should + /// be passed through to the pipeline. + /// + private bool _passThrough; + + #endregion parameter data + + #region protected members + + /// + /// Determines if the provider for the specified path supports ShouldProcess. + /// + /// + protected override bool ProviderSupportsShouldProcess + { + get + { + return base.DoesProviderSupportShouldProcess(base.paths); + } + } + + /// + /// Initializes a CmdletProviderContext instance to the current context of + /// the command. + /// + /// + /// A CmdletProviderContext instance initialized to the context of the current + /// command. + /// + internal CmdletProviderContext GetCurrentContext() + { + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = PassThru; + return currentCommandContext; + } + + #endregion protected members + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs new file mode 100644 index 0000000000000000000000000000000000000000..91efda12263a97eb1617f3406d25fb513f513540 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -0,0 +1,3015 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; // Win32Exception +using System.Diagnostics; // Process class +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Net; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Security.Principal; +using System.Text; +using System.Threading; +using Microsoft.Management.Infrastructure; +using Microsoft.PowerShell.Commands.Internal; +using Microsoft.Win32.SafeHandles; + +namespace Microsoft.PowerShell.Commands +{ + #region ProcessBaseCommand + /// + /// This class implements the base for process commands. + /// + public abstract class ProcessBaseCommand : Cmdlet + { + #region Parameters + /// + /// The various process selection modes. + /// + internal enum MatchMode + { + /// + /// Select all processes. + /// + All, + /// + /// Select processes matching the supplied names. + /// + ByName, + /// + /// Select the processes matching the id. + /// + ById, + /// + /// Select the processes specified as input. + /// + ByInput + } + /// + /// The current process selection mode. + /// + internal MatchMode myMode = MatchMode.All; + + /// + /// The Name parameter is declared in subclasses, + /// since it is optional for GetProcess and mandatory for StopProcess. + /// + internal string[] processNames = null; + + // The Id parameter is declared in subclasses, + // since it is positional for StopProcess but not for GetProcess. + internal int[] processIds = null; + + /// + /// If the input is a stream of [collections of] + /// Process objects, we bypass the Name and + /// Id parameters and read the Process objects + /// directly. This allows us to deal with processes which + /// have wildcard characters in their name. + /// + /// Process objects + [Parameter( + ParameterSetName = "InputObject", + Mandatory = true, + ValueFromPipeline = true)] + public virtual Process[] InputObject + { + get + { + return _input; + } + + set + { + myMode = MatchMode.ByInput; + _input = value; + } + } + + private Process[] _input = null; + #endregion Parameters + + #region Internal + + // We use a Dictionary to optimize the check whether the object + // is already in the list. + private List _matchingProcesses = new(); + private readonly Dictionary _keys = new(); + + /// + /// Retrieve the list of all processes matching the Name, Id + /// and InputObject parameters, sorted by Id. + /// + /// + internal List MatchingProcesses() + { + _matchingProcesses.Clear(); + switch (myMode) + { + case MatchMode.ById: + RetrieveMatchingProcessesById(); + break; + + case MatchMode.ByInput: + RetrieveProcessesByInput(); + break; + default: + // Default is "Name": + RetrieveMatchingProcessesByProcessName(); + break; + } + // 2004/12/16 Note that the processes will be sorted + // before being stopped. PM confirms that this is fine. + _matchingProcesses.Sort(ProcessComparison); + return _matchingProcesses; + } + + /// + /// Sort function to sort by Name first, then Id. + /// + /// First Process object. + /// Second Process object. + /// + /// As string.Compare: returns less than zero if x less than y, + /// greater than 0 if x greater than y, 0 if x == y. + /// + private static int ProcessComparison(Process x, Process y) + { + int diff = string.Compare( + SafeGetProcessName(x), + SafeGetProcessName(y), + StringComparison.OrdinalIgnoreCase); + if (diff != 0) + return diff; + return SafeGetProcessId(x) - SafeGetProcessId(y); + } + + /// + /// Retrieves the list of all processes matching the Name + /// parameter. + /// Generates a non-terminating error for each specified + /// process name which is not found even though it contains + /// no wildcards. + /// + /// + private void RetrieveMatchingProcessesByProcessName() + { + if (processNames == null) + { + _matchingProcesses = new List(AllProcesses); + return; + } + + foreach (string pattern in processNames) + { + WildcardPattern wildcard = + WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + bool found = false; + foreach (Process process in AllProcesses) + { + if (!wildcard.IsMatch(SafeGetProcessName(process))) + continue; + found = true; + AddIdempotent(process); + } + + if (!found && + !WildcardPattern.ContainsWildcardCharacters(pattern)) + { + string errorText = ProcessResources.NoProcessFoundForGivenName; + string errorName = nameof(ProcessResources.NoProcessFoundForGivenName); + + if (int.TryParse(pattern, out int x) && x >= 0) + { + errorText = ProcessResources.RecommendIdTagForGivenName; + errorName = nameof(ProcessResources.RecommendIdTagForGivenName); + } + + WriteNonTerminatingError( + processName: pattern, + processId: 0, + targetObject: pattern, + innerException: null, + resourceId: errorText, + errorId: errorName, + category: ErrorCategory.ObjectNotFound); + } + } + } + + /// + /// Retrieves the list of all processes matching the Id + /// parameter. + /// Generates a non-terminating error for each specified + /// process ID which is not found. + /// + /// + private void RetrieveMatchingProcessesById() + { + if (processIds == null) + { + Diagnostics.Assert(false, "null processIds"); + throw PSTraceSource.NewInvalidOperationException(); + } + + foreach (int processId in processIds) + { + Process process; + try + { + process = Process.GetProcessById(processId); + AddIdempotent(process); + } + catch (ArgumentException) + { + WriteNonTerminatingError( + string.Empty, + processId, + processId, + null, + ProcessResources.NoProcessFoundForGivenId, + "NoProcessFoundForGivenId", + ErrorCategory.ObjectNotFound); + continue; + } + } + } + + /// + /// Retrieves the list of all processes matching the InputObject + /// parameter. + /// + /// + private void RetrieveProcessesByInput() + { + if (InputObject == null) + { + Diagnostics.Assert(false, "null InputObject"); + throw PSTraceSource.NewInvalidOperationException(); + } + + foreach (Process process in InputObject) + { + SafeRefresh(process); + AddIdempotent(process); + } + } + + /// + /// Gets an array of all processes. + /// + /// An array of components that represents all the process resources. + /// + /// MSDN does not document the list of exceptions, + /// but it is reasonable to expect that SecurityException is + /// among them. Errors here will terminate the cmdlet. + /// + internal Process[] AllProcesses => _allProcesses ??= Process.GetProcesses(); + + private Process[] _allProcesses; + + /// + /// Add to , + /// but only if it is not already on . + /// We use a Dictionary to optimize the check whether the object + /// is already in the list. + /// + /// Process to add to list. + private void AddIdempotent( + Process process) + { + int hashCode = SafeGetProcessName(process).GetHashCode() + ^ SafeGetProcessId(process); // XOR + if (!_keys.ContainsKey(hashCode)) + { + _keys.Add(hashCode, process); + _matchingProcesses.Add(process); + } + } + + /// + /// Writes a non-terminating error. + /// + /// + /// + /// + /// + /// + internal void WriteNonTerminatingError( + Process process, + Exception innerException, + string resourceId, string errorId, + ErrorCategory category) + { + WriteNonTerminatingError( + SafeGetProcessName(process), + SafeGetProcessId(process), + process, + innerException, + resourceId, + errorId, + category); + } + + /// + /// Writes a non-terminating error. + /// + /// + /// + /// + /// + /// + /// + /// + internal void WriteNonTerminatingError( + string processName, + int processId, + object targetObject, + Exception innerException, + string resourceId, + string errorId, + ErrorCategory category) + { + string message = StringUtil.Format(resourceId, + processName, + processId, + (innerException == null) ? string.Empty : innerException.Message); + ProcessCommandException exception = + new(message, innerException); + exception.ProcessName = processName; + + WriteError(new ErrorRecord( + exception, errorId, category, targetObject)); + } + + // The Name property is not always available, even for + // live processes (such as the Idle process). + internal static string SafeGetProcessName(Process process) + { + try + { + return process.ProcessName; + } + catch (Win32Exception) + { + return string.Empty; + } + catch (InvalidOperationException) + { + return string.Empty; + } + } + + // 2004/12/17-JonN I saw this fail once too, so we'll play it safe + internal static int SafeGetProcessId(Process process) + { + try + { + return process.Id; + } + catch (Win32Exception) + { + return int.MinValue; + } + catch (InvalidOperationException) + { + return int.MinValue; + } + } + + internal static void SafeRefresh(Process process) + { + try + { + process.Refresh(); + } + catch (Win32Exception) + { + } + catch (InvalidOperationException) + { + } + } + + /// + /// TryHasExited is a helper function used to detect if the process has aready exited or not. + /// + /// + /// Process whose exit status has to be checked. + /// + /// Tre if the process has exited or else returns false. + internal static bool TryHasExited(Process process) + { + bool hasExited = true; + + try + { + hasExited = process.HasExited; + } + catch (Win32Exception) + { + hasExited = false; + } + catch (InvalidOperationException) + { + hasExited = false; + } + + return hasExited; + } + + #endregion Internal + } + #endregion ProcessBaseCommand + + #region GetProcessCommand + /// + /// This class implements the get-process command. + /// + [Cmdlet(VerbsCommon.Get, "Process", DefaultParameterSetName = NameParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096814", RemotingCapability = RemotingCapability.SupportedByCommand)] + [OutputType(typeof(ProcessModule), typeof(FileVersionInfo), typeof(Process))] + public sealed class GetProcessCommand : ProcessBaseCommand + { + #region ParameterSetStrings + + private const string NameParameterSet = "Name"; + private const string IdParameterSet = "Id"; + private const string InputObjectParameterSet = "InputObject"; + private const string NameWithUserNameParameterSet = "NameWithUserName"; + private const string IdWithUserNameParameterSet = "IdWithUserName"; + private const string InputObjectWithUserNameParameterSet = "InputObjectWithUserName"; + + #endregion ParameterSetStrings + + #region Parameters + + /// + /// Has the list of process names on which to this command will work. + /// + [Parameter(Position = 0, ParameterSetName = NameParameterSet, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = NameWithUserNameParameterSet, ValueFromPipelineByPropertyName = true)] + [Alias("ProcessName")] + [ValidateNotNullOrEmpty] + public string[] Name + { + get + { + return processNames; + } + + set + { + myMode = MatchMode.ByName; + processNames = value; + } + } + + /// + /// Gets/sets an array of process IDs. + /// + [Parameter(ParameterSetName = IdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = IdWithUserNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Alias("PID")] + public int[] Id + { + get + { + return processIds; + } + + set + { + myMode = MatchMode.ById; + processIds = value; + } + } + + /// + /// Input is a stream of [collections of] Process objects. + /// + [Parameter(ParameterSetName = InputObjectParameterSet, Mandatory = true, ValueFromPipeline = true)] + [Parameter(ParameterSetName = InputObjectWithUserNameParameterSet, Mandatory = true, ValueFromPipeline = true)] + public override Process[] InputObject + { + get + { + return base.InputObject; + } + + set + { + base.InputObject = value; + } + } + + /// + /// Include the UserName. + /// + [Parameter(ParameterSetName = NameWithUserNameParameterSet, Mandatory = true)] + [Parameter(ParameterSetName = IdWithUserNameParameterSet, Mandatory = true)] + [Parameter(ParameterSetName = InputObjectWithUserNameParameterSet, Mandatory = true)] + public SwitchParameter IncludeUserName { get; set; } + + /// + /// To display the modules of a process. + /// + [Parameter(ParameterSetName = NameParameterSet)] + [Parameter(ParameterSetName = IdParameterSet)] + [Parameter(ParameterSetName = InputObjectParameterSet)] + [ValidateNotNull] + public SwitchParameter Module { get; set; } + + /// + /// To display the fileversioninfo of the main module of a process. + /// + [Parameter(ParameterSetName = NameParameterSet)] + [Parameter(ParameterSetName = IdParameterSet)] + [Parameter(ParameterSetName = InputObjectParameterSet)] + [Alias("FV", "FVI")] + [ValidateNotNull] + public SwitchParameter FileVersionInfo { get; set; } + + #endregion Parameters + + #region Overrides + + /// + /// Write the process objects. + /// + protected override void ProcessRecord() + { + foreach (Process process in MatchingProcesses()) + { + if (Module.IsPresent && FileVersionInfo.IsPresent) + { + ProcessModule tempmodule = null; + try + { + ProcessModuleCollection modules = process.Modules; + foreach (ProcessModule pmodule in modules) + { + // Assigning to tempmodule to rethrow for exceptions on 64 bit machines + tempmodule = pmodule; + WriteObject(pmodule.FileVersionInfo, true); + } + } + catch (InvalidOperationException exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); + } + catch (ArgumentException exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); + } + catch (Win32Exception exception) + { + try + { + if (exception.HResult == 299) + { + WriteObject(tempmodule.FileVersionInfo, true); + } + else + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); + } + } + catch (Win32Exception ex) + { + WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); + } + } + catch (Exception exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); + } + } + else if (Module.IsPresent) + { + try + { + WriteObject(process.Modules, true); + } + catch (Win32Exception exception) + { + try + { + if (exception.HResult == 299) + { + WriteObject(process.Modules, true); + } + else + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); + } + } + catch (Win32Exception ex) + { + WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); + } + } + catch (PipelineStoppedException) + { + throw; + } + catch (Exception exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); + } + } + else if (FileVersionInfo.IsPresent) + { + try + { + ProcessModule mainModule = process.MainModule; + if (mainModule != null) + { + WriteObject(mainModule.FileVersionInfo, true); + } + } + catch (InvalidOperationException exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); + } + catch (ArgumentException exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); + } + catch (Win32Exception exception) + { + try + { + if (exception.HResult == 299) + { + WriteObject(process.MainModule?.FileVersionInfo, true); + } + else + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); + } + } + catch (Win32Exception ex) + { + WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); + } + } + catch (Exception exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); + } + } + else + { + WriteObject(IncludeUserName.IsPresent ? AddUserNameToProcess(process) : process); + } + } + } + + #endregion Overrides + + #region Privates + + /// + /// New PSTypeName added to the process object. + /// + private const string TypeNameForProcessWithUserName = "System.Diagnostics.Process#IncludeUserName"; + + /// + /// Add the 'UserName' NoteProperty to the Process object. + /// + /// + /// + private static PSObject AddUserNameToProcess(Process process) + { + // Return null if we failed to get the owner information + string userName = RetrieveProcessUserName(process); + + PSObject processAsPsobj = PSObject.AsPSObject(process); + PSNoteProperty noteProperty = new("UserName", userName); + + processAsPsobj.Properties.Add(noteProperty, true); + processAsPsobj.TypeNames.Insert(0, TypeNameForProcessWithUserName); + + return processAsPsobj; + } + + /// + /// Retrieve the UserName through PInvoke. + /// + /// + /// + private static string RetrieveProcessUserName(Process process) + { + string userName = null; +#if UNIX + userName = Platform.NonWindowsGetUserFromPid(process.Id); +#else + IntPtr tokenUserInfo = IntPtr.Zero; + IntPtr processTokenHandler = IntPtr.Zero; + + const uint TOKEN_QUERY = 0x0008; + + try + { + int error; + if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) + { + return null; + } + + // Set the default length to be 256, so it will be sufficient for most cases. + int tokenInfoLength = 256; + tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); + if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) + { + error = Marshal.GetLastWin32Error(); + if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER) + { + Marshal.FreeHGlobal(tokenUserInfo); + tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); + + if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) + { + return null; + } + } + else + { + return null; + } + } + + var tokenUser = Marshal.PtrToStructure(tokenUserInfo); + SecurityIdentifier sid = new SecurityIdentifier(tokenUser.User.Sid); + userName = sid.Translate(typeof(System.Security.Principal.NTAccount)).Value; + } + catch (NotSupportedException) + { + // The Process not started yet, or it's a process from a remote machine. + } + catch (IdentityNotMappedException) + { + // SID cannot be mapped to a user + } + catch (InvalidOperationException) + { + // The Process has exited, Process.Handle will raise this exception. + } + catch (Win32Exception) + { + // We might get an AccessDenied error. + } + catch (Exception) + { + // I don't expect to get other exceptions. + } + finally + { + if (tokenUserInfo != IntPtr.Zero) + { + Marshal.FreeHGlobal(tokenUserInfo); + } + + if (processTokenHandler != IntPtr.Zero) + { + Win32Native.CloseHandle(processTokenHandler); + } + } +#endif + return userName; + } + + #endregion Privates + } + #endregion GetProcessCommand + + #region WaitProcessCommand + /// + /// This class implements the Wait-process command. + /// + [Cmdlet(VerbsLifecycle.Wait, "Process", DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097146")] + [OutputType(typeof(Process))] + public sealed class WaitProcessCommand : ProcessBaseCommand + { + #region Parameters + + /// + /// Specifies the process IDs of the processes to be waited on. + /// + [Parameter( + ParameterSetName = "Id", + Position = 0, + Mandatory = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("PID", "ProcessId")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] Id + { + get + { + return processIds; + } + + set + { + myMode = MatchMode.ById; + processIds = value; + } + } + + /// + /// Name of the processes to wait on for termination. + /// + [Parameter( + ParameterSetName = "Name", + Position = 0, + Mandatory = true, + ValueFromPipelineByPropertyName = true)] + [Alias("ProcessName")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get + { + return processNames; + } + + set + { + myMode = MatchMode.ByName; + processNames = value; + } + } + + /// + /// If specified, wait for this number of seconds. + /// + [Parameter(Position = 1)] + [Alias("TimeoutSec")] + [ValidateNotNullOrEmpty] + [ValidateRange(0, 32767)] + public int Timeout + { + get + { + return _timeout; + } + + set + { + _timeout = value; + _timeOutSpecified = true; + } + } + + /// + /// Gets or sets a value indicating whether to return after any one process exits. + /// + [Parameter] + public SwitchParameter Any { get; set; } + + /// + /// Gets or sets a value indicating whether to return the Process objects after waiting. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + private int _timeout = 0; + private bool _timeOutSpecified; + + #endregion Parameters + + private bool _disposed = false; + + #region IDisposable + /// + /// Dispose method of IDisposable interface. + /// + public void Dispose() + { + if (!_disposed) + { + if (_waitHandle != null) + { + _waitHandle.Dispose(); + _waitHandle = null; + } + + _disposed = true; + } + } + + #endregion + + #region private methods + // Handle Exited event and display process information. + private void myProcess_Exited(object sender, System.EventArgs e) + { + if (Any || (Interlocked.Decrement(ref _numberOfProcessesToWaitFor) == 0)) + { + _waitHandle?.Set(); + } + } + + #endregion + + #region Overrides + + private readonly List _processList = new(); + + // Wait handle which is used by thread to sleep. + private ManualResetEvent _waitHandle; + private int _numberOfProcessesToWaitFor; + + /// + /// Gets the list of process. + /// + protected override void ProcessRecord() + { + // adding the processes into the list + foreach (Process process in MatchingProcesses()) + { + // Idle process has processid zero,so handle that because we cannot wait on it. + if (process.Id == 0) + { + WriteNonTerminatingError(process, null, ProcessResources.WaitOnIdleProcess, "WaitOnIdleProcess", ErrorCategory.ObjectNotFound); + continue; + } + + // It cannot wait on itself + if (process.Id.Equals(Environment.ProcessId)) + { + WriteNonTerminatingError(process, null, ProcessResources.WaitOnItself, "WaitOnItself", ErrorCategory.ObjectNotFound); + continue; + } + + _processList.Add(process); + } + } + + /// + /// Wait for the process to terminate. + /// + protected override void EndProcessing() + { + _waitHandle = new ManualResetEvent(false); + foreach (Process process in _processList) + { + try + { + // Check for processes that exit too soon for us to add an event. + if (Any && process.HasExited) + { + _waitHandle.Set(); + } + else if (!process.HasExited) + { + process.EnableRaisingEvents = true; + process.Exited += myProcess_Exited; + if (!process.HasExited) + { + System.Threading.Interlocked.Increment(ref _numberOfProcessesToWaitFor); + } + } + } + catch (Win32Exception exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.ProcessIsNotTerminated, "ProcessNotTerminated", ErrorCategory.CloseError); + } + } + + bool hasTimedOut = false; + if (_numberOfProcessesToWaitFor > 0) + { + if (_timeOutSpecified) + { + hasTimedOut = !_waitHandle.WaitOne(_timeout * 1000); + } + else + { + _waitHandle.WaitOne(); + } + } + + if (hasTimedOut || (!Any && _numberOfProcessesToWaitFor > 0)) + { + foreach (Process process in _processList) + { + try + { + if (!process.HasExited) + { + string message = StringUtil.Format(ProcessResources.ProcessNotTerminated, new object[] { process.ProcessName, process.Id }); + ErrorRecord errorRecord = new(new TimeoutException(message), "ProcessNotTerminated", ErrorCategory.CloseError, process); + WriteError(errorRecord); + } + } + catch (Win32Exception exception) + { + WriteNonTerminatingError(process, exception, ProcessResources.ProcessIsNotTerminated, "ProcessNotTerminated", ErrorCategory.CloseError); + } + } + } + + if (PassThru) + { + WriteObject(_processList, enumerateCollection: true); + } + } + + /// + /// StopProcessing. + /// + protected override void StopProcessing() => _waitHandle?.Set(); + + #endregion Overrides + + } + #endregion WaitProcessCommand + + #region StopProcessCommand + /// + /// This class implements the stop-process command. + /// + /// + /// Processes will be sorted before being stopped. PM confirms + /// that this should be fine. + /// + [Cmdlet(VerbsLifecycle.Stop, "Process", + DefaultParameterSetName = "Id", + SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097058")] + [OutputType(typeof(Process))] + public sealed class StopProcessCommand : ProcessBaseCommand + { + #region Parameters + /// + /// Has the list of process names on which to this command will work. + /// + [Parameter( + ParameterSetName = "Name", + Mandatory = true, + ValueFromPipelineByPropertyName = true)] + [Alias("ProcessName")] + public string[] Name + { + get + { + return processNames; + } + + set + { + processNames = value; + myMode = MatchMode.ByName; + } + } + + /// + /// Gets/sets an array of process IDs. + /// + [Parameter( + Position = 0, + ParameterSetName = "Id", + Mandatory = true, + ValueFromPipelineByPropertyName = true)] + public int[] Id + { + get + { + return processIds; + } + + set + { + myMode = MatchMode.ById; + processIds = value; + } + } + + /// + /// Gets/sets an array of objects. + /// + [Parameter( + Position = 0, + ParameterSetName = "InputObject", + Mandatory = true, + ValueFromPipeline = true)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public new Process[] InputObject + { + get + { + return base.InputObject; + } + + set + { + base.InputObject = value; + } + } + + private bool _passThru; + /// + /// The updated process object should be passed down the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get { return _passThru; } + + set { _passThru = value; } + } + + /// + /// Specifies whether to force a process to kill + /// even if it has dependent services. + /// + /// + [Parameter] + [ValidateNotNullOrEmpty] + public SwitchParameter Force { get; set; } + + #endregion Parameters + + #region Overrides + /// + /// Kill the processes. + /// It is a non-terminating error if the Process.Kill() operation fails. + /// + protected override void ProcessRecord() + { + if (myMode == MatchMode.All || (myMode == MatchMode.ByName && processNames == null)) + { + Diagnostics.Assert(false, "trying to kill all processes"); + throw PSTraceSource.NewInvalidOperationException(); + } + + foreach (Process process in MatchingProcesses()) + { + // confirm the operation first + // this is always false if WhatIf is set + // 2005-06-21 Moved this ahead of the hasExited check + string targetString = StringUtil.Format( + ProcessResources.ProcessNameForConfirmation, + SafeGetProcessName(process), + SafeGetProcessId(process)); + + if (!ShouldProcess(targetString)) + { + continue; + } + + try + { + // Many properties including Name are not available if the process has exited. + // If this is the case, we skip the process. If the process is from a remote + // machine, then we generate a non-terminating error because .NET doesn't support + // terminate a remote process. + if (process.HasExited) + { + if (PassThru) + WriteObject(process); + continue; + } + } + catch (NotSupportedException ex) + { + WriteNonTerminatingError( + process, ex, ProcessResources.CouldNotStopProcess, + "CouldNotStopProcess", ErrorCategory.InvalidOperation); + continue; + } + catch (Win32Exception ex) + { + WriteNonTerminatingError( + process, ex, ProcessResources.CouldNotStopProcess, + "CouldNotStopProcess", ErrorCategory.CloseError); + continue; + } + + try + { + if (Environment.ProcessId == SafeGetProcessId(process)) + { + _shouldKillCurrentProcess = true; + continue; + } + + if (Platform.IsWindows && !Force) + { + if (!IsProcessOwnedByCurrentUser(process)) + { + string message = StringUtil.Format( + ProcessResources.ConfirmStopProcess, + SafeGetProcessName(process), + SafeGetProcessId(process)); + + // caption: null = default caption + if (!ShouldContinue(message, null, ref _yesToAll, ref _noToAll)) + continue; + } + } + + // If the process is svchost stop all the dependent services before killing process + if (string.Equals(SafeGetProcessName(process), "SVCHOST", StringComparison.OrdinalIgnoreCase)) + { + StopDependentService(process); + } + + if (!process.HasExited) + { + process.Kill(); + } + } + catch (Win32Exception exception) + { + if (!TryHasExited(process)) + { + WriteNonTerminatingError( + process, exception, ProcessResources.CouldNotStopProcess, + "CouldNotStopProcess", ErrorCategory.CloseError); + continue; + } + } + catch (InvalidOperationException exception) + { + if (!TryHasExited(process)) + { + WriteNonTerminatingError( + process, exception, ProcessResources.CouldNotStopProcess, + "CouldNotStopProcess", ErrorCategory.CloseError); + continue; + } + } + + if (PassThru) + WriteObject(process); + } + } + + /// + /// Kill the current process here. + /// + protected override void EndProcessing() + { + if (_shouldKillCurrentProcess) + { + StopProcess(Process.GetCurrentProcess()); + } + } + + #endregion Overrides + + #region Private + /// + /// Should the current powershell process to be killed. + /// + private bool _shouldKillCurrentProcess; + + /// + /// Boolean variables to display the warning using ShouldContinue. + /// + private bool _yesToAll, _noToAll; + + /// + /// Current windows user name. + /// + private string _currentUserName; + + /// + /// Gets the owner of the process. + /// + /// + /// Returns the owner. + private bool IsProcessOwnedByCurrentUser(Process process) + { + const uint TOKEN_QUERY = 0x0008; + IntPtr ph = IntPtr.Zero; + try + { + if (Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out ph)) + { + if (_currentUserName == null) + { + using (var currentUser = WindowsIdentity.GetCurrent()) + { + _currentUserName = currentUser.Name; + } + } + + using (var processUser = new WindowsIdentity(ph)) + { + return string.Equals(processUser.Name, _currentUserName, StringComparison.OrdinalIgnoreCase); + } + } + } + catch (IdentityNotMappedException) + { + // Catching IdentityMappedException + // Need not throw error. + } + catch (ArgumentException) + { + // Catching ArgumentException. In Win2k3 Token is zero + // Need not throw error. + } + finally + { + if (ph != IntPtr.Zero) + { + Win32Native.CloseHandle(ph); + } + } + + return false; + } + + /// + /// Stop the service that depends on the process and its child services. + /// + /// + private void StopDependentService(Process process) + { + string queryString = "Select * From Win32_Service Where ProcessId=" + SafeGetProcessId(process) + " And State !='Stopped'"; + + try + { + using (CimSession cimSession = CimSession.Create(null)) + { + IEnumerable serviceList = + cimSession.QueryInstances("root/cimv2", "WQL", queryString); + foreach (CimInstance oService in serviceList) + { + string serviceName = oService.CimInstanceProperties["Name"].Value.ToString(); + using (var service = new System.ServiceProcess.ServiceController(serviceName)) + { + try + { + service.Stop(); + // Wait 2 sec for the status to become 'Stopped' + service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 2)); + } + catch (Win32Exception) { } + catch (InvalidOperationException) { } + catch (System.ServiceProcess.TimeoutException) { } + } + } + } + } + catch (CimException ex) + { + var errorRecord = new ErrorRecord(ex, "GetCimException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + } + + /// + /// Stops the given process throws non terminating error if can't. + /// + /// Process to be stopped. + /// True if process stopped successfully else false. + private void StopProcess(Process process) + { + Exception exception = null; + try + { + if (!process.HasExited) + { + process.Kill(); + } + } + catch (Win32Exception e) + { + exception = e; + } + catch (InvalidOperationException e) + { + exception = e; + } + + if (exception != null) + { + if (!TryHasExited(process)) + { + // This process could not be stopped, + // so write a non-terminating error. + WriteNonTerminatingError( + process, exception, ProcessResources.CouldNotStopProcess, + "CouldNotStopProcess", ErrorCategory.CloseError); + } + } + } + + #endregion Private + } + #endregion StopProcessCommand + + #region DebugProcessCommand + /// + /// This class implements the Debug-process command. + /// + [Cmdlet(VerbsDiagnostic.Debug, "Process", DefaultParameterSetName = "Name", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096809")] + public sealed class DebugProcessCommand : ProcessBaseCommand + { + #region Parameters + + /// + /// Specifies the process IDs of the processes to be waited on. + /// + [Parameter( + ParameterSetName = "Id", + Position = 0, + Mandatory = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("PID", "ProcessId")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] Id + { + get + { + return processIds; + } + + set + { + myMode = MatchMode.ById; + processIds = value; + } + } + + /// + /// Name of the processes to wait on for termination. + /// + [Parameter( + ParameterSetName = "Name", + Position = 0, + Mandatory = true, + ValueFromPipelineByPropertyName = true)] + [Alias("ProcessName")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get + { + return processNames; + } + + set + { + myMode = MatchMode.ByName; + processNames = value; + } + } + + #endregion Parameters + + #region Overrides + + /// + /// Gets the list of process and attach the debugger to the processes. + /// + protected override void ProcessRecord() + { + foreach (Process process in MatchingProcesses()) + { + string targetMessage = StringUtil.Format( + ProcessResources.ProcessNameForConfirmation, + SafeGetProcessName(process), + SafeGetProcessId(process)); + + if (!ShouldProcess(targetMessage)) + { + continue; + } + + // Sometimes Idle process has processid zero,so handle that because we cannot attach debugger to it. + if (process.Id == 0) + { + WriteNonTerminatingError( + process, null, ProcessResources.NoDebuggerFound, + "NoDebuggerFound", ErrorCategory.ObjectNotFound); + continue; + } + + try + { + // If the process has exited, we skip it. If the process is from a remote + // machine, then we generate a non-terminating error. + if (process.HasExited) + { + continue; + } + } + catch (NotSupportedException ex) + { + WriteNonTerminatingError( + process, ex, ProcessResources.CouldNotDebugProcess, + "CouldNotDebugProcess", ErrorCategory.InvalidOperation); + continue; + } + catch (Win32Exception ex) + { + // This process could not be stopped, so write a non-terminating error. + WriteNonTerminatingError( + process, ex, ProcessResources.CouldNotDebugProcess, + "CouldNotDebugProcess", ErrorCategory.CloseError); + continue; + } + + AttachDebuggerToProcess(process); + } + } + + #endregion Overrides + + /// + /// Attach debugger to the process. + /// + private void AttachDebuggerToProcess(Process process) + { + string searchQuery = "Select * From Win32_Process Where ProcessId=" + SafeGetProcessId(process); + using (CimSession cimSession = CimSession.Create(null)) + { + IEnumerable processCollection = + cimSession.QueryInstances("root/cimv2", "WQL", searchQuery); + foreach (CimInstance processInstance in processCollection) + { + try + { + // Call the AttachDebugger method + CimMethodResult result = cimSession.InvokeMethod(processInstance, "AttachDebugger", null); + int returnCode = Convert.ToInt32(result.ReturnValue.Value, System.Globalization.CultureInfo.CurrentCulture); + if (returnCode != 0) + { + var ex = new InvalidOperationException(MapReturnCodeToErrorMessage(returnCode)); + WriteNonTerminatingError( + process, ex, ProcessResources.CouldNotDebugProcess, + "CouldNotDebugProcess", ErrorCategory.InvalidOperation); + } + } + catch (CimException e) + { + string message = e.Message?.Trim(); + + var errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(ProcessResources.DebuggerError, message)), + "GetCimException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + } + } + } + + /// + /// Map the return code from 'AttachDebugger' to error message. + /// + private static string MapReturnCodeToErrorMessage(int returnCode) + { + string errorMessage = returnCode switch + { + 2 => ProcessResources.AttachDebuggerReturnCode2, + 3 => ProcessResources.AttachDebuggerReturnCode3, + 8 => ProcessResources.AttachDebuggerReturnCode8, + 9 => ProcessResources.AttachDebuggerReturnCode9, + 21 => ProcessResources.AttachDebuggerReturnCode21, + _ => string.Empty + }; + + Diagnostics.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty."); + + return errorMessage; + } + } + #endregion DebugProcessCommand + + #region StartProcessCommand + + /// + /// This class implements the Start-process command. + /// + [Cmdlet(VerbsLifecycle.Start, "Process", DefaultParameterSetName = "Default", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097141")] + [OutputType(typeof(Process))] + public sealed class StartProcessCommand : PSCmdlet, IDisposable + { + private readonly CancellationTokenSource _cancellationTokenSource = new(); + private bool _isDefaultSetParameterSpecified = false; + + #region Parameters + + /// + /// Path/FileName of the process to start. + /// + [Parameter(Mandatory = true, Position = 0)] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "Path")] + public string FilePath { get; set; } + + /// + /// Arguments for the process. + /// + [Parameter(Position = 1)] + [Alias("Args")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ArgumentList { get; set; } + + /// + /// Credentials for the process. + /// + [Parameter(ParameterSetName = "Default")] + [Alias("RunAs")] + [ValidateNotNullOrEmpty] + [Credential] + public PSCredential Credential + { + get + { + return _credential; + } + + set + { + _credential = value; + _isDefaultSetParameterSpecified = true; + } + } + + private PSCredential _credential; + + /// + /// Working directory of the process. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string WorkingDirectory { get; set; } + + /// + /// Load user profile from registry. + /// + [Parameter(ParameterSetName = "Default")] + [Alias("Lup")] + public SwitchParameter LoadUserProfile + { + get + { + return _loaduserprofile; + } + + set + { + _loaduserprofile = value; + _isDefaultSetParameterSpecified = true; + } + } + + private SwitchParameter _loaduserprofile = SwitchParameter.Present; + + /// + /// Starts process in the current console window. + /// + [Parameter(ParameterSetName = "Default")] + [Alias("nnw")] + public SwitchParameter NoNewWindow + { + get + { + return _nonewwindow; + } + + set + { + _nonewwindow = value; + _isDefaultSetParameterSpecified = true; + } + } + + private SwitchParameter _nonewwindow; + + /// + /// PassThru parameter. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + /// + /// Redirect error. + /// + [Parameter(ParameterSetName = "Default")] + [Alias("RSE")] + [ValidateNotNullOrEmpty] + public string RedirectStandardError + { + get + { + return _redirectstandarderror; + } + + set + { + _redirectstandarderror = value; + _isDefaultSetParameterSpecified = true; + } + } + + private string _redirectstandarderror; + + /// + /// Redirect input. + /// + [Parameter(ParameterSetName = "Default")] + [Alias("RSI")] + [ValidateNotNullOrEmpty] + public string RedirectStandardInput + { + get + { + return _redirectstandardinput; + } + + set + { + _redirectstandardinput = value; + _isDefaultSetParameterSpecified = true; + } + } + + private string _redirectstandardinput; + + /// + /// Redirect output. + /// + [Parameter(ParameterSetName = "Default")] + [Alias("RSO")] + [ValidateNotNullOrEmpty] + public string RedirectStandardOutput + { + get + { + return _redirectstandardoutput; + } + + set + { + _redirectstandardoutput = value; + _isDefaultSetParameterSpecified = true; + } + } + + private string _redirectstandardoutput; + + /// + /// Verb. + /// + /// + /// The 'Verb' parameter is only supported on Windows Desktop. + /// + [Parameter(ParameterSetName = "UseShellExecute")] + [ValidateNotNullOrEmpty] + [ArgumentCompleter(typeof(VerbArgumentCompleter))] + public string Verb { get; set; } + + /// + /// Window style of the process window. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public ProcessWindowStyle WindowStyle + { + get + { + return _windowstyle; + } + + set + { + _windowstyle = value; + _windowstyleSpecified = true; + } + } + + private ProcessWindowStyle _windowstyle = ProcessWindowStyle.Normal; + private bool _windowstyleSpecified = false; + + /// + /// Wait for the process to terminate. + /// + [Parameter] + public SwitchParameter Wait { get; set; } + + /// + /// Default Environment. + /// + [Parameter(ParameterSetName = "Default")] + public SwitchParameter UseNewEnvironment + { + get + { + return _UseNewEnvironment; + } + + set + { + _UseNewEnvironment = value; + _isDefaultSetParameterSpecified = true; + } + } + + private SwitchParameter _UseNewEnvironment; + + /// + /// Gets or sets the environment variables for the process. + /// + [Parameter] + public Hashtable Environment + { + get + { + return _environment; + } + + set + { + _environment = value; + _isDefaultSetParameterSpecified = true; + } + } + + private Hashtable _environment; + + #endregion + + #region overrides + + /// + /// BeginProcessing. + /// + protected override void BeginProcessing() + { + string message = string.Empty; + + // -Verb and -WindowStyle are not supported on non-Windows platforms as well as Windows headless SKUs + if (Platform.IsWindowsDesktop) + { + // Parameters '-NoNewWindow' and '-WindowStyle' are both valid on full windows SKUs. + if (_nonewwindow && _windowstyleSpecified) + { + message = StringUtil.Format(ProcessResources.ContradictParametersSpecified, "-NoNewWindow", "-WindowStyle"); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + else + { + if (this.ParameterSetName.Equals("UseShellExecute")) + { + message = StringUtil.Format(ProcessResources.ParameterNotSupportedOnPSEdition, "-Verb", "Start-Process"); + } + else if (_windowstyleSpecified) + { + message = StringUtil.Format(ProcessResources.ParameterNotSupportedOnPSEdition, "-WindowStyle", "Start-Process"); + } + + if (!string.IsNullOrEmpty(message)) + { + ErrorRecord er = new(new NotSupportedException(message), "NotSupportedException", ErrorCategory.NotImplemented, null); + ThrowTerminatingError(er); + } + } + + ProcessStartInfo startInfo = new(); + // Use ShellExecute by default if we are running on full windows SKUs + startInfo.UseShellExecute = Platform.IsWindowsDesktop; + + // Path = Mandatory parameter -> Will not be empty. + try + { + CommandInfo cmdinfo = CommandDiscovery.LookupCommandInfo( + FilePath, CommandTypes.Application | CommandTypes.ExternalScript, + SearchResolutionOptions.None, CommandOrigin.Internal, this.Context); + + startInfo.FileName = cmdinfo.Definition; + } + catch (CommandNotFoundException) + { + // codeql[cs/microsoft/command-line-injection-shell-execution] - This is expected Poweshell behavior where user inputted paths are supported for the context of this method. The user assumes trust for the file path they are specifying and the process is on the user's system except for remoting in which case restricted remoting security guidelines should be used. + startInfo.FileName = FilePath; +#if UNIX + // Arguments are passed incorrectly to the executable used for ShellExecute and not to filename https://github.com/dotnet/corefx/issues/30718 + // so don't use ShellExecute if arguments are specified + + // Linux relies on `xdg-open` and macOS relies on `open` which behave differently than Windows ShellExecute when running console commands + // as a new console will be opened. So to avoid that, we only use ShellExecute on non-Windows if the filename is not an actual command (like a URI) + startInfo.UseShellExecute = (ArgumentList == null); +#endif + } + + if (ArgumentList != null) + { + startInfo.Arguments = string.Join(' ', ArgumentList); + } + + if (WorkingDirectory != null) + { + // WorkingDirectory -> Not Exist -> Throw Error + WorkingDirectory = ResolveFilePath(WorkingDirectory); + if (!Directory.Exists(WorkingDirectory)) + { + message = StringUtil.Format(ProcessResources.InvalidInput, "WorkingDirectory"); + ErrorRecord er = new(new DirectoryNotFoundException(message), "DirectoryNotFoundException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + startInfo.WorkingDirectory = WorkingDirectory; + } + else + { + // Working Directory not specified -> Assign Current Path, but only if it still exists + var currentDirectory = PathUtils.ResolveFilePath(this.SessionState.Path.CurrentFileSystemLocation.Path, this, isLiteralPath: true); + if (Directory.Exists(currentDirectory)) + { + startInfo.WorkingDirectory = currentDirectory; + } + } + + if (this.ParameterSetName.Equals("Default")) + { + if (_isDefaultSetParameterSpecified) + { + startInfo.UseShellExecute = false; + } + + if (_UseNewEnvironment) + { + startInfo.EnvironmentVariables.Clear(); + LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); + LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); + } + + if (_environment != null) + { + LoadEnvironmentVariable(startInfo, _environment); + } + + startInfo.WindowStyle = _windowstyle; + + // When starting a process as another user, the 'CreateNoWindow' property value is ignored and a new window is created. + // See details at https://learn.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.createnowindow?view=net-9.0#remarks + if (_nonewwindow && _credential is null) + { + startInfo.CreateNoWindow = _nonewwindow; + } +#if !UNIX + startInfo.LoadUserProfile = _loaduserprofile; +#endif + if (_credential != null) + { + NetworkCredential nwcredential = _credential.GetNetworkCredential(); + startInfo.UserName = nwcredential.UserName; + if (string.IsNullOrEmpty(nwcredential.Domain)) + { + startInfo.Domain = "."; + } + else + { + startInfo.Domain = nwcredential.Domain; + } + + startInfo.Password = _credential.Password; + } + + // RedirectionInput File Check -> Not Exist -> Throw Error + if (_redirectstandardinput != null) + { + _redirectstandardinput = ResolveFilePath(_redirectstandardinput); + if (!File.Exists(_redirectstandardinput)) + { + message = StringUtil.Format(ProcessResources.InvalidInput, "RedirectStandardInput '" + this.RedirectStandardInput + "'"); + ErrorRecord er = new(new FileNotFoundException(message), "FileNotFoundException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + + // RedirectionInput == RedirectionOutput -> Throw Error + if (_redirectstandardinput != null && _redirectstandardoutput != null) + { + _redirectstandardinput = ResolveFilePath(_redirectstandardinput); + _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); + if (_redirectstandardinput.Equals(_redirectstandardoutput, StringComparison.OrdinalIgnoreCase)) + { + message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardOutput"); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + + // RedirectionInput == RedirectionError -> Throw Error + if (_redirectstandardinput != null && _redirectstandarderror != null) + { + _redirectstandardinput = ResolveFilePath(_redirectstandardinput); + _redirectstandarderror = ResolveFilePath(_redirectstandarderror); + if (_redirectstandardinput.Equals(_redirectstandarderror, StringComparison.OrdinalIgnoreCase)) + { + message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardError"); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + + // RedirectionOutput == RedirectionError -> Throw Error + if (_redirectstandardoutput != null && _redirectstandarderror != null) + { + _redirectstandarderror = ResolveFilePath(_redirectstandarderror); + _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); + if (_redirectstandardoutput.Equals(_redirectstandarderror, StringComparison.OrdinalIgnoreCase)) + { + message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardOutput", "RedirectStandardError"); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + } + else if (ParameterSetName.Equals("UseShellExecute")) + { + if (Verb != null) + { + startInfo.Verb = Verb; + } + + startInfo.WindowStyle = _windowstyle; + } + + string targetMessage = StringUtil.Format(ProcessResources.StartProcessTarget, startInfo.FileName, startInfo.Arguments.Trim()); + if (!ShouldProcess(targetMessage)) + { + return; + } + + Process process = null; + +#if !UNIX + using JobProcessCollection jobObject = new(); + bool? jobAssigned = null; +#endif + if (startInfo.UseShellExecute) + { + process = StartWithShellExecute(startInfo); + } + else + { +#if UNIX + process = new Process() { StartInfo = startInfo }; + SetupInputOutputRedirection(process); + process.Start(); + if (process.StartInfo.RedirectStandardOutput) + { + process.BeginOutputReadLine(); + } + + if (process.StartInfo.RedirectStandardError) + { + process.BeginErrorReadLine(); + } + + if (process.StartInfo.RedirectStandardInput) + { + WriteToStandardInput(process); + } +#else + using ProcessInformation processInfo = StartWithCreateProcess(startInfo); + process = Process.GetProcessById(processInfo.ProcessId); + + // Starting a process as another user might make it impossible + // to get the process handle from the S.D.Process object. Use + // the ALL_ACCESS token from CreateProcess here to setup the + // job object assignment early if -Wait was specified. + // https://github.com/PowerShell/PowerShell/issues/17033 + if (Wait) + { + jobAssigned = jobObject.AssignProcessToJobObject(processInfo.Process); + } + + // Since the process wasn't spawned by .NET, we need to trigger .NET to get a lock on the handle of the process. + // Otherwise, accessing properties like `ExitCode` will throw the following exception: + // "Process was not started by this object, so requested information cannot be determined." + // Fetching the process handle will trigger the `Process` object to update its internal state by calling `SetProcessHandle`, + // the result is discarded as it's not used later in this code. + try + { + _ = process.Handle; + } + catch (Win32Exception e) + { + // If the caller was not an admin and the process was started with another user's credentials .NET + // won't be able to retrieve the process handle. As this is not a critical failure we treat this as + // a warning. + if (PassThru) + { + string msg = StringUtil.Format(ProcessResources.FailedToCreateProcessObject, e.Message); + WriteDebug(msg); + } + } + + // Resume the process now that is has been set up. + processInfo.Resume(); +#endif + } + + if (PassThru.IsPresent) + { + if (process != null) + { + WriteObject(process); + } + else + { + message = StringUtil.Format(ProcessResources.CannotStarttheProcess); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + } + + if (Wait.IsPresent) + { + if (process != null) + { + if (!process.HasExited) + { +#if UNIX + process.WaitForExitAsync(_cancellationTokenSource.Token).GetAwaiter().GetResult(); +#else + // Add the process to the job, this may have already + // been done in StartWithCreateProcess. + if (jobAssigned == true || (jobAssigned is null && jobObject.AssignProcessToJobObject(process.SafeHandle))) + { + // Wait for the job object to finish + jobObject.WaitForExit(_cancellationTokenSource.Token); + } + else + { + // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. + // A Remote session is in it's own job and nested job support was only added in Windows 8/Server 2012. + process.WaitForExitAsync(_cancellationTokenSource.Token).GetAwaiter().GetResult(); + } +#endif + } + } + else + { + message = StringUtil.Format(ProcessResources.CannotStarttheProcess); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + } + } + /// + /// Implements ^c, after creating a process. + /// + protected override void StopProcessing() => _cancellationTokenSource.Cancel(); + + #endregion + + #region IDisposable Overrides + + /// + /// Release all resources. + /// + /// + /// Dispose WaitHandle used to honor -Wait parameter. + /// + public void Dispose() + { + _cancellationTokenSource.Dispose(); + } + + #endregion + + #region Private Methods + + private string ResolveFilePath(string path) + { + string filepath = PathUtils.ResolveFilePath(path, this); + return filepath; + } + + private static void LoadEnvironmentVariable(ProcessStartInfo startinfo, IDictionary EnvironmentVariables) + { + var processEnvironment = startinfo.EnvironmentVariables; + foreach (DictionaryEntry entry in EnvironmentVariables) + { + if (processEnvironment.ContainsKey(entry.Key.ToString())) + { + processEnvironment.Remove(entry.Key.ToString()); + } + + if (entry.Value != null) + { + if (entry.Key.ToString().Equals("PATH")) + { +#if UNIX + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); +#else + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString() + Path.PathSeparator + System.Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.Machine) + Path.PathSeparator + System.Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.User)); +#endif + } + else + { + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); + } + } + } + } + +#if UNIX + private StreamWriter _outputWriter; + private StreamWriter _errorWriter; + + private void StdOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) + { + if (!string.IsNullOrEmpty(outLine.Data)) + { + _outputWriter.WriteLine(outLine.Data); + _outputWriter.Flush(); + } + } + + private void StdErrorHandler(object sendingProcess, DataReceivedEventArgs outLine) + { + if (!string.IsNullOrEmpty(outLine.Data)) + { + _errorWriter.WriteLine(outLine.Data); + _errorWriter.Flush(); + } + } + + private void ExitHandler(object sendingProcess, System.EventArgs e) + { + // To avoid a race condition with Std*Handler, let's wait a bit before closing the streams + // System.Timer is not supported in CoreCLR, so let's spawn a new thread to do the wait + + Thread delayedStreamClosing = new Thread(StreamClosing); + delayedStreamClosing.Start(); + } + + private void StreamClosing() + { + Thread.Sleep(1000); + + _outputWriter?.Dispose(); + _errorWriter?.Dispose(); + } + + private void SetupInputOutputRedirection(Process p) + { + if (_redirectstandardinput != null) + { + p.StartInfo.RedirectStandardInput = true; + _redirectstandardinput = ResolveFilePath(_redirectstandardinput); + } + else + { + p.StartInfo.RedirectStandardInput = false; + } + + if (_redirectstandardoutput != null) + { + p.StartInfo.RedirectStandardOutput = true; + _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); + p.OutputDataReceived += new DataReceivedEventHandler(StdOutputHandler); + + // Can't do StreamWriter(string) in coreCLR + _outputWriter = new StreamWriter(new FileStream(_redirectstandardoutput, FileMode.Create)); + } + else + { + p.StartInfo.RedirectStandardOutput = false; + _outputWriter = null; + } + + if (_redirectstandarderror != null) + { + p.StartInfo.RedirectStandardError = true; + _redirectstandarderror = ResolveFilePath(_redirectstandarderror); + p.ErrorDataReceived += new DataReceivedEventHandler(StdErrorHandler); + + // Can't do StreamWriter(string) in coreCLR + _errorWriter = new StreamWriter(new FileStream(_redirectstandarderror, FileMode.Create)); + } + else + { + p.StartInfo.RedirectStandardError = false; + _errorWriter = null; + } + + p.EnableRaisingEvents = true; + p.Exited += new EventHandler(ExitHandler); + } + + private void WriteToStandardInput(Process p) + { + StreamWriter writer = p.StandardInput; + using (StreamReader reader = new StreamReader(new FileStream(_redirectstandardinput, FileMode.Open))) + { + string line = reader.ReadToEnd(); + writer.WriteLine(line); + } + + writer.Dispose(); + } +#else + + private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, FileMode mode) + { + SafeFileHandle sf = null; + try + { + sf = File.OpenHandle(RedirectionPath, mode, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Inheritable, FileOptions.WriteThrough); + } + catch (Win32Exception win32ex) + { + sf?.Dispose(); + string message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + + return sf; + } + + private static StringBuilder BuildCommandLine(string executableFileName, string arguments) + { + StringBuilder builder = new(); + string str = executableFileName.Trim(); + bool flag = str.StartsWith('"') && str.EndsWith('"'); + if (!flag) + { + builder.Append('"'); + } + + builder.Append(str); + if (!flag) + { + builder.Append('"'); + } + + if (!string.IsNullOrEmpty(arguments)) + { + builder.Append(' '); + builder.Append(arguments); + } + + return builder; + } + + private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) + { + string[] array = new string[sd.Count]; + byte[] bytes = null; + sd.Keys.CopyTo(array, 0); + string[] strArray2 = new string[sd.Count]; + sd.Values.CopyTo(strArray2, 0); + Array.Sort(array, strArray2, StringComparer.OrdinalIgnoreCase); + StringBuilder builder = new(); + for (int i = 0; i < sd.Count; i++) + { + builder.Append(array[i]); + builder.Append('='); + builder.Append(strArray2[i]); + builder.Append('\0'); + } + + builder.Append('\0'); + + // Use Unicode encoding + bytes = Encoding.Unicode.GetBytes(builder.ToString()); + + return bytes; + } + + private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods.STARTUPINFO lpStartupInfo, ref int creationFlags) + { + // If we are starting a process using the current console window, we need to set its standard handles + // explicitly when they are not redirected because otherwise they won't be set and the new process will + // fail with the "invalid handle" error. + // + // However, if we are starting a process with a new console window, we should not explicitly set those + // standard handles when they are not redirected, but instead let Windows figure out the default to use + // when creating the process. Otherwise, the standard input handles of the current window and the new + // window will get weirdly tied together and cause problems. + bool hasRedirection = startinfo.CreateNoWindow + || _redirectstandardinput is not null + || _redirectstandardoutput is not null + || _redirectstandarderror is not null; + + // RedirectionStandardInput + if (_redirectstandardinput != null) + { + startinfo.RedirectStandardInput = true; + _redirectstandardinput = ResolveFilePath(_redirectstandardinput); + lpStartupInfo.hStdInput = GetSafeFileHandleForRedirection(_redirectstandardinput, FileMode.Open); + } + else if (startinfo.CreateNoWindow) + { + lpStartupInfo.hStdInput = new SafeFileHandle( + ProcessNativeMethods.GetStdHandle(-10), + ownsHandle: false); + } + + // RedirectionStandardOutput + if (_redirectstandardoutput != null) + { + startinfo.RedirectStandardOutput = true; + _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); + lpStartupInfo.hStdOutput = GetSafeFileHandleForRedirection(_redirectstandardoutput, FileMode.Create); + } + else if (startinfo.CreateNoWindow) + { + lpStartupInfo.hStdOutput = new SafeFileHandle( + ProcessNativeMethods.GetStdHandle(-11), + ownsHandle: false); + } + + // RedirectionStandardError + if (_redirectstandarderror != null) + { + startinfo.RedirectStandardError = true; + _redirectstandarderror = ResolveFilePath(_redirectstandarderror); + lpStartupInfo.hStdError = GetSafeFileHandleForRedirection(_redirectstandarderror, FileMode.Create); + } + else if (startinfo.CreateNoWindow) + { + lpStartupInfo.hStdError = new SafeFileHandle( + ProcessNativeMethods.GetStdHandle(-12), + ownsHandle: false); + } + + if (hasRedirection) + { + // Set STARTF_USESTDHANDLES only if there is redirection. + lpStartupInfo.dwFlags = 0x100; + } + + if (startinfo.CreateNoWindow) + { + // No new window: Inherit the parent process's console window + creationFlags = 0x00000000; + } + else + { + // CREATE_NEW_CONSOLE + creationFlags |= 0x00000010; + + // STARTF_USESHOWWINDOW + lpStartupInfo.dwFlags |= 0x00000001; + + // On headless SKUs like NanoServer and IoT, window style can only be the default value 'Normal'. + switch (startinfo.WindowStyle) + { + case ProcessWindowStyle.Normal: + // SW_SHOWNORMAL + lpStartupInfo.wShowWindow = 1; + break; + case ProcessWindowStyle.Minimized: + // SW_SHOWMINIMIZED + lpStartupInfo.wShowWindow = 2; + break; + case ProcessWindowStyle.Maximized: + // SW_SHOWMAXIMIZED + lpStartupInfo.wShowWindow = 3; + break; + case ProcessWindowStyle.Hidden: + // SW_HIDE + lpStartupInfo.wShowWindow = 0; + break; + } + } + + // Create the new process suspended so we have a chance to get a corresponding Process object in case it terminates quickly. + creationFlags |= 0x00000004; + } + + /// + /// This method will be used on all windows platforms, both full desktop and headless SKUs. + /// + private ProcessInformation StartWithCreateProcess(ProcessStartInfo startinfo) + { + ProcessNativeMethods.STARTUPINFO lpStartupInfo = new(); + ProcessNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); + int error = 0; + GCHandle pinnedEnvironmentBlock = new(); + IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; + string message = string.Empty; + + // building the cmdline with the file name given and it's arguments + StringBuilder cmdLine = BuildCommandLine(startinfo.FileName, startinfo.Arguments); + + try + { + int creationFlags = 0; + + SetStartupInfo(startinfo, ref lpStartupInfo, ref creationFlags); + + // We follow the logic: + // - Ignore `UseNewEnvironment` when we run a process as another user. + // Setting initial environment variables makes sense only for current user. + // - Set environment variables if they present in ProcessStartupInfo. + if (!UseNewEnvironment) + { + var environmentVars = startinfo.EnvironmentVariables; + if (environmentVars != null) + { + // All Windows Operating Systems that we support are Windows NT systems, so we use Unicode for environment. + creationFlags |= 0x400; + + pinnedEnvironmentBlock = GCHandle.Alloc(ConvertEnvVarsToByteArray(environmentVars), GCHandleType.Pinned); + AddressOfEnvironmentBlock = pinnedEnvironmentBlock.AddrOfPinnedObject(); + } + } + + bool flag; + + if (_credential != null) + { + // Run process as another user. + ProcessNativeMethods.LogonFlags logonFlags = 0; + if (startinfo.LoadUserProfile) + { + logonFlags = ProcessNativeMethods.LogonFlags.LOGON_WITH_PROFILE; + } + + IntPtr password = IntPtr.Zero; + try + { + password = (startinfo.Password == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.SecureStringToCoTaskMemUnicode(startinfo.Password); + flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); + if (!flag) + { + error = Marshal.GetLastWin32Error(); + ErrorRecord er = null; + + if (error == 0xc1) + { + message = StringUtil.Format(ProcessResources.InvalidApplication, FilePath); + } + else if (error == 0x424) + { + // The API 'CreateProcessWithLogonW' depends on the 'Secondary Logon' service, but the component 'Microsoft-Windows-SecondaryLogonService' + // is not installed in OneCoreUAP. We will get error code 0x424 when the service is not available. + message = StringUtil.Format(ProcessResources.ParameterNotSupported, "-Credential", "Start-Process"); + er = new ErrorRecord(new NotSupportedException(message), "NotSupportedException", ErrorCategory.NotInstalled, null); + } + else + { + Win32Exception win32ex = new(error); + message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); + } + + er ??= new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + + goto Label_03AE; + } + finally + { + if (password != IntPtr.Zero) + { + Marshal.ZeroFreeCoTaskMemUnicode(password); + } + } + } + + // Run process as current user. + if (UseNewEnvironment) + { + // All Windows Operating Systems that we support are Windows NT systems, so we use Unicode for environment. + creationFlags |= 0x400; + + IntPtr token = WindowsIdentity.GetCurrent().Token; + if (!ProcessNativeMethods.CreateEnvironmentBlock(out AddressOfEnvironmentBlock, token, false)) + { + Win32Exception win32ex = new(error); + message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); + var errorRecord = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(errorRecord); + } + } + + ProcessNativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes = new(); + ProcessNativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes = new(); + flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); + if (!flag) + { + error = Marshal.GetLastWin32Error(); + + Win32Exception win32ex = new(error); + message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + + Label_03AE: + + return new ProcessInformation(lpProcessInformation); + } + finally + { + if (pinnedEnvironmentBlock.IsAllocated) + { + pinnedEnvironmentBlock.Free(); + } + else + { + ProcessNativeMethods.DestroyEnvironmentBlock(AddressOfEnvironmentBlock); + } + + lpStartupInfo.Dispose(); + } + } +#endif + + /// + /// This method will be used only on Windows full desktop. + /// + private Process StartWithShellExecute(ProcessStartInfo startInfo) + { + Process result = null; + try + { + result = Process.Start(startInfo); + } + catch (Win32Exception ex) + { + string message = StringUtil.Format(ProcessResources.InvalidStartProcess, ex.Message); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + + return result; + } + #endregion + } + + /// + /// Provides argument completion for Verb parameter. + /// + public class VerbArgumentCompleter : IArgumentCompleter + { + /// + /// Returns completion results for verb parameter. + /// + /// The command name. + /// The parameter name. + /// The word to complete. + /// The command AST. + /// The fake bound parameters. + /// List of Completion Results. + public IEnumerable CompleteArgument( + string commandName, + string parameterName, + string wordToComplete, + CommandAst commandAst, + IDictionary fakeBoundParameters) + { + // -Verb is not supported on non-Windows platforms as well as Windows headless SKUs + if (!Platform.IsWindowsDesktop) + { + return Array.Empty(); + } + + // Completion: Start-Process -FilePath -Verb + if (commandName.Equals("Start-Process", StringComparison.OrdinalIgnoreCase) + && fakeBoundParameters.Contains("FilePath")) + { + string filePath = fakeBoundParameters["FilePath"].ToString(); + + // Complete file verbs if extension exists + if (Path.HasExtension(filePath)) + { + return CompleteFileVerbs(wordToComplete, filePath); + } + + // Otherwise check if command is an Application to resolve executable full path with extension + // e.g if powershell was given, resolve to powershell.exe to get verbs + using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); + + var commandInfo = new CmdletInfo("Get-Command", typeof(GetCommandCommand)); + + ps.AddCommand(commandInfo); + ps.AddParameter("Name", filePath); + ps.AddParameter("CommandType", CommandTypes.Application); + + Collection commands = ps.Invoke(); + + // Start-Process & Get-Command select first found application based on PATHEXT environment variable + if (commands.Count >= 1) + { + return CompleteFileVerbs(wordToComplete, filePath: commands[0].Source); + } + } + + return Array.Empty(); + } + + /// + /// Completes file verbs. + /// + /// The word to complete. + /// The file path to get verbs. + /// List of file verbs to complete. + private static IEnumerable CompleteFileVerbs(string wordToComplete, string filePath) + => CompletionHelpers.GetMatchingResults( + wordToComplete, + possibleCompletionValues: new ProcessStartInfo(filePath).Verbs); + } + +#if !UNIX + /// + /// ProcessInformation is a helper class that wraps the native PROCESS_INFORMATION structure + /// returned by CreateProcess or CreateProcessWithLogon. It ensures the process and thread + /// HANDLEs are disposed once it's not needed. + /// + internal sealed class ProcessInformation : IDisposable + { + public SafeProcessHandle Process { get; } + + public SafeProcessHandle Thread { get; } + + public Int32 ProcessId { get; } + + public Int32 ThreadId { get; } + + internal ProcessInformation(ProcessNativeMethods.PROCESS_INFORMATION info) + { + Process = new(info.hProcess, true); + Thread = new(info.hThread, true); + ProcessId = info.dwProcessId; + ThreadId = info.dwThreadId; + } + + public void Resume() + { + ProcessNativeMethods.ResumeThread(Thread.DangerousGetHandle()); + } + + public void Dispose() + { + Process.Dispose(); + Thread.Dispose(); + GC.SuppressFinalize(this); + } + + ~ProcessInformation() => Dispose(); + } + + internal static class ProcessNativeMethods + { + [DllImport(PinvokeDllNames.GetStdHandleDllName, SetLastError = true)] + public static extern IntPtr GetStdHandle(int whichHandle); + + [DllImport(PinvokeDllNames.CreateProcessWithLogonWDllName, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CreateProcessWithLogonW(string userName, + string domain, + IntPtr password, + LogonFlags logonFlags, + [MarshalAs(UnmanagedType.LPWStr)] string appName, + StringBuilder cmdLine, + int creationFlags, + IntPtr environmentBlock, + [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, + STARTUPINFO lpStartupInfo, + ref PROCESS_INFORMATION lpProcessInformation); + + [DllImport(PinvokeDllNames.CreateProcessDllName, CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpCommandLine, + SECURITY_ATTRIBUTES lpProcessAttributes, + SECURITY_ATTRIBUTES lpThreadAttributes, + bool bInheritHandles, + int dwCreationFlags, + IntPtr lpEnvironment, + [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, + STARTUPINFO lpStartupInfo, + ref PROCESS_INFORMATION lpProcessInformation); + + [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] + public static extern uint ResumeThread(IntPtr threadHandle); + + [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); + + [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment); + + [Flags] + internal enum LogonFlags + { + LOGON_NETCREDENTIALS_ONLY = 2, + LOGON_WITH_PROFILE = 1 + } + + [StructLayout(LayoutKind.Sequential)] + internal struct PROCESS_INFORMATION + { + public IntPtr hProcess; + public IntPtr hThread; + public int dwProcessId; + public int dwThreadId; + } + + [StructLayout(LayoutKind.Sequential)] + internal sealed class SECURITY_ATTRIBUTES + { + public int nLength; + public SafeLocalMemHandle lpSecurityDescriptor; + public bool bInheritHandle; + + public SECURITY_ATTRIBUTES() + { + this.nLength = 12; + this.bInheritHandle = true; + this.lpSecurityDescriptor = new SafeLocalMemHandle(IntPtr.Zero, true); + } + } + + internal sealed class SafeLocalMemHandle : SafeHandleZeroOrMinusOneIsInvalid + { + // Methods + internal SafeLocalMemHandle() + : base(true) + { + } + + internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle) + : base(ownsHandle) + { + base.SetHandle(existingHandle); + } + + [DllImport(PinvokeDllNames.LocalFreeDllName)] + private static extern IntPtr LocalFree(IntPtr hMem); + + protected override bool ReleaseHandle() + { + return (LocalFree(base.handle) == IntPtr.Zero); + } + } + + [StructLayout(LayoutKind.Sequential)] + internal sealed class STARTUPINFO + { + public int cb; + public IntPtr lpReserved; + public IntPtr lpDesktop; + public IntPtr lpTitle; + public int dwX; + public int dwY; + public int dwXSize; + public int dwYSize; + public int dwXCountChars; + public int dwYCountChars; + public int dwFillAttribute; + public int dwFlags; + public short wShowWindow; + public short cbReserved2; + public IntPtr lpReserved2; + public SafeFileHandle hStdInput; + public SafeFileHandle hStdOutput; + public SafeFileHandle hStdError; + + public STARTUPINFO() + { + this.lpReserved = IntPtr.Zero; + this.lpDesktop = IntPtr.Zero; + this.lpTitle = IntPtr.Zero; + this.lpReserved2 = IntPtr.Zero; + this.hStdInput = new SafeFileHandle(IntPtr.Zero, false); + this.hStdOutput = new SafeFileHandle(IntPtr.Zero, false); + this.hStdError = new SafeFileHandle(IntPtr.Zero, false); + this.cb = Marshal.SizeOf(this); + } + + public void Dispose(bool disposing) + { + if (disposing) + { + if ((this.hStdInput != null) && !this.hStdInput.IsInvalid) + { + this.hStdInput.Dispose(); + this.hStdInput = null; + } + + if ((this.hStdOutput != null) && !this.hStdOutput.IsInvalid) + { + this.hStdOutput.Dispose(); + this.hStdOutput = null; + } + + if ((this.hStdError != null) && !this.hStdError.IsInvalid) + { + this.hStdError.Dispose(); + this.hStdError = null; + } + } + } + + public void Dispose() + { + Dispose(true); + } + } + } +#endif + #endregion + + #region ProcessCommandException + /// + /// Non-terminating errors occurring in the process noun commands. + /// + public class ProcessCommandException : SystemException + { + #region ctors + /// + /// Unimplemented standard constructor. + /// + /// Doesn't return. + public ProcessCommandException() : base() + { + throw new NotImplementedException(); + } + + /// + /// Standard constructor. + /// + /// + /// Constructed object. + public ProcessCommandException(string message) : base(message) + { + } + + /// + /// Standard constructor. + /// + /// + /// + public ProcessCommandException(string message, Exception innerException) + : base(message, innerException) + { + } + #endregion ctors + + #region Serialization + /// + /// Serialization constructor. + /// + /// + /// + /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected ProcessCommandException( + SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + + #endregion Serialization + + #region Properties + /// + /// Name of the process which could not be found or operated upon. + /// + /// + public string ProcessName + { + get { return _processName; } + + set { _processName = value; } + } + + private string _processName = string.Empty; + #endregion Properties + } + + #endregion ProcessCommandException +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..edc0bbc3a91ac9d5092033201d21ae198e308ec2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The base class for the */property commands. + /// + public class ItemPropertyCommandBase : CoreCommandWithCredentialsBase + { + #region Parameters + + /// + /// Gets or sets the filter parameter. + /// + [Parameter] + public override string Filter + { + get + { + return base.Filter; + } + + set + { + base.Filter = value; + } + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get + { + return base.Include; + } + + set + { + base.Include = value; + } + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get + { + return base.Exclude; + } + + set + { + base.Exclude = value; + } + } + #endregion Parameters + + #region parameter data + + /// + /// The path to the item. + /// + internal string[] paths = Array.Empty(); + + #endregion parameter data + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..0d547abfa9d04b5179333e725b18eeebf724c78e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Management; +using System.Management.Automation; +using System.Text; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Registers for an event on an object. + /// + [Cmdlet(VerbsLifecycle.Register, "WmiEvent", DefaultParameterSetName = "class", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135245", RemotingCapability = RemotingCapability.OwnedByCommand)] + public class RegisterWmiEventCommand : ObjectEventRegistrationBase + { + #region parameters + + /// + /// The WMI namespace to use. + /// + [Parameter] + [Alias("NS")] + public string Namespace { get; set; } = "root\\cimv2"; + + /// + /// The credential to use. + /// + [Parameter] + [Credential] + public PSCredential Credential { get; set; } + + /// + /// The ComputerName in which to query. + /// + [Parameter] + [Alias("Cn")] + [ValidateNotNullOrEmpty] + public string ComputerName { get; set; } = "localhost"; + + /// + /// The WMI class to use. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] + public string Class { get; set; } = null; + + /// + /// The query string to search for objects. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")] + public string Query { get; set; } = null; + + /// + /// Timeout in milliseconds. + /// + [Parameter] + [Alias("TimeoutMSec")] + public Int64 Timeout + { + get + { + return _timeOut; + } + + set + { + _timeOut = value; + _timeoutSpecified = true; + } + } + + private Int64 _timeOut = 0; + private bool _timeoutSpecified = false; + + #endregion parameters + #region helper functions + private string BuildEventQuery(string objectName) + { + StringBuilder returnValue = new StringBuilder("select * from "); + returnValue.Append(objectName); + return returnValue.ToString(); + } + + private string GetScopeString(string computer, string namespaceParameter) + { + StringBuilder returnValue = new StringBuilder("\\\\"); + returnValue.Append(computer); + returnValue.Append('\\'); + returnValue.Append(namespaceParameter); + return returnValue.ToString(); + } + #endregion helper functions + + /// + /// Returns the object that generates events to be monitored. + /// + protected override object GetSourceObject() + { + string wmiQuery = this.Query; + if (this.Class != null) + { + // Validate class format + for (int i = 0; i < this.Class.Length; i++) + { + if (char.IsLetterOrDigit(this.Class[i]) || this.Class[i].Equals('_')) + { + continue; + } + + ErrorRecord errorRecord = new ErrorRecord( + new ArgumentException( + string.Format( + Thread.CurrentThread.CurrentCulture, + "Class", this.Class)), + "INVALID_QUERY_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiInvalidClass"); + + ThrowTerminatingError(errorRecord); + return null; + } + + wmiQuery = BuildEventQuery(this.Class); + } + + ConnectionOptions conOptions = new ConnectionOptions(); + if (this.Credential != null) + { + System.Net.NetworkCredential cred = this.Credential.GetNetworkCredential(); + if (string.IsNullOrEmpty(cred.Domain)) + { + conOptions.Username = cred.UserName; + } + else + { + conOptions.Username = cred.Domain + "\\" + cred.UserName; + } + + conOptions.Password = cred.Password; + } + + ManagementScope scope = new ManagementScope(GetScopeString(ComputerName, this.Namespace), conOptions); + EventWatcherOptions evtOptions = new EventWatcherOptions(); + + if (_timeoutSpecified) + { + evtOptions.Timeout = new TimeSpan(_timeOut * 10000); + } + + ManagementEventWatcher watcher = new ManagementEventWatcher(scope, new EventQuery(wmiQuery), evtOptions); + return watcher; + } + + /// + /// Returns the event name to be monitored on the input object. + /// + protected override string GetSourceObjectEventName() + { + return "EventArrived"; + } + + /// + /// Processes the event subscriber after the base class has registered. + /// + protected override void EndProcessing() + { + base.EndProcessing(); + + // Register for the "Unsubscribed" event so that we can stop the + // event watcher. + PSEventSubscriber newSubscriber = NewSubscriber; + if (newSubscriber != null) + { + newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); + } + } + + private void newSubscriber_Unsubscribed(object sender, PSEventUnsubscribedEventArgs e) + { + ManagementEventWatcher watcher = sender as ManagementEventWatcher; + if (watcher != null) + { + watcher.Stop(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..cc60d91adbeb3ec093abc24c70b9857f86280dca --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to remove a property from an item. + /// + [Cmdlet(VerbsCommon.Remove, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097013")] + public class RemoveItemPropertyCommand : ItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return paths; + } + + set + { + paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + /// + /// The name of the property to create on the item. + /// + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] + [Alias("PSProperty")] + public string[] Name + { + get { return _property; } + + set { _property = value ?? Array.Empty(); } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the provider guidance on how vigorous it should be about performing + /// the operation. If true, the provider should do everything possible to perform + /// the operation. If false, the provider should attempt the operation but allow + /// even simple errors to terminate the operation. + /// For example, if the user tries to copy a file to a path that already exists and + /// the destination is read-only, if force is true, the provider should copy over + /// the existing read-only file. If force is false, the provider should write an error. + /// + [Parameter] + public override SwitchParameter Force + { + get { return base.Force; } + + set { base.Force = value; } + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + string propertyName = null; + if (Name != null && Name.Length > 0) + { + propertyName = Name[0]; + } + + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.RemovePropertyDynamicParameters(Path[0], propertyName, context); + } + + return InvokeProvider.Property.RemovePropertyDynamicParameters(".", propertyName, context); + } + + #endregion Parameters + + #region parameter data + + /// + /// The property to be created. + /// + private string[] _property = Array.Empty(); + + #endregion parameter data + + #region Command code + + /// + /// Removes the property from the item. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + foreach (string prop in Name) + { + try + { + InvokeProvider.Property.Remove(path, prop, CmdletProviderContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..cce50ea1563faf061eb47585be80ec41dbeb5486 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to Remove WMI Object. + /// + [Cmdlet(VerbsCommon.Remove, "WmiObject", DefaultParameterSetName = "class", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113381", RemotingCapability = RemotingCapability.OwnedByCommand)] + public class RemoveWmiObject : WmiBaseCmdlet + { + #region Parameters + /// + /// The WMI Object to use. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] + public ManagementObject InputObject + { + get { return _inputObject; } + + set { _inputObject = value; } + } + /// + /// The WMI Path to use. + /// + [Parameter(Mandatory = true, ParameterSetName = "path")] + public string Path + { + get { return _path; } + + set { _path = value; } + } + /// + /// The WMI class to use. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] + public string Class + { + get { return _className; } + + set { _className = value; } + } + + #endregion Parameters + + #region parameter data + private string _path = null; + private string _className = null; + private ManagementObject _inputObject = null; + + #endregion parameter data + #region Command code + /// + /// Remove an object given either path,class name or pipeline input. + /// + protected override void ProcessRecord() + { + if (this.AsJob) + { + RunAsJob("Remove-WMIObject"); + return; + } + + if (_inputObject != null) + { + try + { + if (!ShouldProcess(_inputObject["__PATH"].ToString())) + { + return; + } + + _inputObject.Delete(); + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + + return; + } + else + { + ConnectionOptions options = GetConnectionOption(); + ManagementPath mPath = null; + ManagementObject mObject = null; + if (_path != null) + { + mPath = new ManagementPath(_path); + if (string.IsNullOrEmpty(mPath.NamespacePath)) + { + mPath.NamespacePath = this.Namespace; + } + else if (namespaceSpecified) + { + // ThrowTerminatingError + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "NamespaceSpecifiedWithPath", + ErrorCategory.InvalidOperation, + this.Namespace)); + } + + if (mPath.Server != "." && serverNameSpecified) + { + // ThrowTerminatingError + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "ComputerNameSpecifiedWithPath", + ErrorCategory.InvalidOperation, + this.ComputerName)); + } + + if (!(mPath.Server == "." && serverNameSpecified)) + { + string[] serverName = new string[] { mPath.Server }; + ComputerName = serverName; + } + } + + foreach (string name in ComputerName) + { + try + { + if (_path != null) + { + mPath.Server = name; + if (mPath.IsClass) + { + ManagementClass mClass = new ManagementClass(mPath); + mObject = mClass; + } + else + { + ManagementObject mInstance = new ManagementObject(mPath); + mObject = mInstance; + } + + ManagementScope mScope = new ManagementScope(mPath, options); + mObject.Scope = mScope; + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); + ManagementClass mClass = new ManagementClass(_className); + mObject = mClass; + mObject.Scope = scope; + } + + if (!ShouldProcess(mObject["__PATH"].ToString())) + { + continue; + } + + mObject.Delete(); + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + } + } + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..bdefc6b2c642707edbd3751175320bf22e20d34c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to rename a property of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Rename, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097152")] + public class RenameItemPropertyCommand : PassThroughItemPropertyCommandBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string Path + { + get + { + return _path; + } + + set + { + _path = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _path; + } + + set + { + base.SuppressWildcardExpansion = true; + _path = value; + } + } + + /// + /// The properties to be renamed on the item. + /// + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] + [Alias("PSProperty")] + public string Name { get; set; } + + /// + /// The new name of the property on the item. + /// + [Parameter(Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true)] + public string NewName { get; set; } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null) + { + return InvokeProvider.Property.RenamePropertyDynamicParameters(Path, Name, NewName, context); + } + + return InvokeProvider.Property.RenamePropertyDynamicParameters(".", Name, NewName, context); + } + + #endregion Parameters + + #region parameter data + + /// + /// The path to rename the property on. + /// + private string _path; + + #endregion parameter data + + #region Command code + + /// + /// Renames a property on an item. + /// + protected override void ProcessRecord() + { + try + { + CmdletProviderContext currentContext = CmdletProviderContext; + currentContext.PassThru = PassThru; + + InvokeProvider.Property.Rename(_path, Name, NewName, currentContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..d0f5fecf4954578f54209ea0a1a7f41ea617cc15 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to resolve PowerShell paths containing glob characters to + /// PowerShell paths that match the glob strings. + /// + [Cmdlet(VerbsDiagnostic.Resolve, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097143")] + public class ResolvePathCommand : CoreCommandWithCredentialsBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the value that determines if the resolved path should + /// be resolved to its relative version. + /// + [Parameter(ParameterSetName = "Path")] + [Parameter(ParameterSetName = "LiteralPath")] + public SwitchParameter Relative + { + get + { + return _relative; + } + + set + { + _relative = value; + } + } + + private SwitchParameter _relative; + + /// + /// Gets or sets the path the resolved relative path should be based off. + /// + [Parameter] + public string RelativeBasePath + { + get + { + return _relativeBasePath; + } + + set + { + _relativeBasePath = value; + } + } + + /// + /// Gets or sets the force property. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + + #endregion Parameters + + #region parameter data + + /// + /// The path to resolve. + /// + private string[] _paths; + + private PSDriveInfo _relativeDrive; + private string _relativeBasePath; + + #endregion parameter data + + #region Command code + + /// + /// Finds the path and drive that should be used for relative path resolution + /// represents. + /// + protected override void BeginProcessing() + { + if (!string.IsNullOrEmpty(RelativeBasePath)) + { + try + { + _relativeBasePath = SessionState.Internal.Globber.GetProviderPath(RelativeBasePath, CmdletProviderContext, out _, out _relativeDrive); + } + catch (ProviderNotFoundException providerNotFound) + { + ThrowTerminatingError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (DriveNotFoundException driveNotFound) + { + ThrowTerminatingError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderInvocationException providerInvocation) + { + ThrowTerminatingError( + new ErrorRecord( + providerInvocation.ErrorRecord, + providerInvocation)); + } + catch (NotSupportedException notSupported) + { + ThrowTerminatingError( + new ErrorRecord(notSupported, "ProviderIsNotNavigationCmdletProvider", ErrorCategory.InvalidArgument, RelativeBasePath)); + } + catch (InvalidOperationException invalidOperation) + { + ThrowTerminatingError( + new ErrorRecord(invalidOperation, "InvalidHomeLocation", ErrorCategory.InvalidOperation, RelativeBasePath)); + } + + return; + } + else if (_relative) + { + _relativeDrive = SessionState.Path.CurrentLocation.Drive; + _relativeBasePath = SessionState.Path.CurrentLocation.ProviderPath; + } + } + + /// + /// Resolves the path containing glob characters to the PowerShell paths that it + /// represents. + /// + protected override void ProcessRecord() + { + foreach (string path in Path) + { + Collection result = null; + try + { + if (MyInvocation.BoundParameters.ContainsKey("RelativeBasePath")) + { + // Pushing and popping the location is done because GetResolvedPSPathFromPSPath uses the current path to resolve relative paths. + // It's important that we pop the location before writing an object to the pipeline to avoid affecting downstream commands. + try + { + SessionState.Path.PushCurrentLocation(string.Empty); + _ = SessionState.Path.SetLocation(_relativeBasePath); + result = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); + } + finally + { + _ = SessionState.Path.PopLocation(string.Empty); + } + } + else + { + result = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); + } + + if (_relative) + { + ReadOnlySpan baseCache = null; + ReadOnlySpan adjustedBaseCache = null; + foreach (PathInfo currentPath in result) + { + // When result path and base path is on different PSDrive + // (../)*path should not go beyond the root of base path + if (currentPath.Drive != _relativeDrive && + _relativeDrive != null && + !currentPath.ProviderPath.StartsWith(_relativeDrive.Root, StringComparison.OrdinalIgnoreCase)) + { + WriteObject(currentPath.Path, enumerateCollection: false); + continue; + } + + int leafIndex = currentPath.Path.LastIndexOf(currentPath.Provider.ItemSeparator); + var basePath = currentPath.Path.AsSpan(0, leafIndex); + if (basePath == baseCache) + { + WriteObject(string.Concat(adjustedBaseCache, currentPath.Path.AsSpan(leafIndex + 1)), enumerateCollection: false); + continue; + } + + baseCache = basePath; + string adjustedPath = SessionState.Path.NormalizeRelativePath(currentPath.Path, _relativeBasePath); + + // Do not insert './' if result path is not relative + if (!adjustedPath.StartsWith( + currentPath.Drive?.Root ?? currentPath.Path, StringComparison.OrdinalIgnoreCase) && + !adjustedPath.StartsWith('.')) + { + adjustedPath = SessionState.Path.Combine(".", adjustedPath); + } + + leafIndex = adjustedPath.LastIndexOf(currentPath.Provider.ItemSeparator); + adjustedBaseCache = adjustedPath.AsSpan(0, leafIndex + 1); + + WriteObject(adjustedPath, enumerateCollection: false); + } + } + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + if (!_relative) + { + WriteObject(result, enumerateCollection: true); + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..3d6fc27cc3cabae7a8b033d024127176ae65bb36 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that rolls back a transaction. + /// + [Cmdlet(VerbsCommon.Undo, "Transaction", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135268")] + public class UndoTransactionCommand : PSCmdlet + { + /// + /// Rolls the current transaction back. + /// + protected override void EndProcessing() + { + // Rollback the transaction + if (ShouldProcess( + NavigationResources.TransactionResource, + NavigationResources.RollbackAction)) + { + this.Context.TransactionManager.Rollback(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs new file mode 100644 index 0000000000000000000000000000000000000000..a00f9583d6a599ec2292df3d7ea28fb5b85c8521 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -0,0 +1,2946 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX // Not built on Unix + +using System; +using System.Collections.Generic; +using System.ComponentModel; // Win32Exception +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Runtime.InteropServices; // Marshal, DllImport +using System.Runtime.Serialization; +using System.Security.AccessControl; +using System.ServiceProcess; +using Dbg = System.Management.Automation.Diagnostics; +using DWORD = System.UInt32; +using NakedWin32Handle = System.IntPtr; + +namespace Microsoft.PowerShell.Commands +{ + #region ServiceBaseCommand + + /// + /// This class implements the base for service commands. + /// + public abstract class ServiceBaseCommand : Cmdlet + { + #region Internal + + /// + /// Confirm that the operation should proceed. + /// + /// Service object to be acted on. + /// True if operation should continue, false otherwise. + protected bool ShouldProcessServiceOperation(ServiceController service) + { + return ShouldProcessServiceOperation( + service.DisplayName, + service.ServiceName); + } + + /// + /// Confirm that the operation should proceed. + /// + /// Display name of service to be acted on. + /// Service name of service to be acted on. + /// True if operation should continue, false otherwise. + protected bool ShouldProcessServiceOperation( + string displayName, string serviceName) + { + string name = StringUtil.Format(ServiceResources.ServiceNameForConfirmation, + displayName, + serviceName); + + return ShouldProcess(name); + } + + /// + /// Writes a non-terminating error. + /// + /// + /// + /// + /// + /// + internal void WriteNonTerminatingError( + ServiceController service, + Exception innerException, + string errorId, + string errorMessage, + ErrorCategory category) + { + WriteNonTerminatingError( + service.ServiceName, + service.DisplayName, + service, + innerException, + errorId, + errorMessage, + category); + } + + /// + /// Writes a non-terminating error. + /// + /// + /// + /// + /// + /// + /// + /// + internal void WriteNonTerminatingError( + string serviceName, + string displayName, + object targetObject, + Exception innerException, + string errorId, + string errorMessage, + ErrorCategory category) + { + string message = StringUtil.Format(errorMessage, + serviceName, + displayName, + (innerException == null) ? category.ToString() : innerException.Message); + + var exception = new ServiceCommandException(message, innerException); + exception.ServiceName = serviceName; + + WriteError(new ErrorRecord(exception, errorId, category, targetObject)); + } + + internal void SetServiceSecurityDescriptor( + ServiceController service, + string securityDescriptorSddl, + NakedWin32Handle hService) + { + var rawSecurityDescriptor = new RawSecurityDescriptor(securityDescriptorSddl); + RawAcl rawDiscretionaryAcl = rawSecurityDescriptor.DiscretionaryAcl; + var discretionaryAcl = new DiscretionaryAcl(false, false, rawDiscretionaryAcl); + + byte[] rawDacl = new byte[discretionaryAcl.BinaryLength]; + discretionaryAcl.GetBinaryForm(rawDacl, 0); + rawSecurityDescriptor.DiscretionaryAcl = new RawAcl(rawDacl, 0); + byte[] securityDescriptorByte = new byte[rawSecurityDescriptor.BinaryLength]; + rawSecurityDescriptor.GetBinaryForm(securityDescriptorByte, 0); + + bool status = NativeMethods.SetServiceObjectSecurity( + hService, + SecurityInfos.DiscretionaryAcl, + securityDescriptorByte); + + if (!status) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + bool accessDenied = exception.NativeErrorCode == NativeMethods.ERROR_ACCESS_DENIED; + WriteNonTerminatingError( + service, + exception, + nameof(ServiceResources.CouldNotSetServiceSecurityDescriptorSddl), + StringUtil.Format(ServiceResources.CouldNotSetServiceSecurityDescriptorSddl, service.ServiceName, exception.Message), + accessDenied ? ErrorCategory.PermissionDenied : ErrorCategory.InvalidOperation); + } + } + #endregion Internal + } + #endregion ServiceBaseCommand + + #region MultipleServiceCommandBase + + /// + /// This class implements the base for service commands which can + /// operate on multiple services. + /// + public abstract class MultipleServiceCommandBase : ServiceBaseCommand + { + #region Parameters + + /// + /// The various process selection modes. + /// + internal enum SelectionMode + { + /// + /// Select all services. + /// + Default = 0, + /// + /// Select services matching the supplied names. + /// + DisplayName = 1, + /// + /// Select services based on pipeline input. + /// + InputObject = 2, + /// + /// Select services by Service name. + /// + ServiceName = 3 + } + /// + /// Holds the selection mode setting. + /// + internal SelectionMode selectionMode; + + /// + /// The ServiceName parameter is declared in subclasses, + /// since it is optional for GetService and mandatory otherwise. + /// + internal string[] serviceNames = null; + + /// + /// Gets/sets an array of display names for services. + /// + [Parameter(ParameterSetName = "DisplayName", Mandatory = true)] + public string[] DisplayName + { + get + { + return displayNames; + } + + set + { + displayNames = value; + selectionMode = SelectionMode.DisplayName; + } + } + + internal string[] displayNames = null; + + /// + /// Lets you include particular services. Services not matching + /// one of these (if specified) are excluded. + /// These are interpreted as either ServiceNames or DisplayNames + /// according to the parameter set. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string[] Include + { + get + { + return include; + } + + set + { + include = value; + } + } + + internal string[] include = null; + + /// + /// Lets you exclude particular services. Services matching + /// one of these (if specified) are excluded. + /// These are interpreted as either ServiceNames or DisplayNames + /// according to the parameter set. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string[] Exclude + { + get + { + return exclude; + } + + set + { + exclude = value; + } + } + + internal string[] exclude = null; + + // 1054295-2004/12/01-JonN This also works around 1054295. + /// + /// If the input is a stream of [collections of] + /// ServiceController objects, we bypass the ServiceName and + /// DisplayName parameters and read the ServiceControllers + /// directly. This allows us to deal with services which + /// have wildcard characters in their name (servicename or + /// displayname). + /// + /// ServiceController objects + [Parameter(ParameterSetName = "InputObject", ValueFromPipeline = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public ServiceController[] InputObject + { + get + { + return _inputObject; + } + + set + { + _inputObject = value; + selectionMode = SelectionMode.InputObject; + } + } + + private ServiceController[] _inputObject = null; + #endregion Parameters + + #region Internal + + /// + /// Gets an array of all services. + /// + /// + /// An array of components that represents all the service resources. + /// + /// + /// MSDN does not document the list of exceptions, + /// but it is reasonable to expect that SecurityException is + /// among them. Errors here will terminate the cmdlet. + /// + internal ServiceController[] AllServices => _allServices ??= ServiceController.GetServices(); + + private ServiceController[] _allServices; + + internal ServiceController GetOneService(string nameOfService) + { + Dbg.Assert(!WildcardPattern.ContainsWildcardCharacters(nameOfService), "Caller should verify that nameOfService doesn't contain wildcard characters"); + + try + { + var sc = new ServiceController(nameOfService); + // This will throw if the service doesn't exist + var unused = sc.Status; + + // No exception, then this is an existing, valid service. Return it. + return sc; + } + catch (InvalidOperationException) { } + catch (ArgumentException) { } + + return null; + } + + /// + /// Retrieve the list of all services matching the ServiceName, + /// DisplayName, Include and Exclude parameters, sorted by ServiceName. + /// + /// + internal List MatchingServices() + { + List matchingServices; + switch (selectionMode) + { + case SelectionMode.DisplayName: + matchingServices = MatchingServicesByDisplayName(); + break; + case SelectionMode.InputObject: + matchingServices = MatchingServicesByInput(); + break; + default: + matchingServices = MatchingServicesByServiceName(); + break; + } + // 2004/12/16 Note that the services will be sorted + // before being stopped. JimTru confirms that this is OK. + matchingServices.Sort(ServiceComparison); + return matchingServices; + } + + // sort by servicename + private static int ServiceComparison(ServiceController x, ServiceController y) + { + return string.Compare(x.ServiceName, y.ServiceName, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Retrieves the list of all services matching the ServiceName, + /// Include and Exclude parameters. + /// Generates a non-terminating error for each specified + /// service name which is not found even though it contains + /// no wildcards. + /// + /// + /// + /// We do not use the ServiceController(string serviceName) + /// constructor variant, since the resultant + /// ServiceController.ServiceName is the provided serviceName + /// even when that differs from the real ServiceName by case. + /// + private List MatchingServicesByServiceName() + { + List matchingServices = new(); + + if (serviceNames == null) + { + foreach (ServiceController service in AllServices) + { + IncludeExcludeAdd(matchingServices, service, false); + } + + return matchingServices; + } + + foreach (string pattern in serviceNames) + { + bool found = false; + + if (WildcardPattern.ContainsWildcardCharacters(pattern)) + { + WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + foreach (ServiceController service in AllServices) + { + if (!wildcard.IsMatch(service.ServiceName)) + continue; + found = true; + IncludeExcludeAdd(matchingServices, service, true); + } + } + else + { + ServiceController service = GetOneService(pattern); + if (service != null) + { + found = true; + IncludeExcludeAdd(matchingServices, service, true); + } + } + + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) + { + WriteNonTerminatingError( + pattern, + string.Empty, + pattern, + null, + "NoServiceFoundForGivenName", + ServiceResources.NoServiceFoundForGivenName, + ErrorCategory.ObjectNotFound); + } + } + + return matchingServices; + } + + /// + /// Retrieves the list of all services matching the DisplayName, + /// Include and Exclude parameters. + /// Generates a non-terminating error for each specified + /// display name which is not found even though it contains + /// no wildcards. + /// + /// + private List MatchingServicesByDisplayName() + { + List matchingServices = new(); + if (DisplayName == null) + { + Diagnostics.Assert(false, "null DisplayName"); + throw PSTraceSource.NewInvalidOperationException(); + } + + foreach (string pattern in DisplayName) + { + WildcardPattern wildcard = + WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + bool found = false; + foreach (ServiceController service in AllServices) + { + if (!wildcard.IsMatch(service.DisplayName)) + continue; + found = true; + IncludeExcludeAdd(matchingServices, service, true); + } + + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) + { + WriteNonTerminatingError( + string.Empty, + pattern, + pattern, + null, + "NoServiceFoundForGivenDisplayName", + ServiceResources.NoServiceFoundForGivenDisplayName, + ErrorCategory.ObjectNotFound); + } + } + + return matchingServices; + } + + /// + /// Retrieves the list of all services matching the InputObject, + /// Include and Exclude parameters. + /// + /// + private List MatchingServicesByInput() + { + List matchingServices = new(); + if (InputObject == null) + { + Diagnostics.Assert(false, "null InputObject"); + throw PSTraceSource.NewInvalidOperationException(); + } + + foreach (ServiceController service in InputObject) + { + service.Refresh(); + IncludeExcludeAdd(matchingServices, service, false); + } + + return matchingServices; + } + + /// + /// Add to , + /// but only if it passes the Include and Exclude filters (if present) + /// and (if ) if it is not + /// already on . + /// + /// List of services. + /// Service to add to list. + /// Check list for duplicates. + private void IncludeExcludeAdd( + List list, + ServiceController service, + bool checkDuplicates) + { + if (include != null && !Matches(service, include)) + return; + if (exclude != null && Matches(service, exclude)) + return; + if (checkDuplicates) + { + foreach (ServiceController sc in list) + { + if (sc.ServiceName == service.ServiceName && + sc.MachineName == service.MachineName) + { + return; + } + } + } + + list.Add(service); + } + + /// + /// Check whether matches the list of + /// patterns in . + /// + /// + /// + /// + private bool Matches(ServiceController service, string[] matchList) + { + if (matchList == null) + throw PSTraceSource.NewArgumentNullException(nameof(matchList)); + string serviceID = (selectionMode == SelectionMode.DisplayName) + ? service.DisplayName + : service.ServiceName; + foreach (string pattern in matchList) + { + WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); + if (wildcard.IsMatch(serviceID)) + return true; + } + + return false; + } + #endregion Internal + + } + #endregion MultipleServiceCommandBase + + #region GetServiceCommand + /// + /// This class implements the get-service command. + /// + [Cmdlet(VerbsCommon.Get, "Service", DefaultParameterSetName = "Default", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096496", RemotingCapability = RemotingCapability.SupportedByCommand)] + [OutputType(typeof(ServiceController))] + public sealed class GetServiceCommand : MultipleServiceCommandBase + { + #region Parameters + /// + /// Gets/sets an array of service names. + /// + /// + /// The ServiceName parameter is declared in subclasses, + /// since it is optional for GetService and mandatory otherwise. + /// + [Parameter(Position = 0, ParameterSetName = "Default", ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] + [ValidateNotNullOrEmpty()] + [Alias("ServiceName")] + public string[] Name + { + get + { + return serviceNames; + } + + set + { + serviceNames = value; + selectionMode = SelectionMode.ServiceName; + } + } + + /// + /// This returns the DependentServices of the specified service. + /// + [Parameter] + [Alias("DS")] + public SwitchParameter DependentServices { get; set; } + + /// + /// This returns the ServicesDependedOn of the specified service. + /// + [Parameter] + [Alias("SDO", "ServicesDependedOn")] + public SwitchParameter RequiredServices { get; set; } + + #endregion Parameters + + #region Overrides + /// + /// Write the service objects. + /// + protected override void ProcessRecord() + { + nint scManagerHandle = nint.Zero; + if (!DependentServices && !RequiredServices) + { + // As Get-Service only works on local services we get this once + // to retrieve extra properties added by PowerShell. + scManagerHandle = NativeMethods.OpenSCManagerW( + lpMachineName: null, + lpDatabaseName: null, + dwDesiredAccess: NativeMethods.SC_MANAGER_CONNECT); + if (scManagerHandle == nint.Zero) + { + Win32Exception exception = new(); + string message = StringUtil.Format(ServiceResources.FailToOpenServiceControlManager, exception.Message); + ServiceCommandException serviceException = new ServiceCommandException(message, exception); + ErrorRecord err = new ErrorRecord( + serviceException, + "FailToOpenServiceControlManager", + ErrorCategory.PermissionDenied, + null); + ThrowTerminatingError(err); + } + } + + try + { + foreach (ServiceController service in MatchingServices()) + { + if (!DependentServices.IsPresent && !RequiredServices.IsPresent) + { + WriteObject(AddProperties(scManagerHandle, service)); + } + else + { + if (DependentServices.IsPresent) + { + foreach (ServiceController dependantserv in service.DependentServices) + { + WriteObject(dependantserv); + } + } + + if (RequiredServices.IsPresent) + { + foreach (ServiceController servicedependedon in service.ServicesDependedOn) + { + WriteObject(servicedependedon); + } + } + } + } + } + finally + { + if (scManagerHandle != nint.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(scManagerHandle); + Diagnostics.Assert(succeeded, "SCManager handle close failed"); + } + } + } + + #endregion Overrides + +#nullable enable + + /// + /// Writes a verbose message when a service property query fails. + /// + /// Name of the service. + /// Name of the property that failed to be queried. + private void WriteServicePropertyError(string serviceName, string propertyName) + { + Win32Exception e = new(Marshal.GetLastWin32Error()); + WriteVerbose( + StringUtil.Format( + ServiceResources.CouldNotGetServiceProperty, + serviceName, + propertyName, + e.Message)); + } + + /// + /// Adds UserName, Description, BinaryPathName, DelayedAutoStart and StartupType to a ServiceController object. + /// + /// Handle to the local SCManager instance. + /// + /// ServiceController as PSObject with UserName, Description and StartupType added. + private PSObject AddProperties(nint scManagerHandle, ServiceController service) + { + NakedWin32Handle hService = nint.Zero; + + // As these are optional values, a failure due to permissions or + // other problem is ignored and the properties are set to null. + bool? isDelayedAutoStart = null; + string? binPath = null; + string? description = null; + string? startName = null; + ServiceStartupType startupType = ServiceStartupType.InvalidValue; + try + { + // We don't use service.ServiceHandle as that requests + // SERVICE_ALL_ACCESS when we only need SERVICE_QUERY_CONFIG. + hService = NativeMethods.OpenServiceW( + scManagerHandle, + service.ServiceName, + NativeMethods.SERVICE_QUERY_CONFIG + ); + if (hService != nint.Zero) + { + if (NativeMethods.QueryServiceConfig2( + hService, + NativeMethods.SERVICE_CONFIG_DESCRIPTION, + out NativeMethods.SERVICE_DESCRIPTIONW descriptionInfo)) + { + description = descriptionInfo.lpDescription; + } + else + { + WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_DESCRIPTIONW)); + } + + if (NativeMethods.QueryServiceConfig2( + hService, + NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, + out NativeMethods.SERVICE_DELAYED_AUTO_START_INFO autostartInfo)) + { + isDelayedAutoStart = autostartInfo.fDelayedAutostart; + } + else + { + WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_DELAYED_AUTO_START_INFO)); + } + + if (NativeMethods.QueryServiceConfig( + hService, + out NativeMethods.QUERY_SERVICE_CONFIG serviceInfo)) + { + binPath = serviceInfo.lpBinaryPathName; + startName = serviceInfo.lpServiceStartName; + if (isDelayedAutoStart.HasValue) + { + startupType = NativeMethods.GetServiceStartupType( + (ServiceStartMode)serviceInfo.dwStartType, + isDelayedAutoStart.Value); + } + } + else + { + WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.QUERY_SERVICE_CONFIG)); + } + } + else + { + // handle when OpenServiceW itself fails: + WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_QUERY_CONFIG)); + } + } + finally + { + if (hService != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hService); + Diagnostics.Assert(succeeded, "Failed to close service handle"); + } + } + + PSObject serviceAsPSObj = PSObject.AsPSObject(service); + PSNoteProperty noteProperty = new("UserName", startName); + serviceAsPSObj.Properties.Add(noteProperty, true); + serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#UserName"); + + noteProperty = new PSNoteProperty("Description", description); + serviceAsPSObj.Properties.Add(noteProperty, true); + serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#Description"); + + noteProperty = new PSNoteProperty("DelayedAutoStart", isDelayedAutoStart); + serviceAsPSObj.Properties.Add(noteProperty, true); + serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#DelayedAutoStart"); + + noteProperty = new PSNoteProperty("BinaryPathName", binPath); + serviceAsPSObj.Properties.Add(noteProperty, true); + serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#BinaryPathName"); + + noteProperty = new PSNoteProperty("StartupType", startupType); + serviceAsPSObj.Properties.Add(noteProperty, true); + serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#StartupType"); + + return serviceAsPSObj; + } + } +#nullable disable + #endregion GetServiceCommand + + #region ServiceOperationBaseCommand + /// + /// This class implements the base for service commands which actually + /// act on the service(s). + /// + public abstract class ServiceOperationBaseCommand : MultipleServiceCommandBase + { + #region Parameters + /// + /// Gets/sets an array of service names. + /// + /// + /// The ServiceName parameter is declared in subclasses, + /// since it is optional for GetService and mandatory otherwise. + /// + [Parameter(Position = 0, ParameterSetName = "Default", Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] + [Alias("ServiceName")] + public string[] Name + { + get + { + return serviceNames; + } + + set + { + serviceNames = value; + selectionMode = SelectionMode.ServiceName; + } + } + + /// + /// Service controller objects. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "InputObject", ValueFromPipeline = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public new ServiceController[] InputObject + { + get + { + return base.InputObject; + } + + set + { + base.InputObject = value; + } + } + + /// + /// Specifies whether to write the objects successfully operated upon + /// to the success stream. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + #endregion Parameters + + #region Internal + /// + /// Waits forever for the service to reach the desired status, but + /// writes a string to WriteWarning every 2 seconds. + /// + /// Service on which to operate. + /// Desired status. + /// + /// This is the expected status while the operation is incomplete. + /// If the service is in some other state, this means that the + /// operation failed. + /// + /// + /// resourceId for a string to be written to verbose stream + /// every 2 seconds + /// + /// + /// errorId for a nonterminating error if operation fails + /// + /// + /// errorMessage for a nonterminating error if operation fails + /// + /// True if action succeeded. + /// + /// WriteWarning will throw this if the pipeline has been stopped. + /// This means that the delay between hitting CTRL-C and stopping + /// the cmdlet should be 2 seconds at most. + /// + internal bool DoWaitForStatus( + ServiceController serviceController, + ServiceControllerStatus targetStatus, + ServiceControllerStatus pendingStatus, + string resourceIdPending, + string errorId, + string errorMessage) + { + while (true) + { + try + { + // ServiceController.Start will return before the service is actually started + // This API will wait forever + serviceController.WaitForStatus( + targetStatus, + new TimeSpan(20000000) // 2 seconds + ); + return true; // service reached target status + } + catch (System.ServiceProcess.TimeoutException) // still waiting + { + if (serviceController.Status != pendingStatus + // NTRAID#Windows Out Of Band Releases-919945-2005/09/27-JonN + // Close window where service could complete at + // just the wrong time + && serviceController.Status != targetStatus) + { + WriteNonTerminatingError(serviceController, null, + errorId, + errorMessage, + ErrorCategory.OpenError); + return false; + } + + string message = StringUtil.Format(resourceIdPending, + serviceController.ServiceName, + serviceController.DisplayName + ); + // will throw PipelineStoppedException if user hit CTRL-C + WriteWarning(message); + } + } + } + + /// + /// This will start the service. + /// + /// Service to start. + /// True if-and-only-if the service was started. + internal bool DoStartService(ServiceController serviceController) + { + Exception exception = null; + try + { + serviceController.Start(); + } + catch (Win32Exception e) + { + if (e.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING) + exception = e; + } + catch (InvalidOperationException e) + { + if (e.InnerException is not Win32Exception eInner + || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING) + { + exception = e; + } + } + + if (exception != null) + { + // This service refused to accept the start command, + // so write a non-terminating error. + WriteNonTerminatingError(serviceController, + exception, + "CouldNotStartService", + ServiceResources.CouldNotStartService, + ErrorCategory.OpenError); + return false; + } + + // ServiceController.Start will return + // before the service is actually started. + if (!DoWaitForStatus( + serviceController, + ServiceControllerStatus.Running, + ServiceControllerStatus.StartPending, + ServiceResources.StartingService, + "StartServiceFailed", + ServiceResources.StartServiceFailed)) + { + return false; + } + + return true; + } + + /// + /// This will stop the service. + /// + /// Service to stop. + /// Stop dependent services. + /// + /// True if-and-only-if the service was stopped. + internal List DoStopService(ServiceController serviceController, bool force, bool waitForServiceToStop) + { + // Ignore ServiceController.CanStop. CanStop will be set false + // if the service is not running, but this is not an error. + + List stoppedServices = new(); + ServiceController[] dependentServices = null; + + try + { + dependentServices = serviceController.DependentServices; + } + catch (Win32Exception e) + { + WriteNonTerminatingError(serviceController, e, + "CouldNotAccessDependentServices", + ServiceResources.CouldNotAccessDependentServices, + ErrorCategory.InvalidOperation); + } + catch (InvalidOperationException e) + { + WriteNonTerminatingError(serviceController, e, + "CouldNotAccessDependentServices", + ServiceResources.CouldNotAccessDependentServices, + ErrorCategory.InvalidOperation); + } + + if (!force) + { + if ((dependentServices != null) + && (dependentServices.Length > 0)) + { + // Check if all dependent services are stopped + if (!HaveAllDependentServicesStopped(dependentServices)) + { + // This service has dependent services + // and the force flag is not specified. + // Add a non-critical error for it. + WriteNonTerminatingError(serviceController, + null, + "ServiceHasDependentServices", + ServiceResources.ServiceHasDependentServices, + ErrorCategory.InvalidOperation); + + return stoppedServices; + } + } + } + + if (dependentServices != null) + { + foreach (ServiceController service in dependentServices) + { + if ((service.Status == ServiceControllerStatus.Running || + service.Status == ServiceControllerStatus.StartPending) && + service.CanStop) + { + stoppedServices.Add(service); + } + } + } + + Exception exception = null; + try + { + serviceController.Stop(); + } + catch (Win32Exception e) + { + if (e.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE) + exception = e; + } + catch (InvalidOperationException e) + { + if (e.InnerException is not Win32Exception eInner + || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE) + { + exception = e; + } + } + + if (exception != null) + { + // This service refused to accept the stop command, + // so write a non-terminating error. + WriteNonTerminatingError(serviceController, + exception, + "CouldNotStopService", + ServiceResources.CouldNotStopService, + ErrorCategory.CloseError); + RemoveNotStoppedServices(stoppedServices); + return stoppedServices; + } + + // ServiceController.Stop will return + // before the service is actually stopped. + if (waitForServiceToStop) + { + if (!DoWaitForStatus( + serviceController, + ServiceControllerStatus.Stopped, + ServiceControllerStatus.StopPending, + ServiceResources.StoppingService, + "StopServiceFailed", + ServiceResources.StopServiceFailed)) + { + RemoveNotStoppedServices(stoppedServices); + return stoppedServices; + } + } + + RemoveNotStoppedServices(stoppedServices); + if ((serviceController.Status.Equals(ServiceControllerStatus.Stopped)) || (serviceController.Status.Equals(ServiceControllerStatus.StopPending))) + { + stoppedServices.Add(serviceController); + } + + return stoppedServices; + } + + /// + /// Check if all dependent services are stopped. + /// + /// + /// + /// True if all dependent services are stopped + /// False if not all dependent services are stopped + /// + private static bool HaveAllDependentServicesStopped(ServiceController[] dependentServices) + { + return Array.TrueForAll(dependentServices, static service => service.Status == ServiceControllerStatus.Stopped); + } + + /// + /// This removes all services that are not stopped from a list of services. + /// + /// A list of services. + internal void RemoveNotStoppedServices(List services) + { + // You shall not modify a collection during enumeration. + services.RemoveAll(service => + service.Status != ServiceControllerStatus.Stopped && + service.Status != ServiceControllerStatus.StopPending); + } + + /// + /// This will pause the service. + /// + /// Service to pause. + /// True if-and-only-if the service was paused. + internal bool DoPauseService(ServiceController serviceController) + { + Exception exception = null; + bool serviceNotRunning = false; + try + { + serviceController.Pause(); + } + catch (Win32Exception e) + { + if (e.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) + { + serviceNotRunning = true; + } + + exception = e; + } + catch (InvalidOperationException e) + { + if (e.InnerException is Win32Exception eInner + && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) + { + serviceNotRunning = true; + } + + exception = e; + } + + if (exception != null) + { + // This service refused to accept the pause command, + // so write a non-terminating error. + string resourceIdAndErrorId = ServiceResources.CouldNotSuspendService; + if (serviceNotRunning) + { + WriteNonTerminatingError(serviceController, + exception, + "CouldNotSuspendServiceNotRunning", + ServiceResources.CouldNotSuspendServiceNotRunning, + ErrorCategory.CloseError); + } + else if (!serviceController.CanPauseAndContinue) + { + WriteNonTerminatingError(serviceController, + exception, + "CouldNotSuspendServiceNotSupported", + ServiceResources.CouldNotSuspendServiceNotSupported, + ErrorCategory.CloseError); + } + + WriteNonTerminatingError(serviceController, + exception, + "CouldNotSuspendService", + ServiceResources.CouldNotSuspendService, + ErrorCategory.CloseError); + + return false; + } + + // ServiceController.Pause will return + // before the service is actually paused. + if (!DoWaitForStatus( + serviceController, + ServiceControllerStatus.Paused, + ServiceControllerStatus.PausePending, + ServiceResources.SuspendingService, + "SuspendServiceFailed", + ServiceResources.SuspendServiceFailed)) + { + return false; + } + + return true; + } + + /// + /// This will resume the service. + /// + /// Service to resume. + /// True if-and-only-if the service was resumed. + internal bool DoResumeService(ServiceController serviceController) + { + Exception exception = null; + bool serviceNotRunning = false; + try + { + serviceController.Continue(); + } + catch (Win32Exception e) + { + if (e.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) + { + serviceNotRunning = true; + } + + exception = e; + } + catch (InvalidOperationException e) + { + if (e.InnerException is Win32Exception eInner + && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) + { + serviceNotRunning = true; + } + + exception = e; + } + + if (exception != null) + { + // This service refused to accept the continue command, + // so write a non-terminating error. + if (serviceNotRunning) + { + WriteNonTerminatingError(serviceController, + exception, + "CouldNotResumeServiceNotRunning", + ServiceResources.CouldNotResumeServiceNotRunning, + ErrorCategory.CloseError); + } + else if (!serviceController.CanPauseAndContinue) + { + WriteNonTerminatingError(serviceController, + exception, + "CouldNotResumeServiceNotSupported", + ServiceResources.CouldNotResumeServiceNotSupported, + ErrorCategory.CloseError); + } + + WriteNonTerminatingError(serviceController, + exception, + "CouldNotResumeService", + ServiceResources.CouldNotResumeService, + ErrorCategory.CloseError); + + return false; + } + + // ServiceController.Continue will return + // before the service is actually continued. + if (!DoWaitForStatus( + serviceController, + ServiceControllerStatus.Running, + ServiceControllerStatus.ContinuePending, + ServiceResources.ResumingService, + "ResumeServiceFailed", + ServiceResources.ResumeServiceFailed)) + { + return false; + } + + return true; + } + #endregion Internal + } + #endregion ServiceOperationBaseCommand + + #region StopServiceCommand + + /// + /// This class implements the stop-service command. + /// + /// + /// Note that the services will be sorted before being stopped. + /// PM confirms that this is OK. + /// + [Cmdlet(VerbsLifecycle.Stop, "Service", DefaultParameterSetName = "InputObject", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097052")] + [OutputType(typeof(ServiceController))] + public sealed class StopServiceCommand : ServiceOperationBaseCommand + { + /// + /// Specifies whether to force a service to stop + /// even if it has dependent services. + /// + [Parameter] + public SwitchParameter Force { get; set; } + + /// + /// Specifies whether to wait for a service to reach the stopped state before returning. + /// + [Parameter] + public SwitchParameter NoWait { get; set; } + + /// + /// Stop the services. + /// It is a non-terminating error if -Force is not specified and + /// the service has dependent services, whether or not they + /// are running. + /// It is a non-terminating error if the service stop operation fails. + /// + protected override void ProcessRecord() + { + foreach (ServiceController serviceController in MatchingServices()) + { + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(serviceController)) + { + continue; + } + + List stoppedServices = DoStopService(serviceController, Force, !NoWait); + + if (PassThru && stoppedServices.Count > 0) + { + foreach (ServiceController service in stoppedServices) + { + WriteObject(service); + } + } + } + } + } + #endregion StopServiceCommand + + #region StartServiceCommand + /// + /// This class implements the start-service command. + /// + [Cmdlet(VerbsLifecycle.Start, "Service", DefaultParameterSetName = "InputObject", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097051")] + [OutputType(typeof(ServiceController))] + public sealed class StartServiceCommand : ServiceOperationBaseCommand + { + /// + /// Start the services. + /// + protected override void ProcessRecord() + { + foreach (ServiceController serviceController in MatchingServices()) + { + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(serviceController)) + { + continue; + } + + if (DoStartService(serviceController)) + { + if (PassThru) + WriteObject(serviceController); + } + } + } + } + #endregion StartServiceCommand + + #region SuspendServiceCommand + /// + /// This class implements the suspend-service command. + /// + [Cmdlet(VerbsLifecycle.Suspend, "Service", DefaultParameterSetName = "InputObject", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097053")] + [OutputType(typeof(ServiceController))] + public sealed class SuspendServiceCommand : ServiceOperationBaseCommand + { + /// + /// Start the services. + /// + protected override void ProcessRecord() + { + foreach (ServiceController serviceController in MatchingServices()) + { + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(serviceController)) + { + continue; + } + + if (DoPauseService(serviceController)) + { + if (PassThru) + WriteObject(serviceController); + } + } + } + } + #endregion SuspendServiceCommand + + #region ResumeServiceCommand + /// + /// This class implements the resume-service command. + /// + [Cmdlet(VerbsLifecycle.Resume, "Service", DefaultParameterSetName = "InputObject", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097150")] + [OutputType(typeof(ServiceController))] + public sealed class ResumeServiceCommand : ServiceOperationBaseCommand + { + /// + /// Start the services. + /// + protected override void ProcessRecord() + { + foreach (ServiceController serviceController in MatchingServices()) + { + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(serviceController)) + { + continue; + } + + if (DoResumeService(serviceController)) + { + if (PassThru) + WriteObject(serviceController); + } + } + } + } + #endregion ResumeServiceCommand + + #region RestartServiceCommand + + /// + /// This class implements the restart-service command. + /// + [Cmdlet(VerbsLifecycle.Restart, "Service", DefaultParameterSetName = "InputObject", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097059")] + [OutputType(typeof(ServiceController))] + public sealed class RestartServiceCommand : ServiceOperationBaseCommand + { + /// + /// Specifies whether to force a service to stop + /// even if it has dependent services. + /// + [Parameter] + public SwitchParameter Force { get; set; } + + /// + /// Stop and restart the services. + /// It is a non-terminating error if the service is running, + /// -Force is not specified and the service has dependent services, + /// whether or not the dependent services are running. + /// It is a non-terminating error if the service stop operation fails. + /// + protected override void ProcessRecord() + { + foreach (ServiceController serviceController in MatchingServices()) + { + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(serviceController)) + { + continue; + } + + // Set the NoWait parameter to false since we are not adding this switch to this cmdlet. + List stoppedServices = DoStopService(serviceController, Force, true); + + if (stoppedServices.Count > 0) + { + foreach (ServiceController service in stoppedServices) + { + if (DoStartService(service)) + { + if (PassThru) + WriteObject(service); + } + } + } + } + } + } + #endregion RestartServiceCommand + + #region SetServiceCommand + + /// + /// This class implements the set-service command. + /// + [Cmdlet(VerbsCommon.Set, "Service", SupportsShouldProcess = true, DefaultParameterSetName = "Name", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097148", RemotingCapability = RemotingCapability.SupportedByCommand)] + [OutputType(typeof(ServiceController))] + public class SetServiceCommand : ServiceOperationBaseCommand + { + #region Parameters + + /// + /// Service name. + /// + /// + [Parameter(Mandatory = true, ParameterSetName = "Name", Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Alias("ServiceName", "SN")] + public new string Name + { + get + { + return serviceName; + } + + set + { + serviceName = value; + } + } + + internal string serviceName = null; + + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies a ServiceController object that represents the service to change. + /// Enter a variable that contains the objects or type a command or expression + /// that gets the objects. + /// + [Parameter(Mandatory = true, ParameterSetName = "InputObject", Position = 0, ValueFromPipeline = true)] + public new ServiceController InputObject { get; set; } + + /// + /// The following is the definition of the input parameter "DisplayName". + /// Specifies a new display name for the cmdlet. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("DN")] + public new string DisplayName + { + get + { + return displayName; + } + + set + { + displayName = value; + } + } + + internal string displayName = null; + + /// + /// Account under which the service should run. + /// + /// + [Parameter] + [Credential()] + public PSCredential Credential { get; set; } + + /// + /// The following is the definition of the input parameter "Description". + /// Specifies a new description for the service. + /// The service description appears in Services in Computer Management. + /// Description is not a property of the ServiceController object that + /// Get-Service retrieve. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string Description + { + get + { + return description; + } + + set + { + description = value; + } + } + + internal string description = null; + + /// + /// The following is the definition of the input parameter "StartupType". + /// "Set-Service -StartType" sets ServiceController.InputObject.StartType. + /// Changes the starting mode of the service. Valid values for StartupType are: + /// -- Automatic: Start when the system starts. + /// -- Manual : Starts only when started by a user or program. + /// -- Disabled : Can. + /// + [Parameter] + [Alias("StartMode", "SM", "ST", "StartType")] + [ValidateNotNullOrEmpty] + public ServiceStartupType StartupType + { + get + { + return startupType; + } + + set + { + startupType = value; + } + } + + // We set the initial value to an invalid value so that we can + // distinguish when this is and is not set. + internal ServiceStartupType startupType = ServiceStartupType.InvalidValue; + + /// + /// Sets the SecurityDescriptorSddl of the service using a SDDL string. + /// + [Parameter] + [Alias("sd")] + [ValidateNotNullOrEmpty] + public string SecurityDescriptorSddl + { + get; + set; + } + + /// + /// The following is the definition of the input parameter "Status". + /// This specifies what state the service should be in (e.g. Running, Stopped, + /// Paused). If it is already in that state, do nothing. If it is not, do the + /// appropriate action to bring about the desired result (start/stop/suspend the + /// service) and issue an error if this cannot be achieved. + /// Status can be Paused , Running and Stopped. + /// + [Parameter] + [ValidateSetAttribute(new string[] { "Running", "Stopped", "Paused" })] + public string Status + { + get + { + return serviceStatus; + } + + set + { + serviceStatus = value; + } + } + + internal string serviceStatus = null; + + /// + /// The following is the definition of the input parameter "Force". + /// This parameter is useful only when parameter "Stop" is enabled. + /// If "Force" is enabled, it will also stop the dependent services. + /// If not, it will send an error when this service has dependent ones. + /// + [Parameter] + public SwitchParameter Force { get; set; } + + /// + /// This is not a parameter for this cmdlet. + /// + // This has been shadowed from base class and removed parameter tag to fix gcm "Set-Service" -syntax + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public new string[] Include + { + get + { + return include; + } + + set + { + include = null; + } + } + + internal new string[] include = null; + + /// + /// This is not a parameter for this cmdlet. + /// + // This has been shadowed from base class and removed parameter tag to fix gcm "Set-Service" -syntax + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public new string[] Exclude + { + get + { + return exclude; + } + + set + { + exclude = null; + } + } + + internal new string[] exclude = null; + #endregion Parameters + + #region Overrides + /// + /// + protected override void ProcessRecord() + { + ServiceController service = null; + IntPtr password = IntPtr.Zero; + bool objServiceShouldBeDisposed = false; + + try + { + if (InputObject != null) + { + service = InputObject; + Name = service.ServiceName; + objServiceShouldBeDisposed = false; + } + else + { + service = new ServiceController(serviceName); + objServiceShouldBeDisposed = true; + } + + Diagnostics.Assert(!string.IsNullOrEmpty(Name), "null ServiceName"); + + // "new ServiceController" will succeed even if + // there is no such service. This checks whether + // the service actually exists. + string unusedByDesign = service.DisplayName; + } + catch (ArgumentException ex) + { + // cannot use WriteNonterminatingError as service is null + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.ObjectNotFound, Name); + WriteError(er); + return; + } + catch (InvalidOperationException ex) + { + // cannot use WriteNonterminatingError as service is null + ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, Name); + WriteError(er); + return; + } + + try // In finally we ensure dispose, if object not pipelined. + { + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(service)) + { + return; + } + + NakedWin32Handle hScManager = IntPtr.Zero; + NakedWin32Handle hService = IntPtr.Zero; + IntPtr delayedAutoStartInfoBuffer = IntPtr.Zero; + try + { + hScManager = NativeMethods.OpenSCManagerW( + string.Empty, + null, + NativeMethods.SC_MANAGER_CONNECT + ); + + if (hScManager == IntPtr.Zero) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "FailToOpenServiceControlManager", + ServiceResources.FailToOpenServiceControlManager, + ErrorCategory.PermissionDenied); + return; + } + + var access = NativeMethods.SERVICE_CHANGE_CONFIG; + if (!string.IsNullOrEmpty(SecurityDescriptorSddl)) + access |= NativeMethods.WRITE_DAC | NativeMethods.WRITE_OWNER; + + hService = NativeMethods.OpenServiceW( + hScManager, + Name, + access + ); + + if (hService == IntPtr.Zero) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotSetService", + ServiceResources.CouldNotSetService, + ErrorCategory.PermissionDenied); + return; + } + // Modify startup type or display name or credential + if (!string.IsNullOrEmpty(DisplayName) + || StartupType != ServiceStartupType.InvalidValue || Credential != null) + { + DWORD dwStartType = NativeMethods.SERVICE_NO_CHANGE; + if (!NativeMethods.TryGetNativeStartupType(StartupType, out dwStartType)) + { + WriteNonTerminatingError(StartupType.ToString(), "Set-Service", Name, + new ArgumentException(), "CouldNotSetService", + ServiceResources.UnsupportedStartupType, + ErrorCategory.InvalidArgument); + return; + } + + string username = null; + if (Credential != null) + { + username = Credential.UserName; + password = Marshal.SecureStringToCoTaskMemUnicode(Credential.Password); + } + + bool succeeded = NativeMethods.ChangeServiceConfigW( + hService, + NativeMethods.SERVICE_NO_CHANGE, + dwStartType, + NativeMethods.SERVICE_NO_CHANGE, + null, + null, + IntPtr.Zero, + null, + username, + password, + DisplayName + ); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotSetService", + ServiceResources.CouldNotSetService, + ErrorCategory.PermissionDenied); + return; + } + } + + NativeMethods.SERVICE_DESCRIPTIONW sd = new(); + sd.lpDescription = Description; + int size = Marshal.SizeOf(sd); + IntPtr buffer = Marshal.AllocCoTaskMem(size); + Marshal.StructureToPtr(sd, buffer, false); + + bool status = NativeMethods.ChangeServiceConfig2W( + hService, + NativeMethods.SERVICE_CONFIG_DESCRIPTION, + buffer); + + if (!status) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotSetServiceDescription", + ServiceResources.CouldNotSetServiceDescription, + ErrorCategory.PermissionDenied); + } + + // Set the delayed auto start + NativeMethods.SERVICE_DELAYED_AUTO_START_INFO ds = new(); + ds.fDelayedAutostart = StartupType == ServiceStartupType.AutomaticDelayedStart; + size = Marshal.SizeOf(ds); + delayedAutoStartInfoBuffer = Marshal.AllocCoTaskMem(size); + Marshal.StructureToPtr(ds, delayedAutoStartInfoBuffer, false); + + status = NativeMethods.ChangeServiceConfig2W( + hService, + NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, + delayedAutoStartInfoBuffer); + + if (!status) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotSetServiceDelayedAutoStart", + ServiceResources.CouldNotSetServiceDelayedAutoStart, + ErrorCategory.PermissionDenied); + } + + // Handle the '-Status' parameter + if (!string.IsNullOrEmpty(Status)) + { + if (Status.Equals("Running", StringComparison.OrdinalIgnoreCase)) + { + if (!service.Status.Equals(ServiceControllerStatus.Running)) + { + if (service.Status.Equals(ServiceControllerStatus.Paused)) + // resume service + DoResumeService(service); + else + // start service + DoStartService(service); + } + } + else if (Status.Equals("Stopped", StringComparison.OrdinalIgnoreCase)) + { + if (!service.Status.Equals(ServiceControllerStatus.Stopped)) + { + // Check for the dependent services as set-service dont have force parameter + ServiceController[] dependentServices = service.DependentServices; + + if ((!Force) && (dependentServices != null) && (dependentServices.Length > 0)) + { + WriteNonTerminatingError(service, null, "ServiceHasDependentServicesNoForce", ServiceResources.ServiceHasDependentServicesNoForce, ErrorCategory.InvalidOperation); + return; + } + + // Stop service, pass 'true' to the force parameter as we have already checked for the dependent services. + DoStopService(service, Force, waitForServiceToStop: true); + } + } + else if (Status.Equals("Paused", StringComparison.OrdinalIgnoreCase)) + { + if (!service.Status.Equals(ServiceControllerStatus.Paused)) + { + DoPauseService(service); + } + } + } + + if (!string.IsNullOrEmpty(SecurityDescriptorSddl)) + { + SetServiceSecurityDescriptor(service, SecurityDescriptorSddl, hService); + } + + if (PassThru.IsPresent) + { + // To display the service, refreshing the service would not show the display name after updating + ServiceController displayservice = new(Name); + WriteObject(displayservice); + } + } + finally + { + if (delayedAutoStartInfoBuffer != IntPtr.Zero) + { + Marshal.FreeCoTaskMem(delayedAutoStartInfoBuffer); + } + + if (hService != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hService); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotSetServiceDescription", + ServiceResources.CouldNotSetServiceDescription, + ErrorCategory.PermissionDenied); + } + } + + if (hScManager != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hScManager); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotSetServiceDescription", + ServiceResources.CouldNotSetServiceDescription, + ErrorCategory.PermissionDenied); + } + } + } + } + finally + { + if (password != IntPtr.Zero) + { + Marshal.ZeroFreeCoTaskMemUnicode(password); + } + + if (objServiceShouldBeDisposed) + { + service.Dispose(); + } + } + } + #endregion Overrides + + } + #endregion SetServiceCommand + + #region NewServiceCommand + /// + /// This class implements the New-Service command. + /// + [Cmdlet(VerbsCommon.New, "Service", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096905")] + [OutputType(typeof(ServiceController))] + public class NewServiceCommand : ServiceBaseCommand + { + #region Parameters + /// + /// Name of the service to create. + /// + /// + [Parameter(Position = 0, Mandatory = true)] + [Alias("ServiceName")] + public string Name + { + get { return serviceName; } + + set { serviceName = value; } + } + + internal string serviceName = null; + + /// + /// The executable which implements this service. + /// + /// + [Parameter(Position = 1, Mandatory = true)] + [Alias("Path")] + public string BinaryPathName + { + get { return binaryPathName; } + + set { binaryPathName = value; } + } + + internal string binaryPathName = null; + + /// + /// DisplayName of the service to create. + /// + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string DisplayName + { + get { return displayName; } + + set { displayName = value; } + } + + internal string displayName = null; + + /// + /// Description of the service to create. + /// + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string Description + { + get { return description; } + + set { description = value; } + } + + internal string description = null; + + /// + /// Should the service start automatically? + /// + /// + [Parameter] + public ServiceStartupType StartupType + { + get { return startupType; } + + set { startupType = value; } + } + + internal ServiceStartupType startupType = ServiceStartupType.Automatic; + + /// + /// Account under which the service should run. + /// + /// + [Parameter] + [Credential()] + public PSCredential Credential + { + get { return credential; } + + set { credential = value; } + } + + internal PSCredential credential = null; + + /// + /// Sets the SecurityDescriptorSddl of the service using a SDDL string. + /// + [Parameter] + [Alias("sd")] + [ValidateNotNullOrEmpty] + public string SecurityDescriptorSddl + { + get; + set; + } + + /// + /// Other services on which the new service depends. + /// + /// + [Parameter] + public string[] DependsOn + { + get { return dependsOn; } + + set { dependsOn = value; } + } + + internal string[] dependsOn = null; + #endregion Parameters + + #region Overrides + /// + /// Create the service. + /// + protected override void BeginProcessing() + { + ServiceController service = null; + Diagnostics.Assert(!string.IsNullOrEmpty(Name), + "null ServiceName"); + Diagnostics.Assert(!string.IsNullOrEmpty(BinaryPathName), + "null BinaryPathName"); + + // confirm the operation first + // this is always false if WhatIf is set + if (!ShouldProcessServiceOperation(DisplayName ?? string.Empty, Name)) + { + return; + } + + // Connect to the service controller + NakedWin32Handle hScManager = IntPtr.Zero; + NakedWin32Handle hService = IntPtr.Zero; + IntPtr password = IntPtr.Zero; + IntPtr delayedAutoStartInfoBuffer = IntPtr.Zero; + try + { + hScManager = NativeMethods.OpenSCManagerW( + null, + null, + NativeMethods.SC_MANAGER_CONNECT | NativeMethods.SC_MANAGER_CREATE_SERVICE + ); + if (hScManager == IntPtr.Zero) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotNewService", + ServiceResources.CouldNotNewService, + ErrorCategory.PermissionDenied); + return; + } + + if (!NativeMethods.TryGetNativeStartupType(StartupType, out DWORD dwStartType)) + { + WriteNonTerminatingError(StartupType.ToString(), "New-Service", Name, + new ArgumentException(), "CouldNotNewService", + ServiceResources.UnsupportedStartupType, + ErrorCategory.InvalidArgument); + return; + } + // set up the double-null-terminated lpDependencies parameter + IntPtr lpDependencies = IntPtr.Zero; + if (DependsOn != null) + { + int numchars = 1; // final null + foreach (string dependedOn in DependsOn) + { + numchars += dependedOn.Length + 1; + } + + char[] doubleNullArray = new char[numchars]; + int pos = 0; + foreach (string dependedOn in DependsOn) + { + Array.Copy( + dependedOn.ToCharArray(), 0, + doubleNullArray, pos, + dependedOn.Length + ); + pos += dependedOn.Length; + doubleNullArray[pos++] = (char)0; // null terminator + } + + doubleNullArray[pos++] = (char)0; // double-null terminator + Diagnostics.Assert(pos == numchars, "lpDependencies build error"); + lpDependencies = Marshal.AllocHGlobal( + numchars * Marshal.SystemDefaultCharSize); + Marshal.Copy(doubleNullArray, 0, lpDependencies, numchars); + } + + // set up the Credential parameter + string username = null; + if (Credential != null) + { + username = Credential.UserName; + password = Marshal.SecureStringToCoTaskMemUnicode(Credential.Password); + } + + // Create the service + hService = NativeMethods.CreateServiceW( + hScManager, + Name, + DisplayName, + NativeMethods.SERVICE_CHANGE_CONFIG | NativeMethods.WRITE_DAC | NativeMethods.WRITE_OWNER, + NativeMethods.SERVICE_WIN32_OWN_PROCESS, + dwStartType, + NativeMethods.SERVICE_ERROR_NORMAL, + BinaryPathName, + null, + null, + lpDependencies, + username, + password + ); + if (hService == IntPtr.Zero) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotNewService", + ServiceResources.CouldNotNewService, + ErrorCategory.PermissionDenied); + return; + } + + // Set the service description + NativeMethods.SERVICE_DESCRIPTIONW sd = new(); + sd.lpDescription = Description; + int size = Marshal.SizeOf(sd); + IntPtr buffer = Marshal.AllocCoTaskMem(size); + Marshal.StructureToPtr(sd, buffer, false); + + bool succeeded = NativeMethods.ChangeServiceConfig2W( + hService, + NativeMethods.SERVICE_CONFIG_DESCRIPTION, + buffer); + + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotNewServiceDescription", + ServiceResources.CouldNotNewServiceDescription, + ErrorCategory.PermissionDenied); + } + + // Set the delayed auto start + if (StartupType == ServiceStartupType.AutomaticDelayedStart) + { + NativeMethods.SERVICE_DELAYED_AUTO_START_INFO ds = new(); + ds.fDelayedAutostart = true; + size = Marshal.SizeOf(ds); + delayedAutoStartInfoBuffer = Marshal.AllocCoTaskMem(size); + Marshal.StructureToPtr(ds, delayedAutoStartInfoBuffer, false); + + succeeded = NativeMethods.ChangeServiceConfig2W( + hService, + NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, + delayedAutoStartInfoBuffer); + + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotNewServiceDelayedAutoStart", + ServiceResources.CouldNotNewServiceDelayedAutoStart, + ErrorCategory.PermissionDenied); + } + } + + // write the ServiceController for the new service + service = new ServiceController(Name); + + if (!string.IsNullOrEmpty(SecurityDescriptorSddl)) + { + SetServiceSecurityDescriptor(service, SecurityDescriptorSddl, hService); + } + + WriteObject(service); + } + finally + { + if (delayedAutoStartInfoBuffer != IntPtr.Zero) + { + Marshal.FreeCoTaskMem(delayedAutoStartInfoBuffer); + } + + if (password != IntPtr.Zero) + { + Marshal.ZeroFreeCoTaskMemUnicode(password); + } + + if (hService != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hService); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotNewServiceDescription", + ServiceResources.CouldNotNewServiceDescription, + ErrorCategory.PermissionDenied); + } + } + + if (hScManager != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hScManager); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + Name, + DisplayName, + Name, + exception, + "CouldNotNewServiceDescription", + ServiceResources.CouldNotNewServiceDescription, + ErrorCategory.PermissionDenied); + } + } + } + } + #endregion Overrides + } + #endregion NewServiceCommand + + #region RemoveServiceCommand + /// + /// This class implements the Remove-Service command. + /// + [Cmdlet(VerbsCommon.Remove, "Service", SupportsShouldProcess = true, DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2248980")] + public class RemoveServiceCommand : ServiceBaseCommand + { + #region Parameters + + /// + /// Name of the service to remove. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Name")] + [Alias("ServiceName", "SN")] + public string Name { get; set; } + + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies ServiceController object representing the services to be removed. + /// Enter a variable that contains the objects or type a command or expression + /// that gets the objects. + /// + [Parameter(ValueFromPipeline = true, ParameterSetName = "InputObject")] + public ServiceController InputObject { get; set; } + + #endregion Parameters + + #region Overrides + /// + /// Remove the service. + /// + protected override void ProcessRecord() + { + ServiceController service = null; + bool objServiceShouldBeDisposed = false; + try + { + if (InputObject != null) + { + service = InputObject; + Name = service.ServiceName; + objServiceShouldBeDisposed = false; + } + else + { + service = new ServiceController(Name); + objServiceShouldBeDisposed = true; + } + + Diagnostics.Assert(!string.IsNullOrEmpty(Name), "null ServiceName"); + + // "new ServiceController" will succeed even if there is no such service. + // This checks whether the service actually exists. + string unusedByDesign = service.DisplayName; + } + catch (ArgumentException ex) + { + // Cannot use WriteNonterminatingError as service is null + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.ObjectNotFound, Name); + WriteError(er); + return; + } + catch (InvalidOperationException ex) + { + // Cannot use WriteNonterminatingError as service is null + ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, Name); + WriteError(er); + return; + } + + try // In finally we ensure dispose, if object not pipelined. + { + // Confirm the operation first. + // This is always false if WhatIf is set. + if (!ShouldProcessServiceOperation(service)) + { + return; + } + + NakedWin32Handle hScManager = IntPtr.Zero; + NakedWin32Handle hService = IntPtr.Zero; + try + { + hScManager = NativeMethods.OpenSCManagerW( + lpMachineName: string.Empty, + lpDatabaseName: null, + dwDesiredAccess: NativeMethods.SC_MANAGER_ALL_ACCESS + ); + if (hScManager == IntPtr.Zero) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteObject(exception); + WriteNonTerminatingError( + service, + exception, + "FailToOpenServiceControlManager", + ServiceResources.FailToOpenServiceControlManager, + ErrorCategory.PermissionDenied); + return; + } + + hService = NativeMethods.OpenServiceW( + hScManager, + Name, + NativeMethods.SERVICE_DELETE + ); + if (hService == IntPtr.Zero) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotRemoveService", + ServiceResources.CouldNotRemoveService, + ErrorCategory.PermissionDenied); + return; + } + + bool status = NativeMethods.DeleteService(hService); + + if (!status) + { + int lastError = Marshal.GetLastWin32Error(); + Win32Exception exception = new(lastError); + WriteNonTerminatingError( + service, + exception, + "CouldNotRemoveService", + ServiceResources.CouldNotRemoveService, + ErrorCategory.PermissionDenied); + } + } + finally + { + if (hService != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hService); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Diagnostics.Assert(lastError != 0, "ErrorCode not success"); + } + } + + if (hScManager != IntPtr.Zero) + { + bool succeeded = NativeMethods.CloseServiceHandle(hScManager); + if (!succeeded) + { + int lastError = Marshal.GetLastWin32Error(); + Diagnostics.Assert(lastError != 0, "ErrorCode not success"); + } + } + } + } + finally + { + if (objServiceShouldBeDisposed) + { + service.Dispose(); + } + } + } + #endregion Overrides + } + #endregion RemoveServiceCommand + + #region ServiceCommandException + /// + /// Non-terminating errors occurring in the service noun commands. + /// + public class ServiceCommandException : SystemException + { + #region ctors + /// + /// Unimplemented standard constructor. + /// + /// Doesn't return. + public ServiceCommandException() + : base() + { + throw new NotImplementedException(); + } + + /// + /// Standard constructor. + /// + /// + /// Constructed object. + public ServiceCommandException(string message) + : base(message) + { + } + + /// + /// Standard constructor. + /// + /// + /// + public ServiceCommandException(string message, Exception innerException) + : base(message, innerException) + { + } + #endregion ctors + + #region Serialization + /// + /// Serialization constructor. + /// + /// + /// + /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8, hence this method is now marked as obsolete", DiagnosticId = "SYSLIB0051")] + protected ServiceCommandException(SerializationInfo info, StreamingContext context) + { + throw new NotSupportedException(); + } + + #endregion Serialization + + #region Properties + /// + /// Name of the service which could not be found or operated upon. + /// + /// + public string ServiceName + { + get { return _serviceName; } + + set { _serviceName = value; } + } + + private string _serviceName = string.Empty; + #endregion Properties + } + #endregion ServiceCommandException + + #region NativeMethods + internal static class NativeMethods + { + // from winuser.h + internal const int ERROR_SERVICE_ALREADY_RUNNING = 1056; + internal const int ERROR_SERVICE_NOT_ACTIVE = 1062; + internal const int ERROR_INSUFFICIENT_BUFFER = 122; + internal const DWORD ERROR_ACCESS_DENIED = 0x5; + internal const DWORD SC_MANAGER_CONNECT = 1; + internal const DWORD SC_MANAGER_CREATE_SERVICE = 2; + internal const DWORD SC_MANAGER_ALL_ACCESS = 0xf003f; + internal const DWORD SERVICE_QUERY_CONFIG = 1; + internal const DWORD SERVICE_CHANGE_CONFIG = 2; + internal const DWORD SERVICE_DELETE = 0x10000; + internal const DWORD SERVICE_NO_CHANGE = 0xffffffff; + internal const DWORD SERVICE_AUTO_START = 0x2; + internal const DWORD SERVICE_DEMAND_START = 0x3; + internal const DWORD SERVICE_DISABLED = 0x4; + internal const DWORD SERVICE_CONFIG_DESCRIPTION = 1; + internal const DWORD SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3; + internal const DWORD SERVICE_CONFIG_SERVICE_SID_INFO = 5; + internal const DWORD WRITE_DAC = 262144; + internal const DWORD WRITE_OWNER = 524288; + internal const DWORD SERVICE_WIN32_OWN_PROCESS = 0x10; + internal const DWORD SERVICE_ERROR_NORMAL = 1; + + // from winnt.h + [DllImport(PinvokeDllNames.OpenSCManagerWDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + NakedWin32Handle OpenSCManagerW( + [In, MarshalAs(UnmanagedType.LPWStr)] string lpMachineName, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpDatabaseName, + DWORD dwDesiredAccess + ); + + [DllImport(PinvokeDllNames.OpenServiceWDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + NakedWin32Handle OpenServiceW( + NakedWin32Handle hSCManager, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpServiceName, + DWORD dwDesiredAccess + ); + + [DllImport(PinvokeDllNames.QueryServiceConfigDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + bool QueryServiceConfigW( + NakedWin32Handle hSCManager, + IntPtr lpServiceConfig, + DWORD cbBufSize, + out DWORD pcbBytesNeeded + ); + + [DllImport(PinvokeDllNames.QueryServiceConfig2DllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + bool QueryServiceConfig2W( + NakedWin32Handle hService, + DWORD dwInfoLevel, + IntPtr lpBuffer, + DWORD cbBufSize, + out DWORD pcbBytesNeeded + ); + + [DllImport(PinvokeDllNames.CloseServiceHandleDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + bool CloseServiceHandle( + NakedWin32Handle hSCManagerOrService + ); + + [DllImport(PinvokeDllNames.DeleteServiceDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + bool DeleteService( + NakedWin32Handle hService + ); + + [DllImport(PinvokeDllNames.ChangeServiceConfigWDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + bool ChangeServiceConfigW( + NakedWin32Handle hService, + DWORD dwServiceType, + DWORD dwStartType, + DWORD dwErrorControl, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpBinaryPathName, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpLoadOrderGroup, + IntPtr lpdwTagId, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpDependencies, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpServiceStartName, + [In] IntPtr lpPassword, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpDisplayName + ); + + [DllImport(PinvokeDllNames.ChangeServiceConfig2WDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + bool ChangeServiceConfig2W( + NakedWin32Handle hService, + DWORD dwInfoLevel, + IntPtr lpInfo + ); + + [StructLayout(LayoutKind.Sequential)] + internal struct SERVICE_DESCRIPTIONW + { + [MarshalAs(UnmanagedType.LPWStr)] + internal string lpDescription; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct QUERY_SERVICE_CONFIG + { + internal uint dwServiceType; + internal uint dwStartType; + internal uint dwErrorControl; + [MarshalAs(UnmanagedType.LPWStr)] internal string lpBinaryPathName; + [MarshalAs(UnmanagedType.LPWStr)] internal string lpLoadOrderGroup; + internal uint dwTagId; + [MarshalAs(UnmanagedType.LPWStr)] internal string lpDependencies; + [MarshalAs(UnmanagedType.LPWStr)] internal string lpServiceStartName; + [MarshalAs(UnmanagedType.LPWStr)] internal string lpDisplayName; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SERVICE_DELAYED_AUTO_START_INFO + { + internal bool fDelayedAutostart; + } + + [DllImport(PinvokeDllNames.CreateServiceWDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern + NakedWin32Handle CreateServiceW( + NakedWin32Handle hSCManager, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpServiceName, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpDisplayName, + DWORD dwDesiredAccess, + DWORD dwServiceType, + DWORD dwStartType, + DWORD dwErrorControl, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpBinaryPathName, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpLoadOrderGroup, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpdwTagId, + [In] IntPtr lpDependencies, + [In, MarshalAs(UnmanagedType.LPWStr)] string lpServiceStartName, + [In] IntPtr lpPassword + ); + + [DllImport(PinvokeDllNames.SetServiceObjectSecurityDllName, CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern + bool SetServiceObjectSecurity( + NakedWin32Handle hSCManager, + System.Security.AccessControl.SecurityInfos dwSecurityInformation, + byte[] lpSecurityDescriptor + ); + + internal static bool QueryServiceConfig(NakedWin32Handle hService, out NativeMethods.QUERY_SERVICE_CONFIG configStructure) + { + IntPtr lpBuffer = IntPtr.Zero; + configStructure = default(NativeMethods.QUERY_SERVICE_CONFIG); + DWORD bufferSize, bufferSizeNeeded = 0; + bool status = NativeMethods.QueryServiceConfigW( + hSCManager: hService, + lpServiceConfig: lpBuffer, + cbBufSize: 0, + pcbBytesNeeded: out bufferSizeNeeded); + + if (!status && Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) + { + return status; + } + + try + { + lpBuffer = Marshal.AllocCoTaskMem((int)bufferSizeNeeded); + bufferSize = bufferSizeNeeded; + + status = NativeMethods.QueryServiceConfigW( + hService, + lpBuffer, + bufferSize, + out bufferSizeNeeded); + configStructure = (NativeMethods.QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(lpBuffer, typeof(NativeMethods.QUERY_SERVICE_CONFIG)); + } + finally + { + Marshal.FreeCoTaskMem(lpBuffer); + } + + return status; + } + + internal static bool QueryServiceConfig2(NakedWin32Handle hService, DWORD infolevel, out T configStructure) + { + IntPtr lpBuffer = IntPtr.Zero; + configStructure = default(T); + DWORD bufferSize, bufferSizeNeeded = 0; + + bool status = NativeMethods.QueryServiceConfig2W( + hService: hService, + dwInfoLevel: infolevel, + lpBuffer: lpBuffer, + cbBufSize: 0, + pcbBytesNeeded: out bufferSizeNeeded); + + if (!status && Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) + { + return status; + } + + try + { + lpBuffer = Marshal.AllocCoTaskMem((int)bufferSizeNeeded); + bufferSize = bufferSizeNeeded; + + status = NativeMethods.QueryServiceConfig2W( + hService, + infolevel, + lpBuffer, + bufferSize, + out bufferSizeNeeded); + configStructure = (T)Marshal.PtrToStructure(lpBuffer, typeof(T)); + } + finally + { + Marshal.FreeCoTaskMem(lpBuffer); + } + + return status; + } + + /// + /// Get appropriate win32 StartupType. + /// + /// + /// StartupType provided by the user. + /// + /// + /// Out parameter of the native win32 StartupType + /// + /// + /// If a supported StartupType is provided, funciton returns true, otherwise false. + /// + internal static bool TryGetNativeStartupType(ServiceStartupType StartupType, out DWORD dwStartType) + { + bool success = true; + dwStartType = NativeMethods.SERVICE_NO_CHANGE; + switch (StartupType) + { + case ServiceStartupType.Automatic: + case ServiceStartupType.AutomaticDelayedStart: + dwStartType = NativeMethods.SERVICE_AUTO_START; + break; + case ServiceStartupType.Manual: + dwStartType = NativeMethods.SERVICE_DEMAND_START; + break; + case ServiceStartupType.Disabled: + dwStartType = NativeMethods.SERVICE_DISABLED; + break; + case ServiceStartupType.InvalidValue: + dwStartType = NativeMethods.SERVICE_NO_CHANGE; + break; + default: + success = false; + break; + } + + return success; + } + + internal static ServiceStartupType GetServiceStartupType(ServiceStartMode startMode, bool delayedAutoStart) + { + ServiceStartupType result = ServiceStartupType.Disabled; + switch (startMode) + { + case ServiceStartMode.Automatic: + result = delayedAutoStart ? ServiceStartupType.AutomaticDelayedStart : ServiceStartupType.Automatic; + break; + case ServiceStartMode.Manual: + result = ServiceStartupType.Manual; + break; + case ServiceStartMode.Disabled: + result = ServiceStartupType.Disabled; + break; + } + + return result; + } + } + #endregion NativeMethods + + #region ServiceStartupType + /// + /// Enum for usage with StartupType. Automatic, Manual and Disabled index matched from System.ServiceProcess.ServiceStartMode + /// + public enum ServiceStartupType + { + /// Invalid service + InvalidValue = -1, + /// Automatic service + Automatic = 2, + /// Manual service + Manual = 3, + /// Disabled service + Disabled = 4, + /// Automatic (Delayed Start) service + AutomaticDelayedStart = 10 + } + #endregion ServiceStartupType +} + +#endif // Not built on Unix diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..49ab5d768f67b8ff20577bec5f5feba9b808e97a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Text; +using Microsoft.PowerShell.Commands.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the 'Set-Clipboard' cmdlet. + /// This cmdlet gets the content from system clipboard. + /// + [Cmdlet(VerbsCommon.Set, "Clipboard", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2109826")] + [Alias("scb")] + [OutputType(typeof(string))] + public class SetClipboardCommand : PSCmdlet + { + private readonly List _contentList = new(); + + /// + /// Property that sets clipboard content. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [System.Management.Automation.AllowNull] + [AllowEmptyCollection] + [AllowEmptyString] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Value { get; set; } + + /// + /// Property that sets append parameter. This will allow to append clipboard without clear it. + /// + [Parameter] + public SwitchParameter Append { get; set; } + + /// + /// Gets or sets if the values sent down the pipeline. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + /// + /// Gets or sets whether to use OSC52 escape sequence to set the clipboard of host instead of target. + /// + [Parameter] + [Alias("ToLocalhost")] + public SwitchParameter AsOSC52 { get; set; } + + /// + /// This method implements the BeginProcessing method for Set-Clipboard command. + /// + protected override void BeginProcessing() + { + _contentList.Clear(); + } + + /// + /// This method implements the ProcessRecord method for Set-Clipboard command. + /// + protected override void ProcessRecord() + { + if (Value != null) + { + _contentList.AddRange(Value); + + if (PassThru) + { + WriteObject(Value); + } + } + } + + /// + /// This method implements the EndProcessing method for Set-Clipboard command. + /// + protected override void EndProcessing() + { + SetClipboardContent(_contentList, Append); + } + + /// + /// Set the clipboard content. + /// + /// The content to store into the clipboard. + /// If true, appends to clipboard instead of overwriting. + private void SetClipboardContent(List contentList, bool append) + { + string setClipboardShouldProcessTarget; + + if ((contentList == null || contentList.Count == 0) && !append) + { + setClipboardShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, ClipboardResources.ClipboardCleared); + if (ShouldProcess(setClipboardShouldProcessTarget, "Set-Clipboard")) + { + Clipboard.SetText(string.Empty); + } + + return; + } + + StringBuilder content = new(); + if (append) + { + content.AppendLine(Clipboard.GetText()); + } + + if (contentList != null) + { + content.Append(string.Join(Environment.NewLine, contentList.ToArray(), 0, contentList.Count)); + } + + string verboseString = null; + if (contentList != null) + { + verboseString = contentList[0]; + if (verboseString.Length >= 20) + { + verboseString = verboseString.Substring(0, 20); + verboseString += " ..."; + } + } + + if (append) + { + setClipboardShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, ClipboardResources.AppendClipboardContent, verboseString); + } + else + { + setClipboardShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, ClipboardResources.SetClipboardContent, verboseString); + } + + if (ShouldProcess(setClipboardShouldProcessTarget, "Set-Clipboard")) + { + SetClipboardContent(content.ToString()); + } + } + + /// + /// Set the clipboard content. + /// + /// The content to store into the clipboard. + private void SetClipboardContent(string content) + { + if (!AsOSC52) + { + Clipboard.SetText(content); + return; + } + + var bytes = System.Text.Encoding.UTF8.GetBytes(content); + var encoded = System.Convert.ToBase64String(bytes); + var osc = $"\u001B]52;;{encoded}\u0007"; + + var message = new HostInformationMessage { Message = osc, NoNewLine = true }; + WriteInformation(message, new string[] { "PSHOST" }); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..44f4d904d33a6ac06c32d15d1e6f7eeac97c0d53 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to set the content of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Set, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097142")] + public class SetContentCommand : WriteContentCommandBase + { + #region protected members + + /// + /// Called by the base class before the streams are open for the path. + /// This override clears the content from the item. + /// + /// + /// The path to the items that will be opened for writing content. + /// + internal override void BeforeOpenStreams(string[] paths) + { + if (paths == null || paths.Length == 0) + { + throw PSTraceSource.NewArgumentNullException(nameof(paths)); + } + + CmdletProviderContext context = new(GetCurrentContext()); + + foreach (string path in paths) + { + try + { + InvokeProvider.Content.Clear(path, context); + context.ThrowFirstErrorOrDoNothing(true); + } + catch (PSNotSupportedException) + { + // If the provider doesn't support clear, that is fine. Continue + // on with the setting of the content. + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException) + { + // If the item is not found then there is nothing to clear so ignore this exception. + continue; + } + } + } + + /// + /// Makes the call to ShouldProcess with appropriate action and target strings. + /// + /// + /// The path to the item on which the content will be set. + /// + /// + /// True if the action should continue or false otherwise. + /// + internal override bool CallShouldProcess(string path) + { + string action = NavigationResources.SetContentAction; + + string target = StringUtil.Format(NavigationResources.SetContentTarget, path); + + return ShouldProcess(target, action); + } + #endregion protected members + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..7c5f43aad2b7925e0fa37be8196e906dbf9f2505 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to set the property of an item at a specified path. + /// + [Cmdlet(VerbsCommon.Set, "ItemProperty", DefaultParameterSetName = "propertyValuePathSet", SupportsShouldProcess = true, SupportsTransactions = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097147")] + public class SetItemPropertyCommand : PassThroughItemPropertyCommandBase + { + private const string propertyValuePathSet = "propertyValuePathSet"; + private const string propertyValueLiteralPathSet = "propertyValueLiteralPathSet"; + private const string propertyPSObjectPathSet = "propertyPSObjectPathSet"; + private const string propertyPSObjectLiteralPathSet = "propertyPSObjectLiteralPathSet"; + + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = propertyPSObjectPathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = propertyValuePathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get { return paths; } + + set { paths = value; } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = propertyValueLiteralPathSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = propertyPSObjectLiteralPathSet, + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return paths; + } + + set + { + base.SuppressWildcardExpansion = true; + paths = value; + } + } + + #region Property Value set + + /// + /// The name of the property to set. + /// + /// + /// This value type is determined by the InvokeProvider. + /// + [Parameter(Position = 1, ParameterSetName = propertyValuePathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, ParameterSetName = propertyValueLiteralPathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Alias("PSProperty")] + public string Name { get; set; } = string.Empty; + + /// + /// The value of the property to set. + /// + /// + /// This value type is determined by the InvokeProvider. + /// + [Parameter(Position = 2, ParameterSetName = propertyValuePathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 2, ParameterSetName = propertyValueLiteralPathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [AllowNull] + public object Value { get; set; } + + #endregion Property Value set + + #region Shell object set + + /// + /// A PSObject that contains the properties and values to be set. + /// + /// + [Parameter(ParameterSetName = propertyPSObjectPathSet, Mandatory = true, + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true)] + [Parameter(ParameterSetName = propertyPSObjectLiteralPathSet, Mandatory = true, + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true)] + public PSObject InputObject { get; set; } + + #endregion Shell object set + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + PSObject mshObject = null; + + switch (ParameterSetName) + { + case propertyValuePathSet: + case propertyValueLiteralPathSet: + if (!string.IsNullOrEmpty(Name)) + { + mshObject = new PSObject(); + mshObject.Properties.Add(new PSNoteProperty(Name, Value)); + } + + break; + + default: + mshObject = InputObject; + break; + } + + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Property.SetPropertyDynamicParameters(Path[0], mshObject, context); + } + + return InvokeProvider.Property.SetPropertyDynamicParameters(".", mshObject, context); + } + + #endregion Parameters + + #region parameter data + + #endregion parameter data + + #region Command code + + /// + /// Sets the content of the item at the specified path. + /// + protected override void ProcessRecord() + { + // Default to the CmdletProviderContext that will direct output to + // the pipeline. + + CmdletProviderContext currentCommandContext = CmdletProviderContext; + currentCommandContext.PassThru = PassThru; + + PSObject mshObject = null; + + switch (ParameterSetName) + { + case propertyValuePathSet: + case propertyValueLiteralPathSet: + mshObject = new PSObject(); + mshObject.Properties.Add(new PSNoteProperty(Name, Value)); + break; + + case propertyPSObjectPathSet: + mshObject = InputObject; + break; + + default: + Diagnostics.Assert( + false, + "One of the parameter sets should have been resolved or an error should have been thrown by the command processor"); + break; + } + + foreach (string path in Path) + { + try + { + InvokeProvider.Property.Set(path, mshObject, currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + } + } + #endregion Command code + + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..4b2deac8bef84fb336980504bd460e07aed92e44 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Management; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command to Set WMI Instance. + /// + [Cmdlet(VerbsCommon.Set, "WmiInstance", DefaultParameterSetName = "class", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113402", RemotingCapability = RemotingCapability.OwnedByCommand)] + public sealed class SetWmiInstance : WmiBaseCmdlet + { + #region Parameters + /// + /// The WMI Object to use. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] + public ManagementObject InputObject { get; set; } = null; + + /// + /// The WMI Path to use. + /// + [Parameter(ParameterSetName = "path", Mandatory = true)] + public string Path { get; set; } = null; + + /// + /// The WMI class to use. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] + public string Class { get; set; } = null; + + /// + /// The property name /value pair. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(Position = 2, ParameterSetName = "class")] + [Parameter(ParameterSetName = "object")] + [Alias("Args", "Property")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable Arguments { get; set; } = null; + + /// + /// The Flag to use. + /// + [Parameter] + public PutType PutType + { + get { return _putType; } + + set { _putType = value; flagSpecified = true; } + } + + #endregion Parameters + #region parameter data + internal bool flagSpecified = false; + private PutType _putType = PutType.None; + + #endregion parameter data + + #region Command code + /// + /// Create or modify WMI Instance given either path,class name or pipeline input. + /// + protected override void ProcessRecord() + { + if (this.AsJob) + { + RunAsJob("Set-WMIInstance"); + return; + } + + if (InputObject != null) + { + object result = null; + ManagementObject mObj = null; + try + { + PutOptions pOptions = new PutOptions(); + mObj = SetWmiInstanceGetPipelineObject(); + pOptions.Type = _putType; + if (mObj != null) + { + if (!ShouldProcess(mObj.Path.Path.ToString())) + { + return; + } + + mObj.Put(pOptions); + } + else + { + InvalidOperationException exp = new InvalidOperationException(); + throw exp; + } + + result = mObj; + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + + WriteObject(result); + } + else + { + ManagementPath mPath = null; + // If Class is specified only CreateOnly flag is supported + mPath = this.SetWmiInstanceBuildManagementPath(); + // If server name is specified loop through it. + if (mPath != null) + { + if (!(mPath.Server == "." && serverNameSpecified)) + { + string[] serverName = new string[] { mPath.Server }; + ComputerName = serverName; + } + } + + ConnectionOptions options = GetConnectionOption(); + object result = null; + ManagementObject mObject = null; + foreach (string name in ComputerName) + { + result = null; + try + { + mObject = this.SetWmiInstanceGetObject(mPath, name); + PutOptions pOptions = new PutOptions(); + pOptions.Type = _putType; + if (mObject != null) + { + if (!ShouldProcess(mObject.Path.Path.ToString())) + { + continue; + } + + mObject.Put(pOptions); + } + else + { + InvalidOperationException exp = new InvalidOperationException(); + throw exp; + } + + result = mObject; + } + catch (ManagementException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + catch (System.Runtime.InteropServices.COMException e) + { + ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); + WriteError(errorRecord); + } + + if (result != null) + { + WriteObject(result); + } + } + } + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..58dcfbd1daaa5bdeac44937d81bc71c0f2e125cc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that begins a transaction. + /// + [Cmdlet(VerbsLifecycle.Start, "Transaction", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135262")] + public class StartTransactionCommand : PSCmdlet + { + /// + /// The time, in minutes, before this transaction is rolled back + /// automatically. + /// + [Parameter] + [Alias("TimeoutMins")] + public int Timeout + { + get + { + return (int)_timeout.TotalMinutes; + } + + set + { + // The transactions constructor treats a timeout of + // zero as infinite. So we fudge it to be a bit longer. + if (value == 0) + _timeout = TimeSpan.FromTicks(1); + else + _timeout = TimeSpan.FromMinutes(value); + + _timeoutSpecified = true; + } + } + + private bool _timeoutSpecified = false; + private TimeSpan _timeout = TimeSpan.MinValue; + + /// + /// Gets or sets the flag to determine if this transaction can + /// be committed or rolled back independently of other transactions. + /// + [Parameter] + public SwitchParameter Independent + { + get { return _independent; } + + set { _independent = value; } + } + + private SwitchParameter _independent; + + /// + /// Gets or sets the rollback preference for this transaction. + /// + [Parameter] + public RollbackSeverity RollbackPreference + { + get { return _rollbackPreference; } + + set { _rollbackPreference = value; } + } + + private RollbackSeverity _rollbackPreference = RollbackSeverity.Error; + + /// + /// Creates a new transaction. + /// + protected override void EndProcessing() + { + if (ShouldProcess( + NavigationResources.TransactionResource, + NavigationResources.CreateAction)) + { + // Set the default timeout + if (!_timeoutSpecified) + { + // See if we're being invoked directly at the + // command line. In that case, set the timeout to infinite. + if (MyInvocation.CommandOrigin == CommandOrigin.Runspace) + { + _timeout = TimeSpan.MaxValue; + } + else + { + _timeout = TimeSpan.FromMinutes(30); + } + } + + // Create the new transaction + if (_independent) + { + this.Context.TransactionManager.CreateNew(_rollbackPreference, _timeout); + } + else + { + this.Context.TransactionManager.CreateOrJoin(_rollbackPreference, _timeout); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..2a4a453f8f7f8105019f5fa7c7d4d5ea194ba571 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -0,0 +1,1254 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "Test-Connection" cmdlet. + /// + [Cmdlet(VerbsDiagnostic.Test, "Connection", DefaultParameterSetName = DefaultPingParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097144")] + [OutputType(typeof(PingStatus), ParameterSetName = new string[] { DefaultPingParameterSet })] + [OutputType(typeof(PingStatus), ParameterSetName = new string[] { RepeatPingParameterSet, MtuSizeDetectParameterSet })] + [OutputType(typeof(bool), ParameterSetName = new string[] { DefaultPingParameterSet, RepeatPingParameterSet, TcpPortParameterSet })] + [OutputType(typeof(PingMtuStatus), ParameterSetName = new string[] { MtuSizeDetectParameterSet })] + [OutputType(typeof(int), ParameterSetName = new string[] { MtuSizeDetectParameterSet })] + [OutputType(typeof(TraceStatus), ParameterSetName = new string[] { TraceRouteParameterSet })] + [OutputType(typeof(TcpPortStatus), ParameterSetName = new string[] { TcpPortParameterSet })] + public class TestConnectionCommand : PSCmdlet, IDisposable + { + #region Parameter Set Names + private const string DefaultPingParameterSet = "DefaultPing"; + private const string RepeatPingParameterSet = "RepeatPing"; + private const string TraceRouteParameterSet = "TraceRoute"; + private const string TcpPortParameterSet = "TcpPort"; + private const string MtuSizeDetectParameterSet = "MtuSizeDetect"; + + #endregion + + #region Cmdlet Defaults + + // Count of pings sent to each trace route hop. Default mimics Windows' defaults. + // If this value changes, we need to update 'ConsoleTraceRouteReply' resource string. + private const uint DefaultTraceRoutePingCount = 3; + + // Default size for the send buffer. + private const int DefaultSendBufferSize = 32; + + private const int DefaultMaxHops = 128; + + private const string TestConnectionExceptionId = "TestConnectionException"; + + #endregion + + #region Private Fields + + private static readonly byte[] s_DefaultSendBuffer = Array.Empty(); + + private readonly CancellationTokenSource _dnsLookupCancel = new(); + + private bool _disposed; + + private Ping? _sender; + + #endregion + + #region Parameters + + /// + /// Gets or sets whether to do ping test. + /// Default is true. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + public SwitchParameter Ping { get; set; } = true; + + /// + /// Gets or sets whether to force use of IPv4 protocol. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TraceRouteParameterSet)] + [Parameter(ParameterSetName = MtuSizeDetectParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + public SwitchParameter IPv4 { get; set; } + + /// + /// Gets or sets whether to force use of IPv6 protocol. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TraceRouteParameterSet)] + [Parameter(ParameterSetName = MtuSizeDetectParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + public SwitchParameter IPv6 { get; set; } + + /// + /// Gets or sets whether to do reverse DNS lookup to get names for IP addresses. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TraceRouteParameterSet)] + [Parameter(ParameterSetName = MtuSizeDetectParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + public SwitchParameter ResolveDestination { get; set; } + + /// + /// Gets the source from which to run the selected test. + /// The default is localhost. + /// Remoting is not yet implemented internally in the cmdlet. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TraceRouteParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + public string Source { get; } = Dns.GetHostName(); + + /// + /// Gets or sets the number of times the Ping data packets can be forwarded by routers. + /// As gateways and routers transmit packets through a network, they decrement the Time-to-Live (TTL) + /// value found in the packet header. + /// The default (from Windows) is 128 hops. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TraceRouteParameterSet)] + [ValidateRange(1, DefaultMaxHops)] + [Alias("Ttl", "TimeToLive", "Hops")] + public int MaxHops { get; set; } = DefaultMaxHops; + + /// + /// Gets or sets the number of ping attempts. + /// The default (from Windows) is 4 times. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + [ValidateRange(ValidateRangeKind.Positive)] + public int Count { get; set; } = 4; + + /// + /// Gets or sets the delay between ping attempts. + /// The default (from Windows) is 1 second. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + [ValidateRange(ValidateRangeKind.Positive)] + public int Delay { get; set; } = 1; + + /// + /// Gets or sets the buffer size to send with the ping packet. + /// The default (from Windows) is 32 bytes. + /// Max value is 65500 (limitation imposed by Windows API). + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Alias("Size", "Bytes", "BS")] + [ValidateRange(0, 65500)] + public int BufferSize { get; set; } = DefaultSendBufferSize; + + /// + /// Gets or sets whether to prevent fragmentation of the ICMP packets. + /// Currently CoreFX not supports this on Unix. + /// + [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = RepeatPingParameterSet)] + public SwitchParameter DontFragment { get; set; } + + /// + /// Gets or sets whether to continue pinging until user presses Ctrl-C (or Int.MaxValue threshold reached). + /// + [Parameter(Mandatory = true, ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] + [Alias("Continuous")] + public SwitchParameter Repeat { get; set; } + + /// + /// Gets or sets whether to enable quiet output mode, reducing output to a single simple value only. + /// By default, PingStatus, PingMtuStatus, or TraceStatus objects are emitted. + /// With this switch, standard ping and -Traceroute returns only true / false, and -MtuSize returns an integer. + /// + [Parameter] + public SwitchParameter Quiet { get; set; } + + /// + /// Gets or sets whether to enable detailed output mode while running a TCP connection test. + /// Without this flag, the TCP test will return a boolean result. + /// + [Parameter(ParameterSetName = TcpPortParameterSet)] + public SwitchParameter Detailed; + + /// + /// Gets or sets the timeout value for an individual ping in seconds. + /// If a response is not received in this time, no response is assumed. + /// The default (from Windows) is 5 seconds. + /// + [Parameter] + [ValidateRange(ValidateRangeKind.Positive)] + public int TimeoutSeconds { get; set; } = 5; + + /// + /// Gets or sets the destination hostname or IP address. + /// + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("ComputerName")] + public string[]? TargetName { get; set; } + + /// + /// Gets or sets whether to detect Maximum Transmission Unit size. + /// When selected, only a single ping result is returned, indicating the maximum buffer size + /// the route to the destination can support without fragmenting the ICMP packets. + /// + [Parameter(Mandatory = true, ParameterSetName = MtuSizeDetectParameterSet)] + [Alias("MtuSizeDetect")] + public SwitchParameter MtuSize { get; set; } + + /// + /// Gets or sets whether to perform a traceroute test. + /// + [Parameter(Mandatory = true, ParameterSetName = TraceRouteParameterSet)] + public SwitchParameter Traceroute { get; set; } + + /// + /// Gets or sets whether to perform a TCP connection test. + /// + [ValidateRange(0, 65535)] + [Parameter(Mandatory = true, ParameterSetName = TcpPortParameterSet)] + public int TcpPort { get; set; } + + #endregion Parameters + + /// + /// BeginProcessing implementation for TestConnectionCommand. + /// Sets Count for different types of tests unless specified explicitly. + /// + protected override void BeginProcessing() + { + if (Repeat) + { + Count = int.MaxValue; + } + else if (ParameterSetName == TcpPortParameterSet) + { + SetCountForTcpTest(); + } + } + + /// + /// Process a connection test. + /// + protected override void ProcessRecord() + { + if (TargetName == null) + { + return; + } + + foreach (var targetName in TargetName) + { + if (MtuSize) + { + ProcessMTUSize(targetName); + } + else if (Traceroute) + { + ProcessTraceroute(targetName); + } + else if (ParameterSetName == TcpPortParameterSet) + { + ProcessConnectionByTCPPort(targetName); + } + else + { + // None of the switch parameters are true: handle default ping or -Repeat + ProcessPing(targetName); + } + } + } + + /// + /// On receiving the StopProcessing() request, the cmdlet will immediately cancel any in-progress ping request. + /// This allows a cancellation to occur during a ping request without having to wait for the timeout. + /// + protected override void StopProcessing() + { + _sender?.SendAsyncCancel(); + _dnsLookupCancel.Cancel(); + } + + #region ConnectionTest + + private void SetCountForTcpTest() + { + if (Repeat) + { + Count = int.MaxValue; + } + else if (!MyInvocation.BoundParameters.ContainsKey(nameof(Count))) + { + Count = 1; + } + } + + private void ProcessConnectionByTCPPort(string targetNameOrAddress) + { + if (!TryResolveNameOrAddress(targetNameOrAddress, out _, out IPAddress? targetAddress)) + { + if (Quiet.IsPresent) + { + WriteObject(false); + } + + return; + } + + int timeoutMilliseconds = TimeoutSeconds * 1000; + int delayMilliseconds = Delay * 1000; + + for (var i = 1; i <= Count; i++) + { + long latency = 0; + SocketError status = SocketError.SocketError; + + Stopwatch stopwatch = new Stopwatch(); + + using var client = new TcpClient(); + + try + { + stopwatch.Start(); + + if (client.ConnectAsync(targetAddress, TcpPort).Wait(timeoutMilliseconds, _dnsLookupCancel.Token)) + { + latency = stopwatch.ElapsedMilliseconds; + status = SocketError.Success; + } + else + { + status = SocketError.TimedOut; + } + } + catch (AggregateException ae) + { + ae.Handle((ex) => + { + if (ex is TaskCanceledException) + { + throw new PipelineStoppedException(); + } + if (ex is SocketException socketException) + { + status = socketException.SocketErrorCode; + return true; + } + else + { + return false; + } + }); + } + finally + { + stopwatch.Reset(); + } + + if (!Detailed.IsPresent) + { + WriteObject(status == SocketError.Success); + return; + } + else + { + WriteObject(new TcpPortStatus( + i, + Source, + targetNameOrAddress, + targetAddress, + TcpPort, + latency, + status == SocketError.Success, + status + )); + } + + if (i < Count) + { + Task.Delay(delayMilliseconds).Wait(_dnsLookupCancel.Token); + } + } + } + + #endregion ConnectionTest + + #region TracerouteTest + + private void ProcessTraceroute(string targetNameOrAddress) + { + byte[] buffer = GetSendBuffer(BufferSize); + + if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress)) + { + if (!Quiet.IsPresent) + { + WriteObject(false); + } + + return; + } + + int currentHop = 1; + PingOptions pingOptions = new(currentHop, DontFragment.IsPresent); + PingReply reply; + PingReply discoveryReply; + int timeout = TimeoutSeconds * 1000; + Stopwatch timer = new(); + + IPAddress hopAddress; + do + { + pingOptions.Ttl = currentHop; + +#if !UNIX + // Get intermediate hop target. This needs to be done first, so that we can target it properly + // and get useful responses. + var discoveryAttempts = 0; + bool addressIsValid = false; + do + { + discoveryReply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions); + discoveryAttempts++; + addressIsValid = !(discoveryReply.Address.Equals(IPAddress.Any) + || discoveryReply.Address.Equals(IPAddress.IPv6Any)); + } + while (discoveryAttempts <= DefaultTraceRoutePingCount && addressIsValid); + + // If we aren't able to get a valid address, just re-target the final destination of the trace. + hopAddress = addressIsValid ? discoveryReply.Address : targetAddress; +#else + // Unix Ping API returns nonsense "TimedOut" for ALL intermediate hops. No way around this + // issue for traceroutes as we rely on information (intermediate addresses, etc.) that is + // simply not returned to us by the API. + // The only supported states on Unix seem to be Success and TimedOut. Workaround is to + // keep targeting the final address; at the very least we will be able to tell the user + // the required number of hops to reach the destination. + hopAddress = targetAddress; + discoveryReply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions); +#endif + var hopAddressString = discoveryReply.Address.ToString(); + + string routerName = hopAddressString; + try + { + if (!TryResolveNameOrAddress(hopAddressString, out routerName, out _)) + { + routerName = hopAddressString; + } + } + catch + { + // Swallow hostname resolve exceptions and continue with traceroute + } + + // In traceroutes we don't use 'Count' parameter. + // If we change 'DefaultTraceRoutePingCount' we should change 'ConsoleTraceRouteReply' resource string. + for (uint i = 1; i <= DefaultTraceRoutePingCount; i++) + { + try + { + reply = SendCancellablePing(hopAddress, timeout, buffer, pingOptions, timer); + + if (!Quiet.IsPresent) + { + var status = new PingStatus( + Source, + routerName, + reply, + reply.Status == IPStatus.Success + ? reply.RoundtripTime + : timer.ElapsedMilliseconds, + + // If we use the empty buffer, then .NET actually uses a 32 byte buffer so we want to show + // as the result object the actual buffer size used instead of 0. + buffer.Length == 0 ? DefaultSendBufferSize : buffer.Length, + pingNum: i); + WriteObject(new TraceStatus( + currentHop, + status, + Source, + resolvedTargetName, + targetAddress)); + } + } + catch (PingException ex) + { + string message = StringUtil.Format( + TestConnectionResources.NoPingResult, + resolvedTargetName, + ex.Message); + Exception pingException = new PingException(message, ex.InnerException); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + resolvedTargetName); + WriteError(errorRecord); + + continue; + } + + // We use short delay because it is impossible DoS with trace route. + Thread.Sleep(50); + timer.Reset(); + } + + currentHop++; + } while (currentHop <= MaxHops + && (discoveryReply.Status == IPStatus.TtlExpired + || discoveryReply.Status == IPStatus.TimedOut)); + + if (Quiet.IsPresent) + { + WriteObject(currentHop <= MaxHops); + } + else if (currentHop > MaxHops) + { + var message = StringUtil.Format( + TestConnectionResources.MaxHopsExceeded, + resolvedTargetName, + MaxHops); + var pingException = new PingException(message); + WriteError(new ErrorRecord( + pingException, + TestConnectionExceptionId, + ErrorCategory.ConnectionError, + targetAddress)); + } + } + + #endregion TracerouteTest + + #region MTUSizeTest + private void ProcessMTUSize(string targetNameOrAddress) + { + PingReply? reply, replyResult = null; + if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress)) + { + if (Quiet.IsPresent) + { + WriteObject(-1); + } + + return; + } + + // Caution! Algorithm is sensitive to changing boundary values. + int HighMTUSize = 10000; + int CurrentMTUSize = 1473; + int LowMTUSize = targetAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 1280 : 68; + int timeout = TimeoutSeconds * 1000; + + PingReply? timeoutReply = null; + + try + { + PingOptions pingOptions = new(MaxHops, true); + int retry = 1; + + while (LowMTUSize < (HighMTUSize - 1)) + { + byte[] buffer = GetSendBuffer(CurrentMTUSize); + + WriteDebug(StringUtil.Format( + "LowMTUSize: {0}, CurrentMTUSize: {1}, HighMTUSize: {2}", + LowMTUSize, + CurrentMTUSize, + HighMTUSize)); + + reply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions); + + if (reply.Status == IPStatus.PacketTooBig || reply.Status == IPStatus.TimedOut) + { + HighMTUSize = CurrentMTUSize; + timeoutReply = reply; + retry = 1; + } + else if (reply.Status == IPStatus.Success) + { + LowMTUSize = CurrentMTUSize; + replyResult = reply; + retry = 1; + } + else + { + // If the host didn't reply, try again up to the 'Count' value. + if (retry >= Count) + { + string message = StringUtil.Format( + TestConnectionResources.NoPingResult, + targetAddress, + reply.Status.ToString()); + Exception pingException = new PingException(message); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + targetAddress); + WriteError(errorRecord); + return; + } + else + { + retry++; + continue; + } + } + + CurrentMTUSize = (LowMTUSize + HighMTUSize) / 2; + + // Prevent DoS attack. + Thread.Sleep(100); + } + } + catch (PingException ex) + { + string message = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, ex.Message); + Exception pingException = new PingException(message, ex.InnerException); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + targetAddress); + WriteError(errorRecord); + return; + } + + if (Quiet.IsPresent) + { + WriteObject(CurrentMTUSize); + } + else + { + if (replyResult is null) + { + if (timeoutReply is not null) + { + Exception timeoutException = new TimeoutException(targetAddress.ToString()); + ErrorRecord errorRecord = new( + timeoutException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + timeoutReply); + WriteError(errorRecord); + } + else + { + ArgumentNullException.ThrowIfNull(replyResult); + } + } + else + { + WriteObject(new PingMtuStatus( + Source, + resolvedTargetName, + replyResult, + CurrentMTUSize)); + } + + } + } + + #endregion MTUSizeTest + + #region PingTest + + private void ProcessPing(string targetNameOrAddress) + { + if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress)) + { + if (Quiet.IsPresent) + { + WriteObject(false); + } + + return; + } + + bool quietResult = true; + byte[] buffer = GetSendBuffer(BufferSize); + + PingReply reply; + PingOptions pingOptions = new(MaxHops, DontFragment.IsPresent); + int timeout = TimeoutSeconds * 1000; + int delay = Delay * 1000; + + for (int i = 1; i <= Count; i++) + { + try + { + reply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions); + } + catch (PingException ex) + { + string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message); + Exception pingException = new PingException(message, ex.InnerException); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + resolvedTargetName); + WriteError(errorRecord); + + quietResult = false; + continue; + } + + if (Quiet.IsPresent) + { + // Return 'true' only if all pings have completed successfully. + quietResult &= reply.Status == IPStatus.Success; + } + else + { + WriteObject(new PingStatus( + Source, + resolvedTargetName, + reply, + reply.RoundtripTime, + buffer.Length == 0 ? DefaultSendBufferSize : buffer.Length, + pingNum: (uint)i)); + } + + // Delay between pings, but not after last ping. + if (i < Count && Delay > 0) + { + Thread.Sleep(delay); + } + } + + if (Quiet.IsPresent) + { + WriteObject(quietResult); + } + } + + #endregion PingTest + + private bool TryResolveNameOrAddress( + string targetNameOrAddress, + out string resolvedTargetName, + [NotNullWhen(true)] + out IPAddress? targetAddress) + { + resolvedTargetName = targetNameOrAddress; + + IPHostEntry hostEntry; + if (IPAddress.TryParse(targetNameOrAddress, out targetAddress)) + { + if ((IPv4 && targetAddress.AddressFamily != AddressFamily.InterNetwork) + || (IPv6 && targetAddress.AddressFamily != AddressFamily.InterNetworkV6)) + { + string message = StringUtil.Format( + TestConnectionResources.NoPingResult, + resolvedTargetName, + TestConnectionResources.TargetAddressAbsent); + Exception pingException = new PingException(message, null); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + resolvedTargetName); + WriteError(errorRecord); + return false; + } + + if (ResolveDestination) + { + hostEntry = GetCancellableHostEntry(targetNameOrAddress); + resolvedTargetName = hostEntry.HostName; + } + else + { + resolvedTargetName = targetAddress.ToString(); + } + } + else + { + try + { + hostEntry = GetCancellableHostEntry(targetNameOrAddress); + + if (ResolveDestination) + { + resolvedTargetName = hostEntry.HostName; + hostEntry = GetCancellableHostEntry(hostEntry.HostName); + } + } + catch (PipelineStoppedException) + { + throw; + } + catch (Exception ex) + { + if (!Quiet.IsPresent) + { + string message = StringUtil.Format( + TestConnectionResources.NoPingResult, + resolvedTargetName, + TestConnectionResources.CannotResolveTargetName); + Exception pingException = new PingException(message, ex); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + resolvedTargetName); + WriteError(errorRecord); + } + + return false; + } + + if (IPv6 || IPv4) + { + targetAddress = GetHostAddress(hostEntry); + + if (targetAddress == null) + { + string message = StringUtil.Format( + TestConnectionResources.NoPingResult, + resolvedTargetName, + TestConnectionResources.TargetAddressAbsent); + Exception pingException = new PingException(message, null); + ErrorRecord errorRecord = new( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + resolvedTargetName); + WriteError(errorRecord); + return false; + } + } + else + { + targetAddress = hostEntry.AddressList[0]; + } + } + + return true; + } + + private IPHostEntry GetCancellableHostEntry(string targetNameOrAddress) + { + var task = Dns.GetHostEntryAsync(targetNameOrAddress); + var waitHandles = new[] { ((IAsyncResult)task).AsyncWaitHandle, _dnsLookupCancel.Token.WaitHandle }; + + // WaitAny() returns the index of the first signal it gets; 1 is our cancellation token. + if (WaitHandle.WaitAny(waitHandles) == 1) + { + throw new PipelineStoppedException(); + } + + return task.GetAwaiter().GetResult(); + } + + private IPAddress? GetHostAddress(IPHostEntry hostEntry) + { + AddressFamily addressFamily = IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; + + foreach (var address in hostEntry.AddressList) + { + if (address.AddressFamily == addressFamily) + { + return address; + } + } + + return null; + } + + // Users most often use the default buffer size so we cache the buffer. + // Creates and fills a send buffer. This follows the ping.exe and CoreFX model. + private static byte[] GetSendBuffer(int bufferSize) + { + if (bufferSize == DefaultSendBufferSize) + { + return s_DefaultSendBuffer; + } + + byte[] sendBuffer = new byte[bufferSize]; + + for (int i = 0; i < bufferSize; i++) + { + sendBuffer[i] = (byte)((int)'a' + i % 23); + } + + return sendBuffer; + } + + /// + /// IDisposable implementation, dispose of any disposable resources created by the cmdlet. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Implementation of IDisposable for both manual Dispose() and finalizer-called disposal of resources. + /// + /// + /// Specified as true when Dispose() was called, false if this is called from the finalizer. + /// + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _sender?.Dispose(); + _dnsLookupCancel.Dispose(); + } + + _disposed = true; + } + } + + // Uses the SendAsync() method to send pings, so that Ctrl+C can halt the request early if needed. + private PingReply SendCancellablePing( + IPAddress targetAddress, + int timeout, + byte[] buffer, + PingOptions pingOptions, + Stopwatch? timer = null) + { + try + { + _sender = new Ping(); + + timer?.Start(); + // 'SendPingAsync' always uses the default synchronization context (threadpool). + // This is what we want to avoid the deadlock resulted by async work being scheduled back to the + // pipeline thread due to a change of the current synchronization context of the pipeline thread. + return _sender.SendPingAsync(targetAddress, timeout, buffer, pingOptions).GetAwaiter().GetResult(); + } + catch (PingException ex) when (ex.InnerException is TaskCanceledException) + { + // The only cancellation we have implemented is on pipeline stops via StopProcessing(). + throw new PipelineStoppedException(); + } + finally + { + timer?.Stop(); + _sender?.Dispose(); + _sender = null; + } + } + + /// + /// The class contains information about the TCP connection test. + /// + public class TcpPortStatus + { + /// + /// Initializes a new instance of the class. + /// + /// The number of this test. + /// The source machine name or IP of the test. + /// The target machine name or IP of the test. + /// The resolved IP from the target. + /// The port used for the connection. + /// The latency of the test. + /// If the test connection succeeded. + /// Status of the underlying socket. + internal TcpPortStatus(int id, string source, string target, IPAddress targetAddress, int port, long latency, bool connected, SocketError status) + { + Id = id; + Source = source; + Target = target; + TargetAddress = targetAddress; + Port = port; + Latency = latency; + Connected = connected; + Status = status; + } + + /// + /// Gets and sets the count of the test. + /// + public int Id { get; set; } + + /// + /// Gets the source from which the test was sent. + /// + public string Source { get; } + + /// + /// Gets the target name. + /// + public string Target { get; } + + /// + /// Gets the resolved address for the target. + /// + public IPAddress TargetAddress { get; } + + /// + /// Gets the port used for the test. + /// + public int Port { get; } + + /// + /// Gets or sets the latancy of the connection. + /// + public long Latency { get; set; } + + /// + /// Gets or sets the result of the test. + /// + public bool Connected { get; set; } + + /// + /// Gets or sets the state of the socket after the test. + /// + public SocketError Status { get; set; } + } + + /// + /// The class contains information about the source, the destination and ping results. + /// + public class PingStatus + { + /// + /// Initializes a new instance of the class. + /// This constructor allows manually specifying the initial values for the cases where the PingReply + /// object may be missing some information, specifically in the instances where PingReply objects are + /// utilised to perform a traceroute. + /// + /// The source machine name or IP of the ping. + /// The destination machine name of the ping. + /// The response from the ping attempt. + /// The latency of the ping. + /// The buffer size. + /// The sequence number in the sequence of pings to the hop point. + internal PingStatus( + string source, + string destination, + PingReply reply, + long latency, + int bufferSize, + uint pingNum) + : this(source, destination, reply, pingNum) + { + _bufferSize = bufferSize; + _latency = latency; + } + + /// + /// Initializes a new instance of the class. + /// + /// The source machine name or IP of the ping. + /// The destination machine name of the ping. + /// The response from the ping attempt. + /// The sequence number of the ping in the sequence of pings to the target. + internal PingStatus(string source, string destination, PingReply reply, uint pingNum) + { + Ping = pingNum; + Reply = reply; + Source = source; + Destination = destination; + } + + // These values can be set manually to skirt issues with the Ping API on Unix platforms + // so that we can return meaningful known data that is discarded by the API. + private readonly int _bufferSize = -1; + + private readonly long _latency = -1; + + /// + /// Gets the sequence number of this ping in the sequence of pings to the + /// + public uint Ping { get; } + + /// + /// Gets the source from which the ping was sent. + /// + public string Source { get; } + + /// + /// Gets the destination which was pinged. + /// + public string Destination { get; } + + /// + /// Gets the target address of the ping. + /// + public IPAddress? Address { get => Reply.Status == IPStatus.Success ? Reply.Address : null; } + + /// + /// Gets the target address of the ping if one is available, or "*" if it is not. + /// + public string DisplayAddress { get => Address?.ToString() ?? "*"; } + + /// + /// Gets the roundtrip time of the ping in milliseconds. + /// + public long Latency { get => _latency >= 0 ? _latency : Reply.RoundtripTime; } + + /// + /// Gets the returned status of the ping. + /// + public IPStatus Status { get => Reply.Status; } + + /// + /// Gets the size in bytes of the buffer data sent in the ping. + /// + public int BufferSize { get => _bufferSize >= 0 ? _bufferSize : Reply.Buffer.Length; } + + /// + /// Gets the reply object from this ping. + /// + public PingReply Reply { get; } + } + + /// + /// The class contains information about the source, the destination and ping results. + /// + public class PingMtuStatus : PingStatus + { + /// + /// Initializes a new instance of the class. + /// + /// The source machine name or IP of the ping. + /// The destination machine name of the ping. + /// The response from the ping attempt. + /// The buffer size from the successful ping attempt. + internal PingMtuStatus(string source, string destination, PingReply reply, int bufferSize) + : base(source, destination, reply, 1) + { + MtuSize = bufferSize; + } + + /// + /// Gets the maximum transmission unit size on the network path between the source and destination. + /// + public int MtuSize { get; } + } + + /// + /// The class contains an information about a trace route attempt. + /// + public class TraceStatus + { + /// + /// Initializes a new instance of the class. + /// + /// The hop number of this trace hop. + /// The PingStatus response from this trace hop. + /// The source computer name or IP address of the traceroute. + /// The target destination of the traceroute. + /// The target IPAddress of the overall traceroute. + internal TraceStatus( + int hop, + PingStatus status, + string source, + string destination, + IPAddress destinationAddress) + { + _status = status; + Hop = hop; + Source = source; + Target = destination; + TargetAddress = destinationAddress; + + if (_status.Address == IPAddress.Any + || _status.Address == IPAddress.IPv6Any) + { + Hostname = null; + } + else + { + Hostname = _status.Destination; + } + } + + private readonly PingStatus _status; + + /// + /// Gets the number of the current hop / router. + /// + public int Hop { get; } + + /// + /// Gets the hostname of the current hop point. + /// + /// + public string? Hostname { get; } + + /// + /// Gets the sequence number of the ping in the sequence of pings to the hop point. + /// + public uint Ping { get => _status.Ping; } + + /// + /// Gets the IP address of the current hop point. + /// + public IPAddress? HopAddress { get => _status.Address; } + + /// + /// Gets the latency values of each ping to the current hop point. + /// + public long Latency { get => _status.Latency; } + + /// + /// Gets the status of the traceroute hop. + /// + public IPStatus Status { get => _status.Status; } + + /// + /// Gets the source address of the traceroute command. + /// + public string Source { get; } + + /// + /// Gets the final destination hostname of the trace. + /// + public string Target { get; } + + /// + /// Gets the final destination IP address of the trace. + /// + public IPAddress TargetAddress { get; } + + /// + /// Gets the raw PingReply object received from the ping to this hop point. + /// + public PingReply Reply { get => _status.Reply; } + } + + /// + /// Finalizes an instance of the class. + /// + ~TestConnectionCommand() + { + Dispose(disposing: false); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..50765c0e0aee1064695511212f90273fcbe8fe06 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The valid values for the -PathType parameter for test-path. + /// + public enum TestPathType + { + /// + /// If the item at the path exists, true will be returned. + /// + Any, + + /// + /// If the item at the path exists and is a container, true will be returned. + /// + Container, + + /// + /// If the item at the path exists and is not a container, true will be returned. + /// + Leaf + } + + /// + /// A command to determine if an item exists at a specified path. + /// + [Cmdlet(VerbsDiagnostic.Test, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097057")] + [OutputType(typeof(bool))] + public class TestPathCommand : CoreCommandWithCredentialsBase + { + #region Parameters + + /// + /// Gets or sets the path parameter to the command. + /// + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [AllowNull] + [AllowEmptyCollection] + [AllowEmptyString] + public string[] Path + { + get { return _paths; } + + set { _paths = value; } + } + + /// + /// Gets or sets the literal path parameter to the command. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + [AllowNull] + [AllowEmptyCollection] + [AllowEmptyString] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + base.SuppressWildcardExpansion = true; + _paths = value; + } + } + + /// + /// Gets or sets the filter property. + /// + [Parameter] + public override string Filter + { + get { return base.Filter; } + + set { base.Filter = value; } + } + + /// + /// Gets or sets the include property. + /// + [Parameter] + public override string[] Include + { + get { return base.Include; } + + set { base.Include = value; } + } + + /// + /// Gets or sets the exclude property. + /// + [Parameter] + public override string[] Exclude + { + get { return base.Exclude; } + + set { base.Exclude = value; } + } + + /// + /// Gets or sets the isContainer property. + /// + [Parameter] + [Alias("Type")] + public TestPathType PathType { get; set; } = TestPathType.Any; + + /// + /// Gets or sets the IsValid parameter. + /// + [Parameter] + public SwitchParameter IsValid { get; set; } = new SwitchParameter(); + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + object result = null; + + if (!IsValid) + { + if (Path != null && Path.Length > 0 && Path[0] != null) + { + result = InvokeProvider.Item.ItemExistsDynamicParameters(Path[0], context); + } + else + { + result = InvokeProvider.Item.ItemExistsDynamicParameters(".", context); + } + } + + return result; + } + + #endregion Parameters + + #region parameter data + + /// + /// The path to the item to ping. + /// + private string[] _paths; + + #endregion parameter data + + #region Command code + + /// + /// Determines if an item at the specified path exists. + /// + protected override void ProcessRecord() + { + if (_paths == null || _paths.Length == 0) + { + WriteError(new ErrorRecord( + new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), + "NullPathNotPermitted", + ErrorCategory.InvalidArgument, + Path)); + + return; + } + + CmdletProviderContext currentContext = CmdletProviderContext; + + foreach (string path in _paths) + { + bool result = false; + + if (string.IsNullOrWhiteSpace(path)) + { + if (path is null) + { + WriteError(new ErrorRecord( + new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), + "NullPathNotPermitted", + ErrorCategory.InvalidArgument, + Path)); + } + else + { + WriteObject(result); + } + + continue; + } + + try + { + if (IsValid) + { + result = SessionState.Path.IsValid(path, currentContext); + } + else + { + result = InvokeProvider.Item.Exists(path, currentContext); + + if (this.PathType == TestPathType.Container) + { + result &= InvokeProvider.Item.IsContainer(path, currentContext); + } + else if (this.PathType == TestPathType.Leaf) + { + result &= !InvokeProvider.Item.IsContainer(path, currentContext); + } + } + } + + // Any of the known exceptions means the path does not exist. + catch (PSNotSupportedException) + { + } + catch (DriveNotFoundException) + { + } + catch (ProviderNotFoundException) + { + } + catch (ItemNotFoundException) + { + } + + WriteObject(result); + } + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..22a50e41176842e078673e047ad63a9f68f151cb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs @@ -0,0 +1,795 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Runtime.InteropServices; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A cmdlet to retrieve time zone information. + /// + [Cmdlet(VerbsCommon.Get, "TimeZone", DefaultParameterSetName = "Name", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096904")] + [OutputType(typeof(TimeZoneInfo))] + [Alias("gtz")] + public class GetTimeZoneCommand : PSCmdlet + { + #region Parameters + + /// + /// A list of the local time zone ids that the cmdlet should look up. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Id")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Id { get; set; } + + /// + /// Specifies that the cmdlet should produce a collection of the + /// TimeZoneInfo objects that are available on the system. + /// + [Parameter(Mandatory = true, ParameterSetName = "ListAvailable")] + public SwitchParameter ListAvailable { get; set; } + + /// + /// A list of the local time zone names that the cmdlet should look up. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "Name")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name { get; set; } + + #endregion Parameters + + /// + /// Implementation of the ProcessRecord method for Get-TimeZone. + /// + protected override void ProcessRecord() + { + // make sure we've got the latest time zone settings + TimeZoneInfo.ClearCachedData(); + + if (ListAvailable) + { + // output the list of all available time zones + WriteObject(TimeZoneInfo.GetSystemTimeZones(), true); + } + else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) + { + // lookup each time zone id + foreach (string tzid in Id) + { + try + { + WriteObject(TimeZoneInfo.FindSystemTimeZoneById(tzid)); + } + catch (TimeZoneNotFoundException e) + { + WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, + ErrorCategory.InvalidArgument, "Id")); + } + } + } + else // ParameterSetName == "Name" + { + if (Name != null) + { + // lookup each time zone name (or wildcard pattern) + foreach (string tzname in Name) + { + TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(tzname); + if (timeZones.Length > 0) + { + // manually process each object in the array, so if there is only a single + // entry then the returned type is TimeZoneInfo and not TimeZoneInfo[], and + // it can be pipelined to Set-TimeZone more easily + foreach (TimeZoneInfo timeZone in timeZones) + { + WriteObject(timeZone); + } + } + else + { + string message = string.Format(CultureInfo.InvariantCulture, + TimeZoneResources.TimeZoneNameNotFound, tzname); + + Exception e = new TimeZoneNotFoundException(message); + WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, + ErrorCategory.InvalidArgument, "Name")); + } + } + } + else + { + // return the current system local time zone + WriteObject(TimeZoneInfo.Local); + } + } + } + } + +#if !UNIX + + /// + /// A cmdlet to set the system's local time zone. + /// + [Cmdlet(VerbsCommon.Set, "TimeZone", + SupportsShouldProcess = true, + DefaultParameterSetName = "Name", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097056")] + [OutputType(typeof(TimeZoneInfo))] + [Alias("stz")] + public class SetTimeZoneCommand : PSCmdlet + { + #region string constants + + private const string TimeZoneTarget = "Local System"; + + #endregion string constants + + #region Parameters + + /// + /// The name of the local time zone that the system should use. + /// + [Parameter(Mandatory = true, ParameterSetName = "Id", ValueFromPipelineByPropertyName = true)] + public string Id { get; set; } + + /// + /// A TimeZoneInfo object identifying the local time zone that the system should use. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "InputObject", ValueFromPipeline = true)] + public TimeZoneInfo InputObject { get; set; } + + /// + /// The name of the local time zone that the system should use. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Name")] + public string Name { get; set; } + + /// + /// Request return of the new local time zone as a TimeZoneInfo object. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + #endregion Parameters + + /// + /// Implementation of the ProcessRecord method for Set-TimeZone. + /// + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "Since Name is not a parameter of this method, it confuses FXCop. It is the appropriate value for the exception.")] + protected override void ProcessRecord() + { + // make sure we've got fresh data, in case the requested time zone was added + // to the system (registry) after our process was started + TimeZoneInfo.ClearCachedData(); + + // acquire a TimeZoneInfo if one wasn't supplied. + if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) + { + try + { + InputObject = TimeZoneInfo.FindSystemTimeZoneById(Id); + } + catch (TimeZoneNotFoundException e) + { + ThrowTerminatingError(new ErrorRecord( + e, + TimeZoneHelper.TimeZoneNotFoundError, + ErrorCategory.InvalidArgument, + "Id")); + } + } + else if (this.ParameterSetName.Equals("Name", StringComparison.OrdinalIgnoreCase)) + { + // lookup the time zone name and make sure we have one (and only one) match + TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(Name); + if (timeZones.Length == 0) + { + string message = string.Format(CultureInfo.InvariantCulture, + TimeZoneResources.TimeZoneNameNotFound, Name); + Exception e = new TimeZoneNotFoundException(message); + ThrowTerminatingError(new ErrorRecord(e, + TimeZoneHelper.TimeZoneNotFoundError, + ErrorCategory.InvalidArgument, + "Name")); + } + else if (timeZones.Length > 1) + { + string message = string.Format(CultureInfo.InvariantCulture, + TimeZoneResources.MultipleMatchingTimeZones, Name); + ThrowTerminatingError(new ErrorRecord( + new PSArgumentException(message, "Name"), + TimeZoneHelper.MultipleMatchingTimeZonesError, + ErrorCategory.InvalidArgument, + "Name")); + } + else + { + InputObject = timeZones[0]; + } + } + else // ParameterSetName == "InputObject" + { + try + { + // a TimeZoneInfo object was supplied, so use it to make sure we can find + // a backing system time zone, otherwise it's an error condition + InputObject = TimeZoneInfo.FindSystemTimeZoneById(InputObject.Id); + } + catch (TimeZoneNotFoundException e) + { + ThrowTerminatingError(new ErrorRecord( + e, + TimeZoneHelper.TimeZoneNotFoundError, + ErrorCategory.InvalidArgument, + "InputObject")); + } + } + + if (ShouldProcess(TimeZoneTarget)) + { + bool acquireAccess = false; + try + { + // check to see if permission to set the time zone is already enabled for this process + if (!HasAccess) + { + // acquire permissions to set the timezone + SetAccessToken(true); + acquireAccess = true; + } + } + catch (Win32Exception e) + { + ThrowTerminatingError(new ErrorRecord(e, + TimeZoneHelper.InsufficientPermissionsError, + ErrorCategory.PermissionDenied, null)); + } + + try + { + // construct and populate a new DYNAMIC_TIME_ZONE_INFORMATION structure + NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new(); + dtzi.Bias -= (int)InputObject.BaseUtcOffset.TotalMinutes; + dtzi.StandardName = InputObject.StandardName; + dtzi.DaylightName = InputObject.DaylightName; + dtzi.TimeZoneKeyName = InputObject.Id; + + // Request time zone transition information for the current year + NativeMethods.TIME_ZONE_INFORMATION tzi = new(); + if (!NativeMethods.GetTimeZoneInformationForYear((ushort)DateTime.Now.Year, ref dtzi, ref tzi)) + { + ThrowWin32Error(); + } + + // copy over the transition times + dtzi.StandardBias = tzi.StandardBias; + dtzi.StandardDate = tzi.StandardDate; + dtzi.DaylightBias = tzi.DaylightBias; + dtzi.DaylightDate = tzi.DaylightDate; + + // set the new local time zone for the system + if (!NativeMethods.SetDynamicTimeZoneInformation(ref dtzi)) + { + ThrowWin32Error(); + } + + // broadcast a WM_SETTINGCHANGE notification message to all top-level windows so that they + // know to update their notion of the current system time (and time zone) if applicable + int result = 0; + NativeMethods.SendMessageTimeout((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, + (IntPtr)0, "intl", NativeMethods.SMTO_ABORTIFHUNG, 5000, ref result); + + // clear the time zone data or this PowerShell session + // will not recognize the new time zone settings + TimeZoneInfo.ClearCachedData(); + + if (PassThru.IsPresent) + { + // return the TimeZoneInfo object for the (new) current local time zone + WriteObject(TimeZoneInfo.Local); + } + } + catch (Win32Exception e) + { + ThrowTerminatingError(new ErrorRecord(e, + TimeZoneHelper.SetTimeZoneFailedError, + ErrorCategory.FromStdErr, null)); + } + finally + { + if (acquireAccess) + { + // reset the permissions + SetAccessToken(false); + } + } + } + else + { + if (PassThru.IsPresent) + { + // show the user the time zone settings that would have been used. + WriteObject(InputObject); + } + } + } + + #region Helper functions + + /// + /// True if the current process has access to change the time zone setting. + /// + protected bool HasAccess + { + get + { + bool hasAccess = false; + + // open the access token for the current process + IntPtr hToken = IntPtr.Zero; + IntPtr hProcess = NativeMethods.GetCurrentProcess(); + if (!NativeMethods.OpenProcessToken(hProcess, + NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, ref hToken)) + { + ThrowWin32Error(); + } + + try + { + // setup the privileges being checked + NativeMethods.PRIVILEGE_SET ps = new() + { + PrivilegeCount = 1, + Control = 1, + Luid = 0, + Attributes = NativeMethods.SE_PRIVILEGE_ENABLED, + }; + + // lookup the Luid of the SeTimeZonePrivilege + if (!NativeMethods.LookupPrivilegeValue(null, NativeMethods.SE_TIME_ZONE_NAME, ref ps.Luid)) + { + ThrowWin32Error(); + } + + // set the privilege for the open access token + if (!NativeMethods.PrivilegeCheck(hToken, ref ps, ref hasAccess)) + { + ThrowWin32Error(); + } + } + finally + { + NativeMethods.CloseHandle(hToken); + } + + return (hasAccess); + } + } + + /// + /// Set the SeTimeZonePrivilege, which controls access to the SetDynamicTimeZoneInformation API. + /// + /// Set to true to enable (or false to disable) the privilege. + protected void SetAccessToken(bool enable) + { + // open the access token for the current process + IntPtr hToken = IntPtr.Zero; + IntPtr hProcess = NativeMethods.GetCurrentProcess(); + if (!NativeMethods.OpenProcessToken(hProcess, + NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, ref hToken)) + { + ThrowWin32Error(); + } + + try + { + // setup the privileges being requested + NativeMethods.TOKEN_PRIVILEGES tp = new() + { + PrivilegeCount = 1, + Luid = 0, + Attributes = (enable ? NativeMethods.SE_PRIVILEGE_ENABLED : 0), + }; + + // lookup the Luid of the SeTimeZonePrivilege + if (!NativeMethods.LookupPrivilegeValue(null, NativeMethods.SE_TIME_ZONE_NAME, ref tp.Luid)) + { + ThrowWin32Error(); + } + + // set the privilege for the open access token + if (!NativeMethods.AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero)) + { + ThrowWin32Error(); + } + } + finally + { + NativeMethods.CloseHandle(hToken); + } + } + + /// + /// Get the Win32 error code from GetLastError and throw an exception. + /// + protected void ThrowWin32Error() + { + int error = Marshal.GetLastWin32Error(); + throw new Win32Exception(error); + } + + #endregion Helper functions + + #region Win32 interop helper + + internal static class NativeMethods + { + #region Native DLL locations + + private const string SetDynamicTimeZoneApiDllName = "api-ms-win-core-timezone-l1-1-0.dll"; + private const string GetTimeZoneInformationForYearApiDllName = "api-ms-win-core-timezone-l1-1-0.dll"; + private const string GetCurrentProcessApiDllName = "api-ms-win-downlevel-kernel32-l1-1-0.dll"; + private const string OpenProcessTokenApiDllName = "api-ms-win-downlevel-advapi32-l1-1-1.dll"; + private const string LookupPrivilegeTokenApiDllName = "api-ms-win-downlevel-advapi32-l4-1-0.dll"; + private const string PrivilegeCheckApiDllName = "api-ms-win-downlevel-advapi32-l1-1-1.dll"; + private const string AdjustTokenPrivilegesApiDllName = "api-ms-win-downlevel-advapi32-l1-1-1.dll"; + private const string CloseHandleApiDllName = "api-ms-win-downlevel-kernel32-l1-1-0.dll"; + private const string SendMessageTimeoutApiDllName = "ext-ms-win-rtcore-ntuser-window-ext-l1-1-0.dll"; + + #endregion Native DLL locations + + #region Win32 SetDynamicTimeZoneInformation imports + + /// + /// Used to marshal win32 SystemTime structure to managed code layer. + /// + [StructLayout(LayoutKind.Sequential)] + public struct SystemTime + { + /// + /// The year. + /// + [MarshalAs(UnmanagedType.U2)] + public short Year; + /// + /// The month. + /// + [MarshalAs(UnmanagedType.U2)] + public short Month; + /// + /// The day of the week. + /// + [MarshalAs(UnmanagedType.U2)] + public short DayOfWeek; + /// + /// The day of the month. + /// + [MarshalAs(UnmanagedType.U2)] + public short Day; + /// + /// The hour. + /// + [MarshalAs(UnmanagedType.U2)] + public short Hour; + /// + /// The minute. + /// + [MarshalAs(UnmanagedType.U2)] + public short Minute; + /// + /// The second. + /// + [MarshalAs(UnmanagedType.U2)] + public short Second; + /// + /// The millisecond. + /// + [MarshalAs(UnmanagedType.U2)] + public short Milliseconds; + } + + /// + /// Used to marshal win32 DYNAMIC_TIME_ZONE_INFORMATION structure to managed code layer. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct DYNAMIC_TIME_ZONE_INFORMATION + { + /// + /// The current bias for local time translation on this computer, in minutes. + /// + [MarshalAs(UnmanagedType.I4)] + public int Bias; + /// + /// A description for standard time. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] + public string StandardName; + /// + /// A SystemTime structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. + /// + public SystemTime StandardDate; + /// + /// The bias value to be used during local time translations that occur during standard time. + /// + [MarshalAs(UnmanagedType.I4)] + public int StandardBias; + /// + /// A description for daylight saving time (DST). + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] + public string DaylightName; + /// + /// A SystemTime structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this operating system. + /// + public SystemTime DaylightDate; + /// + /// The bias value to be used during local time translations that occur during daylight saving time. + /// + [MarshalAs(UnmanagedType.I4)] + public int DaylightBias; + /// + /// The name of the time zone registry key on the local computer. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x80)] + public string TimeZoneKeyName; + /// + /// Indicates whether dynamic daylight saving time is disabled. + /// + [MarshalAs(UnmanagedType.U1)] + public bool DynamicDaylightTimeDisabled; + } + + /// + /// Used to marshal win32 TIME_ZONE_INFORMATION structure to managed code layer. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct TIME_ZONE_INFORMATION + { + /// + /// The current bias for local time translation on this computer, in minutes. + /// + [MarshalAs(UnmanagedType.I4)] + public int Bias; + /// + /// A description for standard time. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] + public string StandardName; + /// + /// A SystemTime structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. + /// + public SystemTime StandardDate; + /// + /// The bias value to be used during local time translations that occur during standard time. + /// + [MarshalAs(UnmanagedType.I4)] + public int StandardBias; + /// + /// A description for daylight saving time (DST). + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] + public string DaylightName; + /// + /// A SystemTime structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this operating system. + /// + public SystemTime DaylightDate; + /// + /// The bias value to be used during local time translations that occur during daylight saving time. + /// + [MarshalAs(UnmanagedType.I4)] + public int DaylightBias; + } + + /// + /// PInvoke SetDynamicTimeZoneInformation API. + /// + /// A DYNAMIC_TIME_ZONE_INFORMATION structure representing the desired local time zone. + /// + [DllImport(SetDynamicTimeZoneApiDllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetDynamicTimeZoneInformation([In] ref DYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation); + + [DllImport(GetTimeZoneInformationForYearApiDllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool GetTimeZoneInformationForYear([In] ushort wYear, [In] ref DYNAMIC_TIME_ZONE_INFORMATION pdtzi, ref TIME_ZONE_INFORMATION ptzi); + + #endregion Win32 SetDynamicTimeZoneInformation imports + + #region Win32 AdjustTokenPrivilege imports + + /// + /// Definition of TOKEN_QUERY constant from Win32 API. + /// + public const int TOKEN_QUERY = 0x00000008; + + /// + /// Definition of TOKEN_ADJUST_PRIVILEGES constant from Win32 API. + /// + public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; + + /// + /// Definition of SE_PRIVILEGE_ENABLED constant from Win32 API. + /// + public const int SE_PRIVILEGE_ENABLED = 0x00000002; + + /// + /// Definition of SE_TIME_ZONE_NAME constant from Win32 API. + /// + public const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"; // https://msdn.microsoft.com/library/bb530716(VS.85).aspx + + /// + /// PInvoke GetCurrentProcess API. + /// + /// + [DllImport(GetCurrentProcessApiDllName, ExactSpelling = true)] + public static extern IntPtr GetCurrentProcess(); + + /// + /// PInvoke OpenProcessToken API. + /// + /// + /// + /// + /// + [DllImport(OpenProcessTokenApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle); + + /// + /// PInvoke LookupPrivilegeValue API. + /// + /// + /// + /// + /// + [DllImport(LookupPrivilegeTokenApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref long lpLuid); + + /// + /// PInvoke PrivilegeCheck API. + /// + /// + /// + /// + /// + [DllImport(PrivilegeCheckApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool PrivilegeCheck(IntPtr ClientToken, ref PRIVILEGE_SET RequiredPrivileges, ref bool pfResult); + + /// + /// PInvoke AdjustTokenPrivilege API. + /// + /// + /// + /// + /// + /// + /// + /// + [DllImport(AdjustTokenPrivilegesApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, + ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength); + + /// + /// PInvoke CloseHandle API. + /// + /// + /// + [DllImport(CloseHandleApiDllName, ExactSpelling = true, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CloseHandle(IntPtr hObject); + + /// + /// Used to marshal win32 PRIVILEGE_SET structure to managed code layer. + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct PRIVILEGE_SET + { + public int PrivilegeCount; + public int Control; + public long Luid; + public int Attributes; + } + + /// + /// Used to marshal win32 TOKEN_PRIVILEGES structure to managed code layer. + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct TOKEN_PRIVILEGES + { + public int PrivilegeCount; + public long Luid; + public int Attributes; + } + + #endregion Win32 AdjustTokenPrivilege imports + + #region Win32 SendMessage imports + + /// + /// Definition of WM_SETTINGCHANGE constant from Win32 API. + /// + public const int WM_SETTINGCHANGE = 0x001A; + + /// + /// Definition of HWND_BROADCAST constant from Win32 API. + /// + public const int HWND_BROADCAST = (-1); + + /// + /// Definition of SMTO_ABORTIFHUNG constant from Win32 API. + /// + public const int SMTO_ABORTIFHUNG = 0x0002; + + /// + /// PInvoke SendMessageTimeout API. + /// + /// + /// + /// + /// + /// + /// + /// + /// + [DllImport(SendMessageTimeoutApiDllName, SetLastError = true, CharSet = CharSet.Unicode)] + public static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, string lParam, int fuFlags, int uTimeout, ref int lpdwResult); + + #endregion Win32 SendMessage imports + } + + #endregion Win32 interop helper + } + +#endif + /// + /// Static Helper class for working with system time zones. + /// + internal static class TimeZoneHelper + { + #region Error Ids + + internal const string TimeZoneNotFoundError = "TimeZoneNotFound"; + internal const string MultipleMatchingTimeZonesError = "MultipleMatchingTimeZones"; + internal const string InsufficientPermissionsError = "InsufficientPermissions"; + internal const string SetTimeZoneFailedError = "SetTimeZoneFailed"; + + #endregion Error Ids + + /// + /// Find the system time zone by checking first against StandardName and then, + /// if no matches were found, against the DaylightName. + /// + /// The name (or wildcard pattern) of the system time zone to find. + /// A TimeZoneInfo object array containing information about the specified system time zones. + internal static TimeZoneInfo[] LookupSystemTimeZoneInfoByName(string name) + { + WildcardPattern namePattern = new(name, WildcardOptions.IgnoreCase); + List tzi = new(); + + // get the available system time zones + ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones(); + + // check against the standard and daylight names for each TimeZoneInfo + foreach (TimeZoneInfo zone in zones) + { + if (namePattern.IsMatch(zone.StandardName) || namePattern.IsMatch(zone.DaylightName)) + { + tzi.Add(zone); + } + } + + return (tzi.ToArray()); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..67d3acee44a71e74f751d40a2dea11aa247a9962 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A command that commits a transaction. + /// + [Cmdlet(VerbsOther.Use, "Transaction", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135271")] + public class UseTransactionCommand : PSCmdlet + { + /// + /// This parameter specifies the script block to run in the current + /// PowerShell transaction. + /// + [Parameter(Position = 0, Mandatory = true)] + public ScriptBlock TransactedScript + { + get + { + return _transactedScript; + } + + set + { + _transactedScript = value; + } + } + + private ScriptBlock _transactedScript; + + /// + /// Commits the current transaction. + /// + protected override void EndProcessing() + { + using (CurrentPSTransaction) + { + try + { + var emptyArray = Array.Empty(); + _transactedScript.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: null, + input: emptyArray, + scriptThis: AutomationNull.Value, + args: emptyArray); + } + catch (Exception e) + { + // Catch-all OK. This is a third-party call-out. + + ErrorRecord errorRecord = new ErrorRecord(e, "TRANSACTED_SCRIPT_EXCEPTION", ErrorCategory.NotSpecified, null); + + // The "transaction timed out" exception is + // exceedingly obtuse. We clarify things here. + bool isTimeoutException = false; + Exception tempException = e; + while (tempException != null) + { + if (tempException is System.TimeoutException) + { + isTimeoutException = true; + break; + } + + tempException = tempException.InnerException; + } + + if (isTimeoutException) + { + errorRecord = new ErrorRecord( + new InvalidOperationException( + TransactionResources.TransactionTimedOut), + "TRANSACTION_TIMEOUT", + ErrorCategory.InvalidOperation, + e); + } + + WriteError(errorRecord); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..31670a7d6327ee68dcae32329d9568c5779e2d22 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -0,0 +1,2083 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Provider; +using System.Management.Automation.Remoting; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Text; +using System.Threading; + +using Microsoft.PowerShell.Commands.Internal; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + #region Helper Classes + + /// + /// Base class for all WMI helper classes. This is an abstract class + /// and the helpers need to derive from this. + /// + internal abstract class AsyncCmdletHelper : IThrottleOperation + { + /// + /// Exception raised internally when any method of this class + /// is executed. + /// + internal Exception InternalException + { + get + { + return internalException; + } + } + + protected Exception internalException = null; + } + + /// + /// This class is responsible for creating WMI connection for getting objects and notifications + /// from WMI asynchronously. This spawns a new thread to connect to WMI on remote machine. + /// This allows the main thread to return faster and not blocked on network hops. + /// + internal class WmiAsyncCmdletHelper : AsyncCmdletHelper + { + /// + /// Internal Constructor. + /// + /// Job associated with this operation. + /// Object associated with this operation. + /// Computer on which the operation is invoked. + /// Sink to get wmi objects. + internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results) + { + _wmiObject = wmiObject; + _computerName = computerName; + _results = results; + this.State = WmiState.NotStarted; + _job = childJob; + } + + /// + /// Internal Constructor. This variant takes a count parameter that determines how many times + /// the WMI command is executed. + /// + /// Job associated with this operation. + /// Object associated with this operation. + /// Computer on which the operation is invoked. + /// Sink to return wmi objects. + /// Number of times the WMI command is executed. + internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results, int count) + : this(childJob, wmiObject, computerName, results) + { + _cmdCount = count; + } + + private string _computerName; + internal event EventHandler WmiOperationState; + internal event EventHandler ShutdownComplete; + private ManagementOperationObserver _results; + private int _cmdCount = 1; + private PSWmiChildJob _job; + /// + /// Current operation state. + /// + internal WmiState State + { + get { return _state; } + + set { _state = value; } + } + + private WmiState _state; + + /// + /// Cancel WMI connection. + /// + internal override void StopOperation() + { + _results.Cancel(); + _state = WmiState.Stopped; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + /// + /// Uses this.filter, this.wmiClass and this.property to retrieve the filter. + /// + private string GetWmiQueryString() + { + GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject; + StringBuilder returnValue = new StringBuilder("select "); + returnValue.Append(string.Join(", ", getObject.Property)); + returnValue.Append(" from "); + returnValue.Append(getObject.Class); + if (!string.IsNullOrEmpty(getObject.Filter)) + { + returnValue.Append(" where "); + returnValue.Append(getObject.Filter); + } + + return returnValue.ToString(); + } + + /// + /// Do WMI connection by creating another thread based on type of request and return immediately. + /// + internal override void StartOperation() + { + Thread thread; + if (_wmiObject.GetType() == typeof(GetWmiObjectCommand)) + { + thread = new Thread(new ThreadStart(ConnectGetWMI)); + } + else if (_wmiObject.GetType() == typeof(RemoveWmiObject)) + { + thread = new Thread(new ThreadStart(ConnectRemoveWmi)); + } + else if (_wmiObject is InvokeWmiMethod) + { + thread = new Thread(new ThreadStart(ConnectInvokeWmi)); + } + else if (_wmiObject is SetWmiInstance) + { + thread = new Thread(new ThreadStart(ConnectSetWmi)); + } + else + { + InvalidOperationException exception = new InvalidOperationException("This operation is not supported for this cmdlet."); + internalException = exception; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + thread.IsBackground = true; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + /// + /// + internal override event EventHandler OperationComplete; + + private Cmdlet _wmiObject; + + /// + /// Raise operation completion event. + /// + internal void RaiseOperationCompleteEvent(EventArgs baseEventArgs, OperationState state) + { + OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); + operationStateEventArgs.OperationState = state; + OperationComplete.SafeInvoke(this, operationStateEventArgs); + } + + /// + /// Raise WMI state changed event + /// + internal void RaiseWmiOperationState(EventArgs baseEventArgs, WmiState state) + { + WmiJobStateEventArgs wmiJobStateEventArgs = new WmiJobStateEventArgs(); + wmiJobStateEventArgs.WmiState = state; + WmiOperationState.SafeInvoke(this, wmiJobStateEventArgs); + } + + /// + /// Do the actual connection to remote machine for Set-WMIInstance cmdlet and raise operation complete event. + /// + private void ConnectSetWmi() + { + SetWmiInstance setObject = (SetWmiInstance)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); + if (setObject.InputObject != null) + { + ManagementObject mObj = null; + try + { + PutOptions pOptions = new PutOptions(); + // Extra check + if (setObject.InputObject.GetType() == typeof(ManagementClass)) + { + // Check if Flag specified is CreateOnly or not + if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) + { + InvalidOperationException e = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + mObj = ((ManagementClass)setObject.InputObject).CreateInstance(); + setObject.PutType = PutType.CreateOnly; + } + else + { + // Check if Flag specified is Updateonly or UpdateOrCreateOnly or not + if (setObject.flagSpecified) + { + if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) + { + InvalidOperationException e = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + } + else + { + setObject.PutType = PutType.UpdateOrCreate; + } + + mObj = (ManagementObject)setObject.InputObject.Clone(); + } + + if (setObject.Arguments != null) + { + IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); + while (en.MoveNext()) + { + mObj[en.Key as string] = en.Value; + } + } + + pOptions.Type = setObject.PutType; + if (mObj != null) + { + mObj.Put(_results, pOptions); + } + else + { + InvalidOperationException exp = new InvalidOperationException(); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + } + else + { + ManagementPath mPath = null; + // If Class is specified only CreateOnly flag is supported + if (setObject.Class != null) + { + if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) + { + InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + setObject.PutType = PutType.CreateOnly; + } + else + { + mPath = new ManagementPath(setObject.Path); + if (string.IsNullOrEmpty(mPath.NamespacePath)) + { + mPath.NamespacePath = setObject.Namespace; + } + else if (setObject.namespaceSpecified) + { + InvalidOperationException exp = new InvalidOperationException("NamespaceSpecifiedWithPath"); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + if (mPath.Server != "." && setObject.serverNameSpecified) + { + InvalidOperationException exp = new InvalidOperationException("ComputerNameSpecifiedWithPath"); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + if (mPath.IsClass) + { + if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) + { + InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + setObject.PutType = PutType.CreateOnly; + } + else + { + if (setObject.flagSpecified) + { + if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) + { + InvalidOperationException exp = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + } + else + { + setObject.PutType = PutType.UpdateOrCreate; + } + } + } + // If server name is specified loop through it. + if (mPath != null) + { + if (!(mPath.Server == "." && setObject.serverNameSpecified)) + { + _computerName = mPath.Server; + } + } + + ConnectionOptions options = setObject.GetConnectionOption(); + ManagementObject mObject = null; + try + { + if (setObject.Path != null) + { + mPath.Server = _computerName; + ManagementScope mScope = new ManagementScope(mPath, options); + if (mPath.IsClass) + { + ManagementClass mClass = new ManagementClass(mPath); + mClass.Scope = mScope; + mObject = mClass.CreateInstance(); + } + else + { + // This can throw if path does not exist caller should catch it. + ManagementObject mInstance = new ManagementObject(mPath); + mInstance.Scope = mScope; + try + { + mInstance.Get(); + } + catch (ManagementException e) + { + if (e.ErrorCode != ManagementStatus.NotFound) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + int namespaceIndex = setObject.Path.IndexOf(':'); + if (namespaceIndex == -1) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); + if (classIndex == -1) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + // Get class object and create instance. + string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); + ManagementPath classPath = new ManagementPath(newPath); + ManagementClass mClass = new ManagementClass(classPath); + mClass.Scope = mScope; + mInstance = mClass.CreateInstance(); + } + + mObject = mInstance; + } + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, setObject.Namespace), options); + ManagementClass mClass = new ManagementClass(setObject.Class); + mClass.Scope = scope; + mObject = mClass.CreateInstance(); + } + + if (setObject.Arguments != null) + { + IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); + while (en.MoveNext()) + { + mObject[en.Key as string] = en.Value; + } + } + + PutOptions pOptions = new PutOptions(); + pOptions.Type = setObject.PutType; + if (mObject != null) + { + mObject.Put(_results, pOptions); + } + else + { + InvalidOperationException exp = new InvalidOperationException(); + internalException = exp; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + } + } + + /// + /// Do the actual connection to remote machine for Invoke-WMIMethod cmdlet and raise operation complete event. + /// + private void ConnectInvokeWmi() + { + InvokeWmiMethod invokeObject = (InvokeWmiMethod)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); + + if (invokeObject.InputObject != null) + { + ManagementBaseObject inputParameters = null; + try + { + inputParameters = invokeObject.InputObject.GetMethodParameters(invokeObject.Name); + if (invokeObject.ArgumentList != null) + { + int inParamCount = invokeObject.ArgumentList.Length; + foreach (PropertyData property in inputParameters.Properties) + { + if (inParamCount == 0) + break; + property.Value = invokeObject.ArgumentList[invokeObject.ArgumentList.Length - inParamCount]; + inParamCount--; + } + } + + invokeObject.InputObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + + return; + } + else + { + ConnectionOptions options = invokeObject.GetConnectionOption(); + ManagementPath mPath = null; + ManagementObject mObject = null; + if (invokeObject.Path != null) + { + mPath = new ManagementPath(invokeObject.Path); + if (string.IsNullOrEmpty(mPath.NamespacePath)) + { + mPath.NamespacePath = invokeObject.Namespace; + } + else if (invokeObject.namespaceSpecified) + { + InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath"); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + if (mPath.Server != "." && invokeObject.serverNameSpecified) + { + InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath"); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + // If server name is specified loop through it. + if (!(mPath.Server == "." && invokeObject.serverNameSpecified)) + { + _computerName = mPath.Server; + } + } + + bool isLocal = false, needToEnablePrivilege = false; + PlatformInvokes.TOKEN_PRIVILEGE currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); + try + { + needToEnablePrivilege = NeedToEnablePrivilege(_computerName, invokeObject.Name, ref isLocal); + if (needToEnablePrivilege) + { + if (!(isLocal && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) && + !(!isLocal && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState))) + { + string message = + StringUtil.Format(ComputerResources.PrivilegeNotEnabled, _computerName, + isLocal ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME); + InvalidOperationException e = new InvalidOperationException(message); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + } + + if (invokeObject.Path != null) + { + mPath.Server = _computerName; + if (mPath.IsClass) + { + ManagementClass mClass = new ManagementClass(mPath); + mObject = mClass; + } + else + { + ManagementObject mInstance = new ManagementObject(mPath); + mObject = mInstance; + } + + ManagementScope mScope = new ManagementScope(mPath, options); + mObject.Scope = mScope; + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, invokeObject.Namespace), options); + ManagementClass mClass = new ManagementClass(invokeObject.Class); + mObject = mClass; + mObject.Scope = scope; + } + + ManagementBaseObject inputParameters = mObject.GetMethodParameters(invokeObject.Name); + if (invokeObject.ArgumentList != null) + { + int inParamCount = invokeObject.ArgumentList.Length; + foreach (PropertyData property in inputParameters.Properties) + { + if (inParamCount == 0) + break; + property.Value = invokeObject.ArgumentList[invokeObject.ArgumentList.Length - inParamCount]; + inParamCount--; + } + } + + if (needToEnablePrivilege) + { + ManagementBaseObject result = mObject.InvokeMethod(invokeObject.Name, inputParameters, null); + Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked"); + int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture); + if (returnCode != 0) + { + var e = new Win32Exception(returnCode); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + else + { + ShutdownComplete.SafeInvoke(this, null); + } + } + else + { + mObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); + } + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + finally + { + // Restore the previous privilege state if something unexpected happened + if (needToEnablePrivilege) + { + PlatformInvokes.RestoreTokenPrivilege( + isLocal ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState); + } + } + } + } + + /// + /// Check if we need to enable the shutdown privilege. + /// + /// + /// + /// + /// + private bool NeedToEnablePrivilege(string computer, string methodName, ref bool isLocal) + { + bool result = false; + if (methodName.Equals("Win32Shutdown", StringComparison.OrdinalIgnoreCase)) + { + result = true; + + // CLR 4.0 Port note - use https://msdn.microsoft.com/library/system.net.networkinformation.ipglobalproperties.hostname(v=vs.110).aspx + string localName = System.Net.Dns.GetHostName(); + + // And for this, use PsUtils.GetHostname() + string localFullName = System.Net.Dns.GetHostEntry(string.Empty).HostName; + if (computer.Equals(".") || computer.Equals("localhost", StringComparison.OrdinalIgnoreCase) || + computer.Equals(localName, StringComparison.OrdinalIgnoreCase) || + computer.Equals(localFullName, StringComparison.OrdinalIgnoreCase)) + { + isLocal = true; + } + } + + return result; + } + + /// + /// Do the actual connection to remote machine for Remove-WMIObject cmdlet and raise operation complete event. + /// + private void ConnectRemoveWmi() + { + RemoveWmiObject removeObject = (RemoveWmiObject)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); + if (removeObject.InputObject != null) + { + try + { + removeObject.InputObject.Delete(_results); + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + + return; + } + else + { + ConnectionOptions options = removeObject.GetConnectionOption(); + ManagementPath mPath = null; + ManagementObject mObject = null; + if (removeObject.Path != null) + { + mPath = new ManagementPath(removeObject.Path); + if (string.IsNullOrEmpty(mPath.NamespacePath)) + { + mPath.NamespacePath = removeObject.Namespace; + } + else if (removeObject.namespaceSpecified) + { + InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath"); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + if (mPath.Server != "." && removeObject.serverNameSpecified) + { + InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath"); + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + if (!(mPath.Server == "." && removeObject.serverNameSpecified)) + { + _computerName = mPath.Server; + } + } + + try + { + if (removeObject.Path != null) + { + mPath.Server = _computerName; + if (mPath.IsClass) + { + ManagementClass mClass = new ManagementClass(mPath); + mObject = mClass; + } + else + { + ManagementObject mInstance = new ManagementObject(mPath); + mObject = mInstance; + } + + ManagementScope mScope = new ManagementScope(mPath, options); + mObject.Scope = mScope; + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, removeObject.Namespace), options); + ManagementClass mClass = new ManagementClass(removeObject.Class); + mObject = mClass; + mObject.Scope = scope; + } + + mObject.Delete(_results); + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + } + } + + /// + /// Do the actual connection to remote machine for Get-WMIObject cmdlet and raise operation complete event. + /// + private void ConnectGetWMI() + { + GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); + ConnectionOptions options = getObject.GetConnectionOption(); + if (getObject.List.IsPresent) + { + if (!getObject.ValidateClassFormat()) + { + ArgumentException e = new ArgumentException( + string.Format( + Thread.CurrentThread.CurrentCulture, + "Class", getObject.Class)); + + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + try + { + if (getObject.Recurse.IsPresent) + { + ArrayList namespaceArray = new ArrayList(); + ArrayList sinkArray = new ArrayList(); + ArrayList connectArray = new ArrayList(); // Optimization for remote namespace + int currentNamespaceCount = 0; + namespaceArray.Add(getObject.Namespace); + bool topNamespace = true; + while (currentNamespaceCount < namespaceArray.Count) + { + string connectNamespace = (string)namespaceArray[currentNamespaceCount]; + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, connectNamespace), options); + scope.Connect(); + ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); + foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) + { + if (!getObject.IsLocalizedNamespace((string)obj["Name"])) + { + namespaceArray.Add(connectNamespace + "\\" + obj["Name"]); + } + } + + if (topNamespace) + { + topNamespace = false; + sinkArray.Add(_results); + } + else + { + sinkArray.Add(_job.GetNewSink()); + } + + connectArray.Add(scope); + currentNamespaceCount++; + } + + if ((sinkArray.Count != namespaceArray.Count) || (connectArray.Count != namespaceArray.Count)) // not expected throw exception + { + internalException = new InvalidOperationException(); + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + return; + } + + currentNamespaceCount = 0; + while (currentNamespaceCount < namespaceArray.Count) + { + string connectNamespace = (string)namespaceArray[currentNamespaceCount]; + ManagementObjectSearcher searcher = getObject.GetObjectList((ManagementScope)connectArray[currentNamespaceCount]); + if (searcher == null) + { + currentNamespaceCount++; + continue; + } + + if (topNamespace) + { + topNamespace = false; + searcher.Get(_results); + } + else + { + searcher.Get((ManagementOperationObserver)sinkArray[currentNamespaceCount]); + } + + currentNamespaceCount++; + } + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options); + scope.Connect(); + ManagementObjectSearcher searcher = getObject.GetObjectList(scope); + if (searcher == null) + throw new ManagementException(); + searcher.Get(_results); + } + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + + return; + } + + string queryString = string.IsNullOrEmpty(getObject.Query) ? GetWmiQueryString() : getObject.Query; + ObjectQuery query = new ObjectQuery(queryString.ToString()); + try + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options); + EnumerationOptions enumOptions = new EnumerationOptions(); + enumOptions.UseAmendedQualifiers = getObject.Amended; + enumOptions.DirectRead = getObject.DirectRead; + ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); + + // Execute the WMI command for each count value. + for (int i = 0; i < _cmdCount; ++i) + { + searcher.Get(_results); + } + } + catch (ManagementException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.Runtime.InteropServices.COMException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + catch (System.UnauthorizedAccessException e) + { + internalException = e; + _state = WmiState.Failed; + RaiseOperationCompleteEvent(null, OperationState.StopComplete); + } + } + } + + /// + /// Event which will be triggered when WMI state is changed. + /// Currently it is to notify Jobs that state has changed to running. + /// Other states are notified via OperationComplete. + /// + internal sealed class WmiJobStateEventArgs : EventArgs + { + /// + /// WMI state + /// + internal WmiState WmiState { get; set; } + } + + /// + /// Enumerated type defining the state of the WMI operation. + /// + public enum WmiState + { + /// + /// The operation has not been started. + /// + NotStarted = 0, + /// + /// The operation is executing. + /// + Running = 1, + /// + /// The operation is stoping execution. + /// + Stopping = 2, + /// + /// The operation is completed due to a stop request. + /// + Stopped = 3, + /// + /// The operation has completed. + /// + Completed = 4, + /// + /// The operation completed abnormally due to an error. + /// + Failed = 5, + } + + internal static class WMIHelper + { + internal static string GetScopeString(string computer, string namespaceParameter) + { + StringBuilder returnValue = new StringBuilder("\\\\"); + returnValue.Append(computer); + returnValue.Append('\\'); + returnValue.Append(namespaceParameter); + return returnValue.ToString(); + } + } + #endregion Helper Classes + + /// + /// A class to set WMI connection options. + /// + public class WmiBaseCmdlet : Cmdlet + { + #region Parameters + + /// + /// Perform Async operation. + /// + [Parameter] + public SwitchParameter AsJob { get; set; } = false; + + /// + /// The Impersonation level to use. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + public ImpersonationLevel Impersonation { get; set; } = ImpersonationLevel.Impersonate; + + /// + /// The Authentication level to use. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + public AuthenticationLevel Authentication { get; set; } = AuthenticationLevel.PacketPrivacy; + + /// + /// The Locale to use. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + public string Locale { get; set; } = null; + + /// + /// If all Privileges are enabled. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + public SwitchParameter EnableAllPrivileges { get; set; } + + /// + /// The Authority to use. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + public string Authority { get; set; } = null; + + /// + /// The credential to use. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + [Credential] + public PSCredential Credential { get; set; } + + /// + /// The credential to use. + /// + [Parameter] + public Int32 ThrottleLimit { get; set; } = s_DEFAULT_THROTTLE_LIMIT; + + /// + /// The ComputerName in which to query. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + [ValidateNotNullOrEmpty] + [Alias("Cn")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] ComputerName + { + get { return _computerName; } + + set { _computerName = value; serverNameSpecified = true; } + } + /// + /// The WMI namespace to use. + /// + [Parameter(ParameterSetName = "path")] + [Parameter(ParameterSetName = "class")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] + [Alias("NS")] + public string Namespace + { + get { return _nameSpace; } + + set { _nameSpace = value; namespaceSpecified = true; } + } + #endregion Parameters + + #region parameter data + /// + /// The computer to query. + /// + private string[] _computerName = new string[] { "localhost" }; + /// + /// WMI namespace. + /// + private string _nameSpace = "root\\cimv2"; + /// + /// Specify if namespace was specified or not. + /// + internal bool namespaceSpecified = false; + /// + /// Specify if server name was specified or not. + /// + internal bool serverNameSpecified = false; + + private static int s_DEFAULT_THROTTLE_LIMIT = 32; // maximum number of items to be processed at a time + + #endregion parameter data + + #region Command code + /// + /// Get connection options. + /// + internal ConnectionOptions GetConnectionOption() + { + ConnectionOptions options; + options = new ConnectionOptions(); + options.Authentication = this.Authentication; + options.Locale = this.Locale; + options.Authority = this.Authority; + options.EnablePrivileges = this.EnableAllPrivileges; + options.Impersonation = this.Impersonation; + if (this.Credential != null) + { + if (!(this.Credential.UserName == null && this.Credential.Password == null)) // Empty credential, use implicit credential + { + options.Username = this.Credential.UserName; + options.SecurePassword = this.Credential.Password; + } + } + + return options; + } + /// + /// Set wmi instance helper. + /// + internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName) + { + ConnectionOptions options = GetConnectionOption(); + ManagementObject mObject = null; + var setObject = this as SetWmiInstance; + if (setObject != null) + { + if (setObject.Path != null) + { + mPath.Server = serverName; + ManagementScope mScope = new ManagementScope(mPath, options); + if (mPath.IsClass) + { + ManagementClass mClass = new ManagementClass(mPath); + mClass.Scope = mScope; + mObject = mClass.CreateInstance(); + } + else + { + // This can throw if path does not exist caller should catch it. + ManagementObject mInstance = new ManagementObject(mPath); + mInstance.Scope = mScope; + try + { + mInstance.Get(); + } + catch (ManagementException e) + { + if (e.ErrorCode != ManagementStatus.NotFound) + { + throw; + } + + int namespaceIndex = setObject.Path.IndexOf(':'); + if (namespaceIndex == -1) + { + throw; + } + + int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); + if (classIndex == -1) + { + throw; + } + // Get class object and create instance. + string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); + ManagementPath classPath = new ManagementPath(newPath); + ManagementClass mClass = new ManagementClass(classPath); + mClass.Scope = mScope; + mInstance = mClass.CreateInstance(); + } + + mObject = mInstance; + } + } + else + { + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(serverName, setObject.Namespace), options); + ManagementClass mClass = new ManagementClass(setObject.Class); + mClass.Scope = scope; + mObject = mClass.CreateInstance(); + } + + if (setObject.Arguments != null) + { + IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); + while (en.MoveNext()) + { + mObject[en.Key as string] = en.Value; + } + } + } + + return mObject; + } + /// + /// Set wmi instance helper for building management path. + /// + internal ManagementPath SetWmiInstanceBuildManagementPath() + { + ManagementPath mPath = null; + var wmiInstance = this as SetWmiInstance; + if (wmiInstance != null) + { + // If Class is specified only CreateOnly flag is supported + if (wmiInstance.Class != null) + { + if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) + { + // Throw Terminating error + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "CreateOnlyFlagNotSpecifiedWithClassPath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); + } + + wmiInstance.PutType = PutType.CreateOnly; + } + else + { + mPath = new ManagementPath(wmiInstance.Path); + if (string.IsNullOrEmpty(mPath.NamespacePath)) + { + mPath.NamespacePath = wmiInstance.Namespace; + } + else if (wmiInstance.namespaceSpecified) + { + // ThrowTerminatingError + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "NamespaceSpecifiedWithPath", + ErrorCategory.InvalidOperation, + wmiInstance.Namespace)); + } + + if (mPath.Server != "." && wmiInstance.serverNameSpecified) + { + // ThrowTerminatingError + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "ComputerNameSpecifiedWithPath", + ErrorCategory.InvalidOperation, + wmiInstance.ComputerName)); + } + + if (mPath.IsClass) + { + if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) + { + // Throw Terminating error + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "CreateOnlyFlagNotSpecifiedWithClassPath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); + } + + wmiInstance.PutType = PutType.CreateOnly; + } + else + { + if (wmiInstance.flagSpecified) + { + if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) + { + // Throw terminating error + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "NonUpdateFlagSpecifiedWithInstancePath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); + } + } + else + { + wmiInstance.PutType = PutType.UpdateOrCreate; + } + } + } + } + + return mPath; + } + + /// + /// Set wmi instance helper for pipeline input. + /// + internal ManagementObject SetWmiInstanceGetPipelineObject() + { + // Should only be called from Set-WMIInstance cmdlet + ManagementObject mObj = null; + var wmiInstance = this as SetWmiInstance; + if (wmiInstance != null) + { + // Extra check + if (wmiInstance.InputObject != null) + { + if (wmiInstance.InputObject.GetType() == typeof(ManagementClass)) + { + // Check if Flag specified is CreateOnly or not + if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) + { + // Throw terminating error + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "CreateOnlyFlagNotSpecifiedWithClassPath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); + } + + mObj = ((ManagementClass)wmiInstance.InputObject).CreateInstance(); + wmiInstance.PutType = PutType.CreateOnly; + } + else + { + // Check if Flag specified is Updateonly or UpdateOrCreateOnly or not + if (wmiInstance.flagSpecified) + { + if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) + { + // Throw terminating error + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "NonUpdateFlagSpecifiedWithInstancePath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); + } + } + else + { + wmiInstance.PutType = PutType.UpdateOrCreate; + } + + mObj = (ManagementObject)wmiInstance.InputObject.Clone(); + } + + if (wmiInstance.Arguments != null) + { + IDictionaryEnumerator en = wmiInstance.Arguments.GetEnumerator(); + while (en.MoveNext()) + { + mObj[en.Key as string] = en.Value; + } + } + } + } + + return mObj; + } + + /// + /// Start this cmdlet as a WMI job... + /// + internal void RunAsJob(string cmdletName) + { + PSWmiJob wmiJob = new PSWmiJob(this, ComputerName, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation)); + if (_context != null) + { + ((System.Management.Automation.Runspaces.LocalRunspace)_context.CurrentRunspace).JobRepository.Add(wmiJob); + } + + WriteObject(wmiJob); + } + // Get the PowerShell execution context if it's available at cmdlet creation time... + private System.Management.Automation.ExecutionContext _context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); + + #endregion Command code + } + /// + /// A class to perform async operations for WMI cmdlets. + /// + + internal class PSWmiJob : Job + { + #region internal constructor + + /// + ///Internal constructor for initializing WMI jobs. + /// + internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimt, string command) + : base(command, null) + { + PSJobTypeName = WMIJobType; + _throttleManager.ThrottleLimit = throttleLimt; + for (int i = 0; i < computerName.Length; i++) + { + PSWmiChildJob job = new PSWmiChildJob(cmds, computerName[i], _throttleManager); + job.StateChanged += new EventHandler(HandleChildJobStateChanged); + job.JobUnblocked += new EventHandler(HandleJobUnblocked); + ChildJobs.Add(job); + } + + CommonInit(throttleLimt); + } + + /// + /// Internal constructor for initializing WMI jobs, where WMI command is executed a variable + /// number of times. + /// + internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimit, string command, int count) + : base(command, null) + { + PSJobTypeName = WMIJobType; + _throttleManager.ThrottleLimit = throttleLimit; + for (int i = 0; i < computerName.Length; ++i) + { + PSWmiChildJob childJob = new PSWmiChildJob(cmds, computerName[i], _throttleManager, count); + childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); + childJob.JobUnblocked += new EventHandler(HandleJobUnblocked); + ChildJobs.Add(childJob); + } + + CommonInit(throttleLimit); + } + + #endregion internal constructor + + // Set to true when at least one chil job failed + private bool _atleastOneChildJobFailed = false; + + // Count the number of childs which have finished + private int _finishedChildJobsCount = 0; + + // Count of number of child jobs which are blocked + private int _blockedChildJobsCount = 0; + + // WMI Job type name. + private const string WMIJobType = "WmiJob"; + + /// + /// Handles the StateChanged event from each of the child job objects. + /// + /// + /// + private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) + { + if (e.JobStateInfo.State == JobState.Blocked) + { + // increment count of blocked child jobs + lock (_syncObject) + { + _blockedChildJobsCount++; + } + // if any of the child job is blocked, we set state to blocked + SetJobState(JobState.Blocked, null); + return; + } + + // Ignore state changes which are not resulting in state change to finished. + if ((!IsFinishedState(e.JobStateInfo.State)) || (e.JobStateInfo.State == JobState.NotStarted)) + { + return; + } + + if (e.JobStateInfo.State == JobState.Failed) + { + // If any of the child job failed, we set status to failed + _atleastOneChildJobFailed = true; + } + + bool allChildJobsFinished = false; + lock (_syncObject) + { + _finishedChildJobsCount++; + + // We are done + if (_finishedChildJobsCount == ChildJobs.Count) + { + allChildJobsFinished = true; + } + } + + if (allChildJobsFinished) + { + // if any child job failed, set status to failed + // If stop was called set, status to stopped + // else completed + if (_atleastOneChildJobFailed) + { + SetJobState(JobState.Failed); + } + else if (_stopIsCalled == true) + { + SetJobState(JobState.Stopped); + } + else + { + SetJobState(JobState.Completed); + } + } + } + + private bool _stopIsCalled = false; + private string _statusMessage; + /// + /// Message indicating status of the job. + /// + public override string StatusMessage + { + get + { + return _statusMessage; + } + } + // ISSUE: Implement StatusMessage + /// + /// Checks the status of remote command execution. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + private void SetStatusMessage() + { + _statusMessage = "test"; + } + + private bool _moreData = false; + /// + /// Indicates if more data is available. + /// + /// + /// This has more data if any of the child jobs have more data. + /// + public override bool HasMoreData + { + get + { + // moreData is set to false and will be set to true + // if at least one child is has more data. + + // if ( (!moreData)) + // { + bool atleastOneChildHasMoreData = false; + + for (int i = 0; i < ChildJobs.Count; i++) + { + if (ChildJobs[i].HasMoreData) + { + atleastOneChildHasMoreData = true; + break; + } + } + + _moreData = atleastOneChildHasMoreData; + // } + + return _moreData; + } + } + + /// + /// Computers on which this job is running. + /// + public override string Location + { + get + { + return ConstructLocation(); + } + } + + private string ConstructLocation() + { + StringBuilder location = new StringBuilder(); + + foreach (PSWmiChildJob job in ChildJobs) + { + location.Append(job.Location); + location.Append(','); + } + + location.Remove(location.Length - 1, 1); + + return location.ToString(); + } + /// + /// Stop Job. + /// + public override void StopJob() + { + // AssertNotDisposed(); + + if (!IsFinishedState(JobStateInfo.State)) + { + _stopIsCalled = true; + + _throttleManager.StopAllOperations(); + + Finished.WaitOne(); + } + } + /// + /// Release all the resources. + /// + /// + /// if true, release all the managed objects. + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (!_isDisposed) + { + _isDisposed = true; + try + { + if (!IsFinishedState(JobStateInfo.State)) + { + StopJob(); + } + + _throttleManager.Dispose(); + foreach (Job job in ChildJobs) + { + job.Dispose(); + } + } + finally + { + base.Dispose(disposing); + } + } + } + } + + private bool _isDisposed = false; + /// + /// Initialization common to both constructors. + /// + private void CommonInit(int throttleLimit) + { + // Since no results are produced by any streams. We should + // close all the streams + base.CloseAllStreams(); + + // set status to "in progress" + SetJobState(JobState.Running); + + // submit operations to the throttle manager + _throttleManager.EndSubmitOperations(); + } + /// + /// Handles JobUnblocked event from a child job and decrements + /// count of blocked child jobs. When count reaches 0, sets the + /// state of the parent job to running. + /// + /// Sender of this event, unused. + /// event arguments, should be empty in this + /// case + private void HandleJobUnblocked(object sender, EventArgs eventArgs) + { + bool unblockjob = false; + + lock (_syncObject) + { + _blockedChildJobsCount--; + + if (_blockedChildJobsCount == 0) + { + unblockjob = true; + } + } + + if (unblockjob) + { + SetJobState(JobState.Running, null); + } + } + + private ThrottleManager _throttleManager = new ThrottleManager(); + + private object _syncObject = new object(); // sync object + } + + /// + /// Class for WmiChildJob object. This job object Execute wmi cmdlet. + /// + internal class PSWmiChildJob : Job + { + #region internal constructor + + /// + /// Internal constructor for initializing WMI jobs. + /// + internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager) + : base(null, null) + { + UsesResultsCollection = true; + Location = computerName; + _throttleManager = throttleManager; + _wmiSinkArray = new ArrayList(); + ManagementOperationObserver wmiSink = new ManagementOperationObserver(); + _wmiSinkArray.Add(wmiSink); + _sinkCompleted++; + wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); + wmiSink.Completed += new CompletedEventHandler(this.JobDone); + _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink); + _helper.WmiOperationState += new EventHandler(HandleWMIState); + _helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); + SetJobState(JobState.NotStarted); + IThrottleOperation operation = _helper; + operation.OperationComplete += new EventHandler(HandleOperationComplete); + throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); + throttleManager.AddOperation(operation); + } + + /// + /// Internal constructor for initializing WMI jobs, where WMI command is executed a variable + /// number of times. + /// + internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager, int count) + : base(null, null) + { + UsesResultsCollection = true; + Location = computerName; + _throttleManager = throttleManager; + _wmiSinkArray = new ArrayList(); + ManagementOperationObserver wmiSink = new ManagementOperationObserver(); + _wmiSinkArray.Add(wmiSink); + _sinkCompleted += count; + wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); + wmiSink.Completed += new CompletedEventHandler(this.JobDone); + _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink, count); + _helper.WmiOperationState += new EventHandler(HandleWMIState); + _helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); + SetJobState(JobState.NotStarted); + IThrottleOperation operation = _helper; + operation.OperationComplete += new EventHandler(HandleOperationComplete); + throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); + throttleManager.AddOperation(operation); + } + + #endregion internal constructor + + private WmiAsyncCmdletHelper _helper; + // bool _bFinished; + private ThrottleManager _throttleManager; + private object _syncObject = new object(); // sync object + private int _sinkCompleted; + private bool _bJobFailed; + private bool _bAtLeastOneObject; + + private ArrayList _wmiSinkArray; + /// + /// Event raised by this job to indicate to its parent that + /// its now unblocked by the user. + /// + internal event EventHandler JobUnblocked; + + /// + /// Set the state of the current job from blocked to + /// running and raise an event indicating to this + /// parent job that this job is unblocked. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal void UnblockJob() + { + SetJobState(JobState.Running, null); + JobUnblocked.SafeInvoke(this, EventArgs.Empty); + } + + internal ManagementOperationObserver GetNewSink() + { + ManagementOperationObserver wmiSink = new ManagementOperationObserver(); + _wmiSinkArray.Add(wmiSink); + lock (_syncObject) + { + _sinkCompleted++; + } + + wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); + wmiSink.Completed += new CompletedEventHandler(this.JobDone); + return wmiSink; + } + + /// + /// It receives Management objects. + /// + private void NewObject(object sender, ObjectReadyEventArgs obj) + { + if (!_bAtLeastOneObject) + { + _bAtLeastOneObject = true; + } + + this.WriteObject(obj.NewObject); + } + + /// + /// It is called when WMI job is done. + /// + private void JobDone(object sender, CompletedEventArgs obj) + { + lock (_syncObject) + { + _sinkCompleted--; + } + + if (obj.Status != ManagementStatus.NoError) + { + _bJobFailed = true; + } + + if (_sinkCompleted == 0) + { + // Notify throttle manager and change the state to complete + // Two cases where _bFinished should be set to false. + // 1) Invalid class or some other condition so that after making a connection WMI is throwing an error + // 2) We could not get any instance for the class. + /*if(bAtLeastOneObject ) + _bFinished = true;*/ + _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); + if (!_bJobFailed) + { + _helper.State = WmiState.Completed; + SetJobState(JobState.Completed); + } + else + { + _helper.State = WmiState.Failed; + SetJobState(JobState.Failed); + } + } + } + + /// + /// It is called when the call to Win32shutdown is successfully completed. + /// + private void JobDoneForWin32Shutdown(object sender, EventArgs arg) + { + lock (_syncObject) + { + _sinkCompleted--; + } + + if (_sinkCompleted == 0) + { + _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); + _helper.State = WmiState.Completed; + SetJobState(JobState.Completed); + } + } + + /// + /// Message indicating status of the job. + /// + public override string StatusMessage { get; } = "test"; + + /// + /// Indicates if there is more data available in + /// this Job. + /// + public override bool HasMoreData + { + get + { + return (Results.IsOpen || Results.Count > 0); + } + } + + /// + /// Returns the computer on which this command is + /// running. + /// + public override string Location { get; } + + /// + /// Stops the job. + /// + public override void StopJob() + { + AssertNotDisposed(); + _throttleManager.StopOperation(_helper); + + // if IgnoreStop is set, then StopOperation will + // return immediately, but StopJob should only + // return when job is complete. Waiting on the + // wait handle will ensure that its blocked + // until the job reaches a terminal state + Finished.WaitOne(); + } + + /// + /// Release all the resources. + /// + /// + /// if true, release all the managed objects. + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (!_isDisposed) + { + _isDisposed = true; + base.Dispose(disposing); + } + } + } + + private bool _isDisposed; + + /// + /// Handles operation complete event. + /// + private void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs) + { + WmiAsyncCmdletHelper helper = (WmiAsyncCmdletHelper)sender; + + if (helper.State == WmiState.NotStarted) + { + // This is a case WMI operation was not started. + SetJobState(JobState.Stopped, helper.InternalException); + } + else if (helper.State == WmiState.Running) + { + SetJobState(JobState.Running, helper.InternalException); + } + else if (helper.State == WmiState.Completed) + { + SetJobState(JobState.Completed, helper.InternalException); + } + else if (helper.State == WmiState.Failed) + { + SetJobState(JobState.Failed, helper.InternalException); + } + else + { + SetJobState(JobState.Stopped, helper.InternalException); + } + } + /// + /// Handles WMI state changed. + /// + private void HandleWMIState(object sender, WmiJobStateEventArgs stateEventArgs) + { + if (stateEventArgs.WmiState == WmiState.Running) + { + SetJobState(JobState.Running, _helper.InternalException); + } + else if (stateEventArgs.WmiState == WmiState.NotStarted) + { + SetJobState(JobState.NotStarted, _helper.InternalException); + } + else if (stateEventArgs.WmiState == WmiState.Completed) + { + SetJobState(JobState.Completed); + } + else if (stateEventArgs.WmiState == WmiState.Failed) + { + SetJobState(JobState.Failed, _helper.InternalException); + } + else + { + SetJobState(JobState.Stopped, _helper.InternalException); + } + } + + /// + /// Handle a throttle complete event. + /// + /// Sender of this event. + /// Not used in this method. + private void HandleThrottleComplete(object sender, EventArgs eventArgs) + { + if (_helper.State == WmiState.NotStarted) + { + // This is a case WMI operation was not started. + SetJobState(JobState.Stopped, _helper.InternalException); + } + else if (_helper.State == WmiState.Running) + { + SetJobState(JobState.Running, _helper.InternalException); + } + else if (_helper.State == WmiState.Completed) + { + SetJobState(JobState.Completed, _helper.InternalException); + } + else if (_helper.State == WmiState.Failed) + { + SetJobState(JobState.Failed, _helper.InternalException); + } + else + { + SetJobState(JobState.Stopped, _helper.InternalException); + } + // Do Nothing + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..3f91d597e573e8c190a13ffa93c9ec5a7b47a083 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -0,0 +1,494 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.CodeDom; +using System.CodeDom.Compiler; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management; +using System.Management.Automation; +using System.Net; +using System.Reflection; +using System.Resources; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Web.Services; +using System.Web.Services.Description; +using System.Web.Services.Discovery; +using System.Xml; + +using Microsoft.CSharp; +using Microsoft.Win32; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + #region New-WebServiceProxy + + /// + /// Cmdlet for new-WebService Proxy. + /// + [Cmdlet(VerbsCommon.New, "WebServiceProxy", DefaultParameterSetName = "NoCredentials", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135238")] + public sealed class NewWebServiceProxy : PSCmdlet + { + #region Parameters + + /// + /// URI of the web service. + /// + [Parameter(Mandatory = true, Position = 0)] + [ValidateNotNullOrEmpty] + [Alias("WL", "WSDL", "Path")] + public System.Uri Uri + { + get { return _uri; } + + set + { + _uri = value; + } + } + + private System.Uri _uri; + + /// + /// Parameter Class name. + /// + [Parameter(Position = 1)] + [ValidateNotNullOrEmpty] + [Alias("FileName", "FN")] + public string Class + { + get { return _class; } + + set + { + _class = value; + } + } + + private string _class; + + /// + /// Namespace. + /// + [Parameter(Position = 2)] + [ValidateNotNullOrEmpty] + [Alias("NS")] + public string Namespace + { + get { return _namespace; } + + set + { + _namespace = value; + } + } + + private string _namespace; + + /// + /// Credential. + /// + [Parameter(ParameterSetName = "Credential")] + [ValidateNotNullOrEmpty] + [Credential] + [Alias("Cred")] + public PSCredential Credential + { + get { return _credential; } + + set + { + _credential = value; + } + } + + private PSCredential _credential; + + /// + /// Use default credential.. + /// + [Parameter(ParameterSetName = "UseDefaultCredential")] + [ValidateNotNull] + [Alias("UDC")] + public SwitchParameter UseDefaultCredential + { + get { return _usedefaultcredential; } + + set + { + _usedefaultcredential = value; + } + } + + private SwitchParameter _usedefaultcredential; + + #endregion + + #region overrides + /// + /// Cache for storing URIs. + /// + private static Dictionary s_uriCache = new Dictionary(); + + /// + /// Cache for storing sourcecodehashes. + /// + private static Dictionary s_srccodeCache = new Dictionary(); + + /// + /// Holds the hash code of the source generated. + /// + private int _sourceHash; + /// + /// Random class. + /// + + private object _cachelock = new object(); + private static Random s_rnd = new Random(); + /// + /// BeginProcessing code. + /// + protected override void BeginProcessing() + { + if (string.IsNullOrWhiteSpace(_uri.ToString())) + { + Exception ex = new ArgumentException(WebServiceResources.InvalidUri); + ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + // check if system.web is available.This assembly is not available in win server core. + string AssemblyString = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + try + { + Assembly webAssembly = Assembly.Load(AssemblyString); + } + catch (FileNotFoundException ex) + { + ErrorRecord er = new ErrorRecord(ex, "SystemWebAssemblyNotFound", ErrorCategory.ObjectNotFound, null); + er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported); + ThrowTerminatingError(er); + } + + int sourceCache = 0; + + lock (s_uriCache) + { + if (s_uriCache.ContainsKey(_uri)) + { + // if uri is present in the cache + string ns; + s_uriCache.TryGetValue(_uri, out ns); + string[] data = ns.Split('|'); + if (string.IsNullOrEmpty(_namespace)) + { + if (data[0].StartsWith("Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.", StringComparison.OrdinalIgnoreCase)) + { + _namespace = data[0]; + _class = data[1]; + } + } + + sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture); + } + } + + if (string.IsNullOrEmpty(_namespace)) + { + _namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName(); + } + // if class is null,generate a name for it + if (string.IsNullOrEmpty(_class)) + { + _class = "MyClass" + GenerateRandomName(); + } + + Assembly webserviceproxy = GenerateWebServiceProxyAssembly(_namespace, _class); + if (webserviceproxy == null) + return; + object instance = InstantiateWebServiceProxy(webserviceproxy); + + // to set the credentials into the generated webproxy Object + PropertyInfo[] pinfo = instance.GetType().GetProperties(); + foreach (PropertyInfo pr in pinfo) + { + if (pr.Name.Equals("UseDefaultCredentials", StringComparison.OrdinalIgnoreCase)) + { + if (UseDefaultCredential.IsPresent) + { + bool flag = true; + pr.SetValue(instance, flag as object, null); + } + } + + if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase)) + { + if (Credential != null) + { + NetworkCredential cred = Credential.GetNetworkCredential(); + pr.SetValue(instance, cred as object, null); + } + } + } + + // disposing the entries in a cache + // Adding to Cache + lock (s_uriCache) + { + s_uriCache.Remove(_uri); + } + + if (sourceCache > 0) + { + lock (_cachelock) + { + s_srccodeCache.Remove(sourceCache); + } + } + + string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) }); + lock (s_uriCache) + { + s_uriCache.Add(_uri, key); + } + + lock (_cachelock) + { + s_srccodeCache.Add(_sourceHash, instance); + } + + WriteObject(instance, true); + } + + #endregion + + #region private + + private static ulong s_sequenceNumber = 1; + private static object s_sequenceNumberLock = new object(); + + /// + /// Generates a random name. + /// + /// String. + private string GenerateRandomName() + { + string rndname = null; + string givenuri = _uri.ToString(); + for (int i = 0; i < givenuri.Length; i++) + { + Int32 val = System.Convert.ToInt32(givenuri[i], CultureInfo.InvariantCulture); + if ((val >= 65 && val <= 90) || (val >= 48 && val <= 57) || (val >= 97 && val <= 122)) + { + rndname += givenuri[i]; + } + else + { + rndname += "_"; + } + } + + string sequenceString; + lock (s_sequenceNumberLock) + { + sequenceString = (s_sequenceNumber++).ToString(CultureInfo.InvariantCulture); + } + + if (rndname.Length > 30) + { + return (sequenceString + rndname.Substring(rndname.Length - 30)); + } + + return (sequenceString + rndname); + } + + /// + /// Generates the Assembly. + /// + /// + /// + /// + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] + private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName) + { + DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); + + // if paramset is defaultcredential, set the flag in wcclient + if (_usedefaultcredential.IsPresent) + dcp.UseDefaultCredentials = true; + + // if paramset is credential, assign the credentials + if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase)) + dcp.Credentials = _credential.GetNetworkCredential(); + + try + { + dcp.AllowAutoRedirect = true; + dcp.DiscoverAny(_uri.ToString()); + dcp.ResolveAll(); + } + catch (WebException ex) + { + ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri); + if (ex.InnerException != null) + er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); + WriteError(er); + return null; + } + catch (InvalidOperationException ex) + { + ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri); + WriteError(er); + return null; + } + + // create the namespace + CodeNamespace codeNS = new CodeNamespace(); + if (!string.IsNullOrEmpty(NameSpace)) + codeNS.Name = NameSpace; + + // create the class and add it to the namespace + if (!string.IsNullOrEmpty(ClassName)) + { + CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName); + codeClass.IsClass = true; + codeClass.Attributes = MemberAttributes.Public; + codeNS.Types.Add(codeClass); + } + + // create a web reference to the uri docs + WebReference wref = new WebReference(dcp.Documents, codeNS); + WebReferenceCollection wrefs = new WebReferenceCollection(); + wrefs.Add(wref); + + // create a codecompileunit and add the namespace to it + CodeCompileUnit codecompileunit = new CodeCompileUnit(); + codecompileunit.Namespaces.Add(codeNS); + + WebReferenceOptions wrefOptions = new WebReferenceOptions(); + wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; + wrefOptions.Verbose = true; + + // create a csharpprovider and compile it + CSharpCodeProvider csharpprovider = new CSharpCodeProvider(); + StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions); + + StringBuilder codegenerator = new StringBuilder(); + StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture); + try + { + csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null); + } + catch (NotImplementedException ex) + { + ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); + WriteError(er); + } + // generate the hashcode of the CodeCompileUnit + _sourceHash = codegenerator.ToString().GetHashCode(); + + // if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so + // return the instance of th eproxy in the cache + if (s_srccodeCache.ContainsKey(_sourceHash)) + { + object obj; + s_srccodeCache.TryGetValue(_sourceHash, out obj); + WriteObject(obj, true); + return null; + } + + CompilerParameters options = new CompilerParameters(); + CompilerResults results = null; + + foreach (string warning in Warnings) + { + this.WriteWarning(warning); + } + + // add the references to the required assemblies + options.ReferencedAssemblies.Add("System.dll"); + options.ReferencedAssemblies.Add("System.Data.dll"); + options.ReferencedAssemblies.Add("System.Xml.dll"); + options.ReferencedAssemblies.Add("System.Web.Services.dll"); + options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); + GetReferencedAssemblies(typeof(Cmdlet).Assembly, options); + options.GenerateInMemory = true; + options.TreatWarningsAsErrors = false; + options.WarningLevel = 4; + options.GenerateExecutable = false; + try + { + results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString()); + } + catch (NotImplementedException ex) + { + ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); + WriteError(er); + } + + return results.CompiledAssembly; + } + + /// + /// Function to add all the assemblies required to generate the web proxy. + /// + /// + /// + private void GetReferencedAssemblies(Assembly assembly, CompilerParameters parameters) + { + if (!parameters.ReferencedAssemblies.Contains(assembly.Location)) + { + string location = Path.GetFileName(assembly.Location); + if (!parameters.ReferencedAssemblies.Contains(location)) + { + parameters.ReferencedAssemblies.Add(assembly.Location); + foreach (AssemblyName referencedAssembly in assembly.GetReferencedAssemblies()) + GetReferencedAssemblies(Assembly.Load(referencedAssembly.FullName), parameters); + } + } + } + /// + /// Instantiates the object + /// if a type of WebServiceBindingAttribute is not found, throw an exception. + /// + /// + /// + private object InstantiateWebServiceProxy(Assembly assembly) + { + Type proxyType = null; + // loop through the types of the assembly and identify the type having + // a web service binding attribute + foreach (Type type in assembly.GetTypes()) + { + object[] obj = type.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); + if (obj.Length > 0) + { + proxyType = type; + break; + } + + if (proxyType != null) + { + break; + } + } + + System.Management.Automation.Diagnostics.Assert( + proxyType != null, + "Proxy class should always get generated unless there were some errors earlier (in that case we shouldn't get here)"); + + return assembly.CreateInstance(proxyType.ToString()); + } + + #endregion + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..a2a6387e9da82e8e9918b7d2be634f693481b635 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Provider; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A base class for the commands that write content (set-content, add-content) + /// + public class WriteContentCommandBase : PassThroughContentCommandBase + { + #region Parameters + + /// + /// The value of the content to set. + /// + /// + /// This value type is determined by the InvokeProvider. + /// + [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [AllowNull] + [AllowEmptyCollection] + public object[] Value + { + get + { + return _content; + } + + set + { + _content = value; + } + } + + #endregion Parameters + + #region parameter data + + /// + /// The value of the content to be set. + /// + private object[] _content; + + #endregion parameter data + + #region private Data + + /// + /// This bool is used to determine if the path + /// parameter was specified on the command line or via the pipeline. + /// + private bool _pipingPaths; + + /// + /// True if the content writers have been open. + /// This is used in conjunction with pipingPaths + /// to determine if the content writers need to + /// be closed each time ProgressRecord is called. + /// + private bool _contentWritersOpen; + + #endregion private Data + + #region Command code + + /// + /// Determines if the paths are specified on the command line + /// or being piped in. + /// + protected override void BeginProcessing() + { + if (Path != null && Path.Length > 0) + { + _pipingPaths = false; + } + else + { + _pipingPaths = true; + } + } + + /// + /// Appends the content to the specified item. + /// + protected override void ProcessRecord() + { + CmdletProviderContext currentContext = GetCurrentContext(); + + // Initialize the content + + _content ??= Array.Empty(); + + if (_pipingPaths) + { + // Make sure to clean up the content writers that are already there + + if (contentStreams != null && contentStreams.Count > 0) + { + CloseContent(contentStreams, false); + _contentWritersOpen = false; + contentStreams = new List(); + } + } + + if (!_contentWritersOpen) + { + // Since the paths are being pipelined in, we have + // to get new content writers for the new paths + string[] paths = GetAcceptedPaths(Path, currentContext); + + if (paths.Length > 0) + { + BeforeOpenStreams(paths); + contentStreams = GetContentWriters(paths, currentContext); + SeekContentPosition(contentStreams); + } + + _contentWritersOpen = true; + } + + // Now write the content to the item + try + { + foreach (ContentHolder holder in contentStreams) + { + if (holder.Writer != null) + { + IList result = null; + try + { + result = holder.Writer.Write(_content); + } + catch (Exception e) // Catch-all OK. 3rd party callout + { + ProviderInvocationException providerException = + new( + "ProviderContentWriteError", + SessionStateStrings.ProviderContentWriteError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); + + // Log a provider health event + + MshLog.LogProviderHealthEvent( + this.Context, + holder.PathInfo.Provider.Name, + providerException, + Severity.Warning); + + WriteError( + new ErrorRecord( + providerException.ErrorRecord, + providerException)); + continue; + } + + if (result != null && result.Count > 0 && PassThru) + { + WriteContentObject(result, result.Count, holder.PathInfo, currentContext); + } + } + } + } + finally + { + // Need to close all the writers if the paths are being pipelined + + if (_pipingPaths) + { + CloseContent(contentStreams, false); + _contentWritersOpen = false; + contentStreams = new List(); + } + } + } + + /// + /// Closes all the content writers. + /// + protected override void EndProcessing() + { + Dispose(true); + } + + #endregion Command code + + #region protected members + + /// + /// This method is called by the base class after getting the content writer + /// from the provider. If the current position needs to be changed before writing + /// the content, this method should be overridden to do that. + /// + /// + /// The content holders that contain the writers to be moved. + /// + internal virtual void SeekContentPosition(List contentHolders) + { + // default does nothing. + } + + /// + /// Called by the base class before the streams are open for the path. + /// + /// + /// The path to the items that will be opened for writing content. + /// + internal virtual void BeforeOpenStreams(string[] paths) + { + } + + /// + /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets + /// that require dynamic parameters should override this method and return the + /// dynamic parameter object. + /// + /// + /// The context under which the command is running. + /// + /// + /// An object representing the dynamic parameters for the cmdlet or null if there + /// are none. + /// + internal override object GetDynamicParameters(CmdletProviderContext context) + { + if (Path != null && Path.Length > 0) + { + return InvokeProvider.Content.GetContentWriterDynamicParameters(Path[0], context); + } + + return InvokeProvider.Content.GetContentWriterDynamicParameters(".", context); + } + + /// + /// Gets the IContentWriters for the current path(s) + /// + /// + /// An array of IContentWriters for the current path(s) + /// + internal List GetContentWriters( + string[] writerPaths, + CmdletProviderContext currentCommandContext) + { + // Resolve all the paths into PathInfo objects + + Collection pathInfos = ResolvePaths(writerPaths, true, false, currentCommandContext); + + // Create the results array + + List results = new(); + + foreach (PathInfo pathInfo in pathInfos) + { + // For each path, get the content writer + + Collection writers = null; + + try + { + writers = + InvokeProvider.Content.GetWriter( + pathInfo.Path, + currentCommandContext); + } + catch (PSNotSupportedException notSupported) + { + WriteError( + new ErrorRecord( + notSupported.ErrorRecord, + notSupported)); + continue; + } + catch (DriveNotFoundException driveNotFound) + { + WriteError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError( + new ErrorRecord( + pathNotFound.ErrorRecord, + pathNotFound)); + continue; + } + + if (writers != null && writers.Count > 0) + { + if (writers.Count == 1 && writers[0] != null) + { + ContentHolder holder = + new(pathInfo, null, writers[0]); + + results.Add(holder); + } + } + } + + return results; + } + + /// + /// Gets the list of paths accepted by the user. + /// + /// The list of unfiltered paths. + /// The current context. + /// The list of paths accepted by the user. + private string[] GetAcceptedPaths(string[] unfilteredPaths, CmdletProviderContext currentContext) + { + Collection pathInfos = ResolvePaths(unfilteredPaths, true, false, currentContext); + + var paths = new List(); + + foreach (PathInfo pathInfo in pathInfos) + { + if (CallShouldProcess(pathInfo.Path)) + { + paths.Add(pathInfo.Path); + } + } + + return paths.ToArray(); + } + + #endregion protected members + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..d74321e46ff99acab7b2b6d041374a908f42c2db --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + All of the contents of the Recycle Bin + + + All of the contents of the Recycle Bin for the '{0}' drive + + + Clearing Recycle Bin + + + for the '{0}' drive + + + for all drives + + + Cannot find drive. A drive with the name '{0}' does not exist. Please run the '{1}' cmdlet to see the available Fixed drives in the system. + + + Invalid input. The following formats are supported: '{0}', '{1}' or '{2}'. + + + The drive with the name '{0}' is not a Fixed drive and does not support the Recycle Bin. Please run the '{1}' cmdlet to see the available Fixed drives in the system. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..9e6cbd55cc18ed58556e71a038f74350db816c0b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Set string '{0}' to the clipboard. + + + Append string '{0}' to the clipboard. + + + Set file '{0}' to the clipboard. + + + Append file '{0}' to the clipboard. + + + Set {0} files to the clipboard. + + + Append {0} files to the clipboard. + + + There's no content in Clipboard or the content format is not compatible. Set input object to the Clipboard. + + + The Clipboard has been cleared. + + + TextFormatType can only be combined with Text format. + + + Raw can only be combined with Text or FileDropList format. + + + Html can only be combined with Html Text format. + + + Only Text format is supported on this platform. + + + The clipboard is not supported on this platform. + + + The '-AsHtml' switch is not supported on this platform. + + + The '-TextFormatType' parameter only supports 'Text' on this platform. + + + The '-Path' parameter is not supported on this platform. + + + The '-LiteralPath' parameter is not supported on this platform. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..15bfadffe7b387e134640a7fa7135e90b468db4b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot find the {0} class on the {1} CIM server. Verify the value of the ClassName xml attribute in Cmdlet Definition XML and retry. Valid class name example: ROOT\cimv2\Win32_Process. + {StrContains="ClassName"} {StrContains="ROOT\cimv2\Win32_Process"} +{0} is a placeholder for a name of a (potentially misspelled) CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + + CIM method {1} on the {0} CIM object + {0} is a placeholder for a CIM path. Example: \\SERVER1\ROOT\cimv2:Win32_Process.Handle="11828" +{1} is a placeholder for a CIM method name. Example: Create + + + Failed to run {1}. {0} + {0} is a placeholder for a generic CIM failure. Example: 'Invalid namespace' or '9' +{1} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + Running the following operation: {0}. + {0} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + CIM cmdlets do not support the {0} parameter together with the AsJob parameter. Remove one of these parameters and retry. + {StrContains="AsJob"} +{0} is a placeholder for 'WhatIf' or 'Confirm' cmdlet parameters + + + CIM query for instances of the {0} class on the {1} CIM server: {2} + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + The CIM method returned the following error code: {0} + {0} is a placeholder for an error code returned from a CIM method. Example: 123 + + + The {2} CIM method exposed by the {0} class on the {1} CIM server + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". +{2} is a placeholder for a CIM method name. Example: Create + + + CIM intrinsic type + + + WQL literal + + + Cannot find the {2} output parameter of the {1} method of the {0} CIM object. Verify the value of the ParameterName attribute in Cmdlet Definition XML and retry. + {StrContains="ParameterName"} +{0} is a placeholder for a CIM path. Example: \\SERVER1\ROOT\cimv2:Win32_Process.Handle="11828" +{1} is a placeholder for a name of a (potentially misspelled) CIM method. Example: "Terminate". +{2} is a placeholder for a name of a (potentially misspelled) method parameter. + + + + No matching {1} objects found by {0}. Verify query parameters and retry. + + + No {2} objects found with property '{0}' equal to '{1}'. Verify the value of the property and retry. + + + Type of {0} property ({1}) doesn't match the CIM type ({2}) associated with the type declared in Cmdlet Definition XML. + + + CIM query for enumerating associated instance of the {0} class on the {1} CIM server + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + CIM query for enumerating instances of the {0} class on the {1} CIM server, that are associated with the following instance: {2} + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". +{2} is a placeholder for a string describing a CimInstance. Example: "Win32_Process[Handle=123]". + + + The {0} command cannot complete, because the {1} server is currently busy. The command will be automatically resumed in {2:f2} seconds. + {0} is a placeholder for a command name. Example: "Get-NetAdapter" +{1} is a placeholder for a computer name. Example: "localhost" +{2} is a placeholder for a number of seconds. Example: 1.23 + + + Cannot connect to CIM server. {0} + {0} is a placeholder for a more detailed error message. + + + The cmdlet does not fully support the Inquire action for debug messages. Cmdlet operation will continue during the prompt. Select a different action preference via -Debug switch or $DebugPreference variable, and try again. + {StrContains="Debug"} {StrContains="DebugPreference"} {StrContains="Inquire"} + + + The cmdlet does not fully support the Inquire action for warnings. Cmdlet operation will continue during the prompt. Select a different action preference via -WarningAction parameter or $WarningPreference variable, and try again. + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Inquire"} + + + The cmdlet does not fully support the Stop action for warnings. Cmdlet operation will be stopped with a delay. Select a different action preference via -WarningAction parameter or $WarningPreference variable, and try again. + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Stop"} + + + {0}: {1} + {0} is a placeholder for a computername. Example: "localhost" +{1} is a placeholder for the original message. Example: "Deleting managed resource" + + + {0}: A CimSession to the CIM server uses the DCOM protocol, which does not support the {1} switch. + {0} is a placeholder for a name of a computer +{1} is a placeholder for 'Confirm' or 'WhatIf' + + + No {2} objects found with property '{0}' matching '{1}'. Verify the value of the property and retry. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..8a562f462d488e181b812c6a85f738b4374c3d5b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Loading operating system information + + + Loading hot-patch information + + + Loading registry information + + + Loading BIOS information + + + Loading motherboard information + + + Loading Computer information + + + Loading processor information + + + Loading network adapter information + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..95685239fd7d4ecf2fb9873ddd6b48f40ea2e64d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx @@ -0,0 +1,393 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This functionality is not supported on this operating system. + + + Could not enable drive {0}. + + + The command cannot turn on the restore computer infrastructure on the specified computer because the supplied drive is not valid. Enter a valid drive in the Drive parameter, and then try again. + + + Include System Drive in the list of Drives. + + + The command cannot turn off the restore computer infrastructure because the supplied drive is not valid. Enter a valid drive in the Drive parameter, and then try again. + + + The command cannot disable System Restore on the {0} drive. You may not have sufficient permissions to perform this operation. + + + SystemRestore service is disabled. + + + The system restore infrastructure cannot create a restore point. + + + The last attempt to restore the computer failed. + + + The computer has been restored to the specified restore point. + + + The last attempt to restore the computer was interrupted. + + + The command cannot locate the "{0}" restore point. Verify the "{0}" sequence number, and then try the command again. + + + {0} ({1}) + + + Failed to restart the computer {0} with the following error message: {1}. + + + This command cannot be run on target computer('{1}') due to following error: {0}.{2} + + + Failed to stop the computer {0} with the following error message: {1}. + + + The command cannot restore the computer because "{0}" has not been set as valid restore point. Enter a valid restore point in the RestorePoint parameter, and then try again. + + + The changes will take effect after you restart the computer {1}. + + + After you leave the domain, you will need to know the password of the local Administrator account to log onto this computer. Do you wish to continue? + + + The following computer name is not valid: {0}. Make sure that the computer name is not longer than 255 characters, that it does not contain two or more consecutive dots, that it does not begin with a dot, that it does not contain only numeric characters, and that it does not contain any of the following characters: +{{|}}~[\]^:;<=>?@!"#$%^`()+/, + + + The domain in computer name '{0}' is not valid. Make sure that the domain exists and that the name is a valid domain name. + + + The value specified for the NewComputerName parameter is the same as the value of the ComputerName parameter. Provide a different value for the NewComputerName parameter. + + + "The password of the secure channel between '{0}' and '{1}' has been reset." + + + This command cannot be run due to the following error: the service cannot be started because it is disabled or does not have enabled devices associated with it. + + + Creating a system restore point ... + + + Creating a system restore point... {0}% Completed. + + + Completed. + + + Try below options and Run the command again. +1. Verify that the target computer('{0}') is running. +2. Specify full computer name of the target computer('{0}'). + + + Failed to restart the computer {0}. Access rights {1} cannot be enabled for the calling process. + + + Enable the {0} and restart the computer. + + + Local shutdown access rights + + + Remote shutdown access rights + + + Cannot wait for the local computer to restart. The local computer is ignored when the Wait parameter is specified. + + + The parameters Timeout, For, and Delay are valid only when the parameter Wait is specified. + + + Restarting computers... + + + Restarting computer {0} + + + Completed: {0}/{1}. + + + Verifying that the computer has been restarted... + + + Waiting for PowerShell connectivity... + + + Waiting for the restart to begin... + + + Waiting for WinRM connectivity... + + + Waiting for WMI connectivity... + + + Restart is complete + + + The combined service types are not supported for now. + + + Computer name {0} cannot be resolved with the exception: {1}. + + + The number of new names is not equal to the number of target computers. + + + Skip computer '{0}' with new name '{1}' because the new name is not valid. The new computer name entered is not properly formatted. Standard names may contain letters (a-z, A-Z), numbers (0-9), and hyphens (-), but no spaces or periods (.). The name may not consist entirely of digits, and may not be longer than 63 characters. + + + Skip computer '{0}' with new name '{1}' because the new name is the same as the current name. + + + Cannot remove computer '{0}' because it is not in a domain. + + + Failed to join computer '{0}' to workgroup '{1}' with the following error message: {2} + + + Cannot remove computer(s) from the domain because the local network is down. + + + Fail to rename computer '{0}' to '{1}' due to the following exception: {2}. + + + Join in domain '{0}' + + + Join in workgroup '{0}' + + + Cannot add computer '{0}' to domain '{1}' because it is already in that domain. + + + Cannot add computer '{0}' to workgroup '{1}' because it is already in that workgroup. + + + Computer '{0}' successfully joined the workgroup '{1}', but could not be renamed to '{2}' with the following error message: {3}. + + + Computer '{0}' was successfully unjoined from the domain '{1}', but it failed to join the workgroup '{2}' with the following error message: {3}. + + + Failed to unjoin computer '{0}' from domain '{1}' with the following error message: {2}. + + + Cannot establish the WMI connection to the computer '{0}' with the following error message: {1}. + + + Computer '{0}' failed to join domain '{1}' from its current workgroup '{2}' with following error message: {3}. + + + Computer '{0}' was successfully unjoined from domain '{1}', but failed to join the new domain '{2}' with the following error message: {3}. + + + Computer '{0}' was successfully joined to the new domain '{1}', but renaming it to '{2}' failed with the following error message: {3}. + + + The flag '{0}' is valid only if flag '{1}' is specified. + + + Cannot rename multiple computers. The NewName parameter is valid only if a single computer is specified. + + + Cannot find the computer account for the local computer in the domain {0}. + + + Cannot find the computer account for the local computer from the domain controller {0}. + + + Cannot get domain information about the local computer because of the following exception: {0}. + + + Cannot reset the secure channel password for the computer account in the domain. Operation failed with the following exception: {0}. + + + Resetting the secure channel password for the local computer failed with the following error message: {0}. + + + Administrator rights are required to reset the secure channel password on the local computer. Access is denied. + + + Cannot reset the secure channel password for the account of the local computer. The local computer is not currently part of a domain. + + + The NetBIOS name of the computer is limited to 15 bytes, which is 15 characters in this case. The NetBIOS name will be shortened to "{0}", which may cause conflicts under NetBIOS name resolution. Do you wish to continue? + + + NetBIOS name will be truncated. + + + The specified server name {0} cannot be resolved. + + + A new system restore point cannot be created because one has already been created within the past {0} minutes. The frequency of restore point creation can be changed by creating the DWORD value 'SystemRestorePointCreationFrequency' under the registry key 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore'. The value of this registry key indicates the necessary time interval (in minutes) between two restore point creation. The default value is 1440 minutes (24 hours). + + + The Win32_OperatingSystem WMI object cannot be retrieved. + + + The computer {0} is skipped. Fail to retrieve its LastBootUpTime via the WMI service with the following error message: {1}. + + + Cannot verify the secure channel for the local computer. Operation failed with the following exception: {0}. + + + The attempt to repair the secure channel between the local computer and the domain {0} has failed. + + + The secure channel between the local computer and the domain {0} was successfully repaired. + + + The secure channel between the local computer and the domain {0} is in good condition. + + + The secure channel between the local computer and the domain {0} is broken. + + + Cannot verify the secure channel password for the local computer. The local computer is not currently part of a domain. + + + The operation cannot be performed because the system restore APIs are not supported on the Advanced RISC Machine (ARM) platform. + + + The computer did not finish restarting within the specified time-out period. + + + Cannot validate the time interval for restore point creation. It failed to retrieve the last restore point with the following error message: {0}. + + + The AsJob Parameter Set is not supported. + + + The {0} parameter is not supported for CoreCLR. + + + The required native command 'shutdown' was not found. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..077beaa117f1c174a2ef8b5542c7200aa2525850 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The {0} cmdlet is not supported on this version of Windows. + + + Cannot find any Control Panel item with the given canonical name {0}. + + + Cannot find any control panel item with the given canonical name {0} that satisfies the specified category. + + + Cannot find any control panel item with the given category {0}. + + + Cannot find the Control Panel item based on the given instance of type {0}. + + + Cannot find any control panel item with the given name {0}. + + + Cannot find any Control Panel item with the given name {0} that satisfies the specified category. + + + Cannot find any control panel item that has a canonical name. + + + Cannot find any Control Panel item that satisfies the specified category and has a canonical name. + + + &Open + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..cee97f4adaebd87f7c3d528ee94d1fd0234ea7d2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx @@ -0,0 +1,180 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Log "{0}" could not be read to completion due to the following error. This may have occurred because the log was cleared while still being read. {1} + + + No matches found + + + Do you want to clear the "{0}" log on the computer "{1}"? + + + The Log name "{0}" does not exist in the computer "{1}". + + + The path to the "{1}" computer cannot be found. + + + The source name "{2}" does not exist on computer "{1}". + + + The registry key for the log "{0}" for source "{2}" could not be opened. + + + The operating system reported an error when writing the event entry to the event log. A Windows error code is not available. + + + Do you want to change the properties of the "{0}" log on the "{1}" computer? + + + The registry key for the log "{0}" could not be opened on the computer "{1}". + + + The value supplied for MaximumSize parameter has to be in the range of 64 KB to 4GB with an increment of 64 KB. Please enter a proper value and then retry. + + + Access to the "{1}" computer is denied. + + + The "{2}" source is already registered with the "{0}" log. + + + The "{2}" source is already registered on the "{1}" computer. + + + Do you want to remove the "{0}" log from the "{1}" computer? + + + Do you want to remove the "{0}" source from the "{1}" computer? + + + Retention days is valid only if the overflow action is "OverwriteOlder". Please change and try again. + + + Specify a valid value for the number of retention days. + + + Access is denied. Try running the command again in a session that has been opened with elevated user rights (that is, Run as Administrator). + + + The command is not supported in this version of the operating system. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..a058ae71a119bea58b0ae073ccf80bd29d7b1bf5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot find the requested hotfix on the '{0}' computer. Verify the input and run the command again. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..73de4f80a24d66391675c94fc716f2c5620911e8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This PowerShell Snap-In contains management cmdlets that are used to manage Windows components. + + + Microsoft Corporation + + + Management PSSnapIn + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..6bec473c213892598f0a05673f93ccc2381972ac --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx @@ -0,0 +1,192 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The specified path is a container that has child items. Do you want to delete this container and its child items? + + + Do you want to delete the specified item? + + + Cannot copy because the specified destination already exists. Do you want to overwrite the existing content? + + + New drive + + + Name: {0} Provider: {1} Root: {2} + + + Remove Drive + + + Name: {0} Provider: {1} Root: {2} + + + Cannot remove drive '{0}' because it is in use. + + + The item at {0} has children and the Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue? + + + Cannot remove the item at '{0}' because it is in use. + + + An object at the specified path {0} does not exist, or has been filtered by the -Include or -Exclude parameter. + + + Set Content + + + Path: {0} + + + Add Content + + + Path: {0} + + + Cannot move item because the item at '{0}' does not exist. + + + Cannot move item because the item at '{0}' is in use. + + + Cannot rename because item at '{0}' does not exist. + + + Cannot rename the item at '{0}' because it is in use. + + + Cannot parse path because path '{0}' does not have a qualifier specified. + + + Begin + + + Rollback + + + Commit + + + Current transaction + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..fa4ae71963a04b35e0d0b4c8dde2a46ebee39afd --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx @@ -0,0 +1,151 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Lists processes currently running. + + + +-Id id +[int[]] +[pipeline input allowed] +Comma-separated list of process identifiers that specify the processes to get + +-ProcessName name +[string[]] +[pipeline input allowed] +Comma-separated list of process names that specify the processes to get + +-Exclude name +[ArrayList] +Comma-separated list of process names to be excluded from the output. + +--- +The command enumerates processes from the local computer, and outputs System.Diagnostics.Process object(s). The command writes the process object to the output pipeline one at a time. The command takes parameters like ID(Process Identifier) or Process Name from the command line. The command returns the corresponding system.diagnostics.process for the supplied ID or ProcessName parameters. + + + Exclude works only for process name. + + + Returns all running processes. + + + Returns all processes with names starting with svc. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..b4c1ddbccf8b44e3fc063f3ee86866fb68929582 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx @@ -0,0 +1,234 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot find a process with the name "{0}". Verify the process name and call the cmdlet again. + + + Cannot find a process with the name "{0}". Try running with -Id to search by Id of processes. + + + This command cannot be run because the debugger cannot be attached to the process "{0} ({1})". Specify another process and Run your command. + + + Cannot find a process with the process identifier {1}. + + + Cannot stop process "{0} ({1})" because of the following error: {2} + + + {0} ({1}) + + + {0} {1} + + + Cannot enumerate the modules of the "{0}" process. + + + Cannot enumerate the file version information of the "{0}" process. + + + Cannot enumerate the modules and the file version information of the "{0}" process. + + + Are you sure you want to perform the Stop-Process operation on the following item: {0}({1})? + + + The specified path is not a valid win32 application. Try again with the UseShellExecute. + + + This command stopped operation of "{0} ({1})" because of the following error: {2}. + + + This command cannot be run because Redirection parameters cannot be used with UseShellExecute parameter + + + Exception getting "Modules" or "FileVersion": "This feature is not supported for remote computers.". + + + This command cannot attach the debugger to the process due to {0} because no default debugger is available. + + + This command stopped operation because it cannot wait on 'System Idle' process. Specify another process and Run your command again. + + + This command stopped operation because it cannot wait on itself. Specify another process and Run your command again. + + + This command stopped operation because process "{0} ({1})" is not stopped in the specified time-out. + + + This command cannot be run due to the error: {0} + + + This command cannot be run because the input "{0}" is not a valid Application. Give a valid application and run your command again. + + + This command cannot be run because either the parameter "{0}" has a value that is not valid or cannot be used with this command. Give a valid input and Run your command again. + + + This command cannot be run because "{0}" and "{1}" are same. Give different inputs and Run your command again. + + + This command cannot be run completely because the system cannot find all the information required. + + + Failed to retrieve the new process handle: "{0}". The Process object outputted may have some properties and methods that do not work properly. + + + This command cannot be run due to error 1783. The possible cause of this error can be using of a non-existing user "{0}". Please give a valid user and run your command again. + + + Error adding '{0}' to the network: {1} + + + Error removing '{0}' from the network: {1} + + + Error renaming '{0}': {1} + + + Parameters "{0}" and "{1}" cannot be specified at the same time. + + + Cannot debug process "{0} ({1})" because of the following error: {2} + + + The user does not have access to the requested information. + + + The specified parameter is not valid. + + + The user does not have sufficient privilege. + + + Unknown failure. + + + The path specified does not exist. + + + The parameter '{0}' is not supported for the cmdlet '{1}' on this edition of Windows. + + + The parameter '{0}' is not supported for the cmdlet '{1}' on this edition of PowerShell. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..c19f753529fc6c351671f19dc3adafafb934ad31 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx @@ -0,0 +1,219 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0} ({1}) + + + Cannot find any service with service name '{0}'. + + + Cannot find any service with display name '{1}'. + + + Cannot stop service '{1} ({0})' because it has dependent services. It can only be stopped if the Force flag is set. + + + Cannot stop service '{1} ({0})' because it has dependent services. + + + Service '{1} ({0})' cannot be stopped due to the following error: {2} + + + Service '{1} ({0})' cannot be started due to the following error: {2} + + + Service '{1} ({0})' cannot be suspended due to the following error: {2} + + + Service '{1} ({0})' cannot be suspended because the service does not support being suspended or resumed. + + + Service '{1} ({0})' cannot be suspended because it is not currently running. + + + Service '{1} ({0})' cannot be resumed due to the following error: {2} + + + Service '{1} ({0})' cannot be resumed because the service does not support being suspended or resumed. + + + Service '{1} ({0})' cannot be resumed because it is not currently running. + + + Service '{1} ({0})' cannot be configured due to the following error: {2} + + + Service '{1} ({0})' description cannot be configured due to the following error: {2} + + + Service '{1} ({0})' automatic (delayed start) cannot be configured due to the following error: {2} + + + Service '{0}' security descriptor cannot be configured due to the following error: {1} + + + Service '{1} ({0})' cannot be created due to the following error: {2} + + + Service '{1} ({0})' was created, but its description cannot be configured due to the following error: {2} + + + Service '{1} ({0})' was created, but its StartupType 'Automatic (Delayed Start)' could not be configured due to the following error: {2} + + + Service '{1} ({0})' cannot be removed due to the following error: {2} + + + 'Cannot access dependent services of '{1} ({0})' + + + Waiting for service '{1} ({0})' to start... + + + Waiting for service '{1} ({0})' to stop... + + + Waiting for service '{1} ({0})' to suspend... + + + Waiting for service '{1} ({0})' to resume... + + + Failed to start service '{1} ({0})'. + + + Service '{1} ({0})' stop failed. + + + Service '{1} ({0})' suspend failed. + + + Service '{1} ({0})' resume failed. + + + Failed to open SCManager due to the following error: {0}. Run PowerShell as admin and run your command again. + + + The startup type '{0}' is not supported by {1}. + + + Could not retrieve property '{1}' for service '{0}': {2} + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..ddd4ba8f815d9cead1c7d920cbcb27c308262395 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Testing connection to computer '{0}' failed: {1} + + + Cannot resolve the target name. + + + Target IPv4/IPv6 address absent. + + + Cannot complete traceroute to destination '{0}': Number of hops required to reach host exceeds MaxHops ({1}). + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..c60c4318a641a2f6e5e688cb51bc4109bb192ed3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The provided Path argument was null or an empty collection. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..f474785fd225894b119e7393ff7cd456621e5beb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot set the local time zone because the name '{0}' resolves to multiple entries. + + + The time zone name '{0}' was not found on the local computer. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..9d92573d86db0735a7ea2ec6a1ac88ef7a952c9e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot use transaction. The transaction has timed out. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..91d57c5190242120724d860abac62e7ec938b23f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The Uniform Resource Identifier (URI) cannot be null or empty. Provide a valid URI. + + + The command is not supported on this operating system. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..47f736405ead98cf51b29e9592aebf601dc3baf2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Could not register for event. The class name is invalid. Valid class names consist of letters, digits and the underscore character. + + + Could not get objects from namespace {0}. {1} + + + The class name {0} is invalid. Valid class names consist of letters, digits, '_', '?', '*', '-' and "[]". + + + {0} ({1}) + + + Parameter {0} should be specified to compose the query. + + + {0}"{1}" + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed3495dd334a81558d136e28ba4afb353df226d3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell +{ + /// + /// PSManagementPSSnapIn is a class for facilitating registry + /// of necessary information for PowerShell management PSSnapin. + /// + /// This class will be built with monad management dll. + /// + [RunInstaller(true)] + public sealed class PSManagementPSSnapIn : PSSnapIn + { + /// + /// Create an instance of this class. + /// + public PSManagementPSSnapIn() + : base() + { + } + + /// + /// Get name of this PSSnapin. + /// + public override string Name + { + get + { + return RegistryStrings.ManagementMshSnapinName; + } + } + + /// + /// Get the default vendor string for this PSSnapin. + /// + public override string Vendor + { + get + { + return "Microsoft"; + } + } + + /// + /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. + /// + public override string VendorResource + { + get + { + return "ManagementMshSnapInResources,Vendor"; + } + } + + /// + /// Get the default description string for this PSSnapin. + /// + public override string Description + { + get + { + return "This PSSnapIn contains general management cmdlets used to manage Windows components."; + } + } + + /// + /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. + /// + public override string DescriptionResource + { + get + { + return "ManagementMshSnapInResources,Description"; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj new file mode 100644 index 0000000000000000000000000000000000000000..d6cd95677ab0051fbab32f0fcc5b2820eba6954f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -0,0 +1,40 @@ + + + + PowerShell's Microsoft.PowerShell.Commands.Utility project + $(NoWarn);CS1570;CA1416 + Microsoft.PowerShell.Commands.Utility + + + + + + + + + + $(DefineConstants);CORECLR + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs new file mode 100644 index 0000000000000000000000000000000000000000..4c7601e883f8bbd2609c492b0bac5044e2f6a669 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -0,0 +1,603 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Reflection; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements get-member command. + /// + [Cmdlet(VerbsCommon.Add, "Member", DefaultParameterSetName = "TypeNameSet", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097109", RemotingCapability = RemotingCapability.None)] + public class AddMemberCommand : PSCmdlet + { + private static readonly object s_notSpecified = new(); + + private static bool HasBeenSpecified(object obj) + { + return !System.Object.ReferenceEquals(obj, s_notSpecified); + } + + private PSObject _inputObject; + /// + /// The object to add a member to. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "MemberSet")] + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "TypeNameSet")] + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = NotePropertySingleMemberSet)] + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = NotePropertyMultiMemberSet)] + public PSObject InputObject + { + get { return _inputObject; } + + set { _inputObject = value; } + } + + private PSMemberTypes _memberType; + /// + /// The member type of to be added. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "MemberSet")] + [Alias("Type")] + public PSMemberTypes MemberType + { + get { return _memberType; } + + set { _memberType = value; } + } + + private string _memberName; + /// + /// The name of the new member. + /// + [Parameter(Mandatory = true, Position = 1, ParameterSetName = "MemberSet")] + public string Name + { + get { return _memberName; } + + set { _memberName = value; } + } + + private object _value1 = s_notSpecified; + /// + /// First value of the new member. The meaning of this value changes according to the member type. + /// + [Parameter(Position = 2, ParameterSetName = "MemberSet")] + public object Value + { + get { return _value1; } + + set { _value1 = value; } + } + + private object _value2 = s_notSpecified; + /// + /// Second value of the new member. The meaning of this value changes according to the member type. + /// + [Parameter(Position = 3, ParameterSetName = "MemberSet")] + public object SecondValue + { + get { return _value2; } + + set { _value2 = value; } + } + + private string _typeName; + /// + /// Add new type name to the specified object for TypeNameSet. + /// + [Parameter(Mandatory = true, ParameterSetName = "TypeNameSet")] + [Parameter(ParameterSetName = "MemberSet")] + [Parameter(ParameterSetName = NotePropertySingleMemberSet)] + [Parameter(ParameterSetName = NotePropertyMultiMemberSet)] + [ValidateNotNullOrEmpty] + public string TypeName + { + get { return _typeName; } + + set { _typeName = value; } + } + + private bool _force; + /// + /// True if we should overwrite a possibly existing member. + /// + [Parameter(ParameterSetName = "MemberSet")] + [Parameter(ParameterSetName = NotePropertySingleMemberSet)] + [Parameter(ParameterSetName = NotePropertyMultiMemberSet)] + public SwitchParameter Force + { + get { return _force; } + + set { _force = value; } + } + + private bool _passThru /* = false */; + + /// + /// Gets or sets the parameter -passThru which states output from the command should be placed in the pipeline. + /// + [Parameter(ParameterSetName = "MemberSet")] + [Parameter(ParameterSetName = "TypeNameSet")] + [Parameter(ParameterSetName = NotePropertySingleMemberSet)] + [Parameter(ParameterSetName = NotePropertyMultiMemberSet)] + public SwitchParameter PassThru + { + get { return _passThru; } + + set { _passThru = value; } + } + + #region Simplifying NoteProperty Declaration + + private const string NotePropertySingleMemberSet = "NotePropertySingleMemberSet"; + private const string NotePropertyMultiMemberSet = "NotePropertyMultiMemberSet"; + + private string _notePropertyName; + /// + /// The name of the new NoteProperty member. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = NotePropertySingleMemberSet)] + [ValidateNotePropertyName] + [NotePropertyTransformation] + [ValidateNotNullOrEmpty] + public string NotePropertyName + { + get { return _notePropertyName; } + + set { _notePropertyName = value; } + } + + private object _notePropertyValue; + /// + /// The value of the new NoteProperty member. + /// + [Parameter(Mandatory = true, Position = 1, ParameterSetName = NotePropertySingleMemberSet)] + [AllowNull] + public object NotePropertyValue + { + get { return _notePropertyValue; } + + set { _notePropertyValue = value; } + } + + // Use IDictionary to support both Hashtable and OrderedHashtable + private IDictionary _property; + + /// + /// The NoteProperty members to be set. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = NotePropertyMultiMemberSet)] + [ValidateNotNullOrEmpty] + public IDictionary NotePropertyMembers + { + get { return _property; } + + set { _property = value; } + } + + #endregion Simplifying NoteProperty Declaration + + private static object GetParameterType(object sourceValue, Type destinationType) + { + return LanguagePrimitives.ConvertTo(sourceValue, destinationType, CultureInfo.InvariantCulture); + } + + private void EnsureValue1AndValue2AreNotBothNull() + { + if (_value1 == null && + (_value2 == null || !HasBeenSpecified(_value2))) + { + ThrowTerminatingError(NewError("Value1AndValue2AreNotBothNull", "Value1AndValue2AreNotBothNull", null, _memberType)); + } + } + + private void EnsureValue1IsNotNull() + { + if (_value1 == null) + { + ThrowTerminatingError(NewError("Value1ShouldNotBeNull", "Value1ShouldNotBeNull", null, _memberType)); + } + } + + private void EnsureValue2IsNotNull() + { + if (_value2 == null) + { + ThrowTerminatingError(NewError("Value2ShouldNotBeNull", "Value2ShouldNotBeNull", null, _memberType)); + } + } + + private void EnsureValue1HasBeenSpecified() + { + if (!HasBeenSpecified(_value1)) + { + Collection fdc = new(); + fdc.Add(new FieldDescription("Value")); + string prompt = StringUtil.Format(AddMember.Value1Prompt, _memberType); + Dictionary result = this.Host.UI.Prompt(prompt, null, fdc); + if (result != null) + { + _value1 = result["Value"].BaseObject; + } + } + } + + private void EnsureValue2HasNotBeenSpecified() + { + if (HasBeenSpecified(_value2)) + { + ThrowTerminatingError(NewError("Value2ShouldNotBeSpecified", "Value2ShouldNotBeSpecified", null, _memberType)); + } + } + + private PSMemberInfo GetAliasProperty() + { + EnsureValue1HasBeenSpecified(); + EnsureValue1IsNotNull(); + + string value1Str = (string)GetParameterType(_value1, typeof(string)); + if (HasBeenSpecified(_value2)) + { + EnsureValue2IsNotNull(); + Type value2Type = (Type)GetParameterType(_value2, typeof(Type)); + return new PSAliasProperty(_memberName, value1Str, value2Type); + } + + return new PSAliasProperty(_memberName, value1Str); + } + + private PSMemberInfo GetCodeMethod() + { + EnsureValue1HasBeenSpecified(); + EnsureValue1IsNotNull(); + EnsureValue2HasNotBeenSpecified(); + MethodInfo value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo)); + return new PSCodeMethod(_memberName, value1MethodInfo); + } + + private PSMemberInfo GetCodeProperty() + { + EnsureValue1HasBeenSpecified(); + EnsureValue1AndValue2AreNotBothNull(); + + MethodInfo value1MethodInfo = null; + if (HasBeenSpecified(_value1)) + { + value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo)); + } + + MethodInfo value2MethodInfo = null; + if (HasBeenSpecified(_value2)) + { + value2MethodInfo = (MethodInfo)GetParameterType(_value2, typeof(MethodInfo)); + } + + return new PSCodeProperty(_memberName, value1MethodInfo, value2MethodInfo); + } + + private PSMemberInfo GetMemberSet() + { + EnsureValue2HasNotBeenSpecified(); + if (_value1 == null || !HasBeenSpecified(_value1)) + { + return new PSMemberSet(_memberName); + } + + Collection value1Collection = + (Collection)GetParameterType(_value1, typeof(Collection)); + return new PSMemberSet(_memberName, value1Collection); + } + + private PSMemberInfo GetNoteProperty() + { + EnsureValue1HasBeenSpecified(); + EnsureValue2HasNotBeenSpecified(); + return new PSNoteProperty(_memberName, _value1); + } + + private PSMemberInfo GetPropertySet() + { + EnsureValue2HasNotBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue1IsNotNull(); + Collection value1Collection = + (Collection)GetParameterType(_value1, typeof(Collection)); + return new PSPropertySet(_memberName, value1Collection); + } + + private PSMemberInfo GetScriptMethod() + { + EnsureValue2HasNotBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue1IsNotNull(); + ScriptBlock value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock)); + return new PSScriptMethod(_memberName, value1ScriptBlock); + } + + private PSMemberInfo GetScriptProperty() + { + EnsureValue1HasBeenSpecified(); + EnsureValue1AndValue2AreNotBothNull(); + + ScriptBlock value1ScriptBlock = null; + if (HasBeenSpecified(_value1)) + { + value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock)); + } + + ScriptBlock value2ScriptBlock = null; + if (HasBeenSpecified(_value2)) + { + value2ScriptBlock = (ScriptBlock)GetParameterType(_value2, typeof(ScriptBlock)); + } + + return new PSScriptProperty(_memberName, value1ScriptBlock, value2ScriptBlock); + } + + /// + /// This method implements the ProcessRecord method for add-member command. + /// + protected override void ProcessRecord() + { + if (_typeName != null && string.IsNullOrWhiteSpace(_typeName)) + { + ThrowTerminatingError(NewError("TypeNameShouldNotBeEmpty", "TypeNameShouldNotBeEmpty", _typeName)); + } + + if (ParameterSetName == "TypeNameSet") + { + UpdateTypeNames(); + + if (_passThru) + { + WriteObject(_inputObject); + } + + return; + } + + if (ParameterSetName == NotePropertyMultiMemberSet) + { + ProcessNotePropertyMultiMemberSet(); + return; + } + + PSMemberInfo member = null; + if (ParameterSetName == NotePropertySingleMemberSet) + { + member = new PSNoteProperty(_notePropertyName, _notePropertyValue); + } + else + { + int memberCountHelper = (int)_memberType; + int memberCount = 0; + while (memberCountHelper != 0) + { + if ((memberCountHelper & 1) != 0) + { + memberCount++; + } + + memberCountHelper >>= 1; + } + + if (memberCount != 1) + { + ThrowTerminatingError(NewError("WrongMemberCount", "WrongMemberCount", null, _memberType.ToString())); + return; + } + + switch (_memberType) + { + case PSMemberTypes.AliasProperty: + member = GetAliasProperty(); + break; + case PSMemberTypes.CodeMethod: + member = GetCodeMethod(); + break; + case PSMemberTypes.CodeProperty: + member = GetCodeProperty(); + break; + case PSMemberTypes.MemberSet: + member = GetMemberSet(); + break; + case PSMemberTypes.NoteProperty: + member = GetNoteProperty(); + break; + case PSMemberTypes.PropertySet: + member = GetPropertySet(); + break; + case PSMemberTypes.ScriptMethod: + member = GetScriptMethod(); + break; + case PSMemberTypes.ScriptProperty: + member = GetScriptProperty(); + break; + default: + ThrowTerminatingError(NewError("CannotAddMemberType", "CannotAddMemberType", null, _memberType.ToString())); + break; + } + } + + if (member == null) + { + return; + } + + if (!AddMemberToTarget(member)) + return; + + if (_typeName != null) + { + UpdateTypeNames(); + } + + if (_passThru) + { + WriteObject(_inputObject); + } + } + + /// + /// Add the member to the target object. + /// + /// + /// + private bool AddMemberToTarget(PSMemberInfo member) + { + PSMemberInfo previousMember = _inputObject.Members[member.Name]; + if (previousMember != null) + { + if (!_force) + { + WriteError(NewError("MemberAlreadyExists", + "MemberAlreadyExists", + _inputObject, member.Name)); + return false; + } + else + { + if (previousMember.IsInstance) + { + _inputObject.Members.Remove(member.Name); + } + else + { + WriteError(NewError("CannotRemoveTypeDataMember", + "CannotRemoveTypeDataMember", + _inputObject, member.Name, previousMember.MemberType)); + return false; + } + } + } + + _inputObject.Members.Add(member); + return true; + } + + /// + /// Process the 'NotePropertyMultiMemberSet' parameter set. + /// + private void ProcessNotePropertyMultiMemberSet() + { + bool result = false; + foreach (DictionaryEntry prop in _property) + { + string noteName = PSObject.ToStringParser(this.Context, prop.Key); + object noteValue = prop.Value; + + if (string.IsNullOrEmpty(noteName)) + { + WriteError(NewError("NotePropertyNameShouldNotBeNull", + "NotePropertyNameShouldNotBeNull", noteName)); + continue; + } + + PSMemberInfo member = new PSNoteProperty(noteName, noteValue); + if (AddMemberToTarget(member) && !result) + result = true; + } + + if (result && _typeName != null) + { + UpdateTypeNames(); + } + + if (result && _passThru) + { + WriteObject(_inputObject); + } + } + + private void UpdateTypeNames() + { + // Respect the type shortcut + Type type; + string typeNameInUse = _typeName; + if (LanguagePrimitives.TryConvertTo(_typeName, out type)) + { + typeNameInUse = type.FullName; + } + + _inputObject.TypeNames.Insert(0, typeNameInUse); + } + + private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) + { + ErrorDetails details = new(this.GetType().GetTypeInfo().Assembly, + "Microsoft.PowerShell.Commands.Utility.resources.AddMember", resourceId, args); + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.InvalidOperation, + targetObject); + return errorRecord; + } + + /// + /// This ValidateArgumentsAttribute is used to guarantee the argument to be bound to + /// -NotePropertyName parameter cannot be converted to the enum type PSMemberTypes. + /// So when given a string or a number that can be converted, we make sure it gets + /// bound to -MemberType, instead of -NotePropertyName. + /// + /// + /// This exception will be hidden in the positional binding phase. So we make sure + /// if the argument can be converted to PSMemberTypes, it gets bound to the -MemberType + /// parameter. We are sure that when this exception is thrown, the current positional + /// argument can be successfully bound to. + /// + private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttribute + { + protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) + { + PSMemberTypes memberType; + if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) + { + switch (memberType) + { + case PSMemberTypes.AliasProperty: + case PSMemberTypes.CodeMethod: + case PSMemberTypes.CodeProperty: + case PSMemberTypes.MemberSet: + case PSMemberTypes.NoteProperty: + case PSMemberTypes.PropertySet: + case PSMemberTypes.ScriptMethod: + case PSMemberTypes.ScriptProperty: + string errMsg = StringUtil.Format(AddMember.InvalidValueForNotePropertyName, typeof(PSMemberTypes).FullName); + throw new ValidationMetadataException(errMsg, true); + default: + break; + } + } + } + } + + /// + /// Transform the integer arguments to strings for the parameter NotePropertyName. + /// + internal sealed class NotePropertyTransformationAttribute : ArgumentTransformationAttribute + { + public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) + { + object target = PSObject.Base(inputData); + if (target != null && target.GetType().IsNumeric()) + { + var result = LanguagePrimitives.ConvertTo(target); + return result; + } + + return inputData; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs new file mode 100644 index 0000000000000000000000000000000000000000..7dc0a9c3556b048722e38dd780fbada0caa55fcc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -0,0 +1,1371 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Collections.ObjectModel; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Security; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Loader; +using System.Security; +using System.Text; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Text; +using PathType = System.IO.Path; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Languages supported for code generation. + /// + public enum Language + { + /// + /// The C# programming language. + /// + CSharp + } + + /// + /// Types supported for the OutputAssembly parameter. + /// + public enum OutputAssemblyType + { + /// + /// A Dynamically linked library (DLL). + /// + Library, + + /// + /// An executable application that targets the console subsystem. + /// + ConsoleApplication, + + /// + /// An executable application that targets the graphical subsystem. + /// + WindowsApplication + } + + /// + /// Adds a new type to the Application Domain. + /// This version is based on CodeAnalysis (Roslyn). + /// + [Cmdlet(VerbsCommon.Add, "Type", DefaultParameterSetName = FromSourceParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096601")] + [OutputType(typeof(Type))] + public sealed class AddTypeCommand : PSCmdlet + { + #region Parameters + + /// + /// The source code of this generated type. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromSourceParameterSetName)] + [ValidateTrustedData] + public string TypeDefinition + { + get + { + return _sourceCode; + } + + set + { + _sourceCode = value; + } + } + + /// + /// The name of the type (class) used for auto-generated types. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromMemberParameterSetName)] + [ValidateTrustedData] + public string Name { get; set; } + + /// + /// The source code of this generated method / member. + /// + [Parameter(Mandatory = true, Position = 1, ParameterSetName = FromMemberParameterSetName)] + public string[] MemberDefinition + { + get + { + return new string[] { _sourceCode }; + } + + set + { + _sourceCode = string.Empty; + + if (value != null) + { + _sourceCode = string.Join('\n', value); + } + } + } + + private string _sourceCode; + + /// + /// The namespace used for the auto-generated type. + /// + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [AllowNull] + [Alias("NS")] + public string Namespace { get; set; } = "Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes"; + + /// + /// Any using statements required by the auto-generated type. + /// + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [ValidateNotNull] + [Alias("Using")] + public string[] UsingNamespace { get; set; } = Array.Empty(); + + /// + /// The path to the source code or DLL to load. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromPathParameterSetName)] + [ValidateTrustedData] + public string[] Path + { + get + { + return _paths; + } + + set + { + if (value == null) + { + _paths = null; + return; + } + + string[] pathValue = value; + + List resolvedPaths = new(); + + // Verify that the paths are resolved and valid + foreach (string path in pathValue) + { + // Try to resolve the path + Collection newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(path, out ProviderInfo _); + + // If it didn't resolve, add the original back + // for a better error message. + if (newPaths.Count == 0) + { + resolvedPaths.Add(path); + } + else + { + resolvedPaths.AddRange(newPaths); + } + } + + ProcessPaths(resolvedPaths); + } + } + + /// + /// The literal path to the source code or DLL to load. + /// + [Parameter(Mandatory = true, ParameterSetName = FromLiteralPathParameterSetName)] + [Alias("PSPath", "LP")] + [ValidateTrustedData] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + if (value == null) + { + _paths = null; + return; + } + + List resolvedPaths = new(); + foreach (string path in value) + { + string literalPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); + resolvedPaths.Add(literalPath); + } + + ProcessPaths(resolvedPaths); + } + } + + private void ProcessPaths(List resolvedPaths) + { + // Validate file extensions. + // Make sure we don't mix source files from different languages (if we support any other languages in future). + string activeExtension = null; + foreach (string path in resolvedPaths) + { + string currentExtension = PathType.GetExtension(path).ToUpperInvariant(); + + switch (currentExtension) + { + case ".CS": + Language = Language.CSharp; + break; + + case ".DLL": + _loadAssembly = true; + break; + + // Throw an error if it is an unrecognized extension + default: + ErrorRecord errorRecord = new( + new Exception( + StringUtil.Format(AddTypeStrings.FileExtensionNotSupported, currentExtension)), + "EXTENSION_NOT_SUPPORTED", + ErrorCategory.InvalidArgument, + currentExtension); + + ThrowTerminatingError(errorRecord); + break; + } + + if (activeExtension == null) + { + activeExtension = currentExtension; + } + else if (!string.Equals(activeExtension, currentExtension, StringComparison.OrdinalIgnoreCase)) + { + // All files must have the same extension otherwise throw. + ErrorRecord errorRecord = new( + new Exception( + StringUtil.Format(AddTypeStrings.MultipleExtensionsNotSupported)), + "MULTIPLE_EXTENSION_NOT_SUPPORTED", + ErrorCategory.InvalidArgument, + currentExtension); + + ThrowTerminatingError(errorRecord); + } + } + + _paths = resolvedPaths.ToArray(); + } + + private string[] _paths; + + /// + /// The name of the assembly to load. + /// + [Parameter(Mandatory = true, ParameterSetName = FromAssemblyNameParameterSetName)] + [Alias("AN")] + [ValidateTrustedData] + public string[] AssemblyName { get; set; } + + private bool _loadAssembly = false; + + /// + /// The language used to compile the source code. + /// Default is C#. + /// + [Parameter(ParameterSetName = FromSourceParameterSetName)] + [Parameter(ParameterSetName = FromMemberParameterSetName)] + public Language Language { get; set; } = Language.CSharp; + + /// + /// Any reference DLLs to use in the compilation. + /// + [Parameter(ParameterSetName = FromSourceParameterSetName)] + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [Parameter(ParameterSetName = FromPathParameterSetName)] + [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] + [Alias("RA")] + public string[] ReferencedAssemblies + { + get + { + return _referencedAssemblies; + } + + set + { + if (value != null) + { + _referencedAssemblies = value; + } + } + } + + private string[] _referencedAssemblies = Array.Empty(); + + /// + /// The path to the output assembly. + /// + [Parameter(ParameterSetName = FromSourceParameterSetName)] + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [Parameter(ParameterSetName = FromPathParameterSetName)] + [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] + [Alias("OA")] + public string OutputAssembly + { + get + { + return _outputAssembly; + } + + set + { + _outputAssembly = value; + + if (_outputAssembly != null) + { + _outputAssembly = _outputAssembly.Trim(); + + // Try to resolve the path + ProviderInfo provider = null; + Collection newPaths = new(); + + try + { + newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_outputAssembly, out provider); + } + // Ignore the ItemNotFound -- we handle it. + catch (ItemNotFoundException) { } + + ErrorRecord errorRecord = new( + new Exception( + StringUtil.Format(AddTypeStrings.OutputAssemblyDidNotResolve, _outputAssembly)), + "INVALID_OUTPUT_ASSEMBLY", + ErrorCategory.InvalidArgument, + _outputAssembly); + + // If it resolved to a non-standard provider, + // generate an error. + if (!string.Equals("FileSystem", provider.Name, StringComparison.OrdinalIgnoreCase)) + { + ThrowTerminatingError(errorRecord); + return; + } + + // If it resolved to more than one path, + // generate an error. + if (newPaths.Count > 1) + { + ThrowTerminatingError(errorRecord); + return; + } + // It didn't resolve to any files. They may + // want to create the file. + else if (newPaths.Count == 0) + { + // We can't create one with wildcard characters + if (WildcardPattern.ContainsWildcardCharacters(_outputAssembly)) + { + ThrowTerminatingError(errorRecord); + } + // Create the file + else + { + _outputAssembly = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_outputAssembly); + } + } + // It resolved to a single file + else + { + _outputAssembly = newPaths[0]; + } + } + } + } + + private string _outputAssembly = null; + + /// + /// The output type of the assembly. + /// + [Parameter(ParameterSetName = FromSourceParameterSetName)] + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [Parameter(ParameterSetName = FromPathParameterSetName)] + [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] + [Alias("OT")] + public OutputAssemblyType OutputType { get; set; } = OutputAssemblyType.Library; + + /// + /// Flag to pass the resulting types along. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + /// + /// Flag to ignore warnings during compilation. + /// + [Parameter(ParameterSetName = FromSourceParameterSetName)] + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [Parameter(ParameterSetName = FromPathParameterSetName)] + [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] + public SwitchParameter IgnoreWarnings { get; set; } + + /// + /// Roslyn command line parameters. + /// https://github.com/dotnet/roslyn/blob/master/docs/compilers/CSharp/CommandLine.md + /// + /// Parser options: + /// langversion:string - language version from: + /// [enum]::GetNames([Microsoft.CodeAnalysis.CSharp.LanguageVersion]) + /// define:symbol list - preprocessor symbols: + /// /define:UNIX,DEBUG - CSharp + /// + /// Compilation options: + /// optimize{+|-} - optimization level + /// parallel{+|-} - concurrent build + /// warnaserror{+|-} - report warnings to errors + /// warnaserror{+|-}:strings - report specific warnings to errors + /// warn:number - warning level (0-4) for CSharp + /// nowarn - disable all warnings + /// nowarn:strings - disable a list of individual warnings + /// usings:strings - ';'-delimited usings for CSharp + /// + /// Emit options: + /// platform:string - limit which platforms this code can run on; must be x86, x64, Itanium, arm, AnyCPU32BitPreferred or anycpu (default) + /// delaysign{+|-} - delay-sign the assembly using only the public portion of the strong name key + /// keyfile:file - specifies a strong name key file + /// keycontainer:string - specifies a strong name key container + /// highentropyva{+|-} - enable high-entropy ASLR. + /// + [Parameter(ParameterSetName = FromSourceParameterSetName)] + [Parameter(ParameterSetName = FromMemberParameterSetName)] + [Parameter(ParameterSetName = FromPathParameterSetName)] + [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] + [ValidateNotNullOrEmpty] + public string[] CompilerOptions { get; set; } + + #endregion Parameters + + #region GererateSource + + private string GenerateTypeSource(string typeNamespace, string typeName, string sourceCodeText, Language language) + { + string usingSource = string.Format( + CultureInfo.InvariantCulture, + GetUsingTemplate(language), GetUsingSet(language)); + + string typeSource = string.Format( + CultureInfo.InvariantCulture, + GetMethodTemplate(language), typeName, sourceCodeText); + + if (!string.IsNullOrEmpty(typeNamespace)) + { + return usingSource + string.Format( + CultureInfo.InvariantCulture, + GetNamespaceTemplate(language), typeNamespace, typeSource); + } + else + { + return usingSource + typeSource; + } + } + + // Get the -FromMember template for a given language + private static string GetMethodTemplate(Language language) + { + switch (language) + { + case Language.CSharp: + return + " public class {0}\n" + + " {{\n" + + " {1}\n" + + " }}\n"; + } + + throw PSTraceSource.NewNotSupportedException(); + } + + // Get the -FromMember namespace template for a given language + private static string GetNamespaceTemplate(Language language) + { + switch (language) + { + case Language.CSharp: + return + "namespace {0}\n" + + "{{\n" + + "{1}\n" + + "}}\n"; + } + + throw PSTraceSource.NewNotSupportedException(); + } + + // Get the -FromMember namespace template for a given language + private static string GetUsingTemplate(Language language) + { + switch (language) + { + case Language.CSharp: + return + "using System;\n" + + "using System.Runtime.InteropServices;\n" + + "{0}" + + "\n"; + } + + throw PSTraceSource.NewNotSupportedException(); + } + + // Generate the code for the using statements + private string GetUsingSet(Language language) + { + StringBuilder usingNamespaceSet = new(); + + switch (language) + { + case Language.CSharp: + foreach (string namespaceValue in UsingNamespace) + { + usingNamespaceSet.Append("using " + namespaceValue + ";\n"); + } + + break; + + default: + throw PSTraceSource.NewNotSupportedException(); + } + + return usingNamespaceSet.ToString(); + } + + #endregion GererateSource + + /// + /// Prevent code compilation in ConstrainedLanguage mode. + /// + protected override void BeginProcessing() + { + // Prevent code compilation in ConstrainedLanguage mode, or NoLanguage mode under system lock down. + if (SessionState.LanguageMode == PSLanguageMode.ConstrainedLanguage || + (SessionState.LanguageMode == PSLanguageMode.NoLanguage && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)) + { + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), + nameof(AddTypeStrings.CannotDefineNewType), + ErrorCategory.PermissionDenied, + targetObject: null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: AddTypeStrings.AddTypeLogTitle, + message: AddTypeStrings.AddTypeLogMessage, + fqid: "AddTypeCmdletDisabled", + dropIntoDebugger: true); + } + + // 'ConsoleApplication' and 'WindowsApplication' types are currently not working in .NET Core + if (OutputType != OutputAssemblyType.Library) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(AddTypeStrings.AssemblyTypeNotSupported), + nameof(AddTypeStrings.AssemblyTypeNotSupported), + ErrorCategory.NotImplemented, + targetObject: OutputType)); + } + } + + /// + /// Generate and load the type(s). + /// + protected override void EndProcessing() + { + // Generate an error if they've specified an output + // assembly type without an output assembly + if (string.IsNullOrEmpty(_outputAssembly) && this.MyInvocation.BoundParameters.ContainsKey(nameof(OutputType))) + { + ErrorRecord errorRecord = new( + new Exception( + string.Format( + CultureInfo.CurrentCulture, + AddTypeStrings.OutputTypeRequiresOutputAssembly)), + "OUTPUTTYPE_REQUIRES_ASSEMBLY", + ErrorCategory.InvalidArgument, + OutputType); + + ThrowTerminatingError(errorRecord); + return; + } + + if (_loadAssembly) + { + // File extension is ".DLL" (ParameterSetName = FromPathParameterSetName or FromLiteralPathParameterSetName). + LoadAssemblies(_paths); + } + else if (ParameterSetName == FromAssemblyNameParameterSetName) + { + LoadAssemblies(AssemblyName); + } + else + { + // Process a source code from files or strings. + SourceCodeProcessing(); + } + } + + #region LoadAssembly + + // We now ship .NET Core's reference assemblies with PowerShell, so that Add-Type can work + // in a predictable way and won't be broken when we move to newer version of .NET Core. + // The reference assemblies are located at '$PSHOME\ref' for pwsh. + // + // For applications that host PowerShell, the 'ref' folder will be deployed to the 'publish' + // folder, not where 'System.Management.Automation.dll' is located. So here we should use + // the entry assembly's location to construct the path to the 'ref' folder. + // For pwsh, the entry assembly is 'pwsh.dll', so the entry assembly's location is still + // $PSHOME. + // However, 'Assembly.GetEntryAssembly()' returns null when the managed code is called from + // unmanaged code (PowerShell WSMan remoting scenario), so in that case, we continue to use + // the location of 'System.Management.Automation.dll'. + private static readonly string s_netcoreAppRefFolder = PathType.Combine( + PathType.GetDirectoryName( + (Assembly.GetEntryAssembly() ?? typeof(PSObject).Assembly).Location), + "ref"); + + // Path to the folder where .NET Core runtime assemblies are located. + private static readonly string s_frameworkFolder = PathType.GetDirectoryName(typeof(object).Assembly.Location); + + // These assemblies are always automatically added to ReferencedAssemblies. + private static readonly Lazy s_autoReferencedAssemblies = new(InitAutoIncludedRefAssemblies); + + // A HashSet of assembly names to be ignored if they are specified in '-ReferencedAssemblies' + private static readonly Lazy> s_refAssemblyNamesToIgnore = new(InitRefAssemblyNamesToIgnore); + + // These assemblies are used, when ReferencedAssemblies parameter is not specified. + private static readonly Lazy> s_defaultAssemblies = new(InitDefaultRefAssemblies); + + private bool InMemory { get { return string.IsNullOrEmpty(_outputAssembly); } } + + // These dictionaries prevent reloading already loaded and unchanged code. + // We don't worry about unbounded growing of the cache because in .Net Core 2.0 we can not unload assemblies. + // TODO: review if we will be able to unload assemblies after migrating to .Net Core 2.1. + private static readonly ConcurrentDictionary s_sourceTypesCache = new(); + private static readonly ConcurrentDictionary s_sourceAssemblyCache = new(); + + private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; + + private const ReportDiagnostic defaultDiagnosticOption = ReportDiagnostic.Error; + + private static readonly string[] s_writeInformationTags = new string[] { "PSHOST" }; + private int _syntaxTreesHash; + + private const string FromMemberParameterSetName = "FromMember"; + private const string FromSourceParameterSetName = "FromSource"; + private const string FromPathParameterSetName = "FromPath"; + private const string FromLiteralPathParameterSetName = "FromLiteralPath"; + private const string FromAssemblyNameParameterSetName = "FromAssemblyName"; + + private void LoadAssemblies(IEnumerable assemblies) + { + foreach (string assemblyName in assemblies) + { + // CoreCLR doesn't allow re-load TPA assemblies with different API (i.e. we load them by name and now want to load by path). + // LoadAssemblyHelper helps us avoid re-loading them, if they already loaded. + // codeql[cs/dll-injection-remote] - This is expected PowerShell behavior and integral to the purpose of the class. It allows users to load any C# dependencies they need for their PowerShell application and add other types they require. + Assembly assembly = LoadAssemblyHelper(assemblyName) ?? Assembly.LoadFrom(ResolveAssemblyName(assemblyName, false)); + + if (PassThru) + { + WriteTypes(assembly); + } + } + } + + /// + /// Initialize the list of reference assemblies that will be used when '-ReferencedAssemblies' is not specified. + /// + private static IEnumerable InitDefaultRefAssemblies() + { + // Default reference assemblies consist of .NET reference assemblies and the 'S.M.A' assembly. + // Today, there are 161 .NET reference assemblies, so the needed capacity is 162, but we use 200 + // as the initial capacity to cover the possible increase of .NET reference assemblies in future. + var defaultRefAssemblies = new List(capacity: 200); + + foreach (string file in Directory.EnumerateFiles(s_netcoreAppRefFolder, "*.dll", SearchOption.TopDirectoryOnly)) + { + defaultRefAssemblies.Add(MetadataReference.CreateFromFile(file)); + } + + // Add System.Management.Automation.dll + defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location)); + + return defaultRefAssemblies; + } + + /// + /// Initialize the set of assembly names that should be ignored when they are specified in '-ReferencedAssemblies'. + /// - System.Private.CoreLib.ni.dll - the runtime dll that contains most core/primitive types + /// - System.Private.Uri.dll - the runtime dll that contains 'System.Uri' and related types + /// Referencing these runtime dlls may cause ambiguous type identity or other issues. + /// - System.Runtime.dll - the corresponding reference dll will be automatically included + /// - System.Runtime.InteropServices.dll - the corresponding reference dll will be automatically included. + /// + private static HashSet InitRefAssemblyNamesToIgnore() + { + return new HashSet(StringComparer.OrdinalIgnoreCase) { + PathType.GetFileName(typeof(object).Assembly.Location), + PathType.GetFileName(typeof(Uri).Assembly.Location), + PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(object))), + PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(SecureString))) + }; + } + + /// + /// Initialize the list of reference assemblies that will be automatically added when '-ReferencedAssemblies' is specified. + /// + private static PortableExecutableReference[] InitAutoIncludedRefAssemblies() + { + return new PortableExecutableReference[] { + MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(object))), + MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(SecureString))) + }; + } + + /// + /// Get the path of reference assembly where the type is declared. + /// + private static string GetReferenceAssemblyPathBasedOnType(Type type) + { + string refAsmFileName = PathType.GetFileName(ClrFacade.GetAssemblies(type.FullName).First().Location); + return PathType.Combine(s_netcoreAppRefFolder, refAsmFileName); + } + + private string ResolveAssemblyName(string assembly, bool isForReferenceAssembly) + { + ErrorRecord errorRecord; + + // if it's a path, resolve it + if (assembly.Contains(PathType.DirectorySeparatorChar) || assembly.Contains(PathType.AltDirectorySeparatorChar)) + { + if (PathType.IsPathRooted(assembly)) + { + return assembly; + } + else + { + var paths = SessionState.Path.GetResolvedPSPathFromPSPath(assembly); + if (paths.Count > 0) + { + return paths[0].Path; + } + else + { + errorRecord = new ErrorRecord( + new Exception( + string.Format(ParserStrings.ErrorLoadingAssembly, assembly)), + "ErrorLoadingAssembly", + ErrorCategory.InvalidOperation, + assembly); + + ThrowTerminatingError(errorRecord); + return null; + } + } + } + + string refAssemblyDll = assembly; + if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + { + // It could be a short assembly name or a full assembly name, but we + // always want the short name to find the corresponding assembly file. + var assemblyName = new AssemblyName(assembly); + refAssemblyDll = assemblyName.Name + ".dll"; + } + + // We look up in reference/framework only when it's for resolving reference assemblies. + // In case of 'Add-Type -AssemblyName' scenario, we don't attempt to resolve against framework assemblies because + // 1. Explicitly loading a framework assembly usually is not necessary in PowerShell 6+. + // 2. A user should use assembly name instead of path if they want to explicitly load a framework assembly. + if (isForReferenceAssembly) + { + // If it's for resolving a reference assembly, then we look in NetCoreApp ref assemblies first + string netcoreAppRefPath = PathType.Combine(s_netcoreAppRefFolder, refAssemblyDll); + if (File.Exists(netcoreAppRefPath)) + { + return netcoreAppRefPath; + } + + // Look up the assembly in the framework folder. This may happen when assembly is not part of + // NetCoreApp, but comes from an additional package, such as 'Json.Net'. + string frameworkPossiblePath = PathType.Combine(s_frameworkFolder, refAssemblyDll); + if (File.Exists(frameworkPossiblePath)) + { + return frameworkPossiblePath; + } + + // The assembly name may point to a third-party assembly that is already loaded at run time. + if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + { + Assembly result = LoadAssemblyHelper(assembly); + if (result != null) + { + return result.Location; + } + } + } + + // Look up the assembly in the current folder + var resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(refAssemblyDll); + + if (resolvedPaths.Count > 0) + { + string currentFolderPath = resolvedPaths[0].Path; + if (File.Exists(currentFolderPath)) + { + return currentFolderPath; + } + } + + errorRecord = new ErrorRecord( + new Exception( + string.Format(ParserStrings.ErrorLoadingAssembly, assembly)), + "ErrorLoadingAssembly", + ErrorCategory.InvalidOperation, + assembly); + + ThrowTerminatingError(errorRecord); + return null; + } + + // LoadWithPartialName is deprecated, so we have to write the closest approximation possible. + // However, this does give us a massive usability improvement, as users can just say + // Add-Type -AssemblyName Forms (instead of System.Windows.Forms) + // This is just long, not unmaintainable. + private static Assembly LoadAssemblyHelper(string assemblyName) + { + Assembly loadedAssembly = null; + + // First try by strong name + try + { + loadedAssembly = Assembly.Load(new AssemblyName(assemblyName)); + } + // Generates a FileNotFoundException if you can't load the strong type. + // So we'll try from the short name. + catch (System.IO.FileNotFoundException) { } + // File load exception can happen, when we trying to load from the incorrect assembly name + // or file corrupted. + catch (System.IO.FileLoadException) { } + + return loadedAssembly; + } + + private IEnumerable GetPortableExecutableReferences() + { + if (ReferencedAssemblies.Length > 0) + { + var tempReferences = new List(s_autoReferencedAssemblies.Value); + foreach (string assembly in ReferencedAssemblies) + { + if (string.IsNullOrWhiteSpace(assembly)) + { + continue; + } + + string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); + + // Ignore some specified reference assemblies + string fileName = PathType.GetFileName(resolvedAssemblyPath); + if (s_refAssemblyNamesToIgnore.Value.Contains(fileName)) + { + WriteVerbose(StringUtil.Format(AddTypeStrings.ReferenceAssemblyIgnored, resolvedAssemblyPath)); + continue; + } + + tempReferences.Add(MetadataReference.CreateFromFile(resolvedAssemblyPath)); + } + + return tempReferences; + } + else + { + return s_defaultAssemblies.Value; + } + } + + private void WriteTypes(Assembly assembly) + { + foreach (Type type in assembly.GetTypes()) + { + // We only write out types that are not auto-generated by compiler. + if (type.GetCustomAttribute() is null) + { + WriteObject(type); + } + } + } + + #endregion LoadAssembly + + #region SourceCodeProcessing + + private static OutputKind OutputAssemblyTypeToOutputKind(OutputAssemblyType outputType) + { + switch (outputType) + { + case OutputAssemblyType.Library: + return OutputKind.DynamicallyLinkedLibrary; + + default: + throw PSTraceSource.NewNotSupportedException(); + } + } + + private CommandLineArguments ParseCompilerOption(IEnumerable args) + { + string sdkDirectory = s_defaultSdkDirectory; + string baseDirectory = this.SessionState.Path.CurrentLocation.Path; + + switch (Language) + { + case Language.CSharp: + return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory); + + default: + throw PSTraceSource.NewNotSupportedException(); + } + } + + private SyntaxTree ParseSourceText(SourceText sourceText, ParseOptions parseOptions, string path = "") + { + switch (Language) + { + case Language.CSharp: + return CSharpSyntaxTree.ParseText(sourceText, (CSharpParseOptions)parseOptions, path); + + default: + throw PSTraceSource.NewNotSupportedException(); + } + } + + private CompilationOptions GetDefaultCompilationOptions() + { + switch (Language) + { + case Language.CSharp: + return new CSharpCompilationOptions(OutputAssemblyTypeToOutputKind(OutputType)); + + default: + throw PSTraceSource.NewNotSupportedException(); + } + } + + private bool IsSourceCodeUpdated(List syntaxTrees, out Assembly assembly) + { + Diagnostics.Assert(syntaxTrees.Count != 0, "syntaxTrees should contains a source code."); + + _syntaxTreesHash = SyntaxTreeArrayGetHashCode(syntaxTrees); + + if (s_sourceAssemblyCache.TryGetValue(_syntaxTreesHash, out Assembly hashedAssembly)) + { + assembly = hashedAssembly; + return false; + } + else + { + assembly = null; + return true; + } + } + + private void SourceCodeProcessing() + { + ParseOptions parseOptions = null; + CompilationOptions compilationOptions = null; + EmitOptions emitOptions = null; + + if (CompilerOptions != null) + { + var arguments = ParseCompilerOption(CompilerOptions); + + HandleCompilerErrors(arguments.Errors); + + parseOptions = arguments.ParseOptions; + compilationOptions = arguments.CompilationOptions.WithOutputKind(OutputAssemblyTypeToOutputKind(OutputType)); + emitOptions = arguments.EmitOptions; + } + else + { + parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); + compilationOptions = GetDefaultCompilationOptions(); + } + + if (!IgnoreWarnings.IsPresent) + { + compilationOptions = compilationOptions.WithGeneralDiagnosticOption(defaultDiagnosticOption); + } + + SourceText sourceText; + List syntaxTrees = new(); + + switch (ParameterSetName) + { + case FromPathParameterSetName: + case FromLiteralPathParameterSetName: + foreach (string filePath in _paths) + { + using (var sourceFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + sourceText = SourceText.From(sourceFile); + syntaxTrees.Add(ParseSourceText(sourceText, parseOptions, path: filePath)); + } + } + + break; + case FromMemberParameterSetName: + _sourceCode = GenerateTypeSource(Namespace, Name, _sourceCode, Language); + + sourceText = SourceText.From(_sourceCode); + syntaxTrees.Add(ParseSourceText(sourceText, parseOptions)); + break; + case FromSourceParameterSetName: + sourceText = SourceText.From(_sourceCode); + syntaxTrees.Add(ParseSourceText(sourceText, parseOptions)); + break; + default: + Diagnostics.Assert(false, "Invalid parameter set: {0}", this.ParameterSetName); + break; + } + + if (!string.IsNullOrEmpty(_outputAssembly) && !PassThru.IsPresent) + { + CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); + } + else + { + // if the source code was already compiled and loaded and not changed + // we get the assembly from the cache. + if (IsSourceCodeUpdated(syntaxTrees, out Assembly assembly)) + { + CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); + } + else + { + WriteVerbose(AddTypeStrings.AlreadyCompiledandLoaded); + + if (PassThru) + { + WriteTypes(assembly); + } + } + } + } + + private void CompileToAssembly(List syntaxTrees, CompilationOptions compilationOptions, EmitOptions emitOptions) + { + IEnumerable references = GetPortableExecutableReferences(); + Compilation compilation = null; + + switch (Language) + { + case Language.CSharp: + compilation = CSharpCompilation.Create( + PathType.GetRandomFileName(), + syntaxTrees: syntaxTrees, + references: references, + options: (CSharpCompilationOptions)compilationOptions); + break; + + default: + throw PSTraceSource.NewNotSupportedException(); + } + + DoEmitAndLoadAssembly(compilation, emitOptions); + } + + private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag newTypes) + { + AllNamedTypeSymbolsVisitor visitor = new(); + visitor.Visit(compilation.Assembly.GlobalNamespace); + + foreach (var symbolName in visitor.DuplicateSymbols) + { + ErrorRecord errorRecord = new( + new Exception( + string.Format(AddTypeStrings.TypeAlreadyExists, symbolName)), + "TYPE_ALREADY_EXISTS", + ErrorCategory.InvalidOperation, + symbolName); + WriteError(errorRecord); + } + + if (!visitor.DuplicateSymbols.IsEmpty) + { + ErrorRecord errorRecord = new( + new InvalidOperationException(AddTypeStrings.CompilerErrors), + "COMPILER_ERRORS", + ErrorCategory.InvalidData, + null); + ThrowTerminatingError(errorRecord); + } + + newTypes = visitor.UniqueSymbols; + + return; + } + + // Visit symbols in all namespaces and collect duplicates. + private sealed class AllNamedTypeSymbolsVisitor : SymbolVisitor + { + public readonly ConcurrentBag DuplicateSymbols = new(); + public readonly ConcurrentBag UniqueSymbols = new(); + + public override void VisitNamespace(INamespaceSymbol symbol) + { + // Main cycle. + // For large files we could use symbol.GetMembers().AsParallel().ForAll(s => s.Accept(this)); + foreach (var member in symbol.GetMembers()) + { + member.Accept(this); + } + } + + public override void VisitNamedType(INamedTypeSymbol symbol) + { + // It is namespace-fully-qualified name + var symbolFullName = symbol.ToString(); + + if (s_sourceTypesCache.ContainsKey(symbolFullName)) + { + DuplicateSymbols.Add(symbolFullName); + } + else + { + UniqueSymbols.Add(symbolFullName); + } + } + } + + private static void CacheNewTypes(ConcurrentBag newTypes) + { + foreach (var typeName in newTypes) + { + s_sourceTypesCache.TryAdd(typeName, null); + } + } + + private void CacheAssembly(Assembly assembly) + { + s_sourceAssemblyCache.TryAdd(_syntaxTreesHash, assembly); + } + + private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions) + { + EmitResult emitResult; + + CheckDuplicateTypes(compilation, out ConcurrentBag newTypes); + + if (InMemory) + { + using (var ms = new MemoryStream()) + { + emitResult = compilation.Emit(peStream: ms, options: emitOptions); + + HandleCompilerErrors(emitResult.Diagnostics); + + if (emitResult.Success) + { + ms.Seek(0, SeekOrigin.Begin); + Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); + + CacheNewTypes(newTypes); + CacheAssembly(assembly); + + if (PassThru) + { + WriteTypes(assembly); + } + } + } + } + else + { + using (var fs = new FileStream(_outputAssembly, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) + { + emitResult = compilation.Emit(peStream: fs, options: emitOptions); + } + + HandleCompilerErrors(emitResult.Diagnostics); + + if (emitResult.Success && PassThru) + { + Assembly assembly = Assembly.LoadFrom(_outputAssembly); + + CacheNewTypes(newTypes); + CacheAssembly(assembly); + + WriteTypes(assembly); + } + } + } + + private void HandleCompilerErrors(ImmutableArray compilerDiagnostics) + { + if (compilerDiagnostics.Length > 0) + { + bool IsError = false; + + foreach (var diagnisticRecord in compilerDiagnostics) + { + // We shouldn't specify input and output files in CompilerOptions parameter + // so suppress errors from Roslyn default command line parser: + // CS1562: Outputs without source must have the /out option specified + // CS2008: No inputs specified + // BC2008: No inputs specified + // + // On emit phase some warnings (like CS8019/BS50001) don't suppressed + // and present in diagnostic report with DefaultSeverity equal to Hidden + // so we skip them explicitly here too. + if (diagnisticRecord.IsSuppressed || diagnisticRecord.DefaultSeverity == DiagnosticSeverity.Hidden || + string.Equals(diagnisticRecord.Id, "CS2008", StringComparison.InvariantCulture) || + string.Equals(diagnisticRecord.Id, "CS1562", StringComparison.InvariantCulture) || + string.Equals(diagnisticRecord.Id, "BC2008", StringComparison.InvariantCulture)) + { + continue; + } + + if (!IsError) + { + IsError = diagnisticRecord.Severity == DiagnosticSeverity.Error || + (diagnisticRecord.IsWarningAsError && diagnisticRecord.Severity == DiagnosticSeverity.Warning); + } + + string errorText = BuildErrorMessage(diagnisticRecord); + + if (diagnisticRecord.Severity == DiagnosticSeverity.Warning) + { + WriteWarning(errorText); + } + else if (diagnisticRecord.Severity == DiagnosticSeverity.Info) + { + WriteInformation(errorText, s_writeInformationTags); + } + else + { + ErrorRecord errorRecord = new( + new Exception(errorText), + "SOURCE_CODE_ERROR", + ErrorCategory.InvalidData, + diagnisticRecord); + + WriteError(errorRecord); + } + } + + if (IsError) + { + ErrorRecord errorRecord = new( + new InvalidOperationException(AddTypeStrings.CompilerErrors), + "COMPILER_ERRORS", + ErrorCategory.InvalidData, + null); + ThrowTerminatingError(errorRecord); + } + } + } + + private static string BuildErrorMessage(Diagnostic diagnisticRecord) + { + var location = diagnisticRecord.Location; + + if (location.SourceTree == null) + { + // For some error types (linker?) we don't have related source code. + return diagnisticRecord.ToString(); + } + else + { + var text = location.SourceTree.GetText(); + var textLines = text.Lines; + + var lineSpan = location.GetLineSpan(); // FileLinePositionSpan type. + var errorLineNumber = lineSpan.StartLinePosition.Line; + + // This is typical Roslyn diagnostic message which contains + // a message number, a source context and an error position. + var diagnisticMessage = diagnisticRecord.ToString(); + var errorLineString = textLines[errorLineNumber].ToString(); + var errorPosition = lineSpan.StartLinePosition.Character; + + StringBuilder sb = new(diagnisticMessage.Length + errorLineString.Length * 2 + 4); + + sb.AppendLine(diagnisticMessage); + sb.AppendLine(errorLineString); + + for (var i = 0; i < errorLineString.Length; i++) + { + if (!char.IsWhiteSpace(errorLineString[i])) + { + // We copy white chars from the source string. + sb.Append(errorLineString, 0, i); + // then pad up to the error position. + sb.Append(' ', Math.Max(0, errorPosition - i)); + // then put "^" into the error position. + sb.AppendLine("^"); + break; + } + } + + return sb.ToString(); + } + } + + private static int SyntaxTreeArrayGetHashCode(IEnumerable sts) + { + // We use our extension method EnumerableExtensions.SequenceGetHashCode(). + List stHashes = new(); + foreach (var st in sts) + { + stHashes.Add(SyntaxTreeGetHashCode(st)); + } + + return stHashes.SequenceGetHashCode(); + } + + private static int SyntaxTreeGetHashCode(SyntaxTree st) + { + int hash; + + if (string.IsNullOrEmpty(st.FilePath)) + { + // If the file name does not exist, the source text is set by the user using parameters. + // In this case, we assume that the source text is of a small size and we can re-allocate by ToString(). + hash = st.ToString().GetHashCode(); + } + else + { + // If the file was modified, the write time stamp was also modified + // so we do not need to calculate the entire file hash. + var updateTime = File.GetLastWriteTimeUtc(st.FilePath); + hash = Utils.CombineHashCodes(st.FilePath.GetHashCode(), updateTime.GetHashCode()); + } + + return hash; + } + + #endregion SourceCodeProcessing + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..54a5b07cf5dd3819d2ba880d6d6d77f828a447de --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -0,0 +1,489 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// + [Cmdlet(VerbsData.Compare, "Object", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096605", + RemotingCapability = RemotingCapability.None)] + public sealed class CompareObjectCommand : ObjectCmdletBase + { + #region Parameters + /// + /// + [Parameter(Position = 0, Mandatory = true)] + [AllowEmptyCollection] + public PSObject[] ReferenceObject { get; set; } + + /// + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true)] + [AllowEmptyCollection] + public PSObject[] DifferenceObject { get; set; } + + /// + /// + [Parameter] + [ValidateRange(0, int.MaxValue)] + public int SyncWindow { get; set; } = int.MaxValue; + + /// + /// + /// + [Parameter] + public object[] Property { get; set; } + + /* not implemented + /// + /// + [Parameter] + public SwitchParameter IgnoreWhiteSpace + { + get { return _ignoreWhiteSpace; } + + set { _ignoreWhiteSpace = value; } + } + + private bool _ignoreWhiteSpace = false; + */ + + /// + /// + [Parameter] + public SwitchParameter ExcludeDifferent + { + get { return _excludeDifferent; } + + set { _excludeDifferent = value; } + } + + private bool _excludeDifferent /*=false*/; + + /// + /// + [Parameter] + public SwitchParameter IncludeEqual + { + get + { + return _includeEqual; + } + + set + { + _isIncludeEqualSpecified = true; + _includeEqual = value; + } + } + + private bool _includeEqual /* = false */; + private bool _isIncludeEqualSpecified /* = false */; + + /// + /// + [Parameter] + public SwitchParameter PassThru + { + get { return _passThru; } + + set { _passThru = value; } + } + + private bool _passThru /* = false */; + #endregion Parameters + + #region Internal + private List _referenceEntries; + + private readonly List _referenceEntryBacklog + = new(); + + private readonly List _differenceEntryBacklog + = new(); + + private OrderByProperty _orderByProperty = null; + private OrderByPropertyComparer _comparer = null; + + private int _referenceObjectIndex /* = 0 */; + + // These are programmatic strings, not subject to INTL + private const string SideIndicatorPropertyName = "SideIndicator"; + private const string SideIndicatorMatch = "=="; + private const string SideIndicatorReference = "<="; + private const string SideIndicatorDifference = "=>"; + private const string InputObjectPropertyName = "InputObject"; + + /// + /// The following is the matching algorithm: + /// Retrieve the incoming object (differenceEntry) if any + /// Retrieve the next reference object (referenceEntry) if any + /// If differenceEntry matches referenceEntry + /// Emit referenceEntry as a match + /// Return + /// If differenceEntry matches any entry in referenceEntryBacklog + /// Emit the backlog entry as a match + /// Remove the backlog entry from referenceEntryBacklog + /// Clear differenceEntry + /// If referenceEntry (if any) matches any entry in differenceEntryBacklog + /// Emit referenceEntry as a match + /// Remove the backlog entry from differenceEntryBacklog + /// Clear referenceEntry + /// If differenceEntry is still present + /// If SyncWindow is 0 + /// Emit differenceEntry as unmatched + /// Else + /// While there is no space in differenceEntryBacklog + /// Emit oldest entry in differenceEntryBacklog as unmatched + /// Remove oldest entry from differenceEntryBacklog + /// Add differenceEntry to differenceEntryBacklog + /// If referenceEntry is still present + /// If SyncWindow is 0 + /// Emit referenceEntry as unmatched + /// Else + /// While there is no space in referenceEntryBacklog + /// Emit oldest entry in referenceEntryBacklog as unmatched + /// Remove oldest entry from referenceEntryBacklog + /// Add referenceEntry to referenceEntryBacklog. + /// + /// + private void Process(OrderByPropertyEntry differenceEntry) + { + Diagnostics.Assert(_referenceEntries != null, "null referenceEntries"); + + // Retrieve the next reference object (referenceEntry) if any + OrderByPropertyEntry referenceEntry = null; + if (_referenceObjectIndex < _referenceEntries.Count) + { + referenceEntry = _referenceEntries[_referenceObjectIndex++]; + } + + // If differenceEntry matches referenceEntry + // Emit referenceEntry as a match + // Return + // 2005/07/19 Switched order of referenceEntry and differenceEntry + // so that we cast differenceEntry to the type of referenceEntry. + if (referenceEntry != null && differenceEntry != null && + _comparer.Compare(referenceEntry, differenceEntry) == 0) + { + EmitMatch(referenceEntry); + return; + } + + // If differenceEntry matches any entry in referenceEntryBacklog + // Emit the backlog entry as a match + // Remove the backlog entry from referenceEntryBacklog + // Clear differenceEntry + OrderByPropertyEntry matchingEntry = + MatchAndRemove(differenceEntry, _referenceEntryBacklog); + if (matchingEntry != null) + { + EmitMatch(matchingEntry); + differenceEntry = null; + } + + // If referenceEntry (if any) matches any entry in differenceEntryBacklog + // Emit referenceEntry as a match + // Remove the backlog entry from differenceEntryBacklog + // Clear referenceEntry + matchingEntry = + MatchAndRemove(referenceEntry, _differenceEntryBacklog); + if (matchingEntry != null) + { + EmitMatch(referenceEntry); + referenceEntry = null; + } + + // If differenceEntry is still present + // If SyncWindow is 0 + // Emit differenceEntry as unmatched + // Else + // While there is no space in differenceEntryBacklog + // Emit oldest entry in differenceEntryBacklog as unmatched + // Remove oldest entry from differenceEntryBacklog + // Add differenceEntry to differenceEntryBacklog + if (differenceEntry != null) + { + if (SyncWindow > 0) + { + while (_differenceEntryBacklog.Count >= SyncWindow) + { + EmitDifferenceOnly(_differenceEntryBacklog[0]); + _differenceEntryBacklog.RemoveAt(0); + } + + _differenceEntryBacklog.Add(differenceEntry); + } + else + { + EmitDifferenceOnly(differenceEntry); + } + } + + // If referenceEntry is still present + // If SyncWindow is 0 + // Emit referenceEntry as unmatched + // Else + // While there is no space in referenceEntryBacklog + // Emit oldest entry in referenceEntryBacklog as unmatched + // Remove oldest entry from referenceEntryBacklog + // Add referenceEntry to referenceEntryBacklog + if (referenceEntry != null) + { + if (SyncWindow > 0) + { + while (_referenceEntryBacklog.Count >= SyncWindow) + { + EmitReferenceOnly(_referenceEntryBacklog[0]); + _referenceEntryBacklog.RemoveAt(0); + } + + _referenceEntryBacklog.Add(referenceEntry); + } + else + { + EmitReferenceOnly(referenceEntry); + } + } + } + + private void InitComparer() + { + if (_comparer != null) + return; + + List referenceObjectList = new(ReferenceObject); + _orderByProperty = new OrderByProperty( + this, referenceObjectList, Property, true, _cultureInfo, CaseSensitive); + Diagnostics.Assert(_orderByProperty.Comparer != null, "no comparer"); + Diagnostics.Assert( + _orderByProperty.OrderMatrix != null && + _orderByProperty.OrderMatrix.Count == ReferenceObject.Length, + "no OrderMatrix"); + if (_orderByProperty.Comparer == null || _orderByProperty.OrderMatrix == null || _orderByProperty.OrderMatrix.Count == 0) + { + return; + } + + _comparer = _orderByProperty.Comparer; + _referenceEntries = _orderByProperty.OrderMatrix; + } + + private OrderByPropertyEntry MatchAndRemove( + OrderByPropertyEntry match, + List list) + { + if (match == null || list == null) + return null; + Diagnostics.Assert(_comparer != null, "null comparer"); + for (int i = 0; i < list.Count; i++) + { + OrderByPropertyEntry listEntry = list[i]; + Diagnostics.Assert(listEntry != null, "null listEntry " + i); + if (_comparer.Compare(match, listEntry) == 0) + { + list.RemoveAt(i); + return listEntry; + } + } + + return null; + } + + #region Emit + private void EmitMatch(OrderByPropertyEntry entry) + { + if (_includeEqual) + Emit(entry, SideIndicatorMatch); + } + + private void EmitDifferenceOnly(OrderByPropertyEntry entry) + { + if (!ExcludeDifferent) + Emit(entry, SideIndicatorDifference); + } + + private void EmitReferenceOnly(OrderByPropertyEntry entry) + { + if (!ExcludeDifferent) + Emit(entry, SideIndicatorReference); + } + + private void Emit(OrderByPropertyEntry entry, string sideIndicator) + { + Diagnostics.Assert(entry != null, "null entry"); + + PSObject mshobj; + if (PassThru) + { + mshobj = PSObject.AsPSObject(entry.inputObject); + } + else + { + mshobj = new PSObject(); + if (Property == null || Property.Length == 0) + { + PSNoteProperty inputNote = new( + InputObjectPropertyName, entry.inputObject); + mshobj.Properties.Add(inputNote); + } + else + { + List mshParameterList = _orderByProperty.MshParameterList; + Diagnostics.Assert(mshParameterList != null, "null mshParameterList"); + Diagnostics.Assert(mshParameterList.Count == Property.Length, "mshParameterList.Count " + mshParameterList.Count); + + for (int i = 0; i < Property.Length; i++) + { + // 2005/07/05 This is the closest we can come to + // the string typed by the user + MshParameter mshParameter = mshParameterList[i]; + Diagnostics.Assert(mshParameter != null, "null mshParameter"); + Hashtable hash = mshParameter.hash; + Diagnostics.Assert(hash != null, "null hash"); + object prop = hash[FormatParameterDefinitionKeys.ExpressionEntryKey]; + Diagnostics.Assert(prop != null, "null prop"); + string propName = prop.ToString(); + PSNoteProperty propertyNote = new( + propName, + entry.orderValues[i].PropertyValue); + try + { + mshobj.Properties.Add(propertyNote); + } + catch (ExtendedTypeSystemException) + { + // this is probably a duplicate add + } + } + } + } + + mshobj.Properties.Remove(SideIndicatorPropertyName); + PSNoteProperty sideNote = new( + SideIndicatorPropertyName, sideIndicator); + mshobj.Properties.Add(sideNote); + WriteObject(mshobj); + } + #endregion Emit + #endregion Internal + + #region Overrides + + /// + /// If the parameter 'ExcludeDifferent' is present, then the 'IncludeEqual' + /// switch is turned on unless it's turned off by the user specifically. + /// + protected override void BeginProcessing() + { + if (ExcludeDifferent) + { + if (_isIncludeEqualSpecified && !_includeEqual) + { + return; + } + + _includeEqual = true; + } + } + + /// + /// + protected override void ProcessRecord() + { + if (ReferenceObject == null || ReferenceObject.Length == 0) + { + HandleDifferenceObjectOnly(); + return; + } + else if (DifferenceObject == null || DifferenceObject.Length == 0) + { + HandleReferenceObjectOnly(); + return; + } + + if (_comparer == null && DifferenceObject.Length > 0) + { + InitComparer(); + } + + List differenceList = new(DifferenceObject); + List differenceEntries = + OrderByProperty.CreateOrderMatrix( + this, differenceList, _orderByProperty.MshParameterList); + + foreach (OrderByPropertyEntry incomingEntry in differenceEntries) + { + Process(incomingEntry); + } + } + + /// + /// + protected override void EndProcessing() + { + // Clear remaining reference objects if there are more + // reference objects than difference objects + if (_referenceEntries != null) + { + while (_referenceObjectIndex < _referenceEntries.Count) + { + Process(null); + } + } + + // emit all remaining backlogged objects + foreach (OrderByPropertyEntry differenceEntry in _differenceEntryBacklog) + { + EmitDifferenceOnly(differenceEntry); + } + + _differenceEntryBacklog.Clear(); + foreach (OrderByPropertyEntry referenceEntry in _referenceEntryBacklog) + { + EmitReferenceOnly(referenceEntry); + } + + _referenceEntryBacklog.Clear(); + } + #endregion Overrides + + private void HandleDifferenceObjectOnly() + { + if (DifferenceObject == null || DifferenceObject.Length == 0) + { + return; + } + + List differenceList = new(DifferenceObject); + _orderByProperty = new OrderByProperty( + this, differenceList, Property, true, _cultureInfo, CaseSensitive); + List differenceEntries = + OrderByProperty.CreateOrderMatrix( + this, differenceList, _orderByProperty.MshParameterList); + + foreach (OrderByPropertyEntry entry in differenceEntries) + { + EmitDifferenceOnly(entry); + } + } + + private void HandleReferenceObjectOnly() + { + if (ReferenceObject == null || ReferenceObject.Length == 0) + { + return; + } + + InitComparer(); + Process(null); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..e4d36c6610623ea157b1ecf4a720c87b3dd80b93 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Base class for a variety of commandlets that take color parameters. + /// + public + class ConsoleColorCmdlet : PSCmdlet + { + /// + /// Initializes a new instance of the class. + /// + public ConsoleColorCmdlet() + { + _consoleColorEnumType = typeof(ConsoleColor); + } + + /// + /// The -ForegroundColor parameter. + /// + /// + [Parameter] + public + ConsoleColor + ForegroundColor + { + get + { + if (!_isFgColorSet) + { + _fgColor = this.Host.UI.RawUI.ForegroundColor; + _isFgColorSet = true; + } + + return _fgColor; + } + + set + { + if (value >= (ConsoleColor)0 && value <= (ConsoleColor)15) + { + _fgColor = value; + _isFgColorSet = true; + } + else + { + ThrowTerminatingError(BuildOutOfRangeErrorRecord(value, "SetInvalidForegroundColor")); + } + } + } + + /// + /// + /// + [Parameter] + public + ConsoleColor + BackgroundColor + { + get + { + if (!_isBgColorSet) + { + _bgColor = this.Host.UI.RawUI.BackgroundColor; + _isBgColorSet = true; + } + + return _bgColor; + } + + set + { + if (value >= (ConsoleColor)0 && value <= (ConsoleColor)15) + { + _bgColor = value; + _isBgColorSet = true; + } + else + { + ThrowTerminatingError(BuildOutOfRangeErrorRecord(value, "SetInvalidBackgroundColor")); + } + } + } + + #region helper + private static ErrorRecord BuildOutOfRangeErrorRecord(object val, string errorId) + { + string msg = StringUtil.Format(HostStrings.InvalidColorErrorTemplate, val.ToString()); + ArgumentOutOfRangeException e = new("value", val, msg); + return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null); + } + #endregion helper + + private ConsoleColor _fgColor; + private ConsoleColor _bgColor; + + private bool _isFgColorSet = false; + private bool _isBgColorSet = false; + + private readonly Type _consoleColorEnumType; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs new file mode 100644 index 0000000000000000000000000000000000000000..48bda12cd8a3e07e0055a41c7029aa4b651afd86 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Converts a SDDL string into an object-based representation of a security descriptor. + /// + [Cmdlet(VerbsData.ConvertFrom, "SddlString", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=623636", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(SecurityDescriptorInfo))] + public sealed class ConvertFromSddlStringCommand : PSCmdlet + { + /// + /// Gets and sets the string representing the security descriptor in SDDL syntax. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + public string Sddl { get; set; } + + /// + /// Gets and sets type of rights that this SDDL string represents. + /// + [Parameter] + public AccessRightTypeNames Type + { + get + { + return _type; + } + + set + { + _isTypeSet = true; + _type = value; + } + } + + private AccessRightTypeNames _type; + private bool _isTypeSet = false; + + private static string ConvertToNTAccount(SecurityIdentifier securityIdentifier) + { + try + { + return securityIdentifier?.Translate(typeof(NTAccount)).Value; + } + catch + { + return null; + } + } + + private static List GetApplicableAccessRights(int accessMask, AccessRightTypeNames? typeName) + { + List typesToExamine = new(); + List foundAccessRightNames = new(); + HashSet foundAccessRightValues = new(); + + if (typeName != null) + { + typesToExamine.Add(GetRealAccessRightType(typeName.Value)); + } + else + { + foreach (AccessRightTypeNames member in Enum.GetValues()) + { + typesToExamine.Add(GetRealAccessRightType(member)); + } + } + + foreach (Type accessRightType in typesToExamine) + { + foreach (string memberName in Enum.GetNames(accessRightType)) + { + int memberValue = (int)Enum.Parse(accessRightType, memberName); + if (foundAccessRightValues.Add(memberValue)) + { + if ((accessMask & memberValue) == memberValue) + { + foundAccessRightNames.Add(memberName); + } + } + } + } + + foundAccessRightNames.Sort(StringComparer.OrdinalIgnoreCase); + return foundAccessRightNames; + } + + private static Type GetRealAccessRightType(AccessRightTypeNames typeName) + { + switch (typeName) + { + case AccessRightTypeNames.FileSystemRights: + return typeof(FileSystemRights); + case AccessRightTypeNames.RegistryRights: + return typeof(RegistryRights); + case AccessRightTypeNames.ActiveDirectoryRights: + return typeof(System.DirectoryServices.ActiveDirectoryRights); + case AccessRightTypeNames.MutexRights: + return typeof(MutexRights); + case AccessRightTypeNames.SemaphoreRights: + return typeof(SemaphoreRights); + case AccessRightTypeNames.EventWaitHandleRights: + return typeof(EventWaitHandleRights); + default: + throw new InvalidOperationException(); + } + } + + private static string[] ConvertAccessControlListToStrings(CommonAcl acl, AccessRightTypeNames? typeName) + { + if (acl == null || acl.Count == 0) + { + return Array.Empty(); + } + + List aceStringList = new(acl.Count); + foreach (CommonAce ace in acl) + { + StringBuilder aceString = new(); + string ntAccount = ConvertToNTAccount(ace.SecurityIdentifier); + aceString.Append($"{ntAccount}: {ace.AceQualifier}"); + + if (ace.AceFlags != AceFlags.None) + { + aceString.Append($" {ace.AceFlags}"); + } + + List accessRightList = GetApplicableAccessRights(ace.AccessMask, typeName); + if (accessRightList.Count > 0) + { + string accessRights = string.Join(", ", accessRightList); + aceString.Append($" ({accessRights})"); + } + + aceStringList.Add(aceString.ToString()); + } + + return aceStringList.ToArray(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + CommonSecurityDescriptor rawSecurityDescriptor = null; + try + { + rawSecurityDescriptor = new CommonSecurityDescriptor(isContainer: false, isDS: false, Sddl); + } + catch (Exception e) + { + var ioe = PSTraceSource.NewInvalidOperationException(e, UtilityCommonStrings.InvalidSDDL, e.Message); + ThrowTerminatingError(new ErrorRecord(ioe, "InvalidSDDL", ErrorCategory.InvalidArgument, Sddl)); + } + + string owner = ConvertToNTAccount(rawSecurityDescriptor.Owner); + string group = ConvertToNTAccount(rawSecurityDescriptor.Group); + + AccessRightTypeNames? typeToUse = _isTypeSet ? _type : (AccessRightTypeNames?)null; + string[] discretionaryAcl = ConvertAccessControlListToStrings(rawSecurityDescriptor.DiscretionaryAcl, typeToUse); + string[] systemAcl = ConvertAccessControlListToStrings(rawSecurityDescriptor.SystemAcl, typeToUse); + + var outObj = new SecurityDescriptorInfo(owner, group, discretionaryAcl, systemAcl, rawSecurityDescriptor); + WriteObject(outObj); + } + + /// + /// AccessRight type names. + /// + public enum AccessRightTypeNames + { + /// + /// FileSystemRights. + /// + FileSystemRights, + + /// + /// RegistryRights. + /// + RegistryRights, + + /// + /// ActiveDirectoryRights. + /// + ActiveDirectoryRights, + + /// + /// MutexRights. + /// + MutexRights, + + /// + /// SemaphoreRights. + /// + SemaphoreRights, + + // We have 'CryptoKeyRights' in the list for Windows PowerShell, but that type is not available in .NET Core. + // CryptoKeyRights, + + /// + /// EventWaitHandleRights. + /// + EventWaitHandleRights + } + } + + /// + /// Representation of a security descriptor. + /// + public sealed class SecurityDescriptorInfo + { + internal SecurityDescriptorInfo( + string owner, + string group, + string[] discretionaryAcl, + string[] systemAcl, + CommonSecurityDescriptor rawDescriptor) + { + Owner = owner; + Group = group; + DiscretionaryAcl = discretionaryAcl; + SystemAcl = systemAcl; + RawDescriptor = rawDescriptor; + } + + /// + /// EventWaitHandle rights. + /// + public readonly string Owner; + + /// + /// EventWaitHandle rights. + /// + public readonly string Group; + + /// + /// EventWaitHandle rights. + /// + public readonly string[] DiscretionaryAcl; + + /// + /// EventWaitHandle rights. + /// + public readonly string[] SystemAcl; + + /// + /// EventWaitHandle rights. + /// + public readonly CommonSecurityDescriptor RawDescriptor; + } +} + +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs new file mode 100644 index 0000000000000000000000000000000000000000..9272e85c05dbaa5dc41ae8ddf802de6bac1003ef --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Management.Automation; +using System.Text.RegularExpressions; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class comment. + /// + [Cmdlet(VerbsData.ConvertFrom, "StringData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096602", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(Hashtable))] + public sealed class ConvertFromStringDataCommand : PSCmdlet + { + private string _stringData; + + /// + /// The list of properties to display. + /// These take the form of an PSPropertyExpression. + /// + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + [AllowEmptyString] + public string StringData + { + get + { + return _stringData; + } + + set + { + _stringData = value; + } + } + + /// + /// Gets or sets the delimiter. + /// + [Parameter(Position = 1)] + public char Delimiter { get; set; } = '='; + + /// + /// + protected override void ProcessRecord() + { + Hashtable result = new(StringComparer.OrdinalIgnoreCase); + + if (string.IsNullOrEmpty(_stringData)) + { + WriteObject(result); + return; + } + + string[] lines = _stringData.Split('\n', StringSplitOptions.TrimEntries); + + foreach (string line in lines) + { + if (string.IsNullOrEmpty(line) || line[0] == '#') + continue; + + int index = line.IndexOf(Delimiter); + if (index <= 0) + { + throw PSTraceSource.NewInvalidOperationException( + ConvertFromStringData.InvalidDataLine, + line); + } + + string name = line.Substring(0, index); + name = name.Trim(); + + if (result.ContainsKey(name)) + { + throw PSTraceSource.NewInvalidOperationException( + ConvertFromStringData.DataItemAlreadyDefined, + line, + name); + } + + string value = line.Substring(index + 1); + value = value.Trim(); + + value = Regex.Unescape(value); + + result.Add(name, value); + } + + WriteObject(result); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..28d117f639fdc6fc976ccf027c03f7ad213f8293 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security; +using System.Threading.Tasks; + +using Microsoft.PowerShell.MarkdownRender; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Converts a Markdown string to a MarkdownInfo object. + /// The conversion can be done into a HTML text or VT100 encoding string. + /// + [Cmdlet( + VerbsData.ConvertFrom, "Markdown", + DefaultParameterSetName = PathParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006503")] + [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.MarkdownInfo))] + public class ConvertFromMarkdownCommand : PSCmdlet + { + /// + /// Gets or sets path to the file to convert from Markdown to MarkdownInfo. + /// + [ValidateNotNullOrEmpty] + [Parameter(ParameterSetName = PathParameterSet, Mandatory = true, Position = 0)] + public string[] Path { get; set; } + + /// + /// Gets or sets the path to the file to convert from Markdown to MarkdownInfo. + /// + [ValidateNotNullOrEmpty] + [Alias("PSPath", "LP")] + [Parameter(ParameterSetName = LiteralPathParameterSet, Mandatory = true)] + public string[] LiteralPath { get; set; } + + /// + /// Gets or sets the InputObject of type System.IO.FileInfo or string with content to convert from Markdown to MarkdownInfo. + /// + [ValidateNotNullOrEmpty] + [Parameter(ParameterSetName = InputObjParamSet, Mandatory = true, ValueFromPipeline = true)] + public PSObject InputObject { get; set; } + + /// + /// Gets or sets if the Markdown document should be converted to a VT100 encoded string. + /// + [Parameter] + public SwitchParameter AsVT100EncodedString { get; set; } + + private const string PathParameterSet = "PathParamSet"; + private const string LiteralPathParameterSet = "LiteralParamSet"; + private const string InputObjParamSet = "InputObjParamSet"; + + private MarkdownConversionType _conversionType = MarkdownConversionType.HTML; + private PSMarkdownOptionInfo _mdOption = null; + + /// + /// Read the PSMarkdownOptionInfo set in SessionState. + /// + protected override void BeginProcessing() + { + _mdOption = PSMarkdownOptionInfoCache.Get(this.CommandInfo); + + bool? supportsVT100 = this.Host?.UI.SupportsVirtualTerminal; + + // supportsVT100 == null if the host is null. + // supportsVT100 == false if host does not support VT100. + if (supportsVT100 != true) + { + _mdOption.EnableVT100Encoding = false; + } + + if (AsVT100EncodedString) + { + _conversionType = MarkdownConversionType.VT100; + } + } + + /// + /// Override ProcessRecord. + /// + protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case InputObjParamSet: + object baseObj = InputObject.BaseObject; + + if (baseObj is FileInfo fileInfo) + { + WriteObject( + MarkdownConverter.Convert( + ReadContentFromFile(fileInfo.FullName)?.Result, + _conversionType, + _mdOption)); + } + else if (baseObj is string inpObj) + { + WriteObject(MarkdownConverter.Convert(inpObj, _conversionType, _mdOption)); + } + else + { + string errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); + ErrorRecord errorRecord = new( + new InvalidDataException(errorMessage), + "InvalidInputObject", + ErrorCategory.InvalidData, + InputObject); + + WriteError(errorRecord); + } + + break; + + case PathParameterSet: + ConvertEachFile(Path, _conversionType, isLiteral: false, optionInfo: _mdOption); + break; + + case LiteralPathParameterSet: + ConvertEachFile(LiteralPath, _conversionType, isLiteral: true, optionInfo: _mdOption); + break; + } + } + + private void ConvertEachFile(IEnumerable paths, MarkdownConversionType conversionType, bool isLiteral, PSMarkdownOptionInfo optionInfo) + { + foreach (var path in paths) + { + var resolvedPaths = ResolvePath(path, isLiteral); + + foreach (var resolvedPath in resolvedPaths) + { + WriteObject( + MarkdownConverter.Convert( + ReadContentFromFile(resolvedPath)?.Result, + conversionType, + optionInfo)); + } + } + } + + private async Task ReadContentFromFile(string filePath) + { + ErrorRecord errorRecord = null; + + try + { + using (StreamReader reader = new(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))) + { + string mdContent = await reader.ReadToEndAsync(); + return mdContent; + } + } + catch (FileNotFoundException fnfe) + { + errorRecord = new ErrorRecord( + fnfe, + "FileNotFound", + ErrorCategory.ResourceUnavailable, + filePath); + } + catch (SecurityException se) + { + errorRecord = new ErrorRecord( + se, + "FileSecurityError", + ErrorCategory.SecurityError, + filePath); + } + catch (UnauthorizedAccessException uae) + { + errorRecord = new ErrorRecord( + uae, + "FileUnauthorizedAccess", + ErrorCategory.SecurityError, + filePath); + } + + WriteError(errorRecord); + return null; + } + + private List ResolvePath(string path, bool isLiteral) + { + ProviderInfo provider = null; + PSDriveInfo drive = null; + List resolvedPaths = new(); + + try + { + if (isLiteral) + { + resolvedPaths.Add(Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path, out provider, out drive)); + } + else + { + resolvedPaths.AddRange(Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider)); + } + } + catch (ItemNotFoundException infe) + { + var errorRecord = new ErrorRecord( + infe, + "FileNotFound", + ErrorCategory.ResourceUnavailable, + path); + + WriteError(errorRecord); + } + + if (!provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase)) + { + string errorMessage = StringUtil.Format(ConvertMarkdownStrings.FileSystemPathsOnly, path); + ErrorRecord errorRecord = new( + new ArgumentException(), + "OnlyFileSystemPathsSupported", + ErrorCategory.InvalidArgument, + path); + + WriteError(errorRecord); + + return null; + } + + return resolvedPaths; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs new file mode 100644 index 0000000000000000000000000000000000000000..41dd159a3ba0a42cee2ca47e955d869b1c20dd68 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -0,0 +1,761 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Net; +using System.Text; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class comment. + /// + [Cmdlet(VerbsData.ConvertTo, "Html", DefaultParameterSetName = "Page", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096595", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(string))] + public sealed + class ConvertToHtmlCommand : PSCmdlet + { + /// The incoming object + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject + { + get + { + return _inputObject; + } + + set + { + _inputObject = value; + } + } + + private PSObject _inputObject; + + /// + /// The list of properties to display. + /// These take the form of a PSPropertyExpression. + /// + /// + [Parameter(Position = 0)] + public object[] Property + { + get + { + return _property; + } + + set + { + _property = value; + } + } + + private object[] _property; + + /// + /// Text to go after the opening body tag and before the table. + /// + /// + [Parameter(ParameterSetName = "Page", Position = 3)] + public string[] Body + { + get + { + return _body; + } + + set + { + _body = value; + } + } + + private string[] _body; + + /// + /// Text to go into the head section of the html doc. + /// + /// + [Parameter(ParameterSetName = "Page", Position = 1)] + public string[] Head + { + get + { + return _head; + } + + set + { + _head = value; + } + } + + private string[] _head; + + /// + /// The string for the title tag + /// The title is also placed in the body of the document + /// before the table between h3 tags + /// If the -Head parameter is used, this parameter has no + /// effect. + /// + /// + [Parameter(ParameterSetName = "Page", Position = 2)] + [ValidateNotNullOrEmpty] + public string Title + { + get + { + return _title; + } + + set + { + _title = value; + } + } + + private string _title = "HTML TABLE"; + + /// + /// This specifies whether the objects should + /// be rendered as an HTML TABLE or + /// HTML LIST. + /// + /// + [Parameter] + [ValidateNotNullOrEmpty] + [ValidateSet("Table", "List")] + public string As + { + get + { + return _as; + } + + set + { + _as = value; + } + } + + private string _as = "Table"; + + /// + /// This specifies a full or partial URI + /// for the CSS information. + /// The HTML should reference the CSS file specified. + /// + [Parameter(ParameterSetName = "Page")] + [Alias("cu", "uri")] + [ValidateNotNullOrEmpty] + public Uri CssUri + { + get + { + return _cssuri; + } + + set + { + _cssuri = value; + _cssuriSpecified = true; + } + } + + private Uri _cssuri; + private bool _cssuriSpecified; + + /// + /// When this switch is specified generate only the + /// HTML representation of the incoming object + /// without the HTML,HEAD,TITLE,BODY,etc tags. + /// + [Parameter(ParameterSetName = "Fragment")] + [ValidateNotNullOrEmpty] + public SwitchParameter Fragment + { + get + { + return _fragment; + } + + set + { + _fragment = value; + } + } + + private SwitchParameter _fragment; + + /// + /// Specifies the text to include prior the closing body tag of the HTML output. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] PostContent + { + get + { + return _postContent; + } + + set + { + _postContent = value; + } + } + + private string[] _postContent; + + /// + /// Specifies the text to include after the body tag of the HTML output. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] PreContent + { + get + { + return _preContent; + } + + set + { + _preContent = value; + } + } + + private string[] _preContent; + + /// + /// Sets and Gets the meta property of the HTML head. + /// + /// + [Parameter(ParameterSetName = "Page")] + [ValidateNotNullOrEmpty] + public Hashtable Meta + { + get + { + return _meta; + } + + set + { + _meta = value; + _metaSpecified = true; + } + } + + private Hashtable _meta; + private bool _metaSpecified = false; + + /// + /// Specifies the charset encoding for the HTML document. + /// + [Parameter(ParameterSetName = "Page")] + [ValidateNotNullOrEmpty] + [ValidatePattern("^[A-Za-z0-9]\\w+\\S+[A-Za-z0-9]$")] + public string Charset + { + get + { + return _charset; + } + + set + { + _charset = value; + _charsetSpecified = true; + } + } + + private string _charset; + private bool _charsetSpecified = false; + + /// + /// When this switch statement is specified, + /// it will change the DOCTYPE to XHTML Transitional DTD. + /// + /// + [Parameter(ParameterSetName = "Page")] + [ValidateNotNullOrEmpty] + public SwitchParameter Transitional + { + get + { + return _transitional; + } + + set + { + _transitional = true; + } + } + + private bool _transitional = false; + + /// + /// Definitions for hash table keys. + /// + internal static class ConvertHTMLParameterDefinitionKeys + { + internal const string LabelEntryKey = "label"; + internal const string AlignmentEntryKey = "alignment"; + internal const string WidthEntryKey = "width"; + } + + /// + /// This allows for @{e='foo';label='bar';alignment='center';width='20'}. + /// + internal sealed class ConvertHTMLExpressionParameterDefinition : CommandParameterDefinition + { + protected override void SetEntries() + { + this.hashEntries.Add(new ExpressionEntryDefinition()); + this.hashEntries.Add(new LabelEntryDefinition()); + this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, new[] { typeof(string) })); + + // Note: We accept "width" as either string or int. + this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, new[] { typeof(string), typeof(int) })); + } + } + + /// + /// Create a list of MshParameter from properties. + /// + /// Can be a string, ScriptBlock, or Hashtable. + /// + private List ProcessParameter(object[] properties) + { + TerminatingErrorContext invocationContext = new(this); + ParameterProcessor processor = + new(new ConvertHTMLExpressionParameterDefinition()); + properties ??= new object[] { "*" }; + + return processor.ProcessParameters(properties, invocationContext); + } + + /// + /// Resolve all wildcards in user input Property into resolvedNameMshParameters. + /// + private void InitializeResolvedNameMshParameters() + { + // temp list of properties with wildcards resolved + var resolvedNameProperty = new List(); + + foreach (MshParameter p in _propertyMshParameterList) + { + string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; + string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; + + // Accept the width both as a string and as an int. + string width; + int? widthNum = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as int?; + width = widthNum != null ? widthNum.Value.ToString() : p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string; + PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; + List resolvedNames = ex.ResolveNames(_inputObject); + foreach (PSPropertyExpression resolvedName in resolvedNames) + { + Hashtable ht = CreateAuxPropertyHT(label, alignment, width); + if (resolvedName.Script != null) + { + // The argument is a calculated property whose value is calculated by a script block. + ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.Script); + } + else + { + ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.ToString()); + } + resolvedNameProperty.Add(ht); + } + } + + _resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray()); + } + + private static Hashtable CreateAuxPropertyHT( + string label, + string alignment, + string width) + { + Hashtable ht = new(); + if (label != null) + { + ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label); + } + + if (alignment != null) + { + ht.Add(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, alignment); + } + + if (width != null) + { + ht.Add(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, width); + } + + return ht; + } + + /// + /// Calls ToString. If an exception occurs, eats it and return string.Empty. + /// + /// + /// + private static string SafeToString(object obj) + { + if (obj == null) + { + return string.Empty; + } + + try + { + return obj.ToString(); + } + catch (Exception) + { + // eats exception if safe + } + + return string.Empty; + } + + /// + /// + protected override void BeginProcessing() + { + // ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here + if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim()))) + { + ArgumentException ex = new(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri")); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri"); + ThrowTerminatingError(er); + } + + _propertyMshParameterList = ProcessParameter(_property); + + if (!string.IsNullOrEmpty(_title)) + { + WebUtility.HtmlEncode(_title); + } + + // This first line ensures w3c validation will succeed. However we are not specifying + // an encoding in the HTML because we don't know where the text will be written and + // if a particular encoding will be used. + + if (!_fragment) + { + if (!_transitional) + { + WriteObject(""); + } + else + { + WriteObject(""); + } + + WriteObject(""); + WriteObject(""); + if (_charsetSpecified) + { + WriteObject(""); + } + + if (_metaSpecified) + { + List useditems = new(); + foreach (string s in _meta.Keys) + { + if (!useditems.Contains(s)) + { + switch (s.ToLower()) + { + case "content-type": + case "default-style": + case "x-ua-compatible": + WriteObject(""); + break; + case "application-name": + case "author": + case "description": + case "generator": + case "keywords": + case "viewport": + WriteObject(""); + break; + default: + MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; + string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); + WarningRecord record = new(Message); + + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) + { + record.SetInvocationInfo(invocationInfo); + } + + mshCommandRuntime.WriteWarning(record); + WriteObject(""); + break; + } + + useditems.Add(s); + } + } + } + + WriteObject(_head ?? new string[] { "" + _title + "" }, true); + if (_cssuriSpecified) + { + WriteObject(""); + } + + WriteObject(""); + if (_body != null) + { + WriteObject(_body, true); + } + } + + if (_preContent != null) + { + WriteObject(_preContent, true); + } + + WriteObject(""); + _isTHWritten = false; + } + + /// + /// Reads Width and Alignment from Property and write Col tags. + /// + /// + private void WriteColumns(List mshParams) + { + StringBuilder COLTag = new(); + + COLTag.Append(""); + foreach (MshParameter p in mshParams) + { + COLTag.Append(""); + } + + COLTag.Append(""); + + // The columngroup and col nodes will be printed in a single line. + WriteObject(COLTag.ToString()); + } + + /// + /// Writes the list entries when the As parameter has value List. + /// + private void WriteListEntry() + { + foreach (MshParameter p in _resolvedNameMshParameters) + { + StringBuilder Listtag = new(); + Listtag.Append(""); + + // for writing the property value + Listtag.Append(""); + + WriteObject(Listtag.ToString()); + } + } + + /// + /// To write the Property name. + /// + private static void WritePropertyName(StringBuilder Listtag, MshParameter p) + { + // for writing the property name + if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) is string label) + { + Listtag.Append(label); + } + else + { + PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; + Listtag.Append(ex.ToString()); + } + } + + /// + /// To write the Property value. + /// + private void WritePropertyValue(StringBuilder Listtag, MshParameter p) + { + PSPropertyExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; + + // get the value of the property + List resultList = exValue.GetValues(_inputObject); + foreach (PSPropertyExpressionResult result in resultList) + { + // create comma sep list for multiple results + if (result.Result != null) + { + string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result)); + Listtag.Append(htmlEncodedResult); + } + + Listtag.Append(", "); + } + + if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal)) + { + Listtag.Remove(Listtag.Length - 2, 2); + } + } + + /// + /// To write the Table header for the object property names. + /// + private static void WriteTableHeader(StringBuilder THtag, List resolvedNameMshParameters) + { + // write the property names + foreach (MshParameter p in resolvedNameMshParameters) + { + THtag.Append(""); + } + } + + /// + /// To write the Table row for the object property values. + /// + private void WriteTableRow(StringBuilder TRtag, List resolvedNameMshParameters) + { + // write the property values + foreach (MshParameter p in resolvedNameMshParameters) + { + TRtag.Append(""); + } + } + + // count of the objects + private int _numberObjects = 0; + + /// + /// + protected override void ProcessRecord() + { + // writes the table headers + // it is not in BeginProcessing because the first inputObject is needed for + // the number of columns and column name + if (_inputObject == null || _inputObject == AutomationNull.Value) + { + return; + } + + _numberObjects++; + if (!_isTHWritten) + { + InitializeResolvedNameMshParameters(); + if (_resolvedNameMshParameters == null || _resolvedNameMshParameters.Count == 0) + { + return; + } + + // if the As parameter is given as List + if (_as.Equals("List", StringComparison.OrdinalIgnoreCase)) + { + // if more than one object,write the horizontal rule to put visual separator + if (_numberObjects > 1) + WriteObject(""); + WriteListEntry(); + } + else // if the As parameter is Table, first we have to write the property names + { + WriteColumns(_resolvedNameMshParameters); + + StringBuilder THtag = new(""); + + // write the table header + WriteTableHeader(THtag, _resolvedNameMshParameters); + + THtag.Append(""); + WriteObject(THtag.ToString()); + _isTHWritten = true; + } + } + // if the As parameter is Table, write the property values + if (_as.Equals("Table", StringComparison.OrdinalIgnoreCase)) + { + StringBuilder TRtag = new(""); + + // write the table row + WriteTableRow(TRtag, _resolvedNameMshParameters); + + TRtag.Append(""); + WriteObject(TRtag.ToString()); + } + } + + /// + /// + protected override void EndProcessing() + { + // if fragment,end with table + WriteObject("
"); + + // for writing the property name + WritePropertyName(Listtag, p); + Listtag.Append(':'); + Listtag.Append(""); + WritePropertyValue(Listtag, p); + Listtag.Append("
"); + WritePropertyName(THtag, p); + THtag.Append(""); + WritePropertyValue(TRtag, p); + TRtag.Append("

"); + if (_postContent != null) + WriteObject(_postContent, true); + + // if not fragment end with body and html also + if (!_fragment) + { + WriteObject(""); + } + } + + #region private + + /// + /// List of incoming objects to compare. + /// + private bool _isTHWritten; + private List _propertyMshParameterList; + private List _resolvedNameMshParameters; + // private string ResourcesBaseName = "ConvertHTMLStrings"; + + #endregion private + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs new file mode 100644 index 0000000000000000000000000000000000000000..d0b9f91e7f755aede5443a2f995aa30967072833 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.ObjectModel; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class is used to parse CSV text. + /// + internal sealed class CSVHelper + { + internal CSVHelper(char delimiter) + { + Delimiter = delimiter; + } + + /// + /// Gets or sets the delimiter that separates the values. + /// + internal char Delimiter { get; } = ','; + + /// + /// Parse a CSV string. + /// + /// + /// String to be parsed. + /// + internal Collection ParseCsv(string csv) + { + Collection result = new(); + string tempString = string.Empty; + csv = csv.Trim(); + if (csv.Length == 0 || csv[0] == '#') + { + return result; + } + + bool inQuote = false; + for (int i = 0; i < csv.Length; i++) + { + char c = csv[i]; + if (c == Delimiter) + { + if (!inQuote) + { + result.Add(tempString); + tempString = string.Empty; + } + else + { + tempString += c; + } + } + else + { + switch (c) + { + case '"': + if (inQuote) + { + // If we are at the end of the string or the end of the segment, create a new value + // Otherwise we have an error + if (i == csv.Length - 1) + { + result.Add(tempString); + tempString = string.Empty; + inQuote = false; + break; + } + + if (csv[i + 1] == Delimiter) + { + result.Add(tempString); + tempString = string.Empty; + inQuote = false; + i++; + } + else if (csv[i + 1] == '"') + { + tempString += '"'; + i++; + } + else + { + inQuote = false; + } + } + else + { + inQuote = true; + } + + break; + + default: + tempString += c; + break; + } + } + } + + if (tempString.Length > 0) + { + result.Add(tempString); + } + + return result; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..cb455417531de6a6eb485b3a1028f72d5916fd21 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -0,0 +1,1813 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; + +#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings + +namespace Microsoft.PowerShell.Commands +{ + #region BaseCsvWritingCommand + + /// + /// This class implements the base for exportcsv and converttocsv commands. + /// + public abstract class BaseCsvWritingCommand : PSCmdlet + { + #region Command Line Parameters + + /// + /// Property that sets delimiter. + /// + [Parameter(Position = 1, ParameterSetName = "Delimiter")] + [ValidateNotNull] + public char Delimiter { get; set; } + + /// + /// Culture switch for csv conversion + /// + [Parameter(ParameterSetName = "UseCulture")] + public SwitchParameter UseCulture { get; set; } + + /// + /// Abstract Property - Input Object which is written in Csv format. + /// Derived as Different Attributes.In ConvertTo-CSV, This is a positional parameter. Export-CSV not a Positional behaviour. + /// + public abstract PSObject InputObject { get; set; } + + /// + /// IncludeTypeInformation : The #TYPE line should be generated. Default is false. + /// + [Parameter] + [Alias("ITI")] + public SwitchParameter IncludeTypeInformation { get; set; } + + /// + /// Gets or sets a value indicating whether to suppress the #TYPE line. + /// This parameter is obsolete and has no effect. It is retained for backward compatibility only. + /// + [Parameter(DontShow = true)] + [Alias("NTI")] + [Obsolete("This parameter is obsolete and has no effect. The default behavior is to not include type information. Use -IncludeTypeInformation to include type information.")] + public SwitchParameter NoTypeInformation { get; set; } = true; + + /// + /// Gets or sets list of fields to quote in output. + /// + [Parameter] + [Alias("QF")] + public string[] QuoteFields { get; set; } + + /// + /// Gets or sets option to use or suppress quotes in output. + /// + [Parameter] + [Alias("UQ")] + public QuoteKind UseQuotes { get; set; } = QuoteKind.Always; + + /// + /// Gets or sets property that writes csv file with no headers. + /// + [Parameter] + public SwitchParameter NoHeader { get; set; } + + #endregion Command Line Parameters + + /// + /// Kind of output quoting. + /// + public enum QuoteKind + { + /// + /// Never quote output. + /// + Never, + + /// + /// Always quote output. + /// + Always, + + /// + /// Quote output as needed (a field contains used delimiter). + /// + AsNeeded + } + + /// + /// Write the string to a file or pipeline. + /// + public virtual void WriteCsvLine(string line) + { + } + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + if (this.MyInvocation.BoundParameters.ContainsKey(nameof(QuoteFields)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(UseQuotes))) + { + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyQuoteFieldsAndUseQuotes); + ErrorRecord errorRecord = new(exception, "CannotSpecifyQuoteFieldsAndUseQuotes", ErrorCategory.InvalidData, null); + this.ThrowTerminatingError(errorRecord); + } + + Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture); + } + } + #endregion + + #region Export-CSV Command + + /// + /// Implementation for the Export-Csv command. + /// + [Cmdlet(VerbsData.Export, "Csv", SupportsShouldProcess = true, DefaultParameterSetName = "Delimiter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096608")] + public sealed class ExportCsvCommand : BaseCsvWritingCommand, IDisposable + { + #region Command Line Parameters + + // If a Passthru parameter is added, the ShouldProcess + // implementation will need to be changed. + + /// + /// Input Object for CSV Writing. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public override PSObject InputObject { get; set; } + + /// + /// Mandatory file name to write to. + /// + [Parameter(Position = 0)] + [ValidateNotNullOrEmpty] + public string Path + { + get + { + return _path; + } + + set + { + _path = value; + _specifiedPath = true; + } + } + + private string _path; + private bool _specifiedPath = false; + + /// + /// The literal path of the mandatory file name to write to. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string LiteralPath + { + get + { + return _path; + } + + set + { + _path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// Gets or sets property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force { get; set; } + + /// + /// Gets or sets property that prevents file overwrite. + /// + [Parameter] + [Alias("NoOverwrite")] + public SwitchParameter NoClobber { get; set; } + + /// + /// Gets or sets encoding optional flag. + /// + [Parameter] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + /// + /// Gets or sets property that sets append parameter. + /// + [Parameter] + public SwitchParameter Append { get; set; } + + // true if Append=true AND the file written was not empty (or nonexistent) when the cmdlet was invoked + private bool _isActuallyAppending; + + #endregion + + #region Overrides + + private bool _shouldProcess; + private IList _propertyNames; + private IList _preexistingPropertyNames; + private ExportCsvHelper _helper; + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + base.BeginProcessing(); + + // Validate that they don't provide both Path and LiteralPath, but have provided at least one. + if (!(_specifiedPath ^ _isLiteralPath)) + { + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); + ErrorRecord errorRecord = new(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); + this.ThrowTerminatingError(errorRecord); + } + + // Validate that Append and NoHeader are not specified together. + if (Append && NoHeader) + { + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyAppendAndNoHeader); + ErrorRecord errorRecord = new(exception, "CannotSpecifyBothAppendAndNoHeader", ErrorCategory.InvalidData, null); + this.ThrowTerminatingError(errorRecord); + } + + _shouldProcess = ShouldProcess(Path); + if (!_shouldProcess) + { + return; + } + + CreateFileStream(); + + _helper = new ExportCsvHelper(base.Delimiter, base.UseQuotes, base.QuoteFields); + } + + /// + /// Convert the current input object to Csv and write to file/WriteObject. + /// + protected override void ProcessRecord() + { + if (InputObject == null || _sw == null) + { + return; + } + + if (!_shouldProcess) + { + return; + } + + // Process first object + if (_propertyNames == null) + { + // figure out the column names (and lock-in their order) + _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); + if (_isActuallyAppending && _preexistingPropertyNames != null) + { + this.ReconcilePreexistingPropertyNames(); + } + + // write headers (row1: typename + row2: column names) + if (!_isActuallyAppending && !NoHeader.IsPresent) + { + if (IncludeTypeInformation) + { + WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); + } + + WriteCsvLine(_helper.ConvertPropertyNamesCSV(_propertyNames)); + } + } + + string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); + WriteCsvLine(csv); + } + + /// + /// EndProcessing. + /// + protected override void EndProcessing() + { + CleanUp(); + } + + #endregion Overrides + + #region file + + /// + /// Handle to file stream. + /// + private FileStream _fs; + + /// + /// Stream writer used to write to file. + /// + private StreamWriter _sw = null; + + /// + /// Handle to file whose read-only attribute should be reset when we are done. + /// + private FileInfo _readOnlyFileInfo = null; + + private void CreateFileStream() + { + if (_path == null) + { + throw new InvalidOperationException(CsvCommandStrings.FileNameIsAMandatoryParameter); + } + + string resolvedFilePath = PathUtils.ResolveFilePath(this.Path, this, _isLiteralPath); + + bool isCsvFileEmpty = true; + + if (this.Append && File.Exists(resolvedFilePath)) + { + using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath)) + { + isCsvFileEmpty = streamReader.Peek() == -1; + } + } + + // If the csv file is empty then even append is treated as regular export (i.e., both header & values are added to the CSV file). + _isActuallyAppending = this.Append && File.Exists(resolvedFilePath) && !isCsvFileEmpty; + + if (_isActuallyAppending) + { + Encoding encodingObject; + + using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath)) + { + ImportCsvHelper readingHelper = new( + this, this.Delimiter, null /* header */, null /* typeName */, streamReader); + readingHelper.ReadHeader(); + _preexistingPropertyNames = readingHelper.Header; + + encodingObject = streamReader.CurrentEncoding; + } + + PathUtils.MasterStreamOpen( + this, + this.Path, + encodingObject, + defaultEncoding: false, + Append, + Force, + NoClobber, + out _fs, + out _sw, + out _readOnlyFileInfo, + _isLiteralPath); + } + else + { + PathUtils.MasterStreamOpen( + this, + this.Path, + Encoding, + defaultEncoding: false, + Append, + Force, + NoClobber, + out _fs, + out _sw, + out _readOnlyFileInfo, + _isLiteralPath); + } + } + + private void CleanUp() + { + if (_fs != null) + { + if (_sw != null) + { + _sw.Dispose(); + _sw = null; + } + + _fs.Dispose(); + _fs = null; + + // reset the read-only attribute + if (_readOnlyFileInfo != null) + _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + } + + _helper?.Dispose(); + } + + private void ReconcilePreexistingPropertyNames() + { + if (!_isActuallyAppending) + { + throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenAppending); + } + + if (_preexistingPropertyNames == null) + { + throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenPreexistingPropertyNamesHaveBeenReadSuccessfully); + } + + HashSet appendedPropertyNames = new(StringComparer.OrdinalIgnoreCase); + foreach (string appendedPropertyName in _propertyNames) + { + appendedPropertyNames.Add(appendedPropertyName); + } + + foreach (string preexistingPropertyName in _preexistingPropertyNames) + { + if (!appendedPropertyNames.Contains(preexistingPropertyName)) + { + if (!Force) + { + string errorMessage = string.Format( + CultureInfo.InvariantCulture, // property names and file names are culture invariant + CsvCommandStrings.CannotAppendCsvWithMismatchedPropertyNames, + preexistingPropertyName, + this.Path); + InvalidOperationException exception = new(errorMessage); + ErrorRecord errorRecord = new(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName); + this.ThrowTerminatingError(errorRecord); + } + } + } + + _propertyNames = _preexistingPropertyNames; + _preexistingPropertyNames = null; + } + + /// + /// Write the csv line to file. + /// + /// Line to write. + public override void WriteCsvLine(string line) + { + // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 + if (_disposed) + { + throw PSTraceSource.NewObjectDisposedException("ExportCsvCommand"); + } + + _sw.WriteLine(line); + } + #endregion file + + #region IDisposable Members + + /// + /// Set to true when object is disposed. + /// + private bool _disposed; + + /// + /// Public dispose method. + /// + public void Dispose() + { + if (!_disposed) + { + CleanUp(); + } + + _disposed = true; + } + + #endregion IDisposable Members + } + + #endregion Export-CSV Command + + #region Import-CSV Command + + /// + /// Implements Import-Csv command. + /// + [Cmdlet(VerbsData.Import, "Csv", DefaultParameterSetName = "DelimiterPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097020")] + public sealed class ImportCsvCommand : PSCmdlet + { + #region Command Line Parameters + + /// + /// Gets or sets property that sets delimiter. + /// + [Parameter(Position = 1, ParameterSetName = "DelimiterPath")] + [Parameter(Position = 1, ParameterSetName = "DelimiterLiteralPath")] + [ValidateNotNull] + public char Delimiter { get; set; } + + /// + /// Gets or sets mandatory file name to read from. + /// + [Parameter(Position = 0, ParameterSetName = "DelimiterPath", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "CulturePath", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string[] Path + { + get + { + return _paths; + } + + set + { + _paths = value; + _specifiedPath = true; + } + } + + private string[] _paths; + private bool _specifiedPath = false; + + /// + /// Gets or sets the literal path of the mandatory file name to read from. + /// + [Parameter(ParameterSetName = "DelimiterLiteralPath", Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = "CultureLiteralPath", Mandatory = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + _paths = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// Gets or sets property that sets UseCulture parameter. + /// + [Parameter(ParameterSetName = "CulturePath", Mandatory = true)] + [Parameter(ParameterSetName = "CultureLiteralPath", Mandatory = true)] + [ValidateNotNull] + public SwitchParameter UseCulture { get; set; } + + /// + /// Gets or sets header property to customize the names. + /// + [Parameter(Mandatory = false)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Header { get; set; } + + /// + /// Gets or sets encoding optional flag. + /// + [Parameter] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + /// + /// Avoid writing out duplicate warning messages when there are one or more unspecified names. + /// + private bool _alreadyWarnedUnspecifiedNames = false; + + #endregion Command Line Parameters + + #region Override Methods + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture); + } + + /// + /// ProcessRecord overload. + /// + protected override void ProcessRecord() + { + // Validate that they don't provide both Path and LiteralPath, but have provided at least one. + if (!(_specifiedPath ^ _isLiteralPath)) + { + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); + ErrorRecord errorRecord = new(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); + this.ThrowTerminatingError(errorRecord); + } + + if (_paths != null) + { + foreach (string path in _paths) + { + using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, _isLiteralPath)) + { + ImportCsvHelper helper = new(this, Delimiter, Header, null /* typeName */, streamReader); + + try + { + helper.Import(ref _alreadyWarnedUnspecifiedNames); + } + catch (ExtendedTypeSystemException exception) + { + ErrorRecord errorRecord = new(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null); + this.ThrowTerminatingError(errorRecord); + } + } + } + } + } + } + #endregion Override Methods + + #endregion Import-CSV Command + + #region ConvertTo-CSV Command + + /// + /// Implements ConvertTo-Csv command. + /// + [Cmdlet(VerbsData.ConvertTo, "Csv", DefaultParameterSetName = "Delimiter", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096832", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(string))] + public sealed class ConvertToCsvCommand : BaseCsvWritingCommand + { + #region Parameter + + /// + /// Overrides Base InputObject. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] + public override PSObject InputObject { get; set; } + + #endregion Parameter + + #region Overrides + + /// + /// Stores Property Names. + /// + private IList _propertyNames; + + /// + /// + private ExportCsvHelper _helper; + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + base.BeginProcessing(); + _helper = new ExportCsvHelper(base.Delimiter, base.UseQuotes, base.QuoteFields); + } + + /// + /// Convert the current input object to Csv and write to stream/WriteObject. + /// + protected override void ProcessRecord() + { + if (InputObject == null) + { + return; + } + + // Process first object + if (_propertyNames == null) + { + _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); + + if (!NoHeader.IsPresent) + { + if (IncludeTypeInformation) + { + WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); + } + + // Write property information + string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); + if (!properties.Equals(string.Empty)) + { + WriteCsvLine(properties); + } + } + } + + string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); + + // Write to the output stream + if (csv != string.Empty) + { + WriteCsvLine(csv); + } + } + + #endregion Overrides + + #region CSV conversion + /// + /// Write the line to output. + /// + /// Line to write. + public override void WriteCsvLine(string line) + { + WriteObject(line); + } + + #endregion CSV conversion + } + + #endregion ConvertTo-CSV Command + + #region ConvertFrom-CSV Command + + /// + /// Implements ConvertFrom-Csv command. + /// + [Cmdlet(VerbsData.ConvertFrom, "Csv", DefaultParameterSetName = "Delimiter", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096830", RemotingCapability = RemotingCapability.None)] + public sealed class ConvertFromCsvCommand : PSCmdlet + { + #region Command Line Parameters + + /// + /// Property that sets delimiter. + /// + [Parameter(Position = 1, ParameterSetName = "Delimiter")] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + public char Delimiter { get; set; } + + /// + /// Culture switch for csv conversion + /// + [Parameter(ParameterSetName = "UseCulture", Mandatory = true)] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + public SwitchParameter UseCulture { get; set; } + + /// + /// Gets or sets input object which is written in Csv format. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public PSObject[] InputObject { get; set; } + + /// + /// Gets or sets header property to customize the names. + /// + [Parameter(Mandatory = false)] + [ValidateNotNull] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Header { get; set; } + + /// + /// Avoid writing out duplicate warning messages when there are one or more unspecified names. + /// + private bool _alreadyWarnedUnspecifiedNames = false; + + #endregion Command Line Parameters + + #region Overrides + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture); + } + + /// + /// Convert the current input object to Csv and write to stream/WriteObject. + /// + protected override void ProcessRecord() + { + foreach (PSObject inputObject in InputObject) + { + using (MemoryStream memoryStream = new(Encoding.Unicode.GetBytes(inputObject.ToString()))) + using (StreamReader streamReader = new(memoryStream, System.Text.Encoding.Unicode)) + { + ImportCsvHelper helper = new(this, Delimiter, Header, _typeName, streamReader); + + try + { + helper.Import(ref _alreadyWarnedUnspecifiedNames); + } + catch (ExtendedTypeSystemException exception) + { + ErrorRecord errorRecord = new(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null); + this.ThrowTerminatingError(errorRecord); + } + + if ((Header == null) && (helper.Header != null)) + { + Header = helper.Header.ToArray(); + } + + if ((_typeName == null) && (helper.TypeName != null)) + { + _typeName = helper.TypeName; + } + } + } + } + + #endregion Overrides + + private string _typeName; + } + + #endregion ConvertFrom-CSV Command + + #region CSV conversion + + #region ExportHelperConversion + + /// + /// Helper class for Export-Csv and ConvertTo-Csv. + /// + internal sealed class ExportCsvHelper : IDisposable + { + private readonly char _delimiter; + private readonly BaseCsvWritingCommand.QuoteKind _quoteKind; + private readonly HashSet _quoteFields; + private readonly StringBuilder _outputString; + + /// + /// Initializes a new instance of the class. + /// + /// Delimiter char. + /// Kind of quoting. + /// List of fields to quote. + internal ExportCsvHelper(char delimiter, BaseCsvWritingCommand.QuoteKind quoteKind, string[] quoteFields) + { + _delimiter = delimiter; + _quoteKind = quoteKind; + _quoteFields = quoteFields == null ? null : new HashSet(quoteFields, StringComparer.OrdinalIgnoreCase); + _outputString = new StringBuilder(128); + } + + // Name of properties to be written in CSV format + + /// + /// Get the name of properties from source PSObject and add them to _propertyNames. + /// + internal static IList BuildPropertyNames(PSObject source, IList propertyNames) + { + if (propertyNames != null) + { + throw new InvalidOperationException(CsvCommandStrings.BuildPropertyNamesMethodShouldBeCalledOnlyOncePerCmdletInstance); + } + + propertyNames = new Collection(); + if (source.BaseObject is IDictionary dictionary) + { + foreach (var key in dictionary.Keys) + { + propertyNames.Add(LanguagePrimitives.ConvertTo(key)); + } + + // Add additional extended members added to the dictionary object, if any + var propertiesToSearch = new PSMemberInfoIntegratingCollection( + source, + PSObject.GetPropertyCollection(PSMemberViewTypes.Extended)); + + foreach (var prop in propertiesToSearch) + { + propertyNames.Add(prop.Name); + } + } + else + { + // serialize only Extended and Adapted properties. + PSMemberInfoCollection srcPropertiesToSearch = + new PSMemberInfoIntegratingCollection( + source, + PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted)); + + foreach (PSPropertyInfo prop in srcPropertiesToSearch) + { + propertyNames.Add(prop.Name); + } + } + + return propertyNames; + } + + /// + /// Converts PropertyNames in to a CSV string. + /// + /// Converted string. + internal string ConvertPropertyNamesCSV(IList propertyNames) + { + ArgumentNullException.ThrowIfNull(propertyNames); + + _outputString.Clear(); + bool first = true; + + foreach (string propertyName in propertyNames) + { + if (first) + { + first = false; + } + else + { + _outputString.Append(_delimiter); + } + + if (_quoteFields != null) + { + if (_quoteFields.TryGetValue(propertyName, out _)) + { + AppendStringWithEscapeAlways(_outputString, propertyName); + } + else + { + _outputString.Append(propertyName); + } + } + else + { + switch (_quoteKind) + { + case BaseCsvWritingCommand.QuoteKind.Always: + AppendStringWithEscapeAlways(_outputString, propertyName); + break; + case BaseCsvWritingCommand.QuoteKind.AsNeeded: + + if (propertyName.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1) + { + AppendStringWithEscapeAlways(_outputString, propertyName); + } + else + { + _outputString.Append(propertyName); + } + + break; + case BaseCsvWritingCommand.QuoteKind.Never: + _outputString.Append(propertyName); + break; + } + } + } + + return _outputString.ToString(); + } + + /// + /// Convert PSObject to CSV string. + /// + /// PSObject to convert. + /// Property names. + /// + internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames) + { + ArgumentNullException.ThrowIfNull(propertyNames); + + _outputString.Clear(); + bool first = true; + + foreach (string propertyName in propertyNames) + { + if (first) + { + first = false; + } + else + { + _outputString.Append(_delimiter); + } + + string value = null; + if (mshObject.BaseObject is IDictionary dictionary) + { + if (dictionary.Contains(propertyName)) + { + value = dictionary[propertyName]?.ToString(); + } + else if (mshObject.Properties[propertyName] is PSPropertyInfo property) + { + value = GetToStringValueForProperty(property); + } + } + else if (mshObject.Properties[propertyName] is PSPropertyInfo property) + { + value = GetToStringValueForProperty(property); + } + + // If value is null, assume property is not present and skip it. + if (value != null) + { + if (_quoteFields != null) + { + if (_quoteFields.TryGetValue(propertyName, out _)) + { + AppendStringWithEscapeAlways(_outputString, value); + } + else + { + _outputString.Append(value); + } + } + else + { + switch (_quoteKind) + { + case BaseCsvWritingCommand.QuoteKind.Always: + AppendStringWithEscapeAlways(_outputString, value); + break; + case BaseCsvWritingCommand.QuoteKind.AsNeeded: + if (value != null && value.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1) + { + AppendStringWithEscapeAlways(_outputString, value); + } + else + { + _outputString.Append(value); + } + + break; + case BaseCsvWritingCommand.QuoteKind.Never: + _outputString.Append(value); + break; + default: + Diagnostics.Assert(false, "BaseCsvWritingCommand.QuoteKind has new item."); + break; + } + } + } + } + + return _outputString.ToString(); + } + + /// + /// Get value from property object. + /// + /// Property to convert. + /// ToString() value. + internal static string GetToStringValueForProperty(PSPropertyInfo property) + { + ArgumentNullException.ThrowIfNull(property); + + string value = null; + try + { + object temp = property.Value; + if (temp != null) + { + value = temp.ToString(); + } + } + catch (Exception) + { + // If we cannot read some value, treat it as null. + } + + return value; + } + + /// + /// Prepares string for writing type information. + /// + /// PSObject whose type to determine. + /// String with type information. + internal static string GetTypeString(PSObject source) + { + string type = null; + + // get type of source + Collection tnh = source.TypeNames; + if (tnh == null || tnh.Count == 0) + { + type = "#TYPE"; + } + else + { + if (tnh[0] == null) + { + throw new InvalidOperationException(CsvCommandStrings.TypeHierarchyShouldNotHaveNullValues); + } + + string temp = tnh[0]; + + // If type starts with CSV: remove it. This would happen when you export + // an imported object. import-csv adds CSV. prefix to the type. + if (temp.StartsWith(ImportExportCSVHelper.CSVTypePrefix, StringComparison.OrdinalIgnoreCase)) + { + temp = temp.Substring(4); + } + + type = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"#TYPE {temp}"); + } + + return type; + } + + /// + /// Escapes the " in string if necessary. + /// Encloses the string in double quotes if necessary. + /// + internal static void AppendStringWithEscapeAlways(StringBuilder dest, string source) + { + if (source == null) + { + return; + } + + // Adding Double quote to all strings + dest.Append('"'); + for (int i = 0; i < source.Length; i++) + { + char c = source[i]; + + // Double quote in the string is escaped with double quote + if (c == '"') + { + dest.Append('"'); + } + + dest.Append(c); + } + + dest.Append('"'); + } + + #region IDisposable Members + + /// + /// Set to true when object is disposed. + /// + private bool _disposed; + + /// + /// Public dispose method. + /// + public void Dispose() + { + if (!_disposed) + { + GC.SuppressFinalize(this); + } + + _disposed = true; + } + + #endregion IDisposable Members + } + + #endregion ExportHelperConversion + + #region ImportHelperConversion + + /// + /// Helper class to import single CSV file. + /// + internal sealed class ImportCsvHelper + { + #region constructor + + /// + /// Reference to cmdlet which is using this helper class. + /// + private readonly PSCmdlet _cmdlet; + + /// + /// CSV delimiter (default is the "comma" / "," character). + /// + private readonly char _delimiter; + + /// + /// Use "UnspecifiedName" when the name is null or empty. + /// + private const string UnspecifiedName = "H"; + + /// + /// Avoid writing out duplicate warning messages when there are one or more unspecified names. + /// + private bool _alreadyWarnedUnspecifiedName = false; + + /// + /// Gets reference to header values. + /// + internal IList Header { get; private set; } + + /// + /// Gets ETS type name from the first line / comment in the CSV. + /// + internal string TypeName { get; private set; } + + /// + /// Reader of the csv content. + /// + private readonly StreamReader _sr; + + // Initial sizes of the value list and the line stringbuilder. + // Set to reasonable initial sizes. They may grow beyond these, + // but this will prevent a few reallocations. + private const int ValueCountGuestimate = 16; + private const int LineLengthGuestimate = 256; + + internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList header, string typeName, StreamReader streamReader) + { + ArgumentNullException.ThrowIfNull(cmdlet); + ArgumentNullException.ThrowIfNull(streamReader); + + _cmdlet = cmdlet; + _delimiter = delimiter; + Header = header; + TypeName = typeName; + _sr = streamReader; + } + + #endregion constructor + + #region reading helpers + + /// + /// This is set to true when end of file is reached. + /// + private bool EOF => _sr.EndOfStream; + + private char ReadChar() + { + if (EOF) + { + throw new InvalidOperationException(CsvCommandStrings.EOFIsReached); + } + + int i = _sr.Read(); + return (char)i; + } + + /// + /// Peeks the next character in the stream and returns true if it is same as passed in character. + /// + /// + /// + private bool PeekNextChar(char c) + { + int i = _sr.Peek(); + if (i == -1) + { + return false; + } + + return c == (char)i; + } + + /// + /// Reads a line from file. This consumes the end of line. + /// Only use it when end of line chars are not important. + /// + /// Line from file. + private string ReadLine() => _sr.ReadLine(); + + #endregion reading helpers + + internal void ReadHeader() + { + // Read #Type record if available + if ((TypeName == null) && (!this.EOF)) + { + TypeName = ReadTypeInformation(); + } + + var values = new List(ValueCountGuestimate); + var builder = new StringBuilder(LineLengthGuestimate); + while ((Header == null) && (!this.EOF)) + { + ParseNextRecord(values, builder); + + // Trim all trailing blankspaces and delimiters ( single/multiple ). + // If there is only one element in the row and if its a blankspace we dont trim it. + // A trailing delimiter is represented as a blankspace while being added to result collection + // which is getting trimmed along with blankspaces supplied through the CSV in the below loop. + while (values.Count > 1 && values[values.Count - 1].Equals(string.Empty)) + { + values.RemoveAt(values.Count - 1); + } + + // File starts with '#' and contains '#Fields:' is W3C Extended Log File Format + if (values.Count != 0 && values[0].StartsWith("#Fields: ")) + { + values[0] = values[0].Substring(9); + Header = values; + } + else if (values.Count != 0 && values[0].StartsWith('#')) + { + // Skip all lines starting with '#' + } + else + { + // This is not W3C Extended Log File Format + // By default first line is Header + Header = values; + } + } + + if (Header != null && Header.Count > 0) + { + ValidatePropertyNames(Header); + } + } + + internal void Import(ref bool alreadyWriteOutWarning) + { + _alreadyWarnedUnspecifiedName = alreadyWriteOutWarning; + ReadHeader(); + var prevalidated = false; + var values = new List(ValueCountGuestimate); + var builder = new StringBuilder(LineLengthGuestimate); + while (true) + { + ParseNextRecord(values, builder); + if (values.Count == 0) + break; + + if (values.Count == 1 && string.IsNullOrEmpty(values[0])) + { + // skip the blank lines + continue; + } + + PSObject result = BuildMshobject(TypeName, Header, values, _delimiter, prevalidated); + prevalidated = true; + _cmdlet.WriteObject(result); + } + + alreadyWriteOutWarning = _alreadyWarnedUnspecifiedName; + } + + /// + /// Validate the names of properties. + /// + /// + private static void ValidatePropertyNames(IList names) + { + if (names != null) + { + if (names.Count == 0) + { + // If there are no names, it is an error + } + else + { + HashSet headers = new(StringComparer.OrdinalIgnoreCase); + foreach (string currentHeader in names) + { + if (!string.IsNullOrEmpty(currentHeader)) + { + if (!headers.Add(currentHeader)) + { + // throw a terminating error as there are duplicate headers in the input. + string memberAlreadyPresentMsg = + string.Format( + CultureInfo.InvariantCulture, + ExtendedTypeSystem.MemberAlreadyPresent, + currentHeader); + + ExtendedTypeSystemException exception = new(memberAlreadyPresentMsg); + throw exception; + } + } + } + } + } + } + + /// + /// Read the type information, if present. + /// + /// Type string if present else null. + private string ReadTypeInformation() + { + string type = null; + if (PeekNextChar('#')) + { + string temp = ReadLine(); + if (temp.StartsWith("#Type", StringComparison.OrdinalIgnoreCase)) + { + type = temp.Substring(5); + type = type.Trim(); + if (type.Length == 0) + { + type = null; + } + } + } + + return type; + } + + /// + /// Reads the next record from the file and returns parsed collection of string. + /// + /// + /// Parsed collection of strings. + /// + private void ParseNextRecord(List result, StringBuilder current) + { + result.Clear(); + + // current string + current.Clear(); + + bool seenBeginQuote = false; + + while (!EOF) + { + // Read the next character + char ch = ReadChar(); + + if (ch == _delimiter) + { + if (seenBeginQuote) + { + // Delimiter inside double quotes is part of string. + // Ex: + // "foo, bar" + // is parsed as + // ->foo, bar<- + current.Append(ch); + } + else + { + // Delimiter outside quotes is end of current word. + result.Add(current.ToString()); + current.Remove(0, current.Length); + } + } + else if (ch == '"') + { + if (seenBeginQuote) + { + if (PeekNextChar('"')) + { + // "" inside double quote are single quote + // ex: "foo""bar" + // is read as + // ->foo"bar<- + + // PeekNextChar only peeks. Read the next char. + ReadChar(); + current.Append('"'); + } + else + { + // We have seen a matching end quote. + seenBeginQuote = false; + + // Read + // everything till we hit next delimiter. + // In correct CSV,1) end quote is followed by delimiter + // 2)end quote is followed some whitespaces and + // then delimiter. + // We eat the whitespaces seen after the ending quote. + // However if there are other characters, we add all of them + // to string. + // Ex: ->"foo bar"<- is read as ->foo bar<- + // ->"foo bar" <- is read as ->foo bar<- + // ->"foo bar" ab <- is read as ->"foo bar" ab <- + bool endofRecord = false; + ReadTillNextDelimiter(current, ref endofRecord, true); + result.Add(current.ToString()); + current.Remove(0, current.Length); + if (endofRecord) + break; + } + } + else if (current.Length == 0) + { + // We are at the beginning of a new word. + // This quote is the first quote. + seenBeginQuote = true; + } + else + { + // We are seeing a quote after the start of + // the word. This is error, however we will be + // lenient here and do what excel does: + // Ex: foo "ba,r" + // In above example word read is ->foo "ba<- + // Basically we read till next delimiter + bool endOfRecord = false; + current.Append(ch); + ReadTillNextDelimiter(current, ref endOfRecord, false); + result.Add(current.ToString()); + current.Remove(0, current.Length); + if (endOfRecord) + break; + } + } + else if (ch == ' ' || ch == '\t') + { + if (seenBeginQuote) + { + // Spaces in side quote are valid + current.Append(ch); + } + else if (current.Length == 0) + { + // ignore leading spaces + continue; + } + else + { + // We are not in quote and we are not at the + // beginning of a word. We should not be seeing + // spaces here. This is an error condition, however + // we will be lenient here and do what excel does, + // that is read till next delimiter. + // Ex: ->foo <- is read as ->foo<- + // Ex: ->foo bar<- is read as ->foo bar<- + // Ex: ->foo bar <- is read as ->foo bar <- + // Ex: ->foo bar "er,ror"<- is read as ->foo bar "er<- + bool endOfRecord = false; + current.Append(ch); + ReadTillNextDelimiter(current, ref endOfRecord, true); + result.Add(current.ToString()); + current.Remove(0, current.Length); + + if (endOfRecord) + { + break; + } + } + } + else if (IsNewLine(ch, out string newLine)) + { + if (seenBeginQuote) + { + // newline inside quote are valid + current.Append(newLine); + } + else + { + result.Add(current.ToString()); + current.Remove(0, current.Length); + + // New line outside quote is end of word and end of record + break; + } + } + else + { + current.Append(ch); + } + } + + if (current.Length != 0) + { + result.Add(current.ToString()); + } + } + + // If we detect a newline we return it as a string "\r", "\n" or "\r\n" + private bool IsNewLine(char ch, out string newLine) + { + newLine = string.Empty; + if (ch == '\r') + { + if (PeekNextChar('\n')) + { + ReadChar(); + newLine = "\r\n"; + } + else + { + newLine = "\r"; + } + } + else if (ch == '\n') + { + newLine = "\n"; + } + + return newLine != string.Empty; + } + + /// + /// This function reads the characters till next delimiter and adds them to current. + /// + /// + /// + /// This is true if end of record is reached + /// when delimiter is hit. This would be true if delimiter is NewLine. + /// + /// + /// If this is true, eat the trailing blanks. Note:if there are non + /// whitespace characters present, then trailing blanks are not consumed. + /// + private void ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, bool eatTrailingBlanks) + { + StringBuilder temp = new(); + + // Did we see any non-whitespace character + bool nonWhiteSpace = false; + + while (true) + { + if (EOF) + { + endOfRecord = true; + break; + } + + char ch = ReadChar(); + + if (ch == _delimiter) + { + break; + } + else if (IsNewLine(ch, out string newLine)) + { + endOfRecord = true; + break; + } + else + { + temp.Append(ch); + if (ch != ' ' && ch != '\t') + { + nonWhiteSpace = true; + } + } + } + + if (eatTrailingBlanks && !nonWhiteSpace) + { + string s = temp.ToString(); + s = s.Trim(); + current.Append(s); + } + else + { + current.Append(temp); + } + } + + private PSObject BuildMshobject(string type, IList names, List values, char delimiter, bool preValidated = false) + { + PSObject result = new(names.Count); + char delimiterlocal = delimiter; + int unspecifiedNameIndex = 1; + for (int i = 0; i <= names.Count - 1; i++) + { + string name = names[i]; + string value = null; + + // if name is null and delimiter is '"', use a default property name 'UnspecifiedName' + if (name.Length == 0 && delimiterlocal == '"') + { + name = UnspecifiedName + unspecifiedNameIndex; + unspecifiedNameIndex++; + } + + // if name is null and delimiter is not '"', use a default property name 'UnspecifiedName' + if (string.IsNullOrEmpty(name)) + { + name = UnspecifiedName + unspecifiedNameIndex; + unspecifiedNameIndex++; + } + + // If no value was present in CSV file, we write null. + if (i < values.Count) + { + value = values[i]; + } + + result.Properties.Add(new PSNoteProperty(name, value), preValidated); + } + + if (!_alreadyWarnedUnspecifiedName && unspecifiedNameIndex != 1) + { + _cmdlet.WriteWarning(CsvCommandStrings.UseDefaultNameForUnspecifiedHeader); + _alreadyWarnedUnspecifiedName = true; + } + + if (!string.IsNullOrEmpty(type)) + { + result.TypeNames.Clear(); + result.TypeNames.Add(type); + result.TypeNames.Add(ImportExportCSVHelper.CSVTypePrefix + type); + } + + return result; + } + } + + #endregion ImportHelperConversion + + #region ExportImport Helper + + /// + /// Helper class for CSV conversion. + /// + internal static class ImportExportCSVHelper + { + internal const char CSVDelimiter = ','; + internal const string CSVTypePrefix = "CSV:"; + + internal static char SetDelimiter(PSCmdlet cmdlet, string parameterSetName, char explicitDelimiter, bool useCulture) + { + char delimiter = explicitDelimiter; + switch (parameterSetName) + { + case "Delimiter": + case "DelimiterPath": + case "DelimiterLiteralPath": + + // if delimiter is not given, it should take , as value + if (explicitDelimiter == '\0') + { + delimiter = ImportExportCSVHelper.CSVDelimiter; + } + + break; + case "UseCulture": + case "CulturePath": + case "CultureLiteralPath": + if (useCulture) + { + // ListSeparator is apparently always a character even though the property returns a string, checked via: + // [CultureInfo]::GetCultures("AllCultures") | % { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | ? Length -ne 1 + delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0]; + } + + break; + default: + { + delimiter = ImportExportCSVHelper.CSVDelimiter; + } + + break; + } + + return delimiter; + } + } + + #endregion ExportImport Helper + + #endregion CSV conversion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs new file mode 100644 index 0000000000000000000000000000000000000000..6d224d29007b17295c2ad80d1a57a3961dffa651 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -0,0 +1,1133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation.Internal; +using System.Reflection; +using System.Xml; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace System.Management.Automation +{ + /// + /// This class provides functionality for serializing a PSObject. + /// + internal sealed class CustomSerialization + { + #region constructor + /// + /// Depth of serialization. + /// + private readonly int _depth; + + /// + /// XmlWriter to be used for writing. + /// + private readonly XmlWriter _writer; + + /// + /// Whether type information should be included in the xml. + /// + private readonly bool _notypeinformation; + + /// + /// CustomerSerializer used for formatting the output for _writer. + /// + private CustomInternalSerializer _serializer; + + /// + /// Initializes a new instance of the class. + /// + /// + /// writer to be used for serialization. + /// + /// + /// should the type information to be shown. + /// + /// + /// depth to be used for serialization. If this value is specified, + /// depth from types.xml is not used. + /// + internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentException(nameof(writer)); + } + + if (depth < 1) + { + throw PSTraceSource.NewArgumentException(nameof(writer), Serialization.DepthOfOneRequired); + } + + _depth = depth; + _writer = writer; + _notypeinformation = notypeinformation; + _serializer = null; + } + + /// + /// Default depth of serialization. + /// + public static int MshDefaultSerializationDepth { get; } = 1; + + /// + /// Initializes a new instance of the class. + /// + /// + /// writer to be used for serialization. + /// + /// + /// should the type information to be shown. + /// + internal CustomSerialization(XmlWriter writer, bool notypeinformation) + : this(writer, notypeinformation, MshDefaultSerializationDepth) + { + } + + #endregion constructor + + #region public methods + + private bool _firstCall = true; + + /// + /// Serializes passed in object. + /// + /// + /// Object to be serialized. + /// + internal void Serialize(object source) + { + // Write the root element tag before writing first object. + if (_firstCall) + { + _firstCall = false; + Start(); + } + + _serializer = new CustomInternalSerializer + ( + _writer, + _notypeinformation, + true + ); + _serializer.WriteOneObject(source, null, _depth); + _serializer = null; + } + + /// + /// Serializes passed in object. + /// + /// + /// Object to be serialized. + /// + internal void SerializeAsStream(object source) + { + _serializer = new CustomInternalSerializer + ( + _writer, + _notypeinformation, + true + ); + _serializer.WriteOneObject(source, null, _depth); + _serializer = null; + } + + /// + /// Writes the start of root element. + /// + private void Start() + { + CustomInternalSerializer.WriteStartElement(_writer, CustomSerializationStrings.RootElementTag); + } + + /// + /// Write the end of root element. + /// + internal void Done() + { + if (_firstCall) + { + _firstCall = false; + Start(); + } + + _writer.WriteEndElement(); + _writer.Flush(); + } + + /// + /// Flush the writer. + /// + internal void DoneAsStream() + { + _writer.Flush(); + } + + internal void Stop() + { + CustomInternalSerializer serializer = _serializer; + serializer?.Stop(); + } + + #endregion + } + + /// + /// This internal helper class provides methods for serializing mshObject. + /// + internal sealed class CustomInternalSerializer + { + #region constructor + + /// + /// Xml writer to be used. + /// + private readonly XmlWriter _writer; + + /// + /// Check first call for every pipeline object to write Object tag else property tag. + /// + private bool _firstcall; + + /// + /// Should the type information to be shown. + /// + private readonly bool _notypeinformation; + + /// + /// Check object call. + /// + private bool _firstobjectcall = true; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Xml writer to be used. + /// + /// + /// Xml writer to be used. + /// + /// + /// Check first call for every pipeline object to write Object tag else property tag. + /// + internal CustomInternalSerializer(XmlWriter writer, bool notypeinformation, bool isfirstcallforObject) + { + Dbg.Assert(writer != null, "caller should validate the parameter"); + + _writer = writer; + _notypeinformation = notypeinformation; + _firstcall = isfirstcallforObject; + } + + #endregion + + #region Stopping + + private bool _isStopping = false; + + /// + /// Called from a separate thread will stop the serialization process. + /// + internal void Stop() + { + _isStopping = true; + } + + private void CheckIfStopping() + { + if (_isStopping) + { + throw PSTraceSource.NewInvalidOperationException(Serialization.Stopping); + } + } + + #endregion Stopping + + /// + /// This writes one object. + /// + /// + /// source to be serialized. + /// + /// + /// name of property. If null, name attribute is not written. + /// + /// + /// depth to which this object should be serialized. + /// + internal void WriteOneObject(object source, string property, int depth) + { + Dbg.Assert(depth >= 0, "depth should always be greater or equal to zero"); + + CheckIfStopping(); + + if (source == null) + { + WriteNull(property); + return; + } + + if (HandlePrimitiveKnownType(source, property)) + { + return; + } + + if (HandlePrimitiveKnownTypePSObject(source, property, depth)) + { + return; + } + + // Note: We donot use containers in depth calculation. i.e even if the + // current depth is zero, we serialize the container. All contained items will + // get serialized with depth zero. + if (HandleKnownContainerTypes(source, property, depth)) + { + return; + } + + PSObject mshSource = PSObject.AsPSObject(source); + // If depth is zero, complex type should be serialized as string. + if (depth == 0 || SerializeAsString(mshSource)) + { + HandlePSObjectAsString(mshSource, property, depth); + return; + } + + HandleComplexTypePSObject(mshSource, property, depth); + return; + } + + /// + /// Serializes Primitive Known Types. + /// + /// + /// true if source is handled, else false. + /// + private bool HandlePrimitiveKnownType(object source, string property) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + // Check if source is of primitive known type + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); + if (pktInfo != null) + { + WriteOnePrimitiveKnownType(_writer, property, source, pktInfo); + return true; + } + + return false; + } + + /// + /// Serializes PSObject whose base objects are of primitive known type. + /// + /// + /// + /// + /// + /// true if source is handled, else false. + /// + private bool HandlePrimitiveKnownTypePSObject(object source, string property, int depth) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + bool sourceHandled = false; + if (source is PSObject moSource && !moSource.ImmediateBaseObjectIsEmpty) + { + // Check if baseObject is primitive known type + object baseObject = moSource.ImmediateBaseObject; + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType()); + if (pktInfo != null) + { + WriteOnePrimitiveKnownType(_writer, property, baseObject, pktInfo); + sourceHandled = true; + } + } + + return sourceHandled; + } + + private bool HandleKnownContainerTypes(object source, string property, int depth) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + ContainerType ct = ContainerType.None; + PSObject mshSource = source as PSObject; + IEnumerable enumerable = null; + IDictionary dictionary = null; + + // If passed in object is PSObject with no baseobject, return false. + if (mshSource != null && mshSource.ImmediateBaseObjectIsEmpty) + { + return false; + } + + // Check if source (or baseobject in mshSource) is known container type + GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, + out dictionary, out enumerable); + + if (ct == ContainerType.None) + return false; + + WriteStartOfPSObject(mshSource ?? PSObject.AsPSObject(source), property, true); + switch (ct) + { + case ContainerType.Dictionary: + { + WriteDictionary(dictionary, depth); + } + + break; + case ContainerType.Stack: + case ContainerType.Queue: + case ContainerType.List: + case ContainerType.Enumerable: + { + WriteEnumerable(enumerable, depth); + } + + break; + default: + { + Dbg.Assert(false, "All containers should be handled in the switch"); + } + + break; + } + + // An object which is original enumerable becomes an PSObject + // with arraylist on deserialization. So on roundtrip it will show up + // as List. + // We serialize properties of enumerable and on deserialization mark the object + // as Deserialized. So if object is marked deserialized, we should write properties. + // Note: we do not serialize the properties of IEnumerable if depth is zero. + if (depth != 0 && (ct == ContainerType.Enumerable || (mshSource != null && mshSource.IsDeserialized))) + { + // Note:Depth is the depth for serialization of baseObject. + // Depth for serialization of each property is one less. + WritePSObjectProperties(PSObject.AsPSObject(source), depth); + } + + // If source is PSObject, serialize notes + if (mshSource != null) + { + // Serialize instanceMembers + PSMemberInfoCollection instanceMembers = mshSource.InstanceMembers; + if (instanceMembers != null) + { + WriteMemberInfoCollection(instanceMembers, depth, true); + } + } + + _writer.WriteEndElement(); + + return true; + } + + /// + /// Checks if source is known container type and returns appropriate information. + /// + /// + /// + /// + /// + private static void GetKnownContainerTypeInfo( + object source, out ContainerType ct, out IDictionary dictionary, out IEnumerable enumerable) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + ct = ContainerType.None; + dictionary = null; + enumerable = null; + + dictionary = source as IDictionary; + if (dictionary != null) + { + ct = ContainerType.Dictionary; + return; + } + + if (source is Stack) + { + ct = ContainerType.Stack; + enumerable = LanguagePrimitives.GetEnumerable(source); + Dbg.Assert(enumerable != null, "Stack is enumerable"); + } + else if (source is Queue) + { + ct = ContainerType.Queue; + enumerable = LanguagePrimitives.GetEnumerable(source); + Dbg.Assert(enumerable != null, "Queue is enumerable"); + } + else if (source is IList) + { + ct = ContainerType.List; + enumerable = LanguagePrimitives.GetEnumerable(source); + Dbg.Assert(enumerable != null, "IList is enumerable"); + } + else + { + Type gt = source.GetType(); + if (gt.GetTypeInfo().IsGenericType) + { + if (DerivesFromGenericType(gt, typeof(Stack<>))) + { + ct = ContainerType.Stack; + enumerable = LanguagePrimitives.GetEnumerable(source); + Dbg.Assert(enumerable != null, "Stack is enumerable"); + } + else if (DerivesFromGenericType(gt, typeof(Queue<>))) + { + ct = ContainerType.Queue; + enumerable = LanguagePrimitives.GetEnumerable(source); + Dbg.Assert(enumerable != null, "Queue is enumerable"); + } + else if (DerivesFromGenericType(gt, typeof(List<>))) + { + ct = ContainerType.List; + enumerable = LanguagePrimitives.GetEnumerable(source); + Dbg.Assert(enumerable != null, "Queue is enumerable"); + } + } + } + + // Check if type is IEnumerable + if (ct == ContainerType.None) + { + enumerable = LanguagePrimitives.GetEnumerable(source); + if (enumerable != null) + { + ct = ContainerType.Enumerable; + } + } + } + + /// + /// Checks if derived is of type baseType or a type derived from baseType. + /// + /// + /// + /// + private static bool DerivesFromGenericType(Type derived, Type baseType) + { + Dbg.Assert(derived != null, "caller should validate the parameter"); + Dbg.Assert(baseType != null, "caller should validate the parameter"); + while (derived != null) + { + if (derived.GetTypeInfo().IsGenericType) + derived = derived.GetGenericTypeDefinition(); + + if (derived == baseType) + { + return true; + } + + derived = derived.GetTypeInfo().BaseType; + } + + return false; + } + + #region Write PSObject + + /// + /// Serializes an PSObject whose baseobject is of primitive type. + /// and which has notes. + /// + /// + /// Source from which notes are written. + /// + /// + /// primitive object which is written as base object. In most cases it + /// is same source.ImmediateBaseObject. When PSObject is serialized as string, + /// it can be different. for more info. + /// + /// + /// TypeSerializationInfo for the primitive. + /// + /// + /// + private void WritePrimitiveTypePSObjectWithNotes( + PSObject source, + object primitive, + TypeSerializationInfo pktInfo, + string property, + int depth) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + // Write start of PSObject. Since baseobject is primitive known + // type, we do not need TypeName information. + WriteStartOfPSObject(source, property, source.ToStringFromDeserialization != null); + + if (pktInfo != null) + { + WriteOnePrimitiveKnownType(_writer, null, primitive, pktInfo); + } + + // Serialize instanceMembers + PSMemberInfoCollection instanceMembers = source.InstanceMembers; + if (instanceMembers != null) + { + WriteMemberInfoCollection(instanceMembers, depth, true); + } + + _writer.WriteEndElement(); + } + + private void HandleComplexTypePSObject(PSObject source, string property, int depth) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + WriteStartOfPSObject(source, property, true); + + // Figure out what kind of object we are dealing with + bool isEnum = false; + bool isPSObject = false; + + if (!source.ImmediateBaseObjectIsEmpty) + { + isEnum = source.ImmediateBaseObject is Enum; + isPSObject = source.ImmediateBaseObject is PSObject; + } + + if (isEnum) + { + object baseObject = source.ImmediateBaseObject; + foreach (PSPropertyInfo prop in source.Properties) + { + WriteOneObject(System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), prop.Name, depth); + } + } + else if (isPSObject) + { + if (_firstobjectcall) + { + _firstobjectcall = false; + WritePSObjectProperties(source, depth); + } + else + { + WriteOneObject(source.ImmediateBaseObject, null, depth); + } + } + else + { + WritePSObjectProperties(source, depth); + } + + _writer.WriteEndElement(); + } + + /// + /// Writes start element, attributes and typeNames for PSObject. + /// + /// + /// + /// + /// if true, TypeName information is written, else not. + /// + private void WriteStartOfPSObject( + PSObject mshObject, + string property, + bool writeTNH) + { + Dbg.Assert(mshObject != null, "caller should validate the parameter"); + + if (property != null) + { + WriteStartElement(_writer, CustomSerializationStrings.Properties); + WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property); + } + else + { + if (_firstcall) + { + WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag); + _firstcall = false; + } + else + { + WriteStartElement(_writer, CustomSerializationStrings.Properties); + } + } + + object baseObject = mshObject.BaseObject; + if (!_notypeinformation) + WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, baseObject.GetType().ToString()); + } + + #region membersets + + /// + /// Returns true if PSObject has notes. + /// + /// + /// + /// + private static bool PSObjectHasNotes(PSObject source) + { + if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) + { + return true; + } + + return false; + } + + /// + /// Serialize member set. This method serializes without writing. + /// enclosing tags and attributes. + /// + /// + /// Enumerable containing members + /// + /// + /// + /// if this is true, write an enclosing "" tag. + /// + /// + private void WriteMemberInfoCollection( + PSMemberInfoCollection me, int depth, bool writeEnclosingMemberSetElementTag) + { + Dbg.Assert(me != null, "caller should validate the parameter"); + + foreach (PSMemberInfo info in me) + { + if (!info.ShouldSerialize) + { + continue; + } + + if (info is not PSPropertyInfo property) + { + continue; + } + + WriteStartElement(_writer, CustomSerializationStrings.Properties); + WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, info.Name); + if (!_notypeinformation) + WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, info.GetType().ToString()); + _writer.WriteString(property.Value.ToString()); + _writer.WriteEndElement(); + } + } + + #endregion membersets + + #region properties + + /// + /// Serializes properties of PSObject. + /// + private void WritePSObjectProperties(PSObject source, int depth) + { + Dbg.Assert(source != null, "caller should validate the information"); + + depth = GetDepthOfSerialization(source, depth); + + // Depth available for each property is one less + --depth; + Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); + if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties) + { + PSMemberInfoInternalCollection specificProperties = new(); + foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null)) + { + PSPropertyInfo property = source.Properties[propertyName]; + if (property != null) + { + specificProperties.Add(property); + } + } + + SerializeProperties(specificProperties, CustomSerializationStrings.Properties, depth); + return; + } + + foreach (PSPropertyInfo prop in source.Properties) + { + Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); + object value = AutomationNull.Value; + // PSObject throws GetValueException if it cannot + // get value for a property. + try + { + value = prop.Value; + } + catch (GetValueException) + { + WritePropertyWithNullValue(_writer, prop, depth); + continue; + } + // Write the property + if (value == null) + { + WritePropertyWithNullValue(_writer, prop, depth); + } + else + { + WriteOneObject(value, prop.Name, depth); + } + } + } + + /// + /// Serializes properties from collection. + /// + /// + /// Collection of properties to serialize. + /// + /// + /// Name for enclosing element tag. + /// + /// + /// Depth to which each property should be serialized. + /// + private void SerializeProperties( + PSMemberInfoInternalCollection propertyCollection, string name, int depth) + { + Dbg.Assert(propertyCollection != null, "caller should validate the parameter"); + if (propertyCollection.Count == 0) + return; + + foreach (PSMemberInfo info in propertyCollection) + { + PSPropertyInfo prop = info as PSPropertyInfo; + + Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); + + object value = AutomationNull.Value; + // PSObject throws GetValueException if it cannot + // get value for a property. + try + { + value = prop.Value; + } + catch (GetValueException) + { + continue; + } + // Write the property + WriteOneObject(value, prop.Name, depth); + } + } + + #endregion base properties + + #endregion WritePSObject + + #region enumerable and dictionary + + /// + /// Serializes IEnumerable. + /// + /// + /// Enumerable which is serialized. + /// + /// + private void WriteEnumerable(IEnumerable enumerable, int depth) + { + Dbg.Assert(enumerable != null, "caller should validate the parameter"); + + IEnumerator enumerator = null; + try + { + enumerator = enumerable.GetEnumerator(); + enumerator.Reset(); + } + catch (Exception) + { + enumerator = null; + } + + // AD has incorrect implementation of IEnumerable where they returned null + // for GetEnumerator instead of empty enumerator + if (enumerator != null) + { + while (true) + { + object item = null; + try + { + if (!enumerator.MoveNext()) + { + break; + } + else + { + item = enumerator.Current; + } + } + catch (Exception) + { + break; + } + + WriteOneObject(item, null, depth); + } + } + } + + /// + /// Serializes IDictionary. + /// + /// Dictionary which is serialized. + /// + private void WriteDictionary(IDictionary dictionary, int depth) + { + IDictionaryEnumerator dictionaryEnum = null; + try + { + dictionaryEnum = (IDictionaryEnumerator)dictionary.GetEnumerator(); + } + catch (Exception) + { + } + + if (dictionaryEnum != null) + { + while (dictionaryEnum.MoveNext()) + { + // Write Key + WriteOneObject(dictionaryEnum.Key, CustomSerializationStrings.DictionaryKey, depth); + // Write Value + WriteOneObject(dictionaryEnum.Value, CustomSerializationStrings.DictionaryValue, depth); + } + } + } + + #endregion enumerable and dictionary + + #region serialize as string + + private void HandlePSObjectAsString(PSObject source, string property, int depth) + { + Dbg.Assert(source != null, "caller should validate the information"); + + bool hasNotes = PSObjectHasNotes(source); + string value = GetStringFromPSObject(source); + + if (value != null) + { + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType()); + Dbg.Assert(pktInfo != null, "TypeSerializationInfo should be present for string"); + if (hasNotes) + { + WritePrimitiveTypePSObjectWithNotes(source, value, pktInfo, property, depth); + } + else + { + WriteOnePrimitiveKnownType(_writer, property, source.BaseObject, pktInfo); + } + } + else + { + if (hasNotes) + { + WritePrimitiveTypePSObjectWithNotes(source, null, null, property, depth); + } + else + { + WriteNull(property); + } + } + } + + /// + /// Gets the string from PSObject using the information from + /// types.ps1xml. This string is used for serializing the PSObject. + /// + /// + /// PSObject to be converted to string. + /// + /// + /// string value to use for serializing this PSObject. + /// + private static string GetStringFromPSObject(PSObject source) + { + Dbg.Assert(source != null, "caller should have validated the information"); + + // check if we have a well known string serialization source + PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null); + string result = null; + if (serializationProperty != null) + { + object val = serializationProperty.Value; + if (val != null) + { + try + { + // if we have a string serialization value, return it + result = val.ToString(); + } + catch (Exception) + { + } + } + } + else + { + try + { + // fall back value + result = source.ToString(); + } + catch (Exception) + { + } + } + + return result; + } + + /// + /// Reads the information the PSObject + /// and returns true if this object should be serialized as string. + /// + /// PSObject to be serialized. + /// True if the object needs to be serialized as a string. + private static bool SerializeAsString(PSObject source) + { + return source.GetSerializationMethod(null) == SerializationMethod.String; + } + + #endregion serialize as string + + /// + /// Compute the serialization depth for an PSObject instance subtree. + /// + /// PSObject whose serialization depth has to be computed. + /// Current depth. + /// + private static int GetDepthOfSerialization(PSObject source, int depth) + { + if (source == null) + return depth; + + // get the depth from the PSObject + // NOTE: we assume that the depth out of the PSObject is > 0 + // else we consider it not set in types.ps1xml + int objectLevelDepth = source.GetSerializationDepth(null); + if (objectLevelDepth <= 0) + { + // no override at the type level + return depth; + } + + return objectLevelDepth; + } + + /// + /// Writes null. + /// + /// + private void WriteNull(string property) + { + if (property != null) + { + WriteStartElement(_writer, CustomSerializationStrings.Properties); + WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property); + } + else + { + if (_firstcall) + { + WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag); + _firstcall = false; + } + else + { + WriteStartElement(_writer, CustomSerializationStrings.Properties); + } + } + + _writer.WriteEndElement(); + } + + #region known type serialization + + private void WritePropertyWithNullValue( + XmlWriter writer, PSPropertyInfo source, int depth) + { + WriteStartElement(writer, CustomSerializationStrings.Properties); + WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name); + if (!_notypeinformation) + WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue); + writer.WriteEndElement(); + } + + private void WriteObjectString( + XmlWriter writer, string property, object source, TypeSerializationInfo entry) + { + if (property != null) + { + WriteStartElement(writer, CustomSerializationStrings.Properties); + WriteAttribute(writer, CustomSerializationStrings.NameAttribute, property); + } + else + { + if (_firstcall) + { + WriteStartElement(writer, CustomSerializationStrings.PSObjectTag); + _firstcall = false; + } + else + { + WriteStartElement(writer, CustomSerializationStrings.Properties); + } + } + + if (!_notypeinformation) + WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, source.GetType().ToString()); + + writer.WriteString(source.ToString()); + writer.WriteEndElement(); + } + + /// + /// Writes an item or property in Monad namespace. + /// + /// The XmlWriter stream to which the object is serialized. + /// Name of property. Pass null for item. + /// Object to be written. + /// Serialization information about source. + private void WriteOnePrimitiveKnownType( + XmlWriter writer, string property, object source, TypeSerializationInfo entry) + { + WriteObjectString(writer, property, source, entry); + } + + #endregion known type serialization + + #region misc + + /// + /// Writes start element in Monad namespace. + /// + /// + /// Tag of element. + internal static void WriteStartElement(XmlWriter writer, string elementTag) + { + writer.WriteStartElement(elementTag); + } + + /// + /// Writes attribute in monad namespace. + /// + /// + /// Name of attribute. + /// Value of attribute. + internal static void WriteAttribute(XmlWriter writer, string name, string value) + { + writer.WriteAttributeString(name, value); + } + + #endregion misc + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs new file mode 100644 index 0000000000000000000000000000000000000000..ff4b2580f83fc67187fba8e21fdf5123d61bf58c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace System.Management.Automation +{ + /// + /// This class contains strings required for serialization for ConvertTo-XML. + /// + internal static class CustomSerializationStrings + { + #region element tags + + /// + /// Element tag for root node. + /// + internal const string RootElementTag = "Objects"; + + /// + /// Element tag for PSObject. + /// + internal const string PSObjectTag = "Object"; + + /// + /// Element tag for properties. + /// + internal const string Properties = "Property"; + + #region attribute tags + + /// + /// String for name attribute. + /// + internal const string NameAttribute = "Name"; + + /// + /// String for type attribute. + /// + internal const string TypeAttribute = "Type"; + + #endregion + + #region known container tags + + /// + /// Value of name attribute for dictionary key part in dictionary entry. + /// + internal const string DictionaryKey = "Key"; + + /// + /// Value of name attribute for dictionary value part in dictionary entry. + /// + internal const string DictionaryValue = "Value"; + + #endregion + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..756afff13de439d4a98185d3d97a4d2206c4d15f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -0,0 +1,569 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Remoting.Internal; +using System.Management.Automation.Runspaces; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This cmdlet takes a Runspace object and checks to see if it is debuggable (i.e, if + /// it is running a script or is currently stopped in the debugger. + /// If it is debuggable then it breaks into the Runspace debugger in step mode. + /// + [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] + [Cmdlet(VerbsDiagnostic.Debug, "Runspace", SupportsShouldProcess = true, DefaultParameterSetName = DebugRunspaceCommand.RunspaceParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096917")] + public sealed class DebugRunspaceCommand : PSCmdlet + { + #region Strings + + private const string RunspaceParameterSet = "RunspaceParameterSet"; + private const string NameParameterSet = "NameParameterSet"; + private const string IdParameterSet = "IdParameterSet"; + private const string InstanceIdParameterSet = "InstanceIdParameterSet"; + + #endregion + + #region Private members + + private Runspace _runspace; + private System.Management.Automation.Debugger _debugger; + private PSDataCollection _debugBlockingCollection; + private PSDataCollection _debugAccumulateCollection; + private Pipeline _runningPipeline; + private System.Management.Automation.PowerShell _runningPowerShell; + + // Debugging to persist until Ctrl+C or Debugger 'Exit' stops cmdlet. + private bool _debugging; + private readonly ManualResetEventSlim _newRunningScriptEvent = new(true); + private RunspaceAvailability _previousRunspaceAvailability = RunspaceAvailability.None; + + #endregion + + #region Parameters + + /// + /// The Runspace to be debugged. + /// + [Parameter(Position = 0, + Mandatory = true, + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + ParameterSetName = DebugRunspaceCommand.RunspaceParameterSet)] + public Runspace Runspace + { + get; + set; + } + + /// + /// The name of a Runspace to be debugged. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = DebugRunspaceCommand.NameParameterSet)] + public string Name + { + get; + set; + } + + /// + /// The Id of a Runspace to be debugged. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = DebugRunspaceCommand.IdParameterSet)] + public int Id + { + get; + set; + } + + /// + /// The InstanceId of a Runspace to be debugged. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = DebugRunspaceCommand.InstanceIdParameterSet)] + public Guid InstanceId + { + get; + set; + } + + /// + /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target. + /// + [Parameter] + public SwitchParameter BreakAll { get; set; } + + #endregion + + #region Overrides + + /// + /// End processing. Do work. + /// + protected override void EndProcessing() + { + if (ParameterSetName == DebugRunspaceCommand.RunspaceParameterSet) + { + _runspace = Runspace; + } + else + { + IReadOnlyList runspaces = null; + + switch (ParameterSetName) + { + case DebugRunspaceCommand.NameParameterSet: + runspaces = GetRunspaceUtils.GetRunspacesByName(new string[] { Name }); + break; + + case DebugRunspaceCommand.IdParameterSet: + runspaces = GetRunspaceUtils.GetRunspacesById(new int[] { Id }); + break; + + case DebugRunspaceCommand.InstanceIdParameterSet: + runspaces = GetRunspaceUtils.GetRunspacesByInstanceId(new Guid[] { InstanceId }); + break; + } + + if (runspaces.Count > 1) + { + ThrowTerminatingError( + new ErrorRecord( + new PSArgumentException(Debugger.RunspaceDebuggingTooManyRunspacesFound), + "DebugRunspaceTooManyRunspaceFound", + ErrorCategory.InvalidOperation, + this) + ); + } + + if (runspaces.Count == 1) + { + _runspace = runspaces[0]; + } + } + + if (_runspace == null) + { + ThrowTerminatingError( + new ErrorRecord( + new PSArgumentNullException(Debugger.RunspaceDebuggingNoRunspaceFound), + "DebugRunspaceNoRunspaceFound", + ErrorCategory.InvalidOperation, + this) + ); + } + + Runspace defaultRunspace = LocalRunspace.DefaultRunspace; + if (defaultRunspace == null || defaultRunspace.Debugger == null) + { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException(Debugger.RunspaceDebuggingNoHostRunspaceOrDebugger), + "DebugRunspaceNoHostDebugger", + ErrorCategory.InvalidOperation, + this) + ); + } + + if (_runspace == defaultRunspace) + { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException(Debugger.RunspaceDebuggingCannotDebugDefaultRunspace), + "DebugRunspaceCannotDebugHostRunspace", + ErrorCategory.InvalidOperation, + this) + ); + } + + if (this.Host == null || this.Host.UI == null) + { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException(Debugger.RunspaceDebuggingNoHost), + "DebugRunspaceNoHostAvailable", + ErrorCategory.InvalidOperation, + this) + ); + } + + if (!ShouldProcess(_runspace.Name, VerbsDiagnostic.Debug)) + { + return; + } + + _debugger = defaultRunspace.Debugger; + + try + { + PrepareRunspace(_runspace); + + // Blocking call. Send runspace/command output to host UI while debugging and wait for runspace/command completion. + WaitAndReceiveRunspaceOutput(); + } + finally + { + RestoreRunspace(_runspace); + } + } + + /// + /// Stop processing. + /// + protected override void StopProcessing() + { + _debugging = false; + + // Cancel runspace debugging. + System.Management.Automation.Debugger debugger = _debugger; + if ((debugger != null) && (_runspace != null)) + { + debugger.StopDebugRunspace(_runspace); + } + + // Unblock the data collection. + PSDataCollection debugCollection = _debugBlockingCollection; + debugCollection?.Complete(); + + // Unblock any new command wait. + _newRunningScriptEvent.Set(); + } + + #endregion + + #region Private methods + + private void WaitAndReceiveRunspaceOutput() + { + _debugging = true; + + try + { + HostWriteLine(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceDebuggingStarted, _runspace.Name)); + HostWriteLine(Debugger.RunspaceDebuggingEndSession); + HostWriteLine(string.Empty); + + _runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; + _debugger.NestedDebuggingCancelledEvent += HandleDebuggerNestedDebuggingCancelledEvent; + + // Make sure host debugger has debugging turned on. + _debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); + + // Set up host script debugger to debug the runspace. + _debugger.DebugRunspace(_runspace, breakAll: BreakAll); + + _runspace.IsRemoteDebuggerAttached = true; + _runspace.Events?.GenerateEvent( + PSEngineEvent.OnDebugAttach, + sender: null, + args: Array.Empty(), + extraData: null, + processInCurrentThread: true, + waitForCompletionInCurrentThread: false); + + while (_debugging) + { + // Wait for running script. + _newRunningScriptEvent.Wait(); + + if (!_debugging) + { + return; + } + + AddDataEventHandlers(); + + try + { + // Block cmdlet during debugging until either the command finishes + // or the user terminates the debugging session. + foreach (var streamItem in _debugBlockingCollection) + { + streamItem.WriteStreamObject(this); + } + } + finally + { + RemoveDataEventHandlers(); + } + + if (_debugging && + (!_runspace.InNestedPrompt)) + { + HostWriteLine(string.Empty); + HostWriteLine(Debugger.RunspaceDebuggingScriptCompleted); + HostWriteLine(Debugger.RunspaceDebuggingEndSession); + HostWriteLine(string.Empty); + } + + _newRunningScriptEvent.Reset(); + } + } + finally + { + _runspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged; + _debugger.NestedDebuggingCancelledEvent -= HandleDebuggerNestedDebuggingCancelledEvent; + _runspace.IsRemoteDebuggerAttached = false; + _debugger.StopDebugRunspace(_runspace); + _newRunningScriptEvent.Dispose(); + } + } + + private void HostWriteLine(string line) + { + if ((this.Host != null) && (this.Host.UI != null)) + { + try + { + if (this.Host.UI.RawUI != null) + { + this.Host.UI.WriteLine(ConsoleColor.Yellow, this.Host.UI.RawUI.BackgroundColor, line); + } + else + { + this.Host.UI.WriteLine(line); + } + } + catch (System.Management.Automation.Host.HostException) { } + } + } + + private void AddDataEventHandlers() + { + // Create new collection objects. + _debugBlockingCollection?.Dispose(); + _debugAccumulateCollection?.Dispose(); + + _debugBlockingCollection = new PSDataCollection(); + _debugBlockingCollection.BlockingEnumerator = true; + _debugAccumulateCollection = new PSDataCollection(); + + _runningPowerShell = _runspace.GetCurrentBasePowerShell(); + if (_runningPowerShell != null) + { + if (_runningPowerShell.OutputBuffer != null) + { + _runningPowerShell.OutputBuffer.DataAdding += HandlePowerShellOutputBufferDataAdding; + } + + if (_runningPowerShell.ErrorBuffer != null) + { + _runningPowerShell.ErrorBuffer.DataAdding += HandlePowerShellErrorBufferDataAdding; + } + } + else + { + _runningPipeline = _runspace.GetCurrentlyRunningPipeline(); + if (_runningPipeline != null) + { + if (_runningPipeline.Output != null) + { + _runningPipeline.Output.DataReady += HandlePipelineOutputDataReady; + } + + if (_runningPipeline.Error != null) + { + _runningPipeline.Error.DataReady += HandlePipelineErrorDataReady; + } + } + } + } + + private void RemoveDataEventHandlers() + { + if (_runningPowerShell != null) + { + if (_runningPowerShell.OutputBuffer != null) + { + _runningPowerShell.OutputBuffer.DataAdding -= HandlePowerShellOutputBufferDataAdding; + } + + if (_runningPowerShell.ErrorBuffer != null) + { + _runningPowerShell.ErrorBuffer.DataAdding -= HandlePowerShellErrorBufferDataAdding; + } + + _runningPowerShell = null; + } + else if (_runningPipeline != null) + { + if (_runningPipeline.Output != null) + { + _runningPipeline.Output.DataReady -= HandlePipelineOutputDataReady; + } + + if (_runningPipeline.Error != null) + { + _runningPipeline.Error.DataReady -= HandlePipelineErrorDataReady; + } + + _runningPipeline = null; + } + } + + private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e) + { + // Ignore nested commands. + if (sender is LocalRunspace localRunspace) + { + var basePowerShell = localRunspace.GetCurrentBasePowerShell(); + if ((basePowerShell != null) && (basePowerShell.IsNested)) + { + return; + } + } + + RunspaceAvailability prevAvailability = _previousRunspaceAvailability; + _previousRunspaceAvailability = e.RunspaceAvailability; + + if ((e.RunspaceAvailability == RunspaceAvailability.Available) || (e.RunspaceAvailability == RunspaceAvailability.None)) + { + _debugBlockingCollection.Complete(); + } + else if ((e.RunspaceAvailability == RunspaceAvailability.Busy) && + ((prevAvailability == RunspaceAvailability.Available) || (prevAvailability == RunspaceAvailability.None))) + { + _newRunningScriptEvent.Set(); + } + } + + private void HandleDebuggerNestedDebuggingCancelledEvent(object sender, EventArgs e) + { + StopProcessing(); + } + + private void HandlePipelineOutputDataReady(object sender, EventArgs e) + { + if (sender is PipelineReader reader && reader.IsOpen) + { + WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output); + } + } + + private void HandlePipelineErrorDataReady(object sender, EventArgs e) + { + if (sender is PipelineReader reader && reader.IsOpen) + { + WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); + } + } + + private void WritePipelineCollection(Collection collection, PSStreamObjectType psStreamType) + { + foreach (var item in collection) + { + if (item != null) + { + AddToDebugBlockingCollection(new PSStreamObject(psStreamType, item)); + } + } + } + + private void HandlePowerShellOutputBufferDataAdding(object sender, DataAddingEventArgs e) + { + if (e.ItemAdded != null) + { + HandlePowerShellPStreamItem(new PSStreamObject(PSStreamObjectType.Output, e.ItemAdded)); + } + } + + private void HandlePowerShellErrorBufferDataAdding(object sender, DataAddingEventArgs e) + { + if (e.ItemAdded != null) + { + HandlePowerShellPStreamItem(new PSStreamObject(PSStreamObjectType.Error, e.ItemAdded)); + } + } + + private void HandlePowerShellPStreamItem(PSStreamObject streamItem) + { + if (!_debugger.InBreakpoint) + { + // First write any accumulated items. + foreach (var item in _debugAccumulateCollection.ReadAll()) + { + AddToDebugBlockingCollection(item); + } + + // Handle new item. + if ((_debugBlockingCollection != null) && (_debugBlockingCollection.IsOpen)) + { + AddToDebugBlockingCollection(streamItem); + } + } + else if (_debugAccumulateCollection.IsOpen) + { + // Add to accumulator if debugger is stopped in breakpoint. + _debugAccumulateCollection.Add(streamItem); + } + } + + private void AddToDebugBlockingCollection(PSStreamObject streamItem) + { + if (!_debugBlockingCollection.IsOpen) + { + return; + } + + if (streamItem != null) + { + try + { + _debugBlockingCollection.Add(streamItem); + } + catch (PSInvalidOperationException) { } + } + } + + private void PrepareRunspace(Runspace runspace) + { + SetLocalMode(runspace.Debugger, true); + EnableHostDebugger(runspace, false); + } + + private void RestoreRunspace(Runspace runspace) + { + SetLocalMode(runspace.Debugger, false); + EnableHostDebugger(runspace, true); + } + + private void EnableHostDebugger(Runspace runspace, bool enabled) + { + // Only enable and disable the host's runspace if we are in process attach mode. + if (_debugger is ServerRemoteDebugger) + { + if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) + { + try + { + localRunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled = enabled; + } + catch (PSNotImplementedException) { } + } + } + } + + private static void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode) + { + if (debugger is ServerRemoteDebugger remoteDebugger) + { + remoteDebugger.LocalDebugMode = localMode; + } + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs new file mode 100644 index 0000000000000000000000000000000000000000..1bdd5a5aea8837d8a3919726ba4969ff18232bf5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Disable-PSBreakpoint. + /// + [Cmdlet(VerbsLifecycle.Disable, "PSBreakpoint", SupportsShouldProcess = true, DefaultParameterSetName = BreakpointParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096498")] + [OutputType(typeof(Breakpoint))] + public class DisablePSBreakpointCommand : PSBreakpointUpdaterCommandBase + { + #region parameters + + /// + /// Gets or sets the parameter -passThru which states whether the + /// command should place the breakpoints it processes in the pipeline. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + #endregion parameters + + #region overrides + + /// + /// Disables the given breakpoint. + /// + protected override void ProcessBreakpoint(Breakpoint breakpoint) + { + breakpoint = Runspace.Debugger.DisableBreakpoint(breakpoint); + + if (PassThru) + { + base.ProcessBreakpoint(breakpoint); + } + } + + #endregion overrides + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs new file mode 100644 index 0000000000000000000000000000000000000000..0822e146ae6e3298abb2355342c0186ffa9963f9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Enable-PSBreakpoint. + /// + [Cmdlet(VerbsLifecycle.Enable, "PSBreakpoint", SupportsShouldProcess = true, DefaultParameterSetName = BreakpointParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096700")] + [OutputType(typeof(Breakpoint))] + public class EnablePSBreakpointCommand : PSBreakpointUpdaterCommandBase + { + #region parameters + + /// + /// Gets or sets the parameter -passThru which states whether the + /// command should place the breakpoints it processes in the pipeline. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + #endregion parameters + + #region overrides + + /// + /// Enables the given breakpoint. + /// + protected override void ProcessBreakpoint(Breakpoint breakpoint) + { + breakpoint = Runspace.Debugger.EnableBreakpoint(breakpoint); + + if (PassThru) + { + base.ProcessBreakpoint(breakpoint); + } + } + + #endregion overrides + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..47b83c7877013aa136c51d32431e7b8a72e54f74 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -0,0 +1,532 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +namespace Microsoft.PowerShell.Commands +{ + #region PSRunspaceDebug class + + /// + /// Runspace Debug Options class. + /// + public sealed class PSRunspaceDebug + { + #region Properties + + /// + /// When true this property will cause any breakpoints set in a Runspace to stop + /// the running command or script when the breakpoint is hit, regardless of whether a + /// debugger is currently attached. The script or command will remain stopped until + /// a debugger is attached to debug the breakpoint. + /// + public bool Enabled { get; } + + /// + /// When true this property will cause any running command or script in the Runspace + /// to stop in step mode, regardless of whether a debugger is currently attached. The + /// script or command will remain stopped until a debugger is attached to debug the + /// current stop point. + /// + public bool BreakAll { get; } + + /// + /// Name of runspace for which the options apply. + /// + public string RunspaceName { get; } + + /// + /// Local Id of runspace for which the options apply. + /// + public int RunspaceId { get; } + + #endregion + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// Enable debugger option. + /// BreakAll option. + /// Runspace name. + /// Runspace local Id. + public PSRunspaceDebug(bool enabled, bool breakAll, string runspaceName, int runspaceId) + { + if (string.IsNullOrEmpty(runspaceName)) + { + throw new PSArgumentNullException(nameof(runspaceName)); + } + + this.Enabled = enabled; + this.BreakAll = breakAll; + this.RunspaceName = runspaceName; + this.RunspaceId = runspaceId; + } + + #endregion + } + + #endregion + + #region CommonRunspaceCommandBase class + + /// + /// Abstract class that defines common Runspace Command parameters. + /// + public abstract class CommonRunspaceCommandBase : PSCmdlet + { + #region Strings + + /// + /// RunspaceParameterSet. + /// + protected const string RunspaceParameterSet = "RunspaceParameterSet"; + + /// + /// RunspaceNameParameterSet. + /// + protected const string RunspaceNameParameterSet = "RunspaceNameParameterSet"; + + /// + /// RunspaceIdParameterSet. + /// + protected const string RunspaceIdParameterSet = "RunspaceIdParameterSet"; + + /// + /// RunspaceInstanceIdParameterSet. + /// + protected const string RunspaceInstanceIdParameterSet = "RunspaceInstanceIdParameterSet"; + + /// + /// ProcessNameParameterSet. + /// + protected const string ProcessNameParameterSet = "ProcessNameParameterSet"; + + #endregion + + #region Parameters + + /// + /// Runspace Name. + /// + [Parameter(Position = 0, + ParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] RunspaceName + { + get; + set; + } + + /// + /// Runspace. + /// + [Parameter(Position = 0, + Mandatory = true, + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + ParameterSetName = CommonRunspaceCommandBase.RunspaceParameterSet)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Runspace[] Runspace + { + get; + set; + } + + /// + /// Runspace Id. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = CommonRunspaceCommandBase.RunspaceIdParameterSet)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] RunspaceId + { + get; + set; + } + /// + /// RunspaceInstanceId. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = CommonRunspaceCommandBase.RunspaceInstanceIdParameterSet)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Guid[] RunspaceInstanceId + { + get; + set; + } + + /// + /// Gets or Sets the ProcessName for which runspace debugging has to be enabled or disabled. + /// + [Parameter(Position = 0, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] + [ValidateNotNullOrEmpty] + public string ProcessName + { + get; + set; + } + + /// + /// Gets or Sets the AppDomain Names for which runspace debugging has to be enabled or disabled. + /// + [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", + Target = "Microsoft.PowerShell.Commands.CommonRunspaceCommandBase.#AppDomainName")] + public string[] AppDomainName + { + get; + set; + } + + #endregion + + #region Protected Methods + + /// + /// Returns a list of valid runspaces based on current parameter set. + /// + /// IReadOnlyList. + protected IReadOnlyList GetRunspaces() + { + IReadOnlyList results = null; + + if ((ParameterSetName == CommonRunspaceCommandBase.RunspaceNameParameterSet) && ((RunspaceName == null) || RunspaceName.Length == 0)) + { + results = GetRunspaceUtils.GetAllRunspaces(); + } + else + { + switch (ParameterSetName) + { + case CommonRunspaceCommandBase.RunspaceNameParameterSet: + results = GetRunspaceUtils.GetRunspacesByName(RunspaceName); + break; + + case CommonRunspaceCommandBase.RunspaceIdParameterSet: + results = GetRunspaceUtils.GetRunspacesById(RunspaceId); + break; + + case CommonRunspaceCommandBase.RunspaceParameterSet: + results = new ReadOnlyCollection(new List(Runspace)); + break; + + case CommonRunspaceCommandBase.RunspaceInstanceIdParameterSet: + results = GetRunspaceUtils.GetRunspacesByInstanceId(RunspaceInstanceId); + break; + } + } + + return results; + } + + /// + /// Returns Runspace Debugger. + /// + /// Runspace. + /// Debugger. + protected System.Management.Automation.Debugger GetDebuggerFromRunspace(Runspace runspace) + { + System.Management.Automation.Debugger debugger = null; + try + { + debugger = runspace.Debugger; + } + catch (PSInvalidOperationException) { } + + if (debugger == null) + { + WriteError( + new ErrorRecord( + new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceOptionNoDebugger, runspace.Name)), + "RunspaceDebugOptionNoDebugger", + ErrorCategory.InvalidOperation, + this) + ); + } + + return debugger; + } + + /// + /// SetDebugPreferenceHelper is a helper method used to enable/disable debug preference. + /// + /// Process Name. + /// App Domain Name. + /// Indicates if debug preference has to be enabled or disabled. + /// FullyQualifiedErrorId to be used on error. + protected void SetDebugPreferenceHelper(string processName, string[] appDomainName, bool enable, string fullyQualifiedErrorId) + { + List appDomainNames = null; + if (appDomainName != null) + { + foreach (string currentAppDomainName in appDomainName) + { + if (!string.IsNullOrEmpty(currentAppDomainName)) + { + appDomainNames ??= new List(); + + appDomainNames.Add(currentAppDomainName.ToLowerInvariant()); + } + } + } + + try + { + System.Management.Automation.Runspaces.LocalRunspace.SetDebugPreference(processName.ToLowerInvariant(), appDomainNames, enable); + } + catch (Exception ex) + { + ErrorRecord errorRecord = new( + new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.PersistDebugPreferenceFailure, processName), ex), + fullyQualifiedErrorId, + ErrorCategory.InvalidOperation, + this); + WriteError(errorRecord); + } + } + + #endregion + } + + #endregion + + #region EnableRunspaceDebugCommand Cmdlet + + /// + /// This cmdlet enables debugging for selected runspaces in the current or specified process. + /// + [Cmdlet(VerbsLifecycle.Enable, "RunspaceDebug", DefaultParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096831")] + public sealed class EnableRunspaceDebugCommand : CommonRunspaceCommandBase + { + #region Parameters + + /// + /// When true this property will cause any running command or script in the Runspace + /// to stop in step mode, regardless of whether a debugger is currently attached. The + /// script or command will remain stopped until a debugger is attached to debug the + /// current stop point. + /// + [Parameter(Position = 1, + ParameterSetName = CommonRunspaceCommandBase.RunspaceParameterSet)] + [Parameter(Position = 1, + ParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet)] + [Parameter(Position = 1, + ParameterSetName = CommonRunspaceCommandBase.RunspaceIdParameterSet)] + public SwitchParameter BreakAll + { + get; + set; + } + + #endregion + + #region Overrides + + /// + /// Process Record. + /// + protected override void ProcessRecord() + { + if (this.ParameterSetName.Equals(CommonRunspaceCommandBase.ProcessNameParameterSet)) + { + SetDebugPreferenceHelper(ProcessName, AppDomainName, true, "EnableRunspaceDebugCommandPersistDebugPreferenceFailure"); + return; + } + + IReadOnlyList results = GetRunspaces(); + + foreach (var runspace in results) + { + if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) + { + WriteError( + new ErrorRecord(new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceOptionInvalidRunspaceState, runspace.Name)), + "SetRunspaceDebugOptionCommandInvalidRunspaceState", + ErrorCategory.InvalidOperation, + this)); + + continue; + } + + System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); + if (debugger == null) + { + continue; + } + + // Enable debugging by preserving debug stop events. + debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Wait; + + if (this.MyInvocation.BoundParameters.ContainsKey(nameof(BreakAll))) + { + if (BreakAll) + { + try + { + debugger.SetDebuggerStepMode(true); + } + catch (PSInvalidOperationException e) + { + WriteError( + new ErrorRecord( + e, + "SetRunspaceDebugOptionCommandCannotEnableDebuggerStepping", + ErrorCategory.InvalidOperation, + this)); + } + } + else + { + debugger.SetDebuggerStepMode(false); + } + } + } + } + + #endregion + } + + #endregion + + #region DisableRunspaceDebugCommand Cmdlet + + /// + /// This cmdlet disables Runspace debugging in selected Runspaces. + /// + [Cmdlet(VerbsLifecycle.Disable, "RunspaceDebug", DefaultParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096924")] + public sealed class DisableRunspaceDebugCommand : CommonRunspaceCommandBase + { + #region Overrides + + /// + /// Process Record. + /// + protected override void ProcessRecord() + { + if (this.ParameterSetName.Equals(CommonRunspaceCommandBase.ProcessNameParameterSet)) + { + SetDebugPreferenceHelper(ProcessName.ToLowerInvariant(), AppDomainName, false, "DisableRunspaceDebugCommandPersistDebugPreferenceFailure"); + } + else + { + IReadOnlyList results = GetRunspaces(); + + foreach (var runspace in results) + { + if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) + { + WriteError( + new ErrorRecord( + new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceOptionInvalidRunspaceState, runspace.Name)), + "SetRunspaceDebugOptionCommandInvalidRunspaceState", + ErrorCategory.InvalidOperation, + this) + ); + + continue; + } + + System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); + if (debugger == null) + { + continue; + } + + debugger.SetDebuggerStepMode(false); + debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; + } + } + } + + #endregion + } + + #endregion + + #region GetRunspaceDebugCommand Cmdlet + + /// + /// This cmdlet returns a PSRunspaceDebug object for each found Runspace object. + /// + [Cmdlet(VerbsCommon.Get, "RunspaceDebug", DefaultParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097015")] + [OutputType(typeof(PSRunspaceDebug))] + public sealed class GetRunspaceDebugCommand : CommonRunspaceCommandBase + { + #region Overrides + + /// + /// Process Record. + /// + protected override void ProcessRecord() + { + IReadOnlyList results = GetRunspaces(); + + foreach (var runspace in results) + { + System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); + if (debugger != null) + { + WriteObject( + new PSRunspaceDebug((debugger.UnhandledBreakpointMode == UnhandledBreakpointProcessingMode.Wait), + debugger.IsDebuggerSteppingEnabled, + runspace.Name, + runspace.Id) + ); + } + } + } + + #endregion + } + + #endregion + + #region WaitDebuggerCommand Cmdlet + + /// + /// This cmdlet causes a running script or command to stop in the debugger at the next execution point. + /// + [Cmdlet(VerbsLifecycle.Wait, "Debugger", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097035")] + public sealed class WaitDebuggerCommand : PSCmdlet + { + #region Overrides + + /// + /// EndProcessing. + /// + protected override void EndProcessing() + { + Runspace currentRunspace = this.Context.CurrentRunspace; + + if (currentRunspace != null && currentRunspace.Debugger != null) + { + WriteVerbose(string.Format(CultureInfo.InvariantCulture, Debugger.DebugBreakMessage, MyInvocation.ScriptLineNumber, MyInvocation.ScriptName)); + + currentRunspace.Debugger.Break(); + } + } + + #endregion + } + + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..d6f2c661ad06ad8ec2124e93f7aa3e8391578307 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -0,0 +1,423 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The formats that export-alias supports. + /// + public enum ExportAliasFormat + { + /// + /// Aliases will be exported to a CSV file. + /// + Csv, + + /// + /// Aliases will be exported as a script. + /// + Script + } + + /// + /// The implementation of the "export-alias" cmdlet. + /// + [Cmdlet(VerbsData.Export, "Alias", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096597")] + [OutputType(typeof(AliasInfo))] + public class ExportAliasCommand : PSCmdlet + { + #region Parameters + + /// + /// The Path of the file to export the aliases to. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] + public string Path + { + get { return _path; } + + set { _path = value ?? "."; } + } + + private string _path = "."; + + /// + /// The literal path of the file to export the aliases to. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _path; + } + + set + { + if (value == null) + { + _path = "."; + } + else + { + _path = value; + _isLiteralPath = true; + } + } + } + + private bool _isLiteralPath = false; + + /// + /// The Name parameter for the command. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] + public string[] Name + { + get { return _names; } + + set { _names = value ?? new string[] { "*" }; } + } + + private string[] _names = new string[] { "*" }; + + /// + /// If set to true, the alias that is set is passed to the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThru; + } + + set + { + _passThru = value; + } + } + + private bool _passThru; + + /// + /// Parameter that determines the format of the file created. + /// + [Parameter] + public ExportAliasFormat As { get; set; } = ExportAliasFormat.Csv; + + /// + /// Property that sets append parameter. + /// + [Parameter] + public SwitchParameter Append + { + get + { + return _append; + } + + set + { + _append = value; + } + } + + private bool _append; + + /// + /// Property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// Property that prevents file overwrite. + /// + [Parameter] + [Alias("NoOverwrite")] + public SwitchParameter NoClobber + { + get + { + return _noclobber; + } + + set + { + _noclobber = value; + } + } + + private bool _noclobber; + + /// + /// The description that gets added to the file as a comment. + /// + /// + [Parameter] + public string Description { get; set; } + + /// + /// The scope parameter for the command determines + /// which scope the aliases are retrieved from. + /// + [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + #endregion Parameters + + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + // First get the alias table (from the proper scope if necessary) + IDictionary aliasTable = null; + + if (!string.IsNullOrEmpty(Scope)) + { + // This can throw PSArgumentException and PSArgumentOutOfRangeException + // but just let them go as this is terminal for the pipeline and the + // exceptions are already properly adorned with an ErrorRecord. + + aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope); + } + else + { + aliasTable = SessionState.Internal.GetAliasTable(); + } + + foreach (string aliasName in _names) + { + bool resultFound = false; + + // Create the name pattern + + WildcardPattern namePattern = + WildcardPattern.Get( + aliasName, + WildcardOptions.IgnoreCase); + + // Now loop through the table and write out any aliases that + // match the name and don't match the exclude filters and are + // visible to the caller... + CommandOrigin origin = MyInvocation.CommandOrigin; + foreach (KeyValuePair tableEntry in aliasTable) + { + if (!namePattern.IsMatch(tableEntry.Key)) + { + continue; + } + + if (SessionState.IsVisible(origin, tableEntry.Value)) + { + resultFound = true; + _matchingAliases.Add(tableEntry.Value); + } + } + + if (!resultFound && + !WildcardPattern.ContainsWildcardCharacters(aliasName)) + { + // Need to write an error if the user tries to get an alias + // that doesn't exist and they are not globbing. + + ItemNotFoundException itemNotFound = + new( + aliasName, + "AliasNotFound", + SessionStateStrings.AliasNotFound); + + WriteError( + new ErrorRecord( + itemNotFound.ErrorRecord, + itemNotFound)); + } + } + } + + /// + /// Writes the aliases to the file. + /// + protected override void EndProcessing() + { + StreamWriter writer = null; + FileInfo readOnlyFileInfo = null; + try + { + if (ShouldProcess(Path)) + { + writer = OpenFile(out readOnlyFileInfo); + } + + if (writer != null) + WriteHeader(writer); + + // Now write out the aliases + + foreach (AliasInfo alias in _matchingAliases) + { + string line = null; + if (this.As == ExportAliasFormat.Csv) + { + line = GetAliasLine(alias, "\"{0}\",\"{1}\",\"{2}\",\"{3}\""); + } + else + { + line = GetAliasLine(alias, "set-alias -Name:\"{0}\" -Value:\"{1}\" -Description:\"{2}\" -Option:\"{3}\""); + } + + writer?.WriteLine(line); + + if (PassThru) + { + WriteObject(alias); + } + } + } + finally + { + writer?.Dispose(); + // reset the read-only attribute + if (readOnlyFileInfo != null) + readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + } + } + + /// + /// Holds all the matching aliases for writing to the file. + /// + private readonly Collection _matchingAliases = new(); + + private static string GetAliasLine(AliasInfo alias, string formatString) + { + // Using the invariant culture here because we don't want the + // file to vary based on locale. + + string result = + string.Format( + System.Globalization.CultureInfo.InvariantCulture, + formatString, + alias.Name, + alias.Definition, + alias.Description, + alias.Options); + + return result; + } + + private void WriteHeader(StreamWriter writer) + { + WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderTitle); + + string user = Environment.UserName; + WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderUser, user); + + DateTime now = DateTime.Now; + WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderDate, now); + + string machine = Environment.MachineName; + WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderMachine, machine); + + // Now write the description if there is one + + if (Description != null) + { + // First we need to break up the description on newlines and add a + // # for each line. + + Description = Description.Replace("\n", "\n# "); + + // Now write out the description + writer.WriteLine("#"); + writer.Write("# "); + writer.WriteLine(Description); + } + } + + private static void WriteFormattedResourceString( + StreamWriter writer, + string resourceId, + params object[] args) + { + string line = StringUtil.Format(resourceId, args); + + writer.Write("# "); + + writer.WriteLine(line); + } + + /// + /// Open the file to which aliases should be exported. + /// + /// + /// If not null, this is the file whose read-only attribute + /// was cleared (due to the -Force parameter). The attribute + /// should be reset. + /// + /// + private StreamWriter OpenFile(out FileInfo readOnlyFileInfo) + { + StreamWriter result = null; + FileStream file = null; + readOnlyFileInfo = null; + + PathUtils.MasterStreamOpen( + this, + this.Path, + EncodingConversion.Unicode, + false, // defaultEncoding + Append, + Force, + NoClobber, + out file, + out result, + out readOnlyFileInfo, + _isLiteralPath + ); + + return result; + } + + private void ThrowFileOpenError(Exception e, string pathWithError) + { + string message = StringUtil.Format(AliasCommandStrings.ExportAliasFileOpenFailed, pathWithError, e.Message); + + ErrorRecord errorRecord = new( + e, + "FileOpenFailure", + ErrorCategory.OpenError, + pathWithError); + + errorRecord.ErrorDetails = new ErrorDetails(message); + this.ThrowTerminatingError(errorRecord); + } + + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..65efee78a2865bce27e1bf6bf3533dd335c06646 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + internal abstract class ColumnInfo + { + protected string displayName; + protected string staleObjectPropertyName; + + internal ColumnInfo(string staleObjectPropertyName, string displayName) + { + this.displayName = displayName; + this.staleObjectPropertyName = GraphicalHostReflectionWrapper.EscapeBinding(staleObjectPropertyName); + } + + internal string StaleObjectPropertyName() + { + return this.staleObjectPropertyName; + } + + internal string DisplayName() + { + return this.displayName; + } + + internal abstract object GetValue(PSObject liveObject); + + internal Type GetValueType(PSObject liveObject, out object columnValue) + { + columnValue = GetValue(liveObject); + if (columnValue != null && columnValue is IComparable) + { + return columnValue.GetType(); + } + + return typeof(string); // Use the String type as default. + } + + /// + /// Auxiliar used in GetValue methods since the list does not deal well with unlimited sized lines. + /// + /// Source string. + /// The source string limited in the number of lines. + internal static object LimitString(object src) + { + if (src is not string srcString) + { + return src; + } + + return HostUtilities.GetMaxLines(srcString, 10); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..4d0c8af875c5f41e8a3b1e52c9fabf2d9cb2ccc4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class ExpressionColumnInfo : ColumnInfo + { + private readonly PSPropertyExpression _expression; + + internal ExpressionColumnInfo(string staleObjectPropertyName, string displayName, PSPropertyExpression expression) + : base(staleObjectPropertyName, displayName) + { + _expression = expression; + } + + internal override object GetValue(PSObject liveObject) + { + List resList = _expression.GetValues(liveObject); + + if (resList.Count == 0) + { + return null; + } + + // Only first element is used. + PSPropertyExpressionResult result = resList[0]; + if (result.Exception != null) + { + return null; + } + + object objectResult = result.Result; + return objectResult == null ? string.Empty : ColumnInfo.LimitString(objectResult.ToString()); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..4f4e84a15696b57550058e5beaa5e55465242ab0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class HeaderInfo + { + private readonly List _columns = new(); + + internal void AddColumn(ColumnInfo col) + { + _columns.Add(col); + } + + internal PSObject AddColumnsToWindow(OutWindowProxy windowProxy, PSObject liveObject) + { + PSObject staleObject = new(); + + // Initiate arrays to be of the same size. + int count = _columns.Count; + string[] propertyNames = new string[count]; + string[] displayNames = new string[count]; + Type[] types = new Type[count]; + + count = 0; // Reuse this variable to count cycles. + foreach (ColumnInfo column in _columns) + { + propertyNames[count] = column.StaleObjectPropertyName(); + displayNames[count] = column.DisplayName(); + object columnValue = null; + types[count] = column.GetValueType(liveObject, out columnValue); + + // Add a property to the stale object since a column value has been evaluated to get column's type. + staleObject.Properties.Add(new PSNoteProperty(propertyNames[count], columnValue)); + + count++; + } + + windowProxy.AddColumns(propertyNames, displayNames, types); + + return staleObject; + } + + internal PSObject CreateStalePSObject(PSObject liveObject) + { + PSObject staleObject = new(); + foreach (ColumnInfo column in _columns) + { + // Add a property to the stale PSObject. + staleObject.Properties.Add(new PSNoteProperty(column.StaleObjectPropertyName(), + column.GetValue(liveObject))); + } + + return staleObject; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..4ec5e2240fa4d350f89a489ac8928478c7b93218 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Management.Automation; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class OriginalColumnInfo : ColumnInfo + { + private readonly string _liveObjectPropertyName; + private readonly OutGridViewCommand _parentCmdlet; + + internal OriginalColumnInfo(string staleObjectPropertyName, string displayName, string liveObjectPropertyName, OutGridViewCommand parentCmdlet) + : base(staleObjectPropertyName, displayName) + { + _liveObjectPropertyName = liveObjectPropertyName; + _parentCmdlet = parentCmdlet; + } + + internal override object GetValue(PSObject liveObject) + { + try + { + PSPropertyInfo propertyInfo = liveObject.Properties[_liveObjectPropertyName]; + if (propertyInfo == null) + { + return null; + } + + // The live object has the liveObjectPropertyName property. + object liveObjectValue = propertyInfo.Value; + if (liveObjectValue is ICollection collectionValue) + { + liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); + } + else + { + if (liveObjectValue is PSObject psObjectValue) + { + // Since PSObject implements IComparable there is a need to verify if its BaseObject actually implements IComparable. + if (psObjectValue.BaseObject is IComparable) + { + liveObjectValue = psObjectValue; + } + else + { + // Use the String type as default. + liveObjectValue = _parentCmdlet.ConvertToString(psObjectValue); + } + } + } + + return ColumnInfo.LimitString(liveObjectValue); + } + catch (GetValueException) + { + // ignore + } + catch (ExtendedTypeSystemException) + { + // ignore + } + + return null; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..574ca39426d7a2276f1062e26c6a25991a98fb69 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -0,0 +1,495 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Enum for SelectionMode parameter. + /// + public enum OutputModeOption + { + /// + /// None is the default and it means OK and Cancel will not be present + /// and no objects will be written to the pipeline. + /// The selectionMode of the actual list will still be multiple. + /// + None, + /// + /// Allow selection of one single item to be written to the pipeline. + /// + Single, + /// + ///Allow select of multiple items to be written to the pipeline. + /// + Multiple + } + + /// + /// Implementation for the Out-GridView command. + /// + [Cmdlet(VerbsData.Out, "GridView", DefaultParameterSetName = "PassThru", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109378")] + public class OutGridViewCommand : PSCmdlet, IDisposable + { + #region Properties + + private const string DataNotQualifiedForGridView = "DataNotQualifiedForGridView"; + private const string RemotingNotSupported = "RemotingNotSupported"; + + private TypeInfoDataBase _typeInfoDataBase; + private PSPropertyExpressionFactory _expressionFactory; + private OutWindowProxy _windowProxy; + private GridHeader _gridHeader; + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + public OutGridViewCommand() + { + } + + #endregion Constructors + + #region Input Parameters + + /// + /// This parameter specifies the current pipeline object. + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// Gets/sets the title of the Out-GridView window. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string Title { get; set; } + + /// + /// Get or sets a value indicating whether the cmdlet should wait for the window to be closed. + /// + [Parameter(ParameterSetName = "Wait")] + public SwitchParameter Wait { get; set; } + + /// + /// Get or sets a value indicating whether the selected items should be written to the pipeline + /// and if it should be possible to select multiple or single list items. + /// + [Parameter(ParameterSetName = "OutputMode")] + public OutputModeOption OutputMode { get; set; } + + /// + /// Gets or sets a value indicating whether the selected items should be written to the pipeline. + /// Setting this to true is the same as setting the OutputMode to Multiple. + /// + [Parameter(ParameterSetName = "PassThru")] + public SwitchParameter PassThru + { + get { return OutputMode == OutputModeOption.Multiple ? new SwitchParameter(true) : new SwitchParameter(false); } + + set { this.OutputMode = value.IsPresent ? OutputModeOption.Multiple : OutputModeOption.None; } + } + + #endregion Input Parameters + + #region Public Methods + + /// + /// Provides a one-time, pre-processing functionality for the cmdlet. + /// + protected override void BeginProcessing() + { + // Set up the ExpressionFactory + _expressionFactory = new PSPropertyExpressionFactory(); + + // If the value of the Title parameter is valid, use it as a window's title. + if (this.Title != null) + { + _windowProxy = new OutWindowProxy(this.Title, OutputMode, this); + } + else + { + // Using the command line as a title. + _windowProxy = new OutWindowProxy(this.MyInvocation.Line, OutputMode, this); + } + + // Load the Type info database. + _typeInfoDataBase = this.Context.FormatDBManager.GetTypeInfoDataBase(); + } + + /// + /// Blocks depending on the wait and selected. + /// + protected override void EndProcessing() + { + base.EndProcessing(); + + if (_windowProxy == null) + { + return; + } + + // If -Wait is used or outputMode is not None we have to wait for the window to be closed + // The pipeline will be blocked while we don't return + if (this.Wait || this.OutputMode != OutputModeOption.None) + { + _windowProxy.BlockUntilClosed(); + } + + // Output selected items to pipeline. + List selectedItems = _windowProxy.GetSelectedItems(); + if (this.OutputMode != OutputModeOption.None && selectedItems != null) + { + foreach (PSObject selectedItem in selectedItems) + { + if (selectedItem == null) + { + continue; + } + + PSPropertyInfo originalObjectProperty = selectedItem.Properties[OutWindowProxy.OriginalObjectPropertyName]; + if (originalObjectProperty == null) + { + return; + } + + this.WriteObject(originalObjectProperty.Value, false); + } + } + } + + /// + /// Provides a record-by-record processing functionality for the cmdlet. + /// + protected override void ProcessRecord() + { + if (InputObject == null || InputObject == AutomationNull.Value) + { + return; + } + + if (InputObject.BaseObject is IDictionary dictionary) + { + // Dictionaries should be enumerated through because the pipeline does not enumerate through them. + foreach (DictionaryEntry entry in dictionary) + { + ProcessObject(PSObjectHelper.AsPSObject(entry)); + } + } + else + { + ProcessObject(InputObject); + } + } + + /// + /// StopProcessing is called close the window when Ctrl+C in the command prompt. + /// + protected override void StopProcessing() + { + if (this.Wait || this.OutputMode != OutputModeOption.None) + { + _windowProxy.CloseWindow(); + } + } + + /// + /// Converts the provided PSObject to a string preserving PowerShell formatting. + /// + /// PSObject to be converted to a string. + internal string ConvertToString(PSObject liveObject) + { + StringFormatError formatErrorObject = new(); + string smartToString = PSObjectHelper.SmartToString(liveObject, + _expressionFactory, + InnerFormatShapeCommand.FormatEnumerationLimit(), + formatErrorObject); + if (formatErrorObject.exception != null) + { + // There was a formatting error that should be sent to the console. + this.WriteError( + new ErrorRecord( + formatErrorObject.exception, + "ErrorFormattingType", + ErrorCategory.InvalidResult, + liveObject) + ); + } + + return smartToString; + } + + #endregion Public Methods + + #region Private Methods + + /// + /// Execute formatting on a single object. + /// + /// Object to process. + private void ProcessObject(PSObject input) + { + // Make sure the OGV window is not closed. + if (_windowProxy.IsWindowClosed()) + { + LocalPipeline pipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline(); + + if (pipeline != null && !pipeline.IsStopping) + { + // Stop the pipeline cleanly. + pipeline.StopAsync(); + } + + return; + } + + object baseObject = input.BaseObject; + + // Throw a terminating error for types that are not supported. + if (baseObject is ScriptBlock || + baseObject is SwitchParameter || + baseObject is PSReference || + baseObject is FormatInfoData || + baseObject is PSObject) + { + ErrorRecord error = new( + new FormatException(StringUtil.Format(FormatAndOut_out_gridview.DataNotQualifiedForGridView)), + DataNotQualifiedForGridView, + ErrorCategory.InvalidType, + null); + + this.ThrowTerminatingError(error); + } + + if (_gridHeader == null) + { + // Columns have not been added yet; Start the main window and add columns. + _windowProxy.ShowWindow(); + _gridHeader = GridHeader.ConstructGridHeader(input, this); + } + else + { + _gridHeader.ProcessInputObject(input); + } + + // Some thread synchronization needed. + Exception exception = _windowProxy.GetLastException(); + if (exception != null) + { + ErrorRecord error = new( + exception, + "ManagementListInvocationException", + ErrorCategory.OperationStopped, + null); + + this.ThrowTerminatingError(error); + } + } + + #endregion Private Methods + + internal abstract class GridHeader + { + protected OutGridViewCommand parentCmd; + + internal GridHeader(OutGridViewCommand parentCmd) + { + this.parentCmd = parentCmd; + } + + internal static GridHeader ConstructGridHeader(PSObject input, OutGridViewCommand parentCmd) + { + if (DefaultScalarTypes.IsTypeInList(input.TypeNames) || + !OutOfBandFormatViewManager.HasNonRemotingProperties(input)) + { + return new ScalarTypeHeader(parentCmd, input); + } + + return new NonscalarTypeHeader(parentCmd, input); + } + + internal abstract void ProcessInputObject(PSObject input); + } + + internal sealed class ScalarTypeHeader : GridHeader + { + private readonly Type _originalScalarType; + + internal ScalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) + { + _originalScalarType = input.BaseObject.GetType(); + + // On scalar types the type name is used as a column name. + this.parentCmd._windowProxy.AddColumnsAndItem(input); + } + + internal override void ProcessInputObject(PSObject input) + { + if (!_originalScalarType.Equals(input.BaseObject.GetType())) + { + parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input); + } + else + { + // Columns are already added; Add the input PSObject as an item to the underlying Management List. + base.parentCmd._windowProxy.AddItem(input); + } + } + } + + internal sealed class NonscalarTypeHeader : GridHeader + { + private readonly AppliesTo _appliesTo = null; + + internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) + { + // Prepare a table view. + TableView tableView = new(); + tableView.Initialize(parentCmd._expressionFactory, parentCmd._typeInfoDataBase); + + // Request a view definition from the type database. + ViewDefinition viewDefinition = DisplayDataQuery.GetViewByShapeAndType(parentCmd._expressionFactory, parentCmd._typeInfoDataBase, FormatShape.Table, input.TypeNames, null); + if (viewDefinition != null) + { + // Create a header using a view definition provided by the types database. + parentCmd._windowProxy.AddColumnsAndItem(input, tableView, (TableControlBody)viewDefinition.mainControl); + + // Remember all type names and type groups the current view applies to. + _appliesTo = viewDefinition.appliesTo; + } + else + { + // Create a header using only the input object's properties. + parentCmd._windowProxy.AddColumnsAndItem(input, tableView); + _appliesTo = new AppliesTo(); + + // Add all type names except for Object and MarshalByRefObject types because they are too generic. + // Leave the Object type name if it is the only type name. + int index = 0; + foreach (string typeName in input.TypeNames) + { + if (index > 0 && (typeName.Equals(typeof(object).FullName, StringComparison.OrdinalIgnoreCase) || + typeName.Equals(typeof(MarshalByRefObject).FullName, StringComparison.OrdinalIgnoreCase))) + { + break; + } + + _appliesTo.AddAppliesToType(typeName); + index++; + } + } + } + + internal override void ProcessInputObject(PSObject input) + { + // Find out if the input has matching types in the this.appliesTo collection. + foreach (TypeOrGroupReference typeOrGroupRef in _appliesTo.referenceList) + { + if (typeOrGroupRef is TypeReference) + { + // Add deserialization prefix. + string deserializedTypeName = typeOrGroupRef.name; + Deserializer.AddDeserializationPrefix(ref deserializedTypeName); + + for (int i = 0; i < input.TypeNames.Count; i++) + { + if (typeOrGroupRef.name.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase) + || deserializedTypeName.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase)) + { + // Current view supports the input's Type; + // Add the input PSObject as an item to the underlying Management List. + base.parentCmd._windowProxy.AddItem(input); + return; + } + } + } + else + { + // Find out if the input's Type belongs to the current TypeGroup. + // TypeGroupReference has only a group's name, so use the database to get through all actual TypeGroup's. + List typeGroupList = base.parentCmd._typeInfoDataBase.typeGroupSection.typeGroupDefinitionList; + foreach (TypeGroupDefinition typeGroup in typeGroupList) + { + if (typeGroup.name.Equals(typeOrGroupRef.name, StringComparison.OrdinalIgnoreCase)) + { + // A matching TypeGroup is found in the database. + // Find out if the input's Type belongs to this TypeGroup. + foreach (TypeReference typeRef in typeGroup.typeReferenceList) + { + // Add deserialization prefix. + string deserializedTypeName = typeRef.name; + Deserializer.AddDeserializationPrefix(ref deserializedTypeName); + + if (input.TypeNames.Count > 0 + && (typeRef.name.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase) + || deserializedTypeName.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase))) + { + // Current view supports the input's Type; + // Add the input PSObject as an item to the underlying Management List. + base.parentCmd._windowProxy.AddItem(input); + return; + } + } + } + } + } + } + + // The input's Type is not supported by the current view; + // Switch to the Hetero Type view. + parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input); + } + } + + internal sealed class HeteroTypeHeader : GridHeader + { + internal HeteroTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) + { + // Clear all existed columns and add Type and Value columns. + this.parentCmd._windowProxy.AddHeteroViewColumnsAndItem(input); + } + + internal override void ProcessInputObject(PSObject input) + { + this.parentCmd._windowProxy.AddHeteroViewItem(input); + } + } + + /// + /// Implements IDisposable logic. + /// + /// True if being called from Dispose. + private void Dispose(bool isDisposing) + { + if (isDisposing) + { + if (_windowProxy != null) + { + _windowProxy.Dispose(); + _windowProxy = null; + } + } + } + + /// + /// Dispose method in IDisposable. + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..ef9b0528c75b17472c574ca1d924eec51ee4902d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Reflection; +using System.Threading; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class OutWindowProxy : IDisposable + { + private const string OutGridViewWindowClassName = "Microsoft.Management.UI.Internal.OutGridViewWindow"; + private const string OriginalTypePropertyName = "OriginalType"; + internal const string OriginalObjectPropertyName = "OutGridViewOriginalObject"; + private const string ToStringValuePropertyName = "ToStringValue"; + private const string IndexPropertyName = "IndexValue"; + + private int _index; + + /// Columns definition of the underlying Management List + private HeaderInfo _headerInfo; + + private bool _isWindowStarted; + + private readonly string _title; + + private readonly OutputModeOption _outputMode; + + private AutoResetEvent _closedEvent; + + private readonly OutGridViewCommand _parentCmdlet; + + private readonly GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; + + /// + /// Initializes a new instance of the class. + /// + internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCommand parentCmdlet) + { + _title = title; + _outputMode = outPutMode; + _parentCmdlet = parentCmdlet; + + _graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, OutWindowProxy.OutGridViewWindowClassName); + } + + /// + /// Adds columns to the output window. + /// + /// An array of property names to add. + /// An array of display names to add. + /// An array of types to add. + internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) + { + ArgumentNullException.ThrowIfNull(propertyNames); + + ArgumentNullException.ThrowIfNull(displayNames); + + ArgumentNullException.ThrowIfNull(types); + + try + { + _graphicalHostReflectionWrapper.CallMethod("AddColumns", propertyNames, displayNames, types); + } + catch (TargetInvocationException ex) + { + // Verify if this is an error loading the System.Core dll. + if (ex.InnerException is FileNotFoundException fileNotFoundEx && fileNotFoundEx.FileName.Contains("System.Core")) + { + _parentCmdlet.ThrowTerminatingError( + new ErrorRecord(new InvalidOperationException( + StringUtil.Format(FormatAndOut_out_gridview.RestartPowerShell, + _parentCmdlet.CommandInfo.Name), ex.InnerException), + "ErrorLoadingAssembly", + ErrorCategory.ObjectNotFound, + null)); + } + else + { + // Let PowerShell take care of this problem. + throw; + } + } + } + + // Types that are not defined in the database and are not scalar. + internal void AddColumnsAndItem(PSObject liveObject, TableView tableView) + { + // Create a header using only the input object's properties. + _headerInfo = tableView.GenerateHeaderInfo(liveObject, _parentCmdlet); + + AddColumnsAndItemEnd(liveObject); + } + + // Database defined types. + internal void AddColumnsAndItem(PSObject liveObject, TableView tableView, TableControlBody tableBody) + { + _headerInfo = tableView.GenerateHeaderInfo(liveObject, tableBody, _parentCmdlet); + + AddColumnsAndItemEnd(liveObject); + } + + // Scalar types. + internal void AddColumnsAndItem(PSObject liveObject) + { + _headerInfo = new HeaderInfo(); + + // On scalar types the type name is used as a column name. + _headerInfo.AddColumn(new ScalarTypeColumnInfo(liveObject.BaseObject.GetType())); + AddColumnsAndItemEnd(liveObject); + } + + private void AddColumnsAndItemEnd(PSObject liveObject) + { + // Add columns to the underlying Management list and as a byproduct get a stale PSObject. + PSObject staleObject = _headerInfo.AddColumnsToWindow(this, liveObject); + + // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. + AddExtraProperties(staleObject, liveObject); + + // Add the stale PSObject to the underlying Management list. + _graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); + } + + // Hetero types. + internal void AddHeteroViewColumnsAndItem(PSObject liveObject) + { + _headerInfo = new HeaderInfo(); + + _headerInfo.AddColumn(new IndexColumnInfo(OutWindowProxy.IndexPropertyName, + StringUtil.Format(FormatAndOut_out_gridview.IndexColumnName), _index)); + _headerInfo.AddColumn(new ToStringColumnInfo(OutWindowProxy.ToStringValuePropertyName, + StringUtil.Format(FormatAndOut_out_gridview.ValueColumnName), _parentCmdlet)); + _headerInfo.AddColumn(new TypeNameColumnInfo(OutWindowProxy.OriginalTypePropertyName, + StringUtil.Format(FormatAndOut_out_gridview.TypeColumnName))); + + // Add columns to the underlying Management list and as a byproduct get a stale PSObject. + PSObject staleObject = _headerInfo.AddColumnsToWindow(this, liveObject); + + // Add the stale PSObject to the underlying Management list. + _graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); + } + + private void AddExtraProperties(PSObject staleObject, PSObject liveObject) + { + // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. + staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.IndexPropertyName, _index++)); + staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.OriginalTypePropertyName, liveObject.BaseObject.GetType().FullName)); + staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.OriginalObjectPropertyName, liveObject)); + + // Convert the LivePSObject to a string preserving PowerShell formatting. + staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.ToStringValuePropertyName, + _parentCmdlet.ConvertToString(liveObject))); + } + + /// + /// Adds an item to the out window. + /// + /// + /// The item to add. + /// + internal void AddItem(PSObject livePSObject) + { + ArgumentNullException.ThrowIfNull(livePSObject); + + if (_headerInfo == null) + { + throw new InvalidOperationException(); + } + + PSObject stalePSObject = _headerInfo.CreateStalePSObject(livePSObject); + + // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. + AddExtraProperties(stalePSObject, livePSObject); + + _graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); + } + + /// + /// Adds an item to the out window. + /// + /// + /// The item to add. + /// + internal void AddHeteroViewItem(PSObject livePSObject) + { + ArgumentNullException.ThrowIfNull(livePSObject); + + if (_headerInfo == null) + { + throw new InvalidOperationException(); + } + + PSObject stalePSObject = _headerInfo.CreateStalePSObject(livePSObject); + _graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); + } + + /// + /// Shows the out window if it has not already been displayed. + /// + internal void ShowWindow() + { + if (!_isWindowStarted) + { + _closedEvent = new AutoResetEvent(false); + _graphicalHostReflectionWrapper.CallMethod("StartWindow", _title, _outputMode.ToString(), _closedEvent); + _isWindowStarted = true; + } + } + + internal void BlockUntilClosed() => _closedEvent?.WaitOne(); + + /// + /// Implements IDisposable logic. + /// + /// True if being called from Dispose. + private void Dispose(bool isDisposing) + { + if (isDisposing) + { + if (_closedEvent != null) + { + _closedEvent.Dispose(); + _closedEvent = null; + } + } + } + + /// + /// Dispose method in IDisposable. + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Close the window if it has already been displayed. + /// + internal void CloseWindow() + { + if (_isWindowStarted) + { + _graphicalHostReflectionWrapper.CallMethod("CloseWindow"); + _isWindowStarted = false; + } + } + + /// + /// Gets a value indicating whether the out window is closed. + /// + /// + /// True if the out window is closed, false otherwise. + /// + internal bool IsWindowClosed() + { + return (bool)_graphicalHostReflectionWrapper.CallMethod("GetWindowClosedStatus"); + } + + /// Returns any exception that has been thrown by previous method calls. + /// The thrown and caught exception. It returns null if no exceptions were thrown by any previous method calls. + internal Exception GetLastException() + { + return (Exception)_graphicalHostReflectionWrapper.CallMethod("GetLastException"); + } + + /// + /// Return the selected item of the OutGridView. + /// + /// + /// The selected item. + /// + internal List GetSelectedItems() + { + return (List)_graphicalHostReflectionWrapper.CallMethod("SelectedItems"); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..38cc966885603aa67491cd6398da0be3051b6417 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class ScalarTypeColumnInfo : ColumnInfo + { + private readonly Type _type; + + internal ScalarTypeColumnInfo(Type type) + : base(type.Name, type.Name) + { + _type = type; + } + + internal override object GetValue(PSObject liveObject) + { + // Strip a wrapping PSObject. + object baseObject = ((PSObject)liveObject).BaseObject; + if (baseObject.GetType().Equals(_type)) + { + return ColumnInfo.LimitString(baseObject); + } + + return null; + } + } + + internal sealed class TypeNameColumnInfo : ColumnInfo + { + internal TypeNameColumnInfo(string staleObjectPropertyName, string displayName) + : base(staleObjectPropertyName, displayName) + { } + + internal override object GetValue(PSObject liveObject) + { + // Strip a wrapping PSObject. + object baseObject = ((PSObject)liveObject).BaseObject; + return baseObject.GetType().FullName; + } + } + + internal sealed class ToStringColumnInfo : ColumnInfo + { + private readonly OutGridViewCommand _parentCmdlet; + + internal ToStringColumnInfo(string staleObjectPropertyName, string displayName, OutGridViewCommand parentCmdlet) + : base(staleObjectPropertyName, displayName) + { + _parentCmdlet = parentCmdlet; + } + + internal override object GetValue(PSObject liveObject) + { + // Convert to a string preserving PowerShell formatting. + return ColumnInfo.LimitString(_parentCmdlet.ConvertToString(liveObject)); + } + } + + internal sealed class IndexColumnInfo : ColumnInfo + { + private int _index = 0; + + internal IndexColumnInfo(string staleObjectPropertyName, string displayName, int index) + : base(staleObjectPropertyName, displayName) + { + _index = index; + } + + internal override object GetValue(PSObject liveObject) + { + // Every time this method is called, another raw is added to ML. + return _index++; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs new file mode 100644 index 0000000000000000000000000000000000000000..e152bb7c973979dab5420eef27ce6a13ecc609af --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class TableView + { + private PSPropertyExpressionFactory _expressionFactory; + private TypeInfoDataBase _typeInfoDatabase; + private FormatErrorManager _errorManager; + + internal void Initialize(PSPropertyExpressionFactory expressionFactory, + TypeInfoDataBase db) + { + _expressionFactory = expressionFactory; + _typeInfoDatabase = db; + + // Initialize Format Error Manager. + FormatErrorPolicy formatErrorPolicy = new(); + + formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; + formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; + + _errorManager = new FormatErrorManager(formatErrorPolicy); + } + + internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) + { + HeaderInfo headerInfo = new(); + + // This verification is needed because the database returns "LastWriteTime" value for file system objects + // as strings and it is used to detect this situation and use the actual field value. + bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); + + if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database. + { + // Generate HeaderInfo from the type information database. + List activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input); + + int col = 0; + foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) + { + ColumnInfo columnInfo = null; + string displayName = null; + TableColumnHeaderDefinition colHeader = null; + // Retrieve a matching TableColumnHeaderDefinition + if (col < tableBody.header.columnHeaderDefinitionList.Count) + colHeader = tableBody.header.columnHeaderDefinitionList[col]; + + if (colHeader != null && colHeader.label != null) + { + displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); + } + + FormatToken token = null; + if (rowItem.formatTokenList.Count > 0) + { + token = rowItem.formatTokenList[0]; + } + + if (token != null) + { + if (token is FieldPropertyToken fpt) + { + // If Database does not provide a label(DisplayName) for the current property, use the expression value instead. + displayName ??= fpt.expression.expressionValue; + + if (fpt.expression.isScriptBlock) + { + PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); + // Using the displayName as a propertyName for a stale PSObject. + const string LastWriteTimePropertyName = "LastWriteTime"; + + // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value. + if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) + { + columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet); + } + else + { + columnInfo = new ExpressionColumnInfo(displayName, displayName, ex); + } + } + else + { + columnInfo = new OriginalColumnInfo(fpt.expression.expressionValue, displayName, fpt.expression.expressionValue, parentCmdlet); + } + } + else + { + if (token is TextToken tt) + { + displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); + columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); + } + } + } + + if (columnInfo != null) + { + headerInfo.AddColumn(columnInfo); + } + + col++; + } + } + + return headerInfo; + } + + internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parentCmdlet) + { + HeaderInfo headerInfo = new(); + List activeAssociationList; + + // Get properties from the default property set of the object + activeAssociationList = AssociationManager.ExpandDefaultPropertySet(input, _expressionFactory); + if (activeAssociationList.Count > 0) + { + // we got a valid set of properties from the default property set..add computername for + // remoteobjects (if available) + if (PSObjectHelper.ShouldShowComputerNameProperty(input)) + { + activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, + new PSPropertyExpression(RemotingConstants.ComputerNameNoteProperty))); + } + } + else + { + // We failed to get anything from the default property set + activeAssociationList = AssociationManager.ExpandAll(input); + if (activeAssociationList.Count > 0) + { + // Remove PSComputerName and PSShowComputerName from the display as needed. + AssociationManager.HandleComputerNameProperties(input, activeAssociationList); + FilterActiveAssociationList(activeAssociationList); + } + else + { + // We were unable to retrieve any properties, so we leave an empty list + activeAssociationList = new List(); + } + } + + for (int k = 0; k < activeAssociationList.Count; k++) + { + string propertyName = null; + + MshResolvedExpressionParameterAssociation association = activeAssociationList[k]; + + // set the label of the column + if (association.OriginatingParameter != null) + { + object key = association.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); + if (key != AutomationNull.Value) + propertyName = (string)key; + } + + propertyName ??= association.ResolvedExpression.ToString(); + + ColumnInfo columnInfo = new OriginalColumnInfo(propertyName, propertyName, propertyName, parentCmdlet); + + headerInfo.AddColumn(columnInfo); + } + + return headerInfo; + } + + /// + /// Method to filter resolved expressions as per table view needs. + /// For v1.0, table view supports only 10 properties. + /// + /// This method filters and updates "activeAssociationList" instance property. + /// + /// None. + /// This method updates "activeAssociationList" instance property. + private static void FilterActiveAssociationList(List activeAssociationList) + { + // we got a valid set of properties from the default property set + // make sure we do not have too many properties + + // NOTE: this is an arbitrary number, chosen to be a sensitive default + const int nMax = 256; + + if (activeAssociationList.Count > nMax) + { + List tmp = new(activeAssociationList); + activeAssociationList.Clear(); + for (int k = 0; k < nMax; k++) + activeAssociationList.Add(tmp[k]); + } + + return; + } + + private List GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so) + { + if (tableBody.optionalDefinitionList.Count == 0) + { + // we do not have any override, use default + return tableBody.defaultDefinition.rowItemDefinitionList; + } + + // see if we have an override that matches + TableRowDefinition matchingRowDefinition = null; + + var typeNames = so.InternalTypeNames; + TypeMatch match = new(_expressionFactory, _typeInfoDatabase, typeNames); + + foreach (TableRowDefinition x in tableBody.optionalDefinitionList) + { + if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) + { + matchingRowDefinition = x; + break; + } + } + + matchingRowDefinition ??= match.BestMatch as TableRowDefinition; + + if (matchingRowDefinition == null) + { + Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); + if (typesWithoutPrefix != null) + { + match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix); + + foreach (TableRowDefinition x in tableBody.optionalDefinitionList) + { + if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) + { + matchingRowDefinition = x; + break; + } + } + + matchingRowDefinition ??= match.BestMatch as TableRowDefinition; + } + } + + if (matchingRowDefinition == null) + { + // no matching override, use default + return tableBody.defaultDefinition.rowItemDefinitionList; + } + + // we have an override, we need to compute the merge of the active cells + List activeRowItemDefinitionList = new(); + int col = 0; + foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList) + { + // Check if the row is an override or not + if (rowItem.formatTokenList.Count == 0) + { + // It's a place holder, use the default + activeRowItemDefinitionList.Add(tableBody.defaultDefinition.rowItemDefinitionList[col]); + } + else + { + // Use the override + activeRowItemDefinitionList.Add(rowItem); + } + + col++; + } + + return activeRowItemDefinitionList; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..16d4325f68a0aea9a5d0193a1898cdbea9ddd7a9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Remoting; +using System.Management.Automation.Runspaces; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Gets formatting information from the loading format information database. + /// + /// Currently supports only table controls + /// + [Cmdlet(VerbsCommon.Get, "FormatData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096614")] + [OutputType(typeof(System.Management.Automation.ExtendedTypeDefinition))] + public class GetFormatDataCommand : PSCmdlet + { + private string[] _typename; + private WildcardPattern[] _filter = new WildcardPattern[1]; + + /// + /// Get Formatting information only for the specified typename. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [ValidateNotNullOrEmpty] + [Parameter(Position = 0)] + public string[] TypeName + { + get + { + return _typename; + } + + set + { + _typename = value; + + if (_typename == null) + { + _filter = Array.Empty(); + } + else + { + _filter = new WildcardPattern[_typename.Length]; + for (int i = 0; i < _filter.Length; i++) + { + _filter[i] = WildcardPattern.Get(_typename[i], + WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); + } + } + } + } + + /// + /// When specified, helps control whether or not to send richer formatting data + /// that was not supported by earlier versions of PowerShell. + /// + [Parameter] + public Version PowerShellVersion { get; set; } + + /// + /// Set the default filter. + /// + protected override void BeginProcessing() + { + if (_filter[0] == null) + { + _filter[0] = WildcardPattern.Get("*", WildcardOptions.None); + } + } + + private static Dictionary> GetTypeGroupMap(IEnumerable groupDefinitions) + { + var typeGroupMap = new Dictionary>(); + foreach (TypeGroupDefinition typeGroup in groupDefinitions) + { + // The format system actually allows you to define multiple SelectionSets with the same name, but only the + // first type group will take effect. So we skip the rest groups that have the same name. + if (!typeGroupMap.ContainsKey(typeGroup.name)) + { + var typesInGroup = typeGroup.typeReferenceList.ConvertAll(static typeReference => typeReference.name); + typeGroupMap.Add(typeGroup.name, typesInGroup); + } + } + + return typeGroupMap; + } + + /// + /// Takes out the content from the database and writes them out. + /// + protected override void ProcessRecord() + { + // Remoting detection: + // * Automatic variable $PSSenderInfo is defined in true remoting contexts as well as in background jobs. + // * $PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion contains the client version, as a [version] instance. + // Note: Even though $PSVersionTable.PSVersion is of type [semver] in PowerShell 6+, it is of type [version] here, + // presumably because only the latter type deserializes type-faithfully. + var clientVersion = PowerShellVersion; + PSSenderInfo remotingClientInfo = GetVariableValue("PSSenderInfo") as PSSenderInfo; + if (clientVersion == null && remotingClientInfo != null) + { + clientVersion = PSObject.Base((PSObject.Base(remotingClientInfo.ApplicationArguments["PSVersionTable"]) as PSPrimitiveDictionary)?["PSVersion"]) as Version; + } + + // During remoting, remain compatible with v5.0- clients by default. + // Passing a -PowerShellVersion argument allows overriding the client version. + bool writeOldWay = + (remotingClientInfo != null && clientVersion == null) // To be safe: Remoting client version could unexpectedly not be determined. + || + (clientVersion != null + && + (clientVersion.Major < 5 + || + (clientVersion.Major == 5 && clientVersion.Minor < 1))); + + TypeInfoDataBase db = this.Context.FormatDBManager.Database; + + List viewdefinitions = db.viewDefinitionsSection.viewDefinitionList; + Dictionary> typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList); + + var typedefs = new Dictionary>(ConsolidatedString.EqualityComparer); + + foreach (ViewDefinition definition in viewdefinitions) + { + this.WriteVerbose(string.Format(CultureInfo.CurrentCulture, GetFormatDataStrings.ProcessViewDefinition, definition.name)); + if (definition.isHelpFormatter) + continue; + + var consolidatedTypeName = CreateConsolidatedTypeName(definition, typeGroupMap); + + if (!ShouldGenerateView(consolidatedTypeName)) + continue; + + PSControl control; + + if (definition.mainControl is TableControlBody tableControlBody) + { + control = new TableControl(tableControlBody, definition); + } + else + { + if (definition.mainControl is ListControlBody listControlBody) + { + control = new ListControl(listControlBody, definition); + } + else + { + if (definition.mainControl is WideControlBody wideControlBody) + { + control = new WideControl(wideControlBody, definition); + if (writeOldWay) + { + // Alignment was added to WideControl in V2, but wasn't + // used. It was removed in V5, but old PowerShell clients + // expect this property or fail to rehydrate the remote object. + var psobj = new PSObject(control); + psobj.Properties.Add(new PSNoteProperty("Alignment", 0)); + } + } + else + { + var complexControlBody = (ComplexControlBody)definition.mainControl; + control = new CustomControl(complexControlBody, definition); + } + } + } + + // Older version of PowerShell do not know about something in the control, so + // don't return it. + if (writeOldWay && !control.CompatibleWithOldPowerShell()) + continue; + + var formatdef = new FormatViewDefinition(definition.name, control, definition.InstanceId); + + List viewList; + if (!typedefs.TryGetValue(consolidatedTypeName, out viewList)) + { + viewList = new List(); + typedefs.Add(consolidatedTypeName, viewList); + } + + viewList.Add(formatdef); + } + + // write out all the available type definitions + foreach (var pair in typedefs) + { + var typeNames = pair.Key; + + if (writeOldWay) + { + foreach (var typeName in typeNames) + { + var etd = new ExtendedTypeDefinition(typeName, pair.Value); + WriteObject(etd); + } + } + else + { + var etd = new ExtendedTypeDefinition(typeNames[0], pair.Value); + for (int i = 1; i < typeNames.Count; i++) + { + etd.TypeNames.Add(typeNames[i]); + } + + WriteObject(etd); + } + } + } + + private static ConsolidatedString CreateConsolidatedTypeName(ViewDefinition definition, Dictionary> typeGroupMap) + { + // Create our "consolidated string" typename which is used as a dictionary key + var reflist = definition.appliesTo.referenceList; + var consolidatedTypeName = new ConsolidatedString(ConsolidatedString.Empty); + + foreach (TypeOrGroupReference item in reflist) + { + // If it's a TypeGroup, we need to look that up and add it's members + if (item is TypeGroupReference) + { + List typesInGroup; + if (typeGroupMap.TryGetValue(item.name, out typesInGroup)) + { + foreach (string typeName in typesInGroup) + { + consolidatedTypeName.Add(typeName); + } + } + } + else + { + consolidatedTypeName.Add(item.name); + } + } + + return consolidatedTypeName; + } + + private bool ShouldGenerateView(ConsolidatedString consolidatedTypeName) + { + foreach (WildcardPattern pattern in _filter) + { + foreach (var typeName in consolidatedTypeName) + { + if (pattern.IsMatch(typeName)) + { + return true; + } + } + } + + return false; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..c07539aa25a8a540ad09acc2644fa1e76b6d5cfb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Cmdlet used to write a collection of formatting directives to an XML file. + /// + [Cmdlet(VerbsData.Export, "FormatData", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096834")] + public class ExportFormatDataCommand : PSCmdlet + { + private ExtendedTypeDefinition[] _typeDefinition; + + /// + /// Type definition to include in export. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public ExtendedTypeDefinition[] InputObject + { + get + { + return _typeDefinition; + } + + set + { + _typeDefinition = value; + } + } + + private string _filepath; + + /// + /// Path of the XML file. + /// + [Parameter(ParameterSetName = "ByPath", Mandatory = true)] + [Alias("FilePath")] + public string Path + { + get + { + return _filepath; + } + + set + { + _filepath = value; + } + } + + /// + /// Literal path of the XML file. + /// + [Parameter(ParameterSetName = "ByLiteralPath", Mandatory = true)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _filepath; + } + + set + { + _filepath = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + private readonly List _typeDefinitions = new(); + + private bool _force; + + /// + /// Force writing a file. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + /// + /// Do not overwrite file if exists. + /// + [Parameter] + [Alias("NoOverwrite")] + public SwitchParameter NoClobber + { + get + { + return _noclobber; + } + + set + { + _noclobber = value; + } + } + + private bool _noclobber; + + /// + /// Include scriptblocks for export. + /// + [Parameter] + public SwitchParameter IncludeScriptBlock + { + get + { + return _includescriptblock; + } + + set + { + _includescriptblock = value; + } + } + + private bool _includescriptblock; + + /// + /// Adds the type to the collection. + /// + protected override void ProcessRecord() + { + foreach (ExtendedTypeDefinition typedef in _typeDefinition) + { + _typeDefinitions.Add(typedef); + } + } + + /// + /// Writes out the formatting directives from the + /// collection to the specified XML file. + /// + protected override void EndProcessing() + { + FormatXmlWriter.WriteToPs1Xml(this, _typeDefinitions, _filepath, _force, _noclobber, _includescriptblock, _isLiteralPath); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs new file mode 100644 index 0000000000000000000000000000000000000000..7e9dab8a20387d478b1c82af2729c9e8c93769e3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -0,0 +1,513 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +// Once Serialization is available on CoreCLR: using System.Runtime.Serialization.Formatters.Binary; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Displays the hexadecimal equivalent of the input data. + /// + [Cmdlet(VerbsCommon.Format, "Hex", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096611")] + [OutputType(typeof(ByteCollection))] + [Alias("fhx")] + public sealed class FormatHex : PSCmdlet + { + private const int BUFFERSIZE = 16; + + /// + /// For cases where a homogeneous collection of bytes or other items are directly piped in, we collect all the + /// bytes in a List<byte> and then output the formatted result all at once in EndProcessing(). + /// + private readonly List _inputBuffer = new(); + + /// + /// Expect to group s by default. When receiving input that should not be grouped, + /// e.g., arrays, strings, FileInfo objects, this flag will be disabled until the next groupable + /// is received over the pipeline. + /// + private bool _groupInput = true; + + /// + /// Keep track of prior input types to determine if we're given a heterogeneous collection. + /// + private Type _lastInputType; + + #region Parameters + + /// + /// Gets or sets the path of file(s) to process. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Path")] + [ValidateNotNullOrEmpty] + public string[] Path { get; set; } + + /// + /// Gets or sets the literal path of file to process. + /// + [Parameter(Mandatory = true, ParameterSetName = "LiteralPath")] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "LP")] + public string[] LiteralPath { get; set; } + + /// + /// Gets or sets the object to process. + /// + [Parameter(Mandatory = true, ParameterSetName = "ByInputObject", ValueFromPipeline = true)] + public PSObject InputObject { get; set; } + + /// + /// Gets or sets the type of character encoding for InputObject. + /// + [Parameter(ParameterSetName = "ByInputObject")] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + /// + /// Gets or sets count of bytes to read from the input stream. + /// + [Parameter] + [ValidateRange(ValidateRangeKind.Positive)] + public long Count { get; set; } = long.MaxValue; + + /// + /// Gets or sets offset of bytes to start reading the input stream from. + /// + [Parameter] + [ValidateRange(ValidateRangeKind.NonNegative)] + public long Offset { get; set; } + + /// + /// Gets or sets whether the file input should be swallowed as is. This parameter is no-op, deprecated. + /// + [Parameter(ParameterSetName = "ByInputObject", DontShow = true)] + [Obsolete("Raw parameter is deprecated.", true)] + public SwitchParameter Raw { get; set; } + + #endregion + + #region Overrides + + /// + /// Implements the ProcessRecord method for the FormatHex command. + /// + protected override void ProcessRecord() + { + if (string.Equals(ParameterSetName, "ByInputObject", StringComparison.OrdinalIgnoreCase)) + { + ProcessInputObjects(InputObject); + } + else + { + List pathsToProcess = string.Equals(ParameterSetName, "LiteralPath", StringComparison.OrdinalIgnoreCase) + ? ResolvePaths(LiteralPath, true) + : ResolvePaths(Path, false); + + ProcessPath(pathsToProcess); + } + } + + /// + /// Implements the EndProcessing method for the FormatHex command. + /// + protected override void EndProcessing() + { + FlushInputBuffer(); + } + + #endregion + + #region Paths + + /// + /// Validate each path provided and if valid, add to array of paths to process. + /// If path is a literal path it is added to the array to process; we cannot validate them until we + /// try to process file contents. + /// + /// The file path to resolve. + /// The paths to process. + /// + private List ResolvePaths(string[] path, bool literalPath) + { + List pathsToProcess = new(); + ProviderInfo provider = null; + + foreach (string currentPath in path) + { + List newPaths = new(); + + if (literalPath) + { + newPaths.Add(Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(currentPath, out provider, out _)); + } + else + { + try + { + newPaths.AddRange(Context.SessionState.Path.GetResolvedProviderPathFromPSPath(currentPath, out provider)); + } + catch (ItemNotFoundException e) + { + if (!WildcardPattern.ContainsWildcardCharacters(currentPath)) + { + ErrorRecord errorRecord = new(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); + WriteError(errorRecord); + continue; + } + } + } + + if (!provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase)) + { + // Write a non-terminating error message indicating that path specified is not supported. + string errorMessage = StringUtil.Format(UtilityCommonStrings.FormatHexOnlySupportsFileSystemPaths, currentPath); + ErrorRecord errorRecord = new( + new ArgumentException(errorMessage), + "FormatHexOnlySupportsFileSystemPaths", + ErrorCategory.InvalidArgument, + currentPath); + WriteError(errorRecord); + continue; + } + + pathsToProcess.AddRange(newPaths); + } + + return pathsToProcess; + } + + /// + /// Pass each valid path on to process its contents. + /// + /// The paths to process. + private void ProcessPath(List pathsToProcess) + { + foreach (string path in pathsToProcess) + { + ProcessFileContent(path); + } + } + + /// + /// Creates a binary reader that reads the file content into a buffer (byte[]) 16 bytes at a time, and + /// passes a copy of that array on to the WriteHexadecimal method to output. + /// + /// The file path to retrieve content from for processing. + private void ProcessFileContent(string path) + { + Span buffer = stackalloc byte[BUFFERSIZE]; + + try + { + using var reader = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)); + long offset = Offset; + int bytesRead = 0; + long count = 0; + + reader.BaseStream.Position = Offset; + + while ((bytesRead = reader.Read(buffer)) > 0) + { + count += bytesRead; + if (count > Count) + { + bytesRead -= (int)(count - Count); + WriteHexadecimal(buffer.Slice(0, bytesRead), path, offset); + break; + } + + WriteHexadecimal(buffer.Slice(0, bytesRead), path, offset); + + offset += bytesRead; + } + } + catch (IOException fileException) + { + // IOException takes care of FileNotFoundException, DirectoryNotFoundException, and PathTooLongException + WriteError(new ErrorRecord(fileException, "FormatHexIOError", ErrorCategory.WriteError, path)); + } + catch (ArgumentException argException) + { + WriteError(new ErrorRecord(argException, "FormatHexArgumentError", ErrorCategory.WriteError, path)); + } + catch (NotSupportedException notSupportedException) + { + WriteError(new ErrorRecord( + notSupportedException, + "FormatHexPathRefersToANonFileDevice", + ErrorCategory.InvalidArgument, + path)); + } + catch (SecurityException securityException) + { + WriteError(new ErrorRecord( + securityException, + "FormatHexUnauthorizedAccessError", + ErrorCategory.PermissionDenied, + path)); + } + } + + #endregion + + #region InputObjects + + private void ProcessString(string originalString) + { + Span bytes = Encoding.GetBytes(originalString); + + int offset = Math.Min(bytes.Length, Offset < int.MaxValue ? (int)Offset : int.MaxValue); + int count = Math.Min(bytes.Length - offset, Count < int.MaxValue ? (int)Count : int.MaxValue); + + if (offset != 0 || count != bytes.Length) + { + WriteHexadecimal(bytes.Slice(offset, count), offset: 0, label: GetGroupLabel(typeof(string))); + } + else + { + WriteHexadecimal(bytes, offset: 0, label: GetGroupLabel(typeof(string))); + } + } + + private static readonly Random _idGenerator = new(); + + private static string GetGroupLabel(Type inputType) + => string.Format("{0} ({1}) <{2:X8}>", inputType.Name, inputType.FullName, _idGenerator.Next()); + + private void FlushInputBuffer() + { + if (_inputBuffer.Count == 0) + { + return; + } + + int offset = Math.Min(_inputBuffer.Count, Offset < int.MaxValue ? (int)Offset : int.MaxValue); + int count = Math.Min(_inputBuffer.Count - offset, Count < int.MaxValue ? (int)Count : int.MaxValue); + + if (offset != 0 || count != _inputBuffer.Count) + { + WriteHexadecimal( + _inputBuffer.GetRange(offset, count).ToArray(), + offset: 0, + label: GetGroupLabel(_lastInputType)); + } + else + { + WriteHexadecimal( + _inputBuffer.ToArray(), + offset: 0, + label: GetGroupLabel(_lastInputType)); + } + + // Reset flags so we can go back to filling up the buffer when needed. + _lastInputType = null; + _groupInput = true; + _inputBuffer.Clear(); + } + + /// + /// Creates a byte array from the object passed to the cmdlet (based on type) and passes + /// that array on to the WriteHexadecimal method to output. + /// + /// The pipeline input object being processed. + private void ProcessInputObjects(PSObject inputObject) + { + object obj = inputObject.BaseObject; + + if (obj is FileSystemInfo fsi) + { + // Output already processed objects first, then process the file input. + FlushInputBuffer(); + string[] path = { fsi.FullName }; + List pathsToProcess = ResolvePaths(path, true); + ProcessPath(pathsToProcess); + return; + } + + if (obj is string str) + { + // Output already processed objects first, then process the string input. + FlushInputBuffer(); + ProcessString(str); + return; + } + + byte[] inputBytes = ConvertToBytes(obj); + + if (!_groupInput) + { + FlushInputBuffer(); + } + + if (inputBytes != null) + { + _inputBuffer.AddRange(inputBytes); + } + else + { + string errorMessage = StringUtil.Format(UtilityCommonStrings.FormatHexTypeNotSupported, obj.GetType()); + ErrorRecord errorRecord = new( + new ArgumentException(errorMessage), + "FormatHexTypeNotSupported", + ErrorCategory.InvalidArgument, + obj.GetType()); + WriteError(errorRecord); + } + } + + /// + /// Converts the input object to a byte array based on the underlying type for basic value types and strings, + /// as well as enum values or arrays. + /// + /// The object to convert. + /// Returns a byte array of the input values, or null if there is no available conversion path. + private byte[] ConvertToBytes(object inputObject) + { + Type baseType = inputObject.GetType(); + byte[] result = null; + int elements = 1; + bool isArray = false; + bool isEnum = false; + if (baseType.IsArray) + { + FlushInputBuffer(); + _lastInputType = baseType; + _groupInput = false; + + baseType = baseType.GetElementType(); + dynamic dynamicObject = inputObject; + elements = (int)dynamicObject.Length; + isArray = true; + } + + if (baseType.IsEnum) + { + baseType = baseType.GetEnumUnderlyingType(); + isEnum = true; + } + + if (baseType.IsPrimitive && elements > 0) + { + if (_groupInput) + { + if (_lastInputType != null && baseType != _lastInputType) + { + _groupInput = false; + FlushInputBuffer(); + } + + _lastInputType = baseType; + } + + var elementSize = Marshal.SizeOf(baseType); + result = new byte[elementSize * elements]; + if (!isArray) + { + inputObject = new object[] { inputObject }; + } + + int index = 0; + foreach (dynamic obj in (Array)inputObject) + { + if (elementSize == 1) + { + result[index] = (byte)obj; + } + else + { + dynamic toBytes; + if (isEnum) + { + toBytes = Convert.ChangeType(obj, baseType); + } + else + { + toBytes = obj; + } + + var bytes = BitConverter.GetBytes(toBytes); + for (int i = 0; i < bytes.Length; i++) + { + result[i + index] = bytes[i]; + } + } + + index += elementSize; + } + } + + return result; + } + + #endregion + + #region Output + + /// + /// Outputs the hexadecimal representation of the input data. + /// + /// Bytes for the hexadecimal representation. + /// File path. + /// Offset in the file. + private void WriteHexadecimal(Span inputBytes, string path, long offset) + { + const int bytesPerObject = 16; + for (int index = 0; index < inputBytes.Length; index += bytesPerObject) + { + var count = inputBytes.Length - index < bytesPerObject + ? inputBytes.Length - index + : bytesPerObject; + var bytes = inputBytes.Slice(index, count); + WriteObject(new ByteCollection((ulong)index + (ulong)offset, bytes.ToArray(), path)); + } + } + + /// + /// Outputs the hexadecimal representation of the input data. + /// + /// Bytes for the hexadecimal representation. + /// Offset in the file. + /// + /// The label for the byte group. This may be a file path, a string value, or a + /// formatted identifying string for the group. + /// + private void WriteHexadecimal(Span inputBytes, long offset, string label) + { + const int bytesPerObject = 16; + for (int index = 0; index < inputBytes.Length; index += bytesPerObject) + { + var count = inputBytes.Length - index < bytesPerObject + ? inputBytes.Length - index + : bytesPerObject; + var bytes = inputBytes.Slice(index, count); + WriteObject(new ByteCollection((ulong)index + (ulong)offset, label, bytes.ToArray())); + } + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs new file mode 100644 index 0000000000000000000000000000000000000000..182ea53e258b29ef94c4fa64580182b2f371565f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the Format-List command. + /// + [Cmdlet(VerbsCommon.Format, "List", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096928")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] + public class FormatListCommand : OuterFormatTableAndListBase + { + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public FormatListCommand() + { + this.implementation = new InnerFormatShapeCommand(FormatShape.List); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..693a799c8095ea153a281c6ea3a41107ab85d546 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the Format-Custom command. It just calls the formatting engine on complex shape. + /// + [Cmdlet(VerbsCommon.Format, "Custom", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096929")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] + public class FormatCustomCommand : OuterFormatShapeCommandBase + { + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public FormatCustomCommand() + { + this.implementation = new InnerFormatShapeCommand(FormatShape.Complex); + } + + #region Command Line Switches + + /// + /// Positional parameter for properties, property sets and table sets. + /// specified on the command line. + /// The parameter is optional, since the defaults + /// will be determined using property sets, etc. + /// + [Parameter(Position = 0)] + [ValidateNotNullOrEmpty] + public object[] Property + { + get { return _props; } + + set { _props = value; } + } + + private object[] _props; + + /// + /// Gets or sets the properties to exclude from formatting. + /// + [Parameter] + public string[] ExcludeProperty { get; set; } + + /// + /// + /// + [ValidateRange(1, int.MaxValue)] + [Parameter] + public int Depth + { + get { return _depth; } + + set { _depth = value; } + } + + private int _depth = ComplexSpecificParameters.maxDepthAllowable; + + #endregion + + internal override FormattingCommandLineParameters GetCommandLineParameters() + { + FormattingCommandLineParameters parameters = new(); + + // Check View conflicts first (before any auto-expansion) + if (!string.IsNullOrEmpty(this.View)) + { + // View cannot be used with Property or ExcludeProperty + if ((_props is not null && _props.Length != 0) || (ExcludeProperty is not null && ExcludeProperty.Length != 0)) + { + ReportCannotSpecifyViewAndProperty(); + } + + parameters.viewName = this.View; + } + + if (_props != null) + { + ParameterProcessor processor = new(new FormatObjectParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); + parameters.mshParameterList = processor.ProcessParameters(_props, invocationContext); + } + + if (ExcludeProperty is not null) + { + parameters.excludePropertyFilter = new PSPropertyExpressionFilter(ExcludeProperty); + + // ExcludeProperty implies -Property * for better UX + if (_props is null || _props.Length == 0) + { + ParameterProcessor processor = new(new FormatObjectParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); + parameters.mshParameterList = processor.ProcessParameters(new object[] { "*" }, invocationContext); + } + } + + parameters.groupByParameter = this.ProcessGroupByParameter(); + parameters.forceFormattingAlsoOnOutOfBand = this.Force; + if (this.showErrorsAsMessages.HasValue) + parameters.showErrorsAsMessages = this.showErrorsAsMessages; + if (this.showErrorsInFormattedOutput.HasValue) + parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput; + + parameters.expansion = ProcessExpandParameter(); + + ComplexSpecificParameters csp = new(); + csp.maxDepth = _depth; + parameters.shapeParameters = csp; + + return parameters; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs new file mode 100644 index 0000000000000000000000000000000000000000..a9e35fcdbc34e1bd04b83b43b363e045cef676bf --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the Format-Table command. + /// + [Cmdlet(VerbsCommon.Format, "Table", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096703")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] + public class FormatTableCommand : OuterFormatTableBase + { + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public FormatTableCommand() + { + this.implementation = new InnerFormatShapeCommand(FormatShape.Table); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs new file mode 100644 index 0000000000000000000000000000000000000000..c6aef5c20be243ba8104b71c6677ed2dc459bb96 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the Format-Wide command. + /// + [Cmdlet(VerbsCommon.Format, "Wide", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096930")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] + public class FormatWideCommand : OuterFormatShapeCommandBase + { + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public FormatWideCommand() + { + this.implementation = new InnerFormatShapeCommand(FormatShape.Wide); + } + + #region Command Line Switches + + /// + /// Positional parameter for properties, property sets and table sets specified on the command line. + /// The parameter is optional, since the defaults will be determined using property sets, etc. + /// + [Parameter(Position = 0)] + public object Property + { + get { return _prop; } + + set { _prop = value; } + } + + private object _prop; + + /// + /// Gets or sets the properties to exclude from formatting. + /// + [Parameter] + public string[] ExcludeProperty { get; set; } + + /// + /// Gets or sets a value indicating whether to autosize the output. + /// + [Parameter] + public SwitchParameter AutoSize + { + get => _autosize.GetValueOrDefault(); + set => _autosize = value; + } + + private bool? _autosize = null; + + /// + /// Optional, non positional parameter. + /// + /// + [Parameter] + [ValidateRange(1, int.MaxValue)] + public int Column + { + get => _column.GetValueOrDefault(-1); + set => _column = value; + } + + private int? _column = null; + + #endregion + + internal override FormattingCommandLineParameters GetCommandLineParameters() + { + FormattingCommandLineParameters parameters = new(); + + // Check View conflicts first (before any auto-expansion) + if (!string.IsNullOrEmpty(this.View)) + { + // View cannot be used with Property or ExcludeProperty + if (_prop is not null || (ExcludeProperty is not null && ExcludeProperty.Length != 0)) + { + ReportCannotSpecifyViewAndProperty(); + } + + parameters.viewName = this.View; + } + + if (_prop != null) + { + ParameterProcessor processor = new(new FormatWideParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); + parameters.mshParameterList = processor.ProcessParameters(new object[] { _prop }, invocationContext); + } + + if (ExcludeProperty is not null) + { + parameters.excludePropertyFilter = new PSPropertyExpressionFilter(ExcludeProperty); + + // ExcludeProperty implies -Property * for better UX + if (_prop is null) + { + ParameterProcessor processor = new(new FormatWideParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); + parameters.mshParameterList = processor.ProcessParameters(new object[] { "*" }, invocationContext); + } + } + + // we cannot specify -column and -autosize, they are mutually exclusive + if (AutoSize && _column.HasValue) + { + // the user specified -autosize:true AND a column number + string msg = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyAutosizeAndColumnsError); + + ErrorRecord errorRecord = new( + new InvalidDataException(), + "FormatCannotSpecifyAutosizeAndColumns", + ErrorCategory.InvalidArgument, + null); + + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.ThrowTerminatingError(errorRecord); + } + + parameters.groupByParameter = this.ProcessGroupByParameter(); + parameters.forceFormattingAlsoOnOutOfBand = this.Force; + if (this.showErrorsAsMessages.HasValue) + parameters.showErrorsAsMessages = this.showErrorsAsMessages; + if (this.showErrorsInFormattedOutput.HasValue) + parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput; + + parameters.expansion = ProcessExpandParameter(); + + if (_autosize.HasValue) + parameters.autosize = _autosize.Value; + + WideSpecificParameters wideSpecific = new(); + parameters.shapeParameters = wideSpecific; + if (_column.HasValue) + { + wideSpecific.columns = _column.Value; + } + + return parameters; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs new file mode 100644 index 0000000000000000000000000000000000000000..e585fc1ce08ffe3a27cd09c45bd4afbf21a808de --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Text; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + internal static class InputFileOpenModeConversion + { + internal static FileMode Convert(OpenMode openMode) + { + return SessionStateUtilities.GetFileModeFromOpenMode(openMode); + } + } + + /// + /// Implementation for the out-file command. + /// + [Cmdlet(VerbsData.Out, "File", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096621")] + public class OutFileCommand : FrontEndCommandBase + { + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public OutFileCommand() + { + this.implementation = new OutputManagerInner(); + } + + #region Command Line Parameters + + /// + /// Mandatory file name to write to. + /// + [Alias("Path")] + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] + public string FilePath + { + get { return _fileName; } + + set { _fileName = value; } + } + + private string _fileName; + + /// + /// Mandatory file name to write to. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _fileName; + } + + set + { + _fileName = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// Encoding optional flag. + /// + [Parameter(Position = 1)] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + /// + /// Property that sets append parameter. + /// + [Parameter] + public SwitchParameter Append + { + get { return _append; } + + set { _append = value; } + } + + private bool _append; + + /// + /// Property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force + { + get { return _force; } + + set { _force = value; } + } + + private bool _force; + + /// + /// Property that prevents file overwrite. + /// + [Parameter] + [Alias("NoOverwrite")] + public SwitchParameter NoClobber + { + get { return _noclobber; } + + set { _noclobber = value; } + } + + private bool _noclobber; + + /// + /// Optional, number of columns to use when writing to device. + /// + [ValidateRange(2, int.MaxValue)] + [Parameter] + public int Width + { + get { return (_width != null) ? _width.Value : 0; } + + set { _width = value; } + } + + private int? _width = null; + + /// + /// False to add a newline to the end of the output string, true if not. + /// + [Parameter] + public SwitchParameter NoNewline + { + get + { + return _suppressNewline; + } + + set + { + _suppressNewline = value; + } + } + + private bool _suppressNewline = false; + + #endregion + + /// + /// Read command line parameters. + /// + protected override void BeginProcessing() + { + // set up the Screen Host interface + OutputManagerInner outInner = (OutputManagerInner)this.implementation; + + // NOTICE: if any exception is thrown from here to the end of the method, the + // cleanup code will be called in IDisposable.Dispose() + outInner.LineOutput = InstantiateLineOutputInterface(); + + if (_sw == null) + { + return; + } + + // finally call the base class for general hookup + base.BeginProcessing(); + } + + /// + /// One-time initialization: acquire a screen host interface + /// by creating one on top of a file. + /// NOTICE: we assume that at this time the file name is + /// available in the CRO. JonN recommends: file name has to be + /// a MANDATORY parameter on the command line. + /// + private LineOutput InstantiateLineOutputInterface() + { + string action = StringUtil.Format(FormatAndOut_out_xxx.OutFile_Action); + if (ShouldProcess(FilePath, action)) + { + PathUtils.MasterStreamOpen( + this, + FilePath, + Encoding, + false, // defaultEncoding + Append, + Force, + NoClobber, + out _fs, + out _sw, + out _readOnlyFileInfo, + _isLiteralPath + ); + } + else + return null; + + // compute the # of columns available + int computedWidth = int.MaxValue; + + if (_width != null) + { + // use the value from the command line + computedWidth = _width.Value; + } + + // use the stream writer to create and initialize the Line Output writer + TextWriterLineOutput twlo = new(_sw, computedWidth, _suppressNewline); + + // finally have the ILineOutput interface extracted + return (LineOutput)twlo; + } + + /// + /// Execution entry point. + /// + protected override void ProcessRecord() + { + _processRecordExecuted = true; + if (_sw == null) + { + return; + } + + // NOTICE: if any exception is thrown, the + // cleanup code will be called in IDisposable.Dispose() + base.ProcessRecord(); + _sw.Flush(); + } + + /// + /// Execution entry point. + /// + protected override void EndProcessing() + { + // When the Out-File is used in a redirection pipelineProcessor, + // its ProcessRecord method may not be called when nothing is written to the + // output pipe, for example: + // Write-Error error > test.txt + // In this case, the EndProcess method should return immediately as if it's + // never been called. The cleanup work will be done in IDisposable.Dispose() + if (!_processRecordExecuted) + { + return; + } + + if (_sw == null) + { + return; + } + + // NOTICE: if any exception is thrown, the + // cleanup code will be called in IDisposable.Dispose() + base.EndProcessing(); + + _sw.Flush(); + + CleanUp(); + } + + /// + /// InternalDispose. + /// + protected override void InternalDispose() + { + base.InternalDispose(); + CleanUp(); + } + + private void CleanUp() + { + if (_fs != null) + { + _fs.Dispose(); + _fs = null; + } + + // reset the read-only attribute + if (_readOnlyFileInfo != null) + { + _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + _readOnlyFileInfo = null; + } + } + + /// + /// Handle to file stream. + /// + private FileStream _fs; + + /// + /// Stream writer used to write to file. + /// + private StreamWriter _sw = null; + + /// + /// Indicate whether the ProcessRecord method was executed. + /// When the Out-File is used in a redirection pipelineProcessor, + /// its ProcessRecord method may not be called when nothing is written to the + /// output pipe, for example: + /// Write-Error error > test.txt + /// In this case, the EndProcess method should return immediately as if it's + /// never been called. + /// + private bool _processRecordExecuted = false; + + /// + /// FileInfo of file to clear read-only flag when operation is complete. + /// + private FileInfo _readOnlyFileInfo = null; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs new file mode 100644 index 0000000000000000000000000000000000000000..583421729067751c5f5e561b233299138c6b4f96 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the out-printer command. + /// + [Cmdlet(VerbsData.Out, "Printer", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109553")] + public class OutPrinterCommand : FrontEndCommandBase + { + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public OutPrinterCommand() + { + this.implementation = new OutputManagerInner(); + } + + /// + /// Optional name of the printer to print to. + /// The alias allows "lp -P printer". + /// + [Parameter(Position = 0)] + [Alias("PrinterName")] + public string Name + { + get { return _printerName; } + + set { _printerName = value; } + } + + private string _printerName; + + /// + /// Read command line parameters. + /// + protected override void BeginProcessing() + { + // set up the Screen Host interface + OutputManagerInner outInner = (OutputManagerInner)this.implementation; + + outInner.LineOutput = InstantiateLineOutputInterface(); + + // finally call the base class for general hookup + base.BeginProcessing(); + } + + /// + /// One-time initialization: acquire a screen host interface by creating one on top of a memory buffer. + /// + private LineOutput InstantiateLineOutputInterface() + { + PrinterLineOutput printOutput = new(_printerName); + return (LineOutput)printOutput; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs new file mode 100644 index 0000000000000000000000000000000000000000..94f3fe6a50ecccaa7fffd4c21c2c601f6c557a54 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -0,0 +1,344 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Printing; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands.Internal.Format +{ + /// + /// Implementation of the LineOutput interface for printer. + /// + internal sealed class PrinterLineOutput : LineOutput + { + #region LineOutput implementation + + /// + /// Full buffering for printer. + /// + internal override bool RequiresBuffering { get { return true; } } + + /// + /// Do the printing on playback. + /// + internal override void ExecuteBufferPlayBack(DoPlayBackCall playback) + { + _playbackCall = playback; + DoPrint(); + } + + /// + /// The # of columns for the printer. + /// + /// + internal override int ColumnNumber + { + get + { + CheckStopProcessing(); + return _deviceColumns; + } + } + + /// + /// The # of rows for the printer. + /// + /// + internal override int RowNumber + { + get + { + CheckStopProcessing(); + return _deviceRows; + } + } + + /// + /// Write a line to the output device. + /// + /// Line to write. + internal override void WriteLine(string s) + { + CheckStopProcessing(); + + // Remove all ANSI escape sequences before sending out to the printer. + s = new ValueStringDecorated(s).ToString(OutputRendering.PlainText); + WriteRawText(s); + } + + /// + /// Write a raw text by delegating to the writer underneath, with no change to the text. + /// For example, keeping VT escape sequences intact in it. + /// + /// The raw text to be written to the device. + internal override void WriteRawText(string s) + { + CheckStopProcessing(); + + // Delegate the action to the helper, that will properly break the string into screen lines. + _writeLineHelper.WriteLine(s, ColumnNumber); + } + + #endregion + + /// + /// Initializes static members of the class. + /// Used for static initializations like DefaultPrintFontName. + /// + static PrinterLineOutput() + { + // This default must be loaded from a resource file as different + // cultures will have different defaults and the localizer would + // know the default for different cultures. + s_defaultPrintFontName = OutPrinterDisplayStrings.DefaultPrintFontName; + } + + /// + /// Initializes a new instance of the class. + /// + /// Name of printer, if null use default printer. + internal PrinterLineOutput(string printerName) + { + _printerName = printerName; + + // instantiate the helper to do the line processing when LineOutput.WriteXXX() is called + WriteLineHelper.WriteCallback wl = new(this.OnWriteLine); + WriteLineHelper.WriteCallback w = new(this.OnWrite); + + _writeLineHelper = new WriteLineHelper(true, wl, w, this.DisplayCells); + } + + /// + /// Callback to be called when IConsole.WriteLine() is called by WriteLineHelper. + /// + /// String to write. + private void OnWriteLine(string s) + { + _lines.Enqueue(s); + } + + /// + /// Callback to be called when Console.Write() is called by WriteLineHelper. + /// This is called when the WriteLineHelper needs to write a line whose length + /// is the same as the width of the screen buffer. + /// + /// String to write. + private void OnWrite(string s) + { + _lines.Enqueue(s); + } + + /// + /// Do the printing. + /// + private void DoPrint() + { + try + { + // create a new print document object and set the printer name, if available + PrintDocument pd = new(); + + if (!string.IsNullOrEmpty(_printerName)) + { + pd.PrinterSettings.PrinterName = _printerName; + } + + // set up the callback mechanism + pd.PrintPage += this.pd_PrintPage; + + // start printing + pd.Print(); + } + finally + { + // make sure we do not leak the font + if (_printFont != null) + { + _printFont.Dispose(); + _printFont = null; + } + } + } + + /// + /// Helper to create a font. + /// If the font object exists, it does nothing. + /// Else, the a new object is created and verified. + /// + /// GDI+ graphics object needed for verification. + private void CreateFont(Graphics g) + { + if (_printFont != null) + return; + + // create the font + + // do we have a specified font? + if (string.IsNullOrEmpty(_printFontName)) + { + _printFontName = s_defaultPrintFontName; + } + + if (_printFontSize <= 0) + { + _printFontSize = DefaultPrintFontSize; + } + + _printFont = new Font(_printFontName, _printFontSize); + VerifyFont(g); + } + + /// + /// Internal helper to verify that the font is fixed pitch. If the test fails, + /// it reverts to the default font. + /// + /// GDI+ graphics object needed for verification. + private void VerifyFont(Graphics g) + { + // check if the font is fixed pitch + // HEURISTICS: + // we compute the length of two strings, one made of "large" characters + // one made of "narrow" ones. If they are the same length, we assume that + // the font is fixed pitch. + const string large = "ABCDEF"; + float wLarge = g.MeasureString(large, _printFont).Width / large.Length; + const string narrow = ".;'}l|"; + float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length; + + if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F) + { + // we passed the test + return; + } + + // just get back to the default, since it's not fixed pitch + _printFont.Dispose(); + _printFont = new Font(s_defaultPrintFontName, DefaultPrintFontSize); + } + + /// + /// Event fired for each page to print. + /// + /// Sender, not used. + /// Print page event. + private void pd_PrintPage(object sender, PrintPageEventArgs ev) + { + float yPos = 0; // GDI+ coordinate down the page + int linesPrinted = 0; // linesPrinted + float leftMargin = ev.MarginBounds.Left; + float topMargin = ev.MarginBounds.Top; + + CreateFont(ev.Graphics); + + // compute the height of a line of text + float lineHeight = _printFont.GetHeight(ev.Graphics); + + // Work out the number of lines per page + // Use the MarginBounds on the event to do this + float linesPerPage = ev.MarginBounds.Height / _printFont.GetHeight(ev.Graphics); + + if (!_printingInitialized) + { + // on the first page we have to initialize the metrics for LineOutput + + // work out the number of columns per page assuming fixed pitch font + const string s = "ABCDEF"; + float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length; + float columnsPerPage = ev.MarginBounds.Width / w; + + _printingInitialized = true; + _deviceRows = (int)linesPerPage; + _deviceColumns = (int)columnsPerPage; + + // now that we initialized the column and row count for the LineOutput + // interface we can tell the outputter to playback from cache to do the + // proper computations of line widths + // returning from this call, the string queue on this object is full of + // lines of text to print + _playbackCall(); + } + + // now iterate over the file printing out each line + while ((linesPrinted < linesPerPage) && (_lines.Count > 0)) + { + // get the string to be printed + string line = _lines.Dequeue(); + + // compute the Y position where to draw + yPos = topMargin + (linesPrinted * lineHeight); + + // do the actual drawing + ev.Graphics.DrawString(line, _printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); + linesPrinted++; + } + + // If we have more lines then print another page + ev.HasMorePages = _lines.Count > 0; + } + + /// + /// Flag for one-time initialization of the interface (columns, etc.). + /// + private bool _printingInitialized = false; + + /// + /// Callback to ask the outputter to playback its cache. + /// + private DoPlayBackCall _playbackCall; + + /// + /// Name of the printer to print to. Null means default printer. + /// + private readonly string _printerName = null; + + /// + /// Name of the font to use, if null the default is used. + /// + private string _printFontName = null; + + /// + /// Font size. + /// + private int _printFontSize = 0; + + /// + /// Default font, used if the printFont is not specified or if the + /// printFont is not fixed pitch. + /// + /// + /// This default must be loaded from a resource file as different + /// cultures will have different defaults and the localizer would + /// know the default for different cultures. + /// + private static readonly string s_defaultPrintFontName; + + /// + /// Default size for the default font. + /// + private const int DefaultPrintFontSize = 8; + + /// + /// Number of columns on the sheet. + /// + private int _deviceColumns = 80; + + // number of rows per sheet + private int _deviceRows = 40; + + /// + /// Text lines ready to print (after output cache playback). + /// + private readonly Queue _lines = new(); + + /// + /// Cached font object. + /// + private Font _printFont = null; + + private readonly WriteLineHelper _writeLineHelper; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs new file mode 100644 index 0000000000000000000000000000000000000000..0f485bec06a52456f95976c5ffc2cd880af355fa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Text; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the out-string command. + /// + [Cmdlet(VerbsData.Out, "String", DefaultParameterSetName = "NoNewLineFormatting", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097024", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(string))] + public class OutStringCommand : FrontEndCommandBase + { + #region Command Line Parameters + /// + /// Optional, non positional parameter to specify the streaming behavior. + /// FALSE: accumulate all the data, then write a single string. + /// TRUE: write one line at the time. + /// + [Parameter(ParameterSetName = "StreamFormatting")] + public SwitchParameter Stream + { + get { return _stream; } + + set { _stream = value; } + } + + private bool _stream; + + /// + /// Optional, number of columns to use when writing to device. + /// + [ValidateRange(2, int.MaxValue)] + [Parameter] + public int Width + { + get { return (_width != null) ? _width.Value : 0; } + + set { _width = value; } + } + + private int? _width = null; + + /// + /// False to add a newline to the end of the output string, true if not. + /// + [Parameter(ParameterSetName = "NoNewLineFormatting")] + public SwitchParameter NoNewline + { + get { return _noNewLine; } + + set { _noNewLine = value; } + } + + private bool _noNewLine = false; + + #endregion + + /// + /// Initializes a new instance of the class + /// and sets the inner command. + /// + public OutStringCommand() + { + this.implementation = new OutputManagerInner(); + } + + /// + /// Read command line parameters. + /// + protected override void BeginProcessing() + { + // set up the LineOutput interface + OutputManagerInner outInner = (OutputManagerInner)this.implementation; + + outInner.LineOutput = InstantiateLineOutputInterface(); + + // finally call the base class for general hookup + base.BeginProcessing(); + } + + /// + /// One-time initialization: acquire a screen host interface + /// by creating one on top of a stream. + /// + private LineOutput InstantiateLineOutputInterface() + { + // set up the streaming text writer + StreamingTextWriter.WriteLineCallback callback = new(this.OnWriteLine); + + _writer = new StreamingTextWriter(callback, Host.CurrentCulture); + + // compute the # of columns available + int computedWidth = int.MaxValue; + + if (_width != null) + { + // use the value from the command line + computedWidth = _width.Value; + } + + // use it to create and initialize the Line Output writer + TextWriterLineOutput twlo = new(_writer, computedWidth); + + // finally have the LineOutput interface extracted + return (LineOutput)twlo; + } + + /// + /// Callback to add lines to the buffer or to write them to the output stream. + /// + /// + private void OnWriteLine(string s) + { + if (_stream) + { + this.WriteObject(s); + } + else + { + if (_noNewLine) + { + _buffer.Append(s); + } + else + { + _buffer.AppendLine(s); + } + } + } + + /// + /// Execution entry point. + /// + protected override void ProcessRecord() + { + base.ProcessRecord(); + _writer.Flush(); + } + + /// + /// Execution entry point. + /// + protected override void EndProcessing() + { + base.EndProcessing(); + + // close the writer + _writer.Flush(); + _writer.Dispose(); + + if (!_stream) + this.WriteObject(_buffer.ToString()); + } + + /// + /// Writer used by the LineOutput. + /// + private StreamingTextWriter _writer = null; + + /// + /// Buffer used when buffering until the end. + /// + private readonly StringBuilder _buffer = new(); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs new file mode 100644 index 0000000000000000000000000000000000000000..3af01087ad767dbc89083b5903ffafba802be89c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class for Get-Error implementation. + /// + [Cmdlet(VerbsCommon.Get, "Error", + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2241804", + DefaultParameterSetName = NewestParameterSetName)] + [OutputType("System.Management.Automation.ErrorRecord#PSExtendedError", "System.Exception#PSExtendedError")] + public sealed class GetErrorCommand : PSCmdlet + { + internal const string ErrorParameterSetName = "Error"; + internal const string NewestParameterSetName = "Newest"; + internal const string AliasNewest = "Last"; + internal const string ErrorRecordPSExtendedError = "System.Management.Automation.ErrorRecord#PSExtendedError"; + internal const string ExceptionPSExtendedError = "System.Exception#PSExtendedError"; + + /// + /// Gets or sets the error object to resolve. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = ErrorParameterSetName)] + [ValidateNotNullOrEmpty] + public PSObject InputObject { get; set; } + + /// + /// Gets or sets the number of error objects to resolve starting with newest first. + /// + [Parameter(ParameterSetName = NewestParameterSetName)] + [Alias(AliasNewest)] + [ValidateRange(1, int.MaxValue)] + public int Newest { get; set; } = 1; + + /// + /// Process the error object. + /// + protected override void ProcessRecord() + { + var errorRecords = new List(); + var index = 0; + + if (InputObject != null) + { + if (InputObject.BaseObject is Exception || InputObject.BaseObject is ErrorRecord) + { + errorRecords.Add(InputObject); + } + } + else + { + var errorVariable = SessionState.PSVariable.Get("error"); + var count = Newest; + ArrayList errors = (ArrayList)errorVariable.Value; + if (count > errors.Count) + { + count = errors.Count; + } + + while (count > 0) + { + errorRecords.Add(errors[index]); + index++; + count--; + } + } + + index = 0; + bool addErrorIdentifier = errorRecords.Count > 1; + + foreach (object errorRecord in errorRecords) + { + var obj = PSObject.AsPSObject(errorRecord, storeTypeNameAndInstanceMembersLocally: true); + + if (obj.TypeNames.Contains("System.Management.Automation.ErrorRecord")) + { + if (!obj.TypeNames.Contains(ErrorRecordPSExtendedError)) + { + obj.TypeNames.Insert(0, ErrorRecordPSExtendedError); + + // Need to remove so this rendering doesn't take precedence as ErrorRecords is "OutOfBand" + obj.TypeNames.Remove("System.Management.Automation.ErrorRecord"); + } + } + + if (obj.TypeNames.Contains("System.Exception")) + { + if (!obj.TypeNames.Contains(ExceptionPSExtendedError)) + { + obj.TypeNames.Insert(0, ExceptionPSExtendedError); + + // Need to remove so this rendering doesn't take precedence as Exception is "OutOfBand" + obj.TypeNames.Remove("System.Exception"); + } + } + + if (addErrorIdentifier) + { + obj.Properties.Add(new PSNoteProperty("PSErrorIndex", index++)); + } + + WriteObject(obj); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs new file mode 100644 index 0000000000000000000000000000000000000000..c675a0f6dc1175a7db56a7b87c3ad78a9ed66165 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Types of breakpoints. + /// + public enum BreakpointType + { + /// Breakpoint on a line within a script + Line, + + /// Breakpoint on a variable + Variable, + + /// Breakpoint on a command + Command + } + + /// + /// This class implements Get-PSBreakpoint. + /// + [Cmdlet(VerbsCommon.Get, "PSBreakpoint", DefaultParameterSetName = LineParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097108")] + [OutputType(typeof(CommandBreakpoint), ParameterSetName = new[] { CommandParameterSetName })] + [OutputType(typeof(LineBreakpoint), ParameterSetName = new[] { LineParameterSetName })] + [OutputType(typeof(VariableBreakpoint), ParameterSetName = new[] { VariableParameterSetName })] + [OutputType(typeof(Breakpoint), ParameterSetName = new[] { TypeParameterSetName, IdParameterSetName })] + public class GetPSBreakpointCommand : PSBreakpointAccessorCommandBase + { + #region strings + + internal const string TypeParameterSetName = "Type"; + internal const string IdParameterSetName = "Id"; + + #endregion strings + + #region parameters + /// + /// Scripts of the breakpoints to output. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")] + [Parameter(ParameterSetName = LineParameterSetName, Position = 0, ValueFromPipeline = true)] + [Parameter(ParameterSetName = CommandParameterSetName)] + [Parameter(ParameterSetName = VariableParameterSetName)] + [Parameter(ParameterSetName = TypeParameterSetName)] + [ValidateNotNullOrEmpty()] + public string[] Script { get; set; } + + /// + /// IDs of the breakpoints to output. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")] + [Parameter(ParameterSetName = IdParameterSetName, Mandatory = true, Position = 0, ValueFromPipeline = true)] + [ValidateNotNull] + public int[] Id { get; set; } + + /// + /// Variables of the breakpoints to output. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")] + [Parameter(ParameterSetName = VariableParameterSetName, Mandatory = true)] + [ValidateNotNull] + public string[] Variable { get; set; } + + /// + /// Commands of the breakpoints to output. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")] + [Parameter(ParameterSetName = CommandParameterSetName, Mandatory = true)] + [ValidateNotNull] + public string[] Command { get; set; } + + /// + /// Commands of the breakpoints to output. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")] + [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Type is OK for a cmdlet parameter")] + [Parameter(ParameterSetName = TypeParameterSetName, Mandatory = true, Position = 0, ValueFromPipeline = true)] + [ValidateNotNull] + public BreakpointType[] Type { get; set; } + + #endregion parameters + + #region overrides + + /// + /// Remove breakpoints. + /// + protected override void ProcessRecord() + { + List breakpoints = Runspace.Debugger.GetBreakpoints(); + + // Filter by parameter set + if (ParameterSetName.Equals(LineParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + // no filter + } + else if (ParameterSetName.Equals(IdParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + breakpoints = Filter( + breakpoints, + Id, + static (Breakpoint breakpoint, int id) => breakpoint.Id == id); + } + else if (ParameterSetName.Equals(CommandParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + breakpoints = Filter( + breakpoints, + Command, + (Breakpoint breakpoint, string command) => + { + if (breakpoint is not CommandBreakpoint commandBreakpoint) + { + return false; + } + + return commandBreakpoint.Command.Equals(command, StringComparison.OrdinalIgnoreCase); + }); + } + else if (ParameterSetName.Equals(VariableParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + breakpoints = Filter( + breakpoints, + Variable, + (Breakpoint breakpoint, string variable) => + { + if (breakpoint is not VariableBreakpoint variableBreakpoint) + { + return false; + } + + return variableBreakpoint.Variable.Equals(variable, StringComparison.OrdinalIgnoreCase); + }); + } + else if (ParameterSetName.Equals(TypeParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + breakpoints = Filter( + breakpoints, + Type, + (Breakpoint breakpoint, BreakpointType type) => + { + switch (type) + { + case BreakpointType.Line: + if (breakpoint is LineBreakpoint) + { + return true; + } + + break; + + case BreakpointType.Command: + if (breakpoint is CommandBreakpoint) + { + return true; + } + + break; + + case BreakpointType.Variable: + if (breakpoint is VariableBreakpoint) + { + return true; + } + + break; + } + + return false; + }); + } + else + { + Diagnostics.Assert(false, "Invalid parameter set: {0}", this.ParameterSetName); + } + + // Filter by script + if (Script != null) + { + breakpoints = Filter( + breakpoints, + Script, + (Breakpoint breakpoint, string script) => + { + if (breakpoint.Script == null) + { + return false; + } + + return string.Equals( + SessionState.Path.GetUnresolvedProviderPathFromPSPath(breakpoint.Script), + SessionState.Path.GetUnresolvedProviderPathFromPSPath(script), + StringComparison.OrdinalIgnoreCase + ); + }); + } + + // Output results + foreach (Breakpoint b in breakpoints) + { + ProcessBreakpoint(b); + } + } + + #endregion overrides + + #region private methods + + /// + /// Gives the criteria to filter breakpoints. + /// + private delegate bool FilterSelector(Breakpoint breakpoint, T target); + + /// + /// Returns the items in the input list that match an item in the filter array according to + /// the given selection criterion. + /// + private static List Filter(List input, T[] filter, FilterSelector selector) + { + List output = new(); + + for (int i = 0; i < input.Count; i++) + { + for (int j = 0; j < filter.Length; j++) + { + if (selector(input[i], filter[j])) + { + output.Add(input[i]); + break; + } + } + } + + return output; + } + + #endregion private methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs new file mode 100644 index 0000000000000000000000000000000000000000..4d2d05175698296e2f150e039e3c215ebd362d36 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Get-PSCallStack. + /// + [Cmdlet(VerbsCommon.Get, "PSCallStack", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096705")] + [OutputType(typeof(CallStackFrame))] + public class GetPSCallStackCommand : PSCmdlet + { + /// + /// Get the call stack. + /// + protected override void ProcessRecord() + { + foreach (CallStackFrame frame in Context.Debugger.GetCallStack()) + { + WriteObject(frame); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..7b93b555c5c08133739fe8e305feb492ddf55d17 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "get-alias" cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "Alias", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096702")] + [OutputType(typeof(AliasInfo))] + public class GetAliasCommand : PSCmdlet + { + #region Parameters + + /// + /// The Name parameter for the command. + /// + [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty()] + public string[] Name + { + get { return _names; } + + set { _names = value ?? new string[] { "*" }; } + } + + private string[] _names = new string[] { "*" }; + + /// + /// The Exclude parameter for the command. + /// + [Parameter] + public string[] Exclude + { + get { return _excludes; } + + set { _excludes = value ?? Array.Empty(); } + } + + private string[] _excludes = Array.Empty(); + + /// + /// The scope parameter for the command determines + /// which scope the aliases are retrieved from. + /// + [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + /// + /// Parameter definition to retrieve aliases based on their definitions. + /// + [Parameter(ParameterSetName = "Definition")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Definition { get; set; } + + #endregion Parameters + + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + if (ParameterSetName.Equals("Definition")) + { + foreach (string defn in Definition) + { + WriteMatches(defn, "Definition"); + } + } + else + { + foreach (string aliasName in _names) + { + WriteMatches(aliasName, "Default"); + } + } + } + #endregion Command code + + private void WriteMatches(string value, string parametersetname) + { + // First get the alias table (from the proper scope if necessary) + IDictionary aliasTable = null; + + // get the command origin + CommandOrigin origin = MyInvocation.CommandOrigin; + string displayString = "name"; + if (!string.IsNullOrEmpty(Scope)) + { + // This can throw PSArgumentException and PSArgumentOutOfRangeException + // but just let them go as this is terminal for the pipeline and the + // exceptions are already properly adorned with an ErrorRecord. + + aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope); + } + else + { + aliasTable = SessionState.Internal.GetAliasTable(); + } + + bool matchfound = false; + bool ContainsWildcard = WildcardPattern.ContainsWildcardCharacters(value); + WildcardPattern wcPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + + // excluding patter for Default paramset. + Collection excludePatterns = + SessionStateUtilities.CreateWildcardsFromStrings( + _excludes, + WildcardOptions.IgnoreCase); + + List results = new(); + foreach (KeyValuePair tableEntry in aliasTable) + { + if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase)) + { + displayString = "definition"; + if (!wcPattern.IsMatch(tableEntry.Value.Definition)) + { + continue; + } + + if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false)) + { + continue; + } + } + else + { + if (!wcPattern.IsMatch(tableEntry.Key)) + { + continue; + } + // excludes pattern + if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Key, excludePatterns, false)) + { + continue; + } + } + + if (ContainsWildcard) + { + // Only write the command if it is visible to the requestor + if (SessionState.IsVisible(origin, tableEntry.Value)) + { + matchfound = true; + results.Add(tableEntry.Value); + } + } + else + { + // For specifically named elements, generate an error for elements that aren't visible... + try + { + SessionState.ThrowIfNotVisible(origin, tableEntry.Value); + results.Add(tableEntry.Value); + matchfound = true; + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + // Even though it resulted in an error, a result was found + // so we don't want to generate the nothing found error + // at the end... + matchfound = true; + continue; + } + } + } + + results.Sort( + static (AliasInfo left, AliasInfo right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)); + foreach (AliasInfo alias in results) + { + this.WriteObject(alias); + } + + if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0)) + { + // Need to write an error if the user tries to get an alias + // tat doesn't exist and they are not globbing. + + ItemNotFoundException itemNotFound = new(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value)); + ErrorRecord er = new(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value); + WriteError(er); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..82a725ba2121aa2f17889643ac36a0672b0343eb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Returns: + /// - the thread's current culture + /// - culture by name + /// - list of all supported cultures. + /// + [Cmdlet(VerbsCommon.Get, "Culture", DefaultParameterSetName = CurrentCultureParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097017")] + [OutputType(typeof(System.Globalization.CultureInfo))] + public sealed class GetCultureCommand : PSCmdlet + { + private const string CurrentCultureParameterSet = "CurrentCulture"; + private const string NameParameterSet = "Name"; + private const string ListAvailableParameterSet = "ListAvailable"; + + /// + /// Gets or sets culture names for which CultureInfo values are returned. + /// Empty string matches Invariant culture. + /// + [Parameter(ParameterSetName = NameParameterSet, Position = 0, ValueFromPipeline = true)] + [ValidateSet(typeof(ValidateCultureNamesGenerator))] + [ValidateNotNull] + public string[] Name { get; set; } + + /// + /// Gets or sets a switch to return current culture with user overrides (by default). + /// With the switch on, we return current culture without user overrides. + /// + [Parameter(ParameterSetName = CurrentCultureParameterSet)] + [Parameter(ParameterSetName = NameParameterSet)] + public SwitchParameter NoUserOverrides { get; set; } + + /// + /// Gets or sets a switch to list all available cultures. + /// + [Parameter(ParameterSetName = ListAvailableParameterSet)] + public SwitchParameter ListAvailable { get; set; } + + /// + /// Output: + /// - the thread's current culture + /// - culture by name + /// - list of all supported cultures. + /// + protected override void ProcessRecord() + { + CultureInfo ci; + + switch (ParameterSetName) + { + case CurrentCultureParameterSet: + if (NoUserOverrides) + { + ci = CultureInfo.GetCultureInfo(Host.CurrentCulture.Name); + } + else + { + ci = Host.CurrentCulture; + } + + WriteObject(ci); + + break; + case NameParameterSet: + try + { + foreach (var cultureName in Name) + { + if (!NoUserOverrides && string.Equals(cultureName, Host.CurrentCulture.Name, StringComparison.CurrentCultureIgnoreCase)) + { + ci = Host.CurrentCulture; + } + else + { + ci = CultureInfo.GetCultureInfo(cultureName); + } + + WriteObject(ci); + } + } + catch (CultureNotFoundException exc) + { + WriteError(new ErrorRecord(exc, "ItemNotFoundException", ErrorCategory.ObjectNotFound, Name)); + } + + break; + case ListAvailableParameterSet: + foreach (var cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures)) + { + WriteObject(cultureInfo); + } + + break; + } + } + } + + /// + /// Get list of valid culture names for ValidateSet attribute. + /// + public class ValidateCultureNamesGenerator : IValidateSetValuesGenerator + { + string[] IValidateSetValuesGenerator.GetValidValues() + { + var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); + var result = new List(cultures.Length); + foreach (var cultureInfo in cultures) + { + result.Add(cultureInfo.Name); + } + + return result.ToArray(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..6717cc7196b15cb02c2c6bde914b98b23c8f4e12 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -0,0 +1,600 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + #region get-date + + /// + /// Implementation for the get-date command. + /// + [Cmdlet(VerbsCommon.Get, "Date", DefaultParameterSetName = DateAndFormatParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096615")] + [OutputType(typeof(string))] + [OutputType(typeof(DateTime), ParameterSetName = new[] { DateAndFormatParameterSet, UnixTimeSecondsAndFormatParameterSet })] + public sealed class GetDateCommand : Cmdlet + { + #region parameters + + /// + /// Allows user to override the date/time object that will be processed. + /// + [Parameter(ParameterSetName = DateAndFormatParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = DateAndUFormatParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Alias("LastWriteTime")] + public DateTime Date + { + get + { + return _date; + } + + set + { + _date = value; + _dateSpecified = true; + } + } + + private DateTime _date; + private bool _dateSpecified; + + // The const comes from DateTimeOffset.MinValue.ToUnixTimeSeconds() + private const long MinimumUnixTimeSecond = -62135596800; + + // The const comes from DateTimeOffset.MaxValue.ToUnixTimeSeconds() + private const long MaximumUnixTimeSecond = 253402300799; + + /// + /// Gets or sets whether to treat a numeric input as ticks, or unix time. + /// + [Parameter(ParameterSetName = UnixTimeSecondsAndFormatParameterSet, Mandatory = true)] + [Parameter(ParameterSetName = UnixTimeSecondsAndUFormatParameterSet, Mandatory = true)] + [ValidateRange(MinimumUnixTimeSecond, MaximumUnixTimeSecond)] + [Alias("UnixTime")] + public long UnixTimeSeconds + { + get + { + return _unixTimeSeconds; + } + + set + { + _unixTimeSeconds = value; + _unixTimeSecondsSpecified = true; + } + } + + private long _unixTimeSeconds; + private bool _unixTimeSecondsSpecified; + + /// + /// Allows the user to override the year. + /// + [Parameter] + [ValidateRange(1, 9999)] + public int Year + { + get + { + return _year; + } + + set + { + _year = value; + _yearSpecified = true; + } + } + + private int _year; + private bool _yearSpecified; + + /// + /// Allows the user to override the month. + /// + [Parameter] + [ValidateRange(1, 12)] + public int Month + { + get + { + return _month; + } + + set + { + _month = value; + _monthSpecified = true; + } + } + + private int _month; + private bool _monthSpecified; + + /// + /// Allows the user to override the day. + /// + [Parameter] + [ValidateRange(1, 31)] + public int Day + { + get + { + return _day; + } + + set + { + _day = value; + _daySpecified = true; + } + } + + private int _day; + private bool _daySpecified; + + /// + /// Allows the user to override the hour. + /// + [Parameter] + [ValidateRange(0, 23)] + public int Hour + { + get + { + return _hour; + } + + set + { + _hour = value; + _hourSpecified = true; + } + } + + private int _hour; + private bool _hourSpecified; + + /// + /// Allows the user to override the minute. + /// + [Parameter] + [ValidateRange(0, 59)] + public int Minute + { + get + { + return _minute; + } + + set + { + _minute = value; + _minuteSpecified = true; + } + } + + private int _minute; + private bool _minuteSpecified; + + /// + /// Allows the user to override the second. + /// + [Parameter] + [ValidateRange(0, 59)] + public int Second + { + get + { + return _second; + } + + set + { + _second = value; + _secondSpecified = true; + } + } + + private int _second; + private bool _secondSpecified; + + /// + /// Allows the user to override the millisecond. + /// + [Parameter] + [ValidateRange(0, 999)] + public int Millisecond + { + get + { + return _millisecond; + } + + set + { + _millisecond = value; + _millisecondSpecified = true; + } + } + + private int _millisecond; + private bool _millisecondSpecified; + + /// + /// This option determines the default output format used to display the object get-date emits. + /// + [Parameter] + public DisplayHintType DisplayHint { get; set; } = DisplayHintType.DateTime; + + /// + /// Unix format string. + /// + [Parameter(ParameterSetName = DateAndUFormatParameterSet, Mandatory = true)] + [Parameter(ParameterSetName = UnixTimeSecondsAndUFormatParameterSet, Mandatory = true)] + public string UFormat { get; set; } + + /// + /// DotNet format string. + /// + [Parameter(ParameterSetName = DateAndFormatParameterSet)] + [Parameter(ParameterSetName = UnixTimeSecondsAndFormatParameterSet)] + [ArgumentCompletions("FileDate", "FileDateUniversal", "FileDateTime", "FileDateTimeUniversal")] + public string Format { get; set; } + + /// + /// Gets or sets a value that converts date to UTC before formatting. + /// + [Parameter] + public SwitchParameter AsUTC { get; set; } + #endregion + + #region methods + + /// + /// Get the time. + /// + protected override void ProcessRecord() + { + DateTime dateToUse = DateTime.Now; + int offset; + + // use passed date object if specified + if (_dateSpecified) + { + dateToUse = Date; + } + else if (_unixTimeSecondsSpecified) + { + dateToUse = DateTimeOffset.FromUnixTimeSeconds(UnixTimeSeconds).LocalDateTime; + } + + // use passed year if specified + if (_yearSpecified) + { + offset = Year - dateToUse.Year; + dateToUse = dateToUse.AddYears(offset); + } + + // use passed month if specified + if (_monthSpecified) + { + offset = Month - dateToUse.Month; + dateToUse = dateToUse.AddMonths(offset); + } + + // use passed day if specified + if (_daySpecified) + { + offset = Day - dateToUse.Day; + dateToUse = dateToUse.AddDays(offset); + } + + // use passed hour if specified + if (_hourSpecified) + { + offset = Hour - dateToUse.Hour; + dateToUse = dateToUse.AddHours(offset); + } + + // use passed minute if specified + if (_minuteSpecified) + { + offset = Minute - dateToUse.Minute; + dateToUse = dateToUse.AddMinutes(offset); + } + + // use passed second if specified + if (_secondSpecified) + { + offset = Second - dateToUse.Second; + dateToUse = dateToUse.AddSeconds(offset); + } + + // use passed millisecond if specified + if (_millisecondSpecified) + { + offset = Millisecond - dateToUse.Millisecond; + dateToUse = dateToUse.AddMilliseconds(offset); + dateToUse = dateToUse.Subtract(TimeSpan.FromTicks(dateToUse.Ticks % 10000)); + } + + if (AsUTC) + { + dateToUse = dateToUse.ToUniversalTime(); + } + + if (UFormat != null) + { + // format according to UFormat string + WriteObject(UFormatDateString(dateToUse)); + } + else if (Format != null) + { + // format according to Format string + + // Special case built-in primitives: FileDate, FileDateTime. + // These are the ISO 8601 "basic" formats, dropping dashes and colons + // so that they can be used in file names + + if (string.Equals("FileDate", Format, StringComparison.OrdinalIgnoreCase)) + { + Format = "yyyyMMdd"; + } + else if (string.Equals("FileDateUniversal", Format, StringComparison.OrdinalIgnoreCase)) + { + dateToUse = dateToUse.ToUniversalTime(); + Format = "yyyyMMddZ"; + } + else if (string.Equals("FileDateTime", Format, StringComparison.OrdinalIgnoreCase)) + { + Format = "yyyyMMddTHHmmssffff"; + } + else if (string.Equals("FileDateTimeUniversal", Format, StringComparison.OrdinalIgnoreCase)) + { + dateToUse = dateToUse.ToUniversalTime(); + Format = "yyyyMMddTHHmmssffffZ"; + } + + WriteObject(dateToUse.ToString(Format, CultureInfo.CurrentCulture)); + } + else + { + // output DateTime object wrapped in an PSObject with DisplayHint attached + PSObject outputObj = new(dateToUse); + PSNoteProperty note = new("DisplayHint", DisplayHint); + outputObj.Properties.Add(note); + + WriteObject(outputObj); + } + } + + /// + /// This is more an implementation of the UNIX strftime. + /// + private string UFormatDateString(DateTime dateTime) + { + int offset = 0; + StringBuilder sb = new(); + + // folks may include the "+" as part of the format string + if (UFormat[0] == '+') + { + offset++; + } + + for (int i = offset; i < UFormat.Length; i++) + { + if (UFormat[i] == '%') + { + i++; + switch (UFormat[i]) + { + case 'A': + sb.Append("{0:dddd}"); + break; + + case 'a': + sb.Append("{0:ddd}"); + break; + + case 'B': + sb.Append("{0:MMMM}"); + break; + + case 'b': + sb.Append("{0:MMM}"); + break; + + case 'C': + sb.Append(dateTime.Year / 100); + break; + + case 'c': + sb.Append("{0:ddd} {0:dd} {0:MMM} {0:yyyy} {0:HH}:{0:mm}:{0:ss}"); + break; + + case 'D': + sb.Append("{0:MM/dd/yy}"); + break; + + case 'd': + sb.Append("{0:dd}"); + break; + + case 'e': + sb.Append(StringUtil.Format("{0,2}", dateTime.Day)); + break; + + case 'F': + sb.Append("{0:yyyy}-{0:MM}-{0:dd}"); + break; + + case 'G': + sb.Append(StringUtil.Format("{0:0000}", ISOWeek.GetYear(dateTime))); + break; + + case 'g': + int isoYearWithoutCentury = ISOWeek.GetYear(dateTime) % 100; + sb.Append(StringUtil.Format("{0:00}", isoYearWithoutCentury)); + break; + + case 'H': + sb.Append("{0:HH}"); + break; + + case 'h': + sb.Append("{0:MMM}"); + break; + + case 'I': + sb.Append("{0:hh}"); + break; + + case 'j': + sb.Append(StringUtil.Format("{0:000}", dateTime.DayOfYear)); + break; + + case 'k': + sb.Append(StringUtil.Format("{0,2:0}", dateTime.Hour)); + break; + + case 'l': + sb.Append("{0,2:%h}"); + break; + + case 'M': + sb.Append("{0:mm}"); + break; + + case 'm': + sb.Append("{0:MM}"); + break; + + case 'n': + sb.Append('\n'); + break; + + case 'p': + sb.Append("{0:tt}"); + break; + + case 'R': + sb.Append("{0:HH:mm}"); + break; + + case 'r': + sb.Append("{0:hh:mm:ss tt}"); + break; + + case 'S': + sb.Append("{0:ss}"); + break; + + case 's': + sb.Append(StringUtil.Format("{0:0}", dateTime.ToUniversalTime().Subtract(DateTime.UnixEpoch).TotalSeconds)); + break; + + case 'T': + sb.Append("{0:HH:mm:ss}"); + break; + + case 't': + sb.Append('\t'); + break; + + case 'U': + sb.Append(dateTime.DayOfYear / 7); + break; + + case 'u': + int dayOfWeek = dateTime.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)dateTime.DayOfWeek; + sb.Append(dayOfWeek); + break; + + case 'V': + sb.Append(StringUtil.Format("{0:00}", ISOWeek.GetWeekOfYear(dateTime))); + break; + + case 'W': + sb.Append(dateTime.DayOfYear / 7); + break; + + case 'w': + sb.Append((int)dateTime.DayOfWeek); + break; + + case 'X': + sb.Append("{0:HH:mm:ss}"); + break; + + case 'x': + sb.Append("{0:MM/dd/yy}"); + break; + + case 'Y': + sb.Append("{0:yyyy}"); + break; + + case 'y': + sb.Append("{0:yy}"); + break; + + case 'Z': + sb.Append("{0:zz}"); + break; + + default: + sb.Append(UFormat[i]); + break; + } + } + else + { + // It's not a known format specifier, so just append it + sb.Append(UFormat[i]); + } + } + + return StringUtil.Format(sb.ToString(), dateTime); + } + + #endregion + + private const string DateAndFormatParameterSet = "DateAndFormat"; + private const string DateAndUFormatParameterSet = "DateAndUFormat"; + private const string UnixTimeSecondsAndFormatParameterSet = "UnixTimeSecondsAndFormat"; + private const string UnixTimeSecondsAndUFormatParameterSet = "UnixTimeSecondsAndUFormat"; + } + + #endregion + + #region DisplayHintType enum + + /// + /// Display Hint type. + /// + public enum DisplayHintType + { + /// + /// Display preference Date-Only. + /// + Date, + /// + /// Display preference Time-Only. + /// + Time, + /// + /// Display preference Date and Time. + /// + DateTime + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..f4ab18ac75abc999c2c1d527cdb148384d940c7c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Gets events from the event queue. + /// + [Cmdlet(VerbsCommon.Get, "Event", DefaultParameterSetName = "BySource", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097014")] + [OutputType(typeof(PSEventArgs))] + public class GetEventCommand : PSCmdlet + { + #region parameters + + /// + /// An identifier for this event subscription. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "BySource")] + [ValidateNotNullOrEmpty] + public string SourceIdentifier + { + get + { + return _sourceIdentifier; + } + + set + { + _sourceIdentifier = value; + + if (value != null) + { + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + } + } + } + + private string _sourceIdentifier = null; + + /// + /// An identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "ById")] + [Alias("Id")] + public int EventIdentifier + { + get + { + return _eventId; + } + + set + { + _eventId = value; + } + } + + private int _eventId = -1; + + #endregion parameters + + private WildcardPattern _matchPattern; + + /// + /// Get the requested events. + /// + protected override void EndProcessing() + { + bool foundMatch = false; + + // Go through all the received events and write them to the output + // pipeline + List eventArgsCollection; + lock (Events.ReceivedEvents.SyncRoot) + { + eventArgsCollection = new List(Events.ReceivedEvents); + } + + foreach (PSEventArgs eventArg in eventArgsCollection) + { + // If they specified a event identifier and we don't match, continue + if ((_sourceIdentifier != null) && + (!_matchPattern.IsMatch(eventArg.SourceIdentifier))) + { + continue; + } + + // If they specified an event identifier and we don't match, continue + if ((_eventId >= 0) && + (eventArg.EventIdentifier != _eventId)) + { + continue; + } + + WriteObject(eventArg); + foundMatch = true; + } + + // Generate an error if we couldn't find the subscription identifier, + // and no globbing was done. + if (!foundMatch) + { + bool lookingForSource = (_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)); + bool lookingForId = (_eventId >= 0); + + if (lookingForSource || lookingForId) + { + object identifier = null; + string error = null; + + if (lookingForSource) + { + identifier = _sourceIdentifier; + error = EventingStrings.SourceIdentifierNotFound; + } + else if (lookingForId) + { + identifier = _eventId; + error = EventingStrings.EventIdentifierNotFound; + } + + ErrorRecord errorRecord = new( + new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)), + "INVALID_SOURCE_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + + WriteError(errorRecord); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..f95c708fa502687ab183876250de10c8b789d2fa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Lists all event subscribers. + /// + [Cmdlet(VerbsCommon.Get, "EventSubscriber", DefaultParameterSetName = "BySource", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096607")] + [OutputType(typeof(PSEventSubscriber))] + public class GetEventSubscriberCommand : PSCmdlet + { + #region parameters + + /// + /// An identifier for this event subscription. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "BySource")] + [ValidateNotNullOrEmpty] + public string SourceIdentifier + { + get + { + return _sourceIdentifier; + } + + set + { + _sourceIdentifier = value; + + if (value != null) + { + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + } + } + } + + private string _sourceIdentifier = null; + + /// + /// An identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "ById")] + [Alias("Id")] + public int SubscriptionId { get; set; } = -1; + + /// + /// Also show supporting events. + /// + [Parameter(Position = 1)] + public SwitchParameter Force { get; set; } + + #endregion parameters + + private WildcardPattern _matchPattern; + + /// + /// Get the subscribers. + /// + protected override void ProcessRecord() + { + bool foundMatch = false; + + // Go through all the received events and write them to the output + // pipeline + List subscribers = new(Events.Subscribers); + foreach (PSEventSubscriber subscriber in subscribers) + { + // If they specified a event identifier and we don't match, continue + if ((_sourceIdentifier != null) && + (!_matchPattern.IsMatch(subscriber.SourceIdentifier))) + { + continue; + } + + // If they specified a subscription identifier and we don't match, continue + if ((SubscriptionId >= 0) && + (subscriber.SubscriptionId != SubscriptionId)) + { + continue; + } + + // Don't display support events by default + if (subscriber.SupportEvent && (!Force)) + { + continue; + } + + WriteObject(subscriber); + foundMatch = true; + } + + // Generate an error if we couldn't find the subscription identifier, + // and no globbing was done. + if (!foundMatch) + { + bool lookingForSource = (_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)); + bool lookingForId = (SubscriptionId >= 0); + + if (lookingForSource || lookingForId) + { + object identifier = null; + string error = null; + + if (lookingForSource) + { + identifier = _sourceIdentifier; + error = EventingStrings.EventSubscriptionSourceNotFound; + } + else if (lookingForId) + { + identifier = SubscriptionId; + error = EventingStrings.EventSubscriptionNotFound; + } + + ErrorRecord errorRecord = new( + new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)), + "INVALID_SOURCE_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + + WriteError(errorRecord); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs new file mode 100644 index 0000000000000000000000000000000000000000..6f4b2f53cef66974c9c88a522c690671bc4a025f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Management.Automation; +using System.Security.Cryptography; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Get-FileHash. + /// + [Cmdlet(VerbsCommon.Get, "FileHash", DefaultParameterSetName = PathParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=517145")] + [OutputType(typeof(FileHashInfo))] + public class GetFileHashCommand : HashCmdletBase + { + /// + /// Path parameter. + /// The paths of the files to calculate hash values. + /// Resolved wildcards. + /// + /// + [Parameter(Mandatory = true, ParameterSetName = PathParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Path + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + /// + /// LiteralPath parameter. + /// The literal paths of the files to calculate a hashs. + /// Don't resolved wildcards. + /// + /// + [Parameter(Mandatory = true, ParameterSetName = LiteralPathParameterSet, Position = 0, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + private string[] _paths; + + /// + /// InputStream parameter. + /// The stream of the file to calculate a hash. + /// + /// + [Parameter(Mandatory = true, ParameterSetName = StreamParameterSet, Position = 0)] + public Stream InputStream { get; set; } + + /// + /// ProcessRecord() override. + /// This is for paths collecting from pipe. + /// + protected override void ProcessRecord() + { + List pathsToProcess = new(); + ProviderInfo provider = null; + + switch (ParameterSetName) + { + case PathParameterSet: + // Resolve paths and check existence + foreach (string path in _paths) + { + try + { + Collection newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); + if (newPaths != null) + { + pathsToProcess.AddRange(newPaths); + } + } + catch (ItemNotFoundException e) + { + if (!WildcardPattern.ContainsWildcardCharacters(path)) + { + ErrorRecord errorRecord = new(e, + "FileNotFound", + ErrorCategory.ObjectNotFound, + path); + WriteError(errorRecord); + } + } + } + + break; + case LiteralPathParameterSet: + foreach (string path in _paths) + { + string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); + pathsToProcess.Add(newPath); + } + + break; + } + + foreach (string path in pathsToProcess) + { + if (ComputeFileHash(path, out string hash)) + { + WriteHashResult(Algorithm, hash, path); + } + } + } + + private byte[] ComputeHash(Stream stream) + { + switch (Algorithm) + { + case HashAlgorithmNames.SHA1: + return SHA1.HashData(stream); + case HashAlgorithmNames.SHA256: + return SHA256.HashData(stream); + case HashAlgorithmNames.SHA384: + return SHA384.HashData(stream); + case HashAlgorithmNames.SHA512: + return SHA512.HashData(stream); + case HashAlgorithmNames.MD5: + return MD5.HashData(stream); + } + + Debug.Assert(false, "invalid hash algorithm"); + return SHA256.HashData(stream); + } + + /// + /// Perform common error checks. + /// Populate source code. + /// + protected override void EndProcessing() + { + if (ParameterSetName == StreamParameterSet) + { + byte[] bytehash = ComputeHash(InputStream); + + string hash = Convert.ToHexString(bytehash); + WriteHashResult(Algorithm, hash, string.Empty); + } + } + + /// + /// Read the file and calculate the hash. + /// + /// Path to file which will be hashed. + /// Will contain the hash of the file content. + /// Boolean value indicating whether the hash calculation succeeded or failed. + private bool ComputeFileHash(string path, out string hash) + { + Stream openfilestream = null; + + hash = null; + + try + { + openfilestream = File.OpenRead(path); + byte[] bytehash = ComputeHash(openfilestream); + + hash = Convert.ToHexString(bytehash); + } + catch (FileNotFoundException ex) + { + var errorRecord = new ErrorRecord( + ex, + "FileNotFound", + ErrorCategory.ObjectNotFound, + path); + WriteError(errorRecord); + } + catch (UnauthorizedAccessException ex) + { + var errorRecord = new ErrorRecord( + ex, + "UnauthorizedAccessError", + ErrorCategory.InvalidData, + path); + WriteError(errorRecord); + } + catch (IOException ioException) + { + var errorRecord = new ErrorRecord( + ioException, + "FileReadError", + ErrorCategory.ReadError, + path); + WriteError(errorRecord); + } + finally + { + openfilestream?.Dispose(); + } + + return hash != null; + } + + /// + /// Create FileHashInfo object and output it. + /// + private void WriteHashResult(string Algorithm, string hash, string path) + { + FileHashInfo result = new(); + result.Algorithm = Algorithm; + result.Hash = hash; + result.Path = path; + WriteObject(result); + } + + /// + /// Parameter set names. + /// + private const string PathParameterSet = "Path"; + private const string LiteralPathParameterSet = "LiteralPath"; + private const string StreamParameterSet = "StreamParameterSet"; + } + + /// + /// Base Cmdlet for cmdlets which deal with crypto hashes. + /// + public class HashCmdletBase : PSCmdlet + { + /// + /// Algorithm parameter. + /// The hash algorithm name: "SHA1", "SHA256", "SHA384", "SHA512", "MD5". + /// + /// + [Parameter(Position = 1)] + [ValidateSet(HashAlgorithmNames.SHA1, + HashAlgorithmNames.SHA256, + HashAlgorithmNames.SHA384, + HashAlgorithmNames.SHA512, + HashAlgorithmNames.MD5)] + public string Algorithm + { + get + { + return _Algorithm; + } + + set + { + // A hash algorithm name is case sensitive + // and always must be in upper case + _Algorithm = value.ToUpper(); + } + } + + private string _Algorithm = HashAlgorithmNames.SHA256; + + /// + /// Hash algorithm names. + /// + internal static class HashAlgorithmNames + { + public const string MD5 = "MD5"; + public const string SHA1 = "SHA1"; + public const string SHA256 = "SHA256"; + public const string SHA384 = "SHA384"; + public const string SHA512 = "SHA512"; + } + } + + /// + /// FileHashInfo class contains information about a file hash. + /// + public class FileHashInfo + { + /// + /// Hash algorithm name. + /// + public string Algorithm { get; set; } + + /// + /// Hash value. + /// + public string Hash { get; set; } + + /// + /// File path. + /// + public string Path { get; set; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..fec8bafe34a427a46fe5f3dd7b0218c709cc38f7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Writes the PSHost object to the success stream. + /// + [Cmdlet(VerbsCommon.Get, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097110", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(System.Management.Automation.Host.PSHost))] + public + class GetHostCommand : PSCmdlet + { + /// + /// See base class. + /// + protected override void BeginProcessing() + { + WriteObject(this.Host); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs new file mode 100644 index 0000000000000000000000000000000000000000..0b11af842006962a736de4ceb3228059049bb12e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -0,0 +1,282 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class with member information that this cmdlet writes to the pipeline. + /// + public class MemberDefinition + { + /// + /// Returns the member definition. + /// + public override string ToString() + { + return Definition; + } + /// + /// Initializes a new instance of the class. + /// + public MemberDefinition(string typeName, string name, PSMemberTypes memberType, string definition) + { + Name = name; + Definition = definition; + MemberType = memberType; + TypeName = typeName; + } + + /// + /// Type name. + /// + public string TypeName { get; } + + /// + /// Member name. + /// + public string Name { get; } + + /// + /// Member type. + /// + public PSMemberTypes MemberType { get; } + + /// + /// Member definition. + /// + public string Definition { get; } + } + + /// + /// This class implements get-member command. + /// + [Cmdlet(VerbsCommon.Get, "Member", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096704", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(MemberDefinition))] + public class GetMemberCommand : PSCmdlet + { + /// + /// The object to retrieve properties from. + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } + + /// + /// The member names to be retrieved. + /// + [Parameter(Position = 0)] + [ValidateNotNullOrEmpty] + public string[] Name { get; set; } = new string[] { "*" }; + + /// + /// The member types to be retrieved. + /// + [Parameter] + [Alias("Type")] + public PSMemberTypes MemberType { get; set; } = PSMemberTypes.All; + + /// + /// View from which the members are retrieved. + /// + [Parameter] + public PSMemberViewTypes View { get; set; } = PSMemberViewTypes.Adapted | PSMemberViewTypes.Extended; + + private bool _staticParameter = false; + /// + /// True if we should return static members. + /// + [Parameter] + public SwitchParameter Static + { + get { return _staticParameter; } + + set { _staticParameter = value; } + } + + /// + /// Gets or sets the force property. + /// + /// + /// Gives the Member matcher guidance on how vigorous the Match should be. + /// If set to true all members in a given view + membertype are displayed. + /// This parameter is added to hide Get/Set property accessor methods by default. + /// If a user wants to see these methods, -force should be set to true. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return (_matchOptions == MshMemberMatchOptions.IncludeHidden); + } + + set + { + if (value) + { + // Include hidden members if force parameter is set + _matchOptions = MshMemberMatchOptions.IncludeHidden; + } + else + { + _matchOptions = MshMemberMatchOptions.None; + } + } + } + + private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None; + + private readonly HybridDictionary _typesAlreadyDisplayed = new(); + + /// + /// This method implements the ProcessRecord method for get-member command. + /// + protected override void ProcessRecord() + { + if (this.InputObject == null || this.InputObject == AutomationNull.Value) + { + return; + } + + Type baseObjectAsType = null; + + string typeName; + Adapter staticAdapter = null; + if (this.Static == true) + { + staticAdapter = PSObject.DotNetStaticAdapter; + object baseObject = this.InputObject.BaseObject; + baseObjectAsType = baseObject as System.Type ?? baseObject.GetType(); + typeName = baseObjectAsType.FullName; + } + else + { + var typeNames = this.InputObject.InternalTypeNames; + if (typeNames.Count != 0) + { + typeName = typeNames[0]; + } + else + { + // This is never used for display. It is used only as a key to typesAlreadyDisplayed + typeName = ""; + } + } + + if (_typesAlreadyDisplayed.Contains(typeName)) + { + return; + } + else + { + _typesAlreadyDisplayed.Add(typeName, string.Empty); + } + + PSMemberTypes memberTypeToSearch = MemberType; + PSMemberViewTypes viewToSearch = View; + + if (((View & PSMemberViewTypes.Extended) == 0) && + (!typeof(PSMemberSet).ToString().Equals(typeName, StringComparison.OrdinalIgnoreCase))) + { + // PSMemberSet is an internal memberset and its properties/methods are populated differently. + // PSMemberSet instance is created to represent PSExtended, PSAdapted, PSBase, PSObject hidden + // properties. We should honor extended properties for such case. + + // request is to search dotnet or adapted or both members. + // dotnet,adapted members cannot be Script*,Note*,Code* + memberTypeToSearch ^= (PSMemberTypes.AliasProperty | PSMemberTypes.CodeMethod | PSMemberTypes.CodeProperty + | PSMemberTypes.MemberSet | PSMemberTypes.NoteProperty | PSMemberTypes.PropertySet | PSMemberTypes.ScriptMethod + | PSMemberTypes.ScriptProperty); + } + + if (((View & PSMemberViewTypes.Adapted) == 0) && (View & PSMemberViewTypes.Base) == 0) + { + // base and adapted are not mentioned in the view so ignore respective properties + memberTypeToSearch ^= (PSMemberTypes.Property | PSMemberTypes.ParameterizedProperty | PSMemberTypes.Method); + } + + if (((View & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) && + (InputObject.InternalBaseDotNetAdapter == null)) + { + // the input object don't have a custom adapter.. + // for this case adapted view and base view are the same. + viewToSearch |= PSMemberViewTypes.Adapted; + } + + PSMemberInfoCollection membersToSearch; + if (this.Static == true) + { + membersToSearch = staticAdapter.BaseGetMembers(baseObjectAsType); + } + else + { + Collection> memberCollection = PSObject.GetMemberCollection(viewToSearch); + membersToSearch = new PSMemberInfoIntegratingCollection(this.InputObject, memberCollection); + } + + foreach (string nameElement in this.Name) + { + ReadOnlyPSMemberInfoCollection readOnlyMembers; + readOnlyMembers = membersToSearch.Match(nameElement, memberTypeToSearch, _matchOptions); + + MemberDefinition[] members = new MemberDefinition[readOnlyMembers.Count]; + int resultCount = 0; + foreach (PSMemberInfo member in readOnlyMembers) + { + if (!Force) + { + if ((member is PSMethod memberAsPSMethod) && (memberAsPSMethod.IsSpecial)) + { + continue; + } + } + + members[resultCount] = new MemberDefinition(typeName, member.Name, member.MemberType, member.ToString()); + resultCount++; + } + + Array.Sort(members, 0, resultCount, new MemberComparer()); + for (int index = 0; index < resultCount; index++) + { + this.WriteObject(members[index]); + } + } + } + + private sealed class MemberComparer : System.Collections.Generic.IComparer + { + public int Compare(MemberDefinition first, MemberDefinition second) + { + int result = string.Compare(first.MemberType.ToString(), second.MemberType.ToString(), + StringComparison.OrdinalIgnoreCase); + if (result != 0) + { + return result; + } + + return string.Compare(first.Name, second.Name, StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// This method implements the End method for get-member command. + /// + protected override void EndProcessing() + { + if (_typesAlreadyDisplayed.Count == 0) + { + ErrorRecord errorRecord = new( + new InvalidOperationException(GetMember.NoObjectSpecified), + "NoObjectInGetMember", + ErrorCategory.CloseError, + null); + WriteError(errorRecord); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..c77c25c5f4fef101b0b9c7ed91e6613f4380b000 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements `Get-Random` cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommandBase.RandomNumberParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097016", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(int), typeof(long), typeof(double))] + public sealed class GetRandomCommand : GetRandomCommandBase + { + /// + /// Seed used to reinitialize random numbers generator. + /// + [Parameter] + [ValidateNotNull] + public int? SetSeed { get; set; } + + /// + /// This method implements the BeginProcessing method for get-random command. + /// + protected override void BeginProcessing() + { + if (SetSeed.HasValue) + { + Generator = new PolymorphicRandomNumberGenerator(SetSeed.Value); + } + + base.BeginProcessing(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..8e50b1cf5a9981cf1259a89f95b2242b31c61833 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs @@ -0,0 +1,719 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Numerics; +using System.Reflection; +using System.Security.Cryptography; +using System.Threading; + +using Debug = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements base class for `Get-Random` and `Get-SecureRandom` cmdlets. + /// + public class GetRandomCommandBase : PSCmdlet + { + #region Parameter set handling + + internal const string RandomNumberParameterSet = "RandomNumberParameterSet"; + private const string RandomListItemParameterSet = "RandomListItemParameterSet"; + private const string ShuffleParameterSet = "ShuffleParameterSet"; + + private static readonly object[] _nullInArray = new object[] { null }; + + private enum MyParameterSet + { + Unknown, + RandomNumber, + RandomListItem + } + + private MyParameterSet _effectiveParameterSet; + + private MyParameterSet EffectiveParameterSet + { + get + { + // cache MyParameterSet enum instead of doing string comparison every time + if (_effectiveParameterSet == MyParameterSet.Unknown) + { + if (MyInvocation.ExpectingInput && (Maximum == null) && (Minimum == null)) + { + _effectiveParameterSet = MyParameterSet.RandomListItem; + } + else if (ParameterSetName == GetRandomCommandBase.RandomListItemParameterSet + || ParameterSetName == GetRandomCommandBase.ShuffleParameterSet) + { + _effectiveParameterSet = MyParameterSet.RandomListItem; + } + else if (ParameterSetName.Equals(GetRandomCommandBase.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase)) + { + if ((Maximum != null) && Maximum.GetType().IsArray) + { + InputObject = (object[])Maximum; + _effectiveParameterSet = MyParameterSet.RandomListItem; + } + else + { + _effectiveParameterSet = MyParameterSet.RandomNumber; + } + } + else + { + Debug.Assert(false, "Unrecognized parameter set"); + } + } + + return _effectiveParameterSet; + } + } + + #endregion Parameter set handling + + #region Error handling + + private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) + { + if (minValue == null) + { + throw PSTraceSource.NewArgumentNullException("min"); + } + + if (maxValue == null) + { + throw PSTraceSource.NewArgumentNullException("max"); + } + + ErrorRecord errorRecord = new( + new ArgumentException(string.Format( + CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)), + "MinGreaterThanOrEqualMax", + ErrorCategory.InvalidArgument, + null); + + ThrowTerminatingError(errorRecord); + } + + #endregion + + #region Random generator state + + private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new(); + + // 1-to-1 mapping of cmdlet + runspacesId and random number generators + private static readonly Dictionary s_runspaceGeneratorMap = new(); + + private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) + { + switch (e.RunspaceStateInfo.State) + { + case RunspaceState.Broken: + case RunspaceState.Closed: + try + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterWriteLock(); + GetRandomCommandBase.s_runspaceGeneratorMap.Remove(MethodBase.GetCurrentMethod().DeclaringType.Name + ((Runspace)sender).InstanceId.ToString()); + } + finally + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitWriteLock(); + } + + break; + } + } + + private PolymorphicRandomNumberGenerator _generator; + + /// + /// Gets and sets generator associated with the current cmdlet and runspace. + /// + internal PolymorphicRandomNumberGenerator Generator + { + get + { + if (_generator == null) + { + string runspaceId = Context.CurrentRunspace.InstanceId.ToString(); + + bool needToInitialize = false; + try + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterReadLock(); + needToInitialize = !GetRandomCommandBase.s_runspaceGeneratorMap.TryGetValue(this.GetType().Name + runspaceId, out _generator); + } + finally + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitReadLock(); + } + + if (needToInitialize) + { + Generator = new PolymorphicRandomNumberGenerator(); + } + } + + return _generator; + } + + set + { + _generator = value; + Runspace myRunspace = Context.CurrentRunspace; + + try + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterWriteLock(); + if (!GetRandomCommandBase.s_runspaceGeneratorMap.ContainsKey(this.GetType().Name + myRunspace.InstanceId.ToString())) + { + // make sure we won't leave the generator around after runspace exits + myRunspace.StateChanged += CurrentRunspace_StateChanged; + } + + GetRandomCommandBase.s_runspaceGeneratorMap[this.GetType().Name + myRunspace.InstanceId.ToString()] = _generator; + } + finally + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitWriteLock(); + } + } + } + + #endregion + + #region Parameters for RandomNumberParameterSet + + /// + /// Gets or sets the maximum number to generate. + /// + [Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)] + public object Maximum { get; set; } + + /// + /// Gets or sets the minimum number to generate. + /// + [Parameter(ParameterSetName = RandomNumberParameterSet)] + public object Minimum { get; set; } + + private static bool IsInt(object o) + { + if (o == null || o is int) + { + return true; + } + + return false; + } + + private static bool IsInt64(object o) + { + if (o == null || o is long) + { + return true; + } + + return false; + } + + private static object ProcessOperand(object o) + { + if (o == null) + { + return null; + } + + PSObject pso = PSObject.AsPSObject(o); + object baseObject = pso.BaseObject; + + if (baseObject is string) + { + // The type argument passed in does not decide the number type we want to convert to. ScanNumber will return + // int/long/double based on the string form number passed in. + baseObject = System.Management.Automation.Language.Parser.ScanNumber((string)baseObject, typeof(int)); + } + + return baseObject; + } + + private static double ConvertToDouble(object o, double defaultIfNull) + { + if (o == null) + { + return defaultIfNull; + } + + double result = (double)LanguagePrimitives.ConvertTo(o, typeof(double), CultureInfo.InvariantCulture); + return result; + } + + #endregion + + #region Parameters and variables for RandomListItemParameterSet + + private List _chosenListItems; + private int _numberOfProcessedListItems; + + /// + /// Gets or sets the list from which random elements are chosen. + /// + [Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] + [Parameter(ParameterSetName = ShuffleParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] + [System.Management.Automation.AllowNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public object[] InputObject { get; set; } + + /// + /// Gets or sets the number of items to output (number of list items or of numbers). + /// + [Parameter(ParameterSetName = RandomNumberParameterSet)] + [Parameter(ParameterSetName = RandomListItemParameterSet)] + [ValidateRange(1, int.MaxValue)] + public int Count { get; set; } = 1; + + #endregion + + #region Shuffle parameter + + /// + /// Gets or sets whether the command should return all input objects in randomized order. + /// + [Parameter(ParameterSetName = ShuffleParameterSet, Mandatory = true)] + public SwitchParameter Shuffle { get; set; } + + #endregion + + #region Cmdlet processing methods + + private double GetRandomDouble(double minValue, double maxValue) + { + double randomNumber; + double diff = maxValue - minValue; + + // I couldn't find a better fix for bug #216893 then + // to test and retry if a random number falls outside the bounds + // because of floating-point-arithmetic inaccuracies. + // + // Performance in the normal case is not impacted much. + // In low-precision situations we should converge to a solution quickly + // (diff gets smaller at a quick pace). + if (double.IsInfinity(diff)) + { + do + { + double r = Generator.NextDouble(); + randomNumber = minValue + (r * maxValue) - (r * minValue); + } + while (randomNumber >= maxValue); + } + else + { + do + { + double r = Generator.NextDouble(); + randomNumber = minValue + (r * diff); + diff *= r; + } + while (randomNumber >= maxValue); + } + + return randomNumber; + } + + /// + /// Get a random Int64 type number. + /// + /// Minimum value. + /// Maximum value. + /// Rnadom long. + private long GetRandomInt64(long minValue, long maxValue) + { + // Randomly generate eight bytes and convert the byte array to UInt64 + var buffer = new byte[sizeof(ulong)]; + ulong randomUint64; + + BigInteger bigIntegerDiff = (BigInteger)maxValue - (BigInteger)minValue; + + // When the difference is less than int.MaxValue, use Random.Next(int, int) + if (bigIntegerDiff <= int.MaxValue) + { + int randomDiff = Generator.Next(0, (int)(maxValue - minValue)); + return minValue + randomDiff; + } + + // The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number. + ulong uint64Diff = (ulong)bigIntegerDiff; + + // Calculate the number of bits to represent the diff in type UInt64 + int bitsToRepresentDiff = 0; + ulong diffCopy = uint64Diff; + for (; diffCopy != 0; bitsToRepresentDiff++) + { + diffCopy >>= 1; + } + + // Get the mask for the number of bits + ulong mask = 0xffffffffffffffff >> (64 - bitsToRepresentDiff); + do + { + // Randomly fill the buffer + Generator.NextBytes(buffer); + randomUint64 = BitConverter.ToUInt64(buffer, 0); + + // Get the last 'bitsToRepresentDiff' number of random bits + randomUint64 &= mask; + } while (uint64Diff <= randomUint64); + + double randomNumber = (minValue * 1.0) + (randomUint64 * 1.0); + return (long)randomNumber; + } + + /// + /// This method implements the BeginProcessing method for derived cmdlets. + /// + protected override void BeginProcessing() + { + 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))) + { + long minValue = minOperand != null ? ((minOperand is long) ? (long)minOperand : (int)minOperand) : 0; + long maxValue = maxOperand != null ? ((maxOperand is long) ? (long)maxOperand : (int)maxOperand) : long.MaxValue; + + if (minValue >= maxValue) + { + ThrowMinGreaterThanOrEqualMax(minValue, maxValue); + } + + for (int i = 0; i < Count; i++) + { + long 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(); + _numberOfProcessedListItems = 0; + } + } + + // rough proof that when choosing random K items out of N items + // each item has got K/N probability of being included in the final list + // + // probability that a particular item in chosenListItems is NOT going to be replaced + // when processing I-th input item [assumes I > K]: + // P_one_step(I) = 1 - ((K / I) * ((K - 1) / K) + ((I - K) / I) = (I - 1) / I + // <--A--> <-----B-----> <-----C-----> + // A - probability that I-th element is going to be replacing an element from chosenListItems + // (see (1) in the code below) + // B - probability that a particular element from chosenListItems is NOT going to be replaced + // (see (2) in the code below) + // C - probability that I-th element is NOT going to be replacing an element from chosenListItems + // (see (1) in the code below) + // + // probability that a particular item in chosenListItems is NOT going to be replaced + // when processing input items J through N [assumes J > K] + // P_removal(J) = Multiply(for I = J to N) P(I) = + // = ((J - 1) / J) * (J / (J + 1)) * ... * ((N - 2) / (N - 1)) * ((N - 1) / N) = + // = (J - 1) / N + // + // probability that when processing an element it is going to be put into chosenListItems + // P_insertion(I) = 1.0 when I <= K - see (3) in the code below + // P_insertion(I) = K/N otherwise - see (1) in the code below + // + // probability that a given element is going to be a part of the final list + // P_final(I) = P_insertion(I) * P_removal(max(I + 1, K + 1)) + // [for I <= K] = 1.0 * ((K + 1) - 1) / N = K / N + // [otherwise] = (K / I) * ((I + 1) - 1) / N = K / N + // + // which proves that P_final(I) = K / N for all values of I. QED. + + /// + /// This method implements the ProcessRecord method for derived cmdlets. + /// + protected override void ProcessRecord() + { + if (EffectiveParameterSet == MyParameterSet.RandomListItem) + { + if (Shuffle) + { + // this allows for $null to be in an array passed to InputObject + foreach (object item in InputObject ?? _nullInArray) + { + _chosenListItems.Add(item); + } + } + else + { + foreach (object item in InputObject ?? _nullInArray) + { + // (3) + if (_numberOfProcessedListItems < Count) + { + Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems"); + _chosenListItems.Add(item); + } + else + { + Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K"); + + // (1) + if (Generator.Next(_numberOfProcessedListItems + 1) < Count) + { + // (2) + int indexToReplace = Generator.Next(_chosenListItems.Count); + _chosenListItems[indexToReplace] = item; + } + } + + _numberOfProcessedListItems++; + } + } + } + } + + /// + /// This method implements the EndProcessing method for derived cmdlets. + /// + protected override void EndProcessing() + { + if (EffectiveParameterSet == MyParameterSet.RandomListItem) + { + // make sure the order is truly random + // (all permutations with the same probability) + // O(n) time + int n = _chosenListItems.Count; + for (int i = 0; i < n; i++) + { + // randomly choose j from [i...n) + int j = Generator.Next(i, n); + + WriteObject(_chosenListItems[j]); + + // remove the output object from consideration in the next iteration. + if (i != j) + { + _chosenListItems[j] = _chosenListItems[i]; + } + } + } + } + + #endregion Processing methods + } + + /// + /// Provides an adapter API for random numbers that may be either cryptographically random, or + /// generated with the regular pseudo-random number generator. Re-implementations of + /// methods using the NextBytes() primitive based on the CLR implementation: + /// https://referencesource.microsoft.com/#mscorlib/system/random.cs. + /// + internal sealed class PolymorphicRandomNumberGenerator + { + /// + /// Initializes a new instance of the class. + /// + public PolymorphicRandomNumberGenerator() + { + _cryptographicGenerator = RandomNumberGenerator.Create(); + _pseudoGenerator = null; + } + + /// + /// Initializes a new instance of the using pseudorandom generator instead of the cryptographic one. + /// + /// The seed value. + internal PolymorphicRandomNumberGenerator(int seed) + { + _cryptographicGenerator = null; + _pseudoGenerator = new Random(seed); + } + + private readonly Random _pseudoGenerator = null; + private readonly RandomNumberGenerator _cryptographicGenerator = null; + + /// + /// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0. + /// + /// A random floating-point number that is greater than or equal to 0.0, and less than 1.0. + internal double NextDouble() + { + // According to the CLR source: + // "Including this division at the end gives us significantly improved random number distribution." + return Next() * (1.0 / int.MaxValue); + } + + /// + /// Generates a non-negative random integer. + /// + /// A non-negative random integer. + internal int Next() + { + int randomNumber; + + // The CLR implementation just fudges + // Int32.MaxValue down to (Int32.MaxValue - 1). This implementation + // errs on the side of correctness. + do + { + randomNumber = InternalSample(); + } + while (randomNumber == int.MaxValue); + + if (randomNumber < 0) + { + randomNumber += int.MaxValue; + } + + return randomNumber; + } + + /// + /// Returns a random integer that is within a specified range. + /// + /// The exclusive upper bound of the random number returned. + /// Next random integer. + internal int Next(int maxValue) + { + if (maxValue < 0) + { + throw new ArgumentOutOfRangeException(nameof(maxValue), GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi); + } + + return Next(0, maxValue); + } + + /// + /// Returns a random integer that is within a specified range. + /// + /// The inclusive lower bound of the random number returned. + /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. + /// Next random integer. + public int Next(int minValue, int maxValue) + { + if (minValue > maxValue) + { + throw new ArgumentOutOfRangeException(nameof(minValue), GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); + } + + int randomNumber = 0; + + long range = (long)maxValue - (long)minValue; + if (range <= int.MaxValue) + { + randomNumber = (int)(NextDouble() * range) + minValue; + } + else + { + double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)int.MaxValue))); + randomNumber = (int)((long)(largeSample * range) + minValue); + } + + return randomNumber; + } + + /// + /// Fills the elements of a specified array of bytes with random numbers. + /// + /// The array to be filled. + internal void NextBytes(byte[] buffer) + { + if (_cryptographicGenerator != null) + { + _cryptographicGenerator.GetBytes(buffer); + } + else + { + _pseudoGenerator.NextBytes(buffer); + } + } + + /// + /// Samples a random integer. + /// + /// A random integer, using the full range of Int32. + private int InternalSample() + { + int randomNumber; + byte[] data = new byte[sizeof(int)]; + + NextBytes(data); + randomNumber = BitConverter.ToInt32(data, 0); + + return randomNumber; + } + + /// + /// Samples a random int when the range is large. This does + /// not need to be in the range of -Double.MaxValue .. Double.MaxValue, + /// just 0.. (2 * Int32.MaxValue) - 1 . + /// + /// A random double. + private double InternalSampleLargeRange() + { + double randomNumber; + + do + { + randomNumber = InternalSample(); + } + while (randomNumber == int.MaxValue); + + randomNumber += int.MaxValue; + return randomNumber; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..10c050a456266c18e57c4a2960b1b25f24918b28 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This cmdlet returns runspaces in the PowerShell session. + /// + [Cmdlet(VerbsCommon.Get, "Runspace", DefaultParameterSetName = GetRunspaceCommand.NameParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096616")] + [OutputType(typeof(Runspace))] + public sealed class GetRunspaceCommand : PSCmdlet + { + #region Strings + + private const string NameParameterSet = "NameParameterSet"; + private const string IdParameterSet = "IdParameterSet"; + private const string InstanceIdParameterSet = "InstanceIdParameterSet"; + + #endregion + + #region Parameters + + /// + /// Specifies name or names of Runspaces to return. + /// + [Parameter(Position = 0, + ParameterSetName = GetRunspaceCommand.NameParameterSet)] + [ValidateNotNullOrEmpty()] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get; + set; + } + + /// + /// Specifies one or more Ids of Runspaces to return. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = GetRunspaceCommand.IdParameterSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] Id + { + get; + set; + } + + /// + /// Specifies one or more InstanceId Guids of Runspaces to return. + /// + [Parameter(Position = 0, + Mandatory = true, + ParameterSetName = GetRunspaceCommand.InstanceIdParameterSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Guid[] InstanceId + { + get; + set; + } + + #endregion + + #region Overrides + + /// + /// Process record. + /// + protected override void ProcessRecord() + { + IReadOnlyList 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().AsReadOnly(); + break; + } + } + + foreach (Runspace runspace in results) + { + WriteObject(runspace); + } + } + + #endregion + } + + #region GetRunspaceUtils + + internal static class GetRunspaceUtils + { + internal static IReadOnlyList GetAllRunspaces() + { + return Runspace.RunspaceList; + } + + internal static IReadOnlyList GetRunspacesByName(string[] names) + { + List rtnRunspaces = new(); + IReadOnlyList runspaces = Runspace.RunspaceList; + + foreach (string name in names) + { + WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase); + foreach (Runspace runspace in runspaces) + { + if (namePattern.IsMatch(runspace.Name)) + { + rtnRunspaces.Add(runspace); + } + } + } + + return rtnRunspaces.AsReadOnly(); + } + + internal static IReadOnlyList GetRunspacesById(int[] ids) + { + List rtnRunspaces = new(); + + foreach (int id in ids) + { + WeakReference runspaceRef; + + if (Runspace.RunspaceDictionary.TryGetValue(id, out runspaceRef)) + { + Runspace runspace; + if (runspaceRef.TryGetTarget(out runspace)) + { + rtnRunspaces.Add(runspace); + } + } + } + + return rtnRunspaces.AsReadOnly(); + } + + internal static IReadOnlyList GetRunspacesByInstanceId(Guid[] instanceIds) + { + List rtnRunspaces = new(); + IReadOnlyList runspaces = Runspace.RunspaceList; + + foreach (Guid instanceId in instanceIds) + { + foreach (Runspace runspace in runspaces) + { + if (runspace.InstanceId == instanceId) + { + // Because of disconnected remote runspace sessions, it is possible to have + // more than one runspace with the same instance Id (remote session ids are + // the same as the runspace object instance Id). + rtnRunspaces.Add(runspace); + } + } + } + + return rtnRunspaces.AsReadOnly(); + } + } + + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..e0ea7e68dbfe6ab7728abb022d8ab461c3cee942 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements `Get-SecureRandom` cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "SecureRandom", DefaultParameterSetName = GetRandomCommandBase.RandomNumberParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2235055", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(int), typeof(long), typeof(double))] + public sealed class GetSecureRandomCommand : GetRandomCommandBase + { + // nothing unique from base class + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..53e8c5d3adfe62936daee33acde7ff15622ef2c8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Returns the thread's current UI culture. + /// + [Cmdlet(VerbsCommon.Get, "UICulture", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096613")] + [OutputType(typeof(System.Globalization.CultureInfo))] + public sealed class GetUICultureCommand : PSCmdlet + { + /// + /// Output the current UI Culture info object. + /// + protected override void BeginProcessing() + { + WriteObject(Host.CurrentUICulture); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs new file mode 100644 index 0000000000000000000000000000000000000000..09bc78d96933a91a82290aa91e22e5605622790a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// + [Cmdlet(VerbsCommon.Get, "Unique", DefaultParameterSetName = "AsString", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097028", RemotingCapability = RemotingCapability.None)] + public sealed class GetUniqueCommand : PSCmdlet + { + #region Parameters + /// + /// + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// This parameter specifies that objects should be converted to + /// strings and the strings should be compared. + /// + /// + [Parameter(ParameterSetName = "AsString")] + public SwitchParameter AsString + { + get { return _asString; } + + set { _asString = value; } + } + + private bool _asString; + + /// + /// This parameter specifies that just the types of the objects + /// should be compared. + /// + /// + [Parameter(ParameterSetName = "UniqueByType")] + public SwitchParameter OnType + { + get { return _onType; } + + set { _onType = value; } + } + + private bool _onType = false; + + /// + /// Gets or sets case insensitive switch for string comparison. + /// + [Parameter] + public SwitchParameter CaseInsensitive { get; set; } + + #endregion Parameters + + #region Overrides + /// + /// + protected override void ProcessRecord() + { + bool isUnique = true; + if (_lastObject == null) + { + // always write first object, but return nothing + // on "MSH> get-unique" + if (AutomationNull.Value == InputObject) + return; + } + else if (OnType) + { + isUnique = (InputObject.InternalTypeNames[0] != _lastObject.InternalTypeNames[0]); + } + else if (AsString) + { + string inputString = InputObject.ToString(); + _lastObjectAsString ??= _lastObject.ToString(); + + if (string.Equals( + inputString, + _lastObjectAsString, + CaseInsensitive.IsPresent ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture)) + { + isUnique = false; + } + else + { + _lastObjectAsString = inputString; + } + } + else // compare as objects + { + _comparer ??= new ObjectCommandComparer( + ascending: true, + CultureInfo.CurrentCulture, + caseSensitive: !CaseInsensitive.IsPresent); + + isUnique = (_comparer.Compare(InputObject, _lastObject) != 0); + } + + if (isUnique) + { + WriteObject(InputObject); + _lastObject = InputObject; + } + } + #endregion Overrides + + #region Internal + private PSObject _lastObject = null; + private string _lastObjectAsString = null; + private ObjectCommandComparer _comparer = null; + #endregion Internal + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs new file mode 100644 index 0000000000000000000000000000000000000000..c21165301e24ca12812c272f1209867b6f1b97d6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Get-Uptime. + /// + [Cmdlet(VerbsCommon.Get, "Uptime", DefaultParameterSetName = TimespanParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?linkid=834862")] + [OutputType(typeof(TimeSpan), ParameterSetName = new string[] { TimespanParameterSet })] + [OutputType(typeof(DateTime), ParameterSetName = new string[] { SinceParameterSet })] + public class GetUptimeCommand : PSCmdlet + { + /// + /// The system startup time. + /// + /// + [Parameter(ParameterSetName = SinceParameterSet)] + public SwitchParameter Since { get; set; } = new SwitchParameter(); + + /// + /// This is the main entry point for the cmdlet. + /// + protected override void ProcessRecord() + { + // Get-Uptime throw if IsHighResolution = false + // because stopwatch.GetTimestamp() return DateTime.UtcNow.Ticks + // instead of ticks from system startup. + // InternalTestHooks.StopwatchIsNotHighResolution is used as test hook. + if (Stopwatch.IsHighResolution && !InternalTestHooks.StopwatchIsNotHighResolution) + { + TimeSpan uptime = TimeSpan.FromSeconds(Stopwatch.GetTimestamp() / Stopwatch.Frequency); + + if (Since) + { + // Output the time of the last system boot. + WriteObject(DateTime.Now.Subtract(uptime)); + } + else + { + // Output the time elapsed since the last system boot. + WriteObject(uptime); + } + } + else + { + WriteDebug("System.Diagnostics.Stopwatch.IsHighResolution returns 'False'."); + Exception exc = new NotSupportedException(GetUptimeStrings.GetUptimePlatformIsNotSupported); + ThrowTerminatingError(new ErrorRecord(exc, "GetUptimePlatformIsNotSupported", ErrorCategory.NotImplemented, null)); + } + } + + /// + /// Parameter set name for Timespan OutputType. + /// + private const string TimespanParameterSet = "Timespan"; + + /// + /// Parameter set name for DateTime OutputType. + /// + private const string SinceParameterSet = "Since"; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..61a0fe1a3909d1a7576a218c4ef6229c97c124dd --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using static System.Management.Automation.Verbs; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation of the Get Verb Command. + /// + [Cmdlet(VerbsCommon.Get, "Verb", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097026")] + [OutputType(typeof(VerbInfo))] + public class GetVerbCommand : Cmdlet + { + /// + /// Optional Verb filter. + /// + [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0)] + [ArgumentCompleter(typeof(VerbArgumentCompleter))] + public string[] Verb + { + get; set; + } + + /// + /// Optional Group filter. + /// + [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 1)] + [ValidateSet("Common", "Communications", "Data", "Diagnostic", "Lifecycle", "Other", "Security")] + public string[] Group + { + get; set; + } + + /// + /// Returns a list of verbs. + /// + protected override void ProcessRecord() + { + foreach (VerbInfo verb in FilterByVerbsAndGroups(Verb, Group)) + { + WriteObject(verb); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..1f527258939502d1c5bb140d5fb5e8882e1938c3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// PSTuple is a helper class used to create Tuple from an input array. + /// + internal static class PSTuple + { + /// + /// ArrayToTuple is a helper method used to create a tuple for the supplied input array. + /// + /// The first generic type parameter. + /// Input objects used to create a tuple. + /// Tuple object. + internal static object ArrayToTuple(IList inputObjects) + { + return ArrayToTuple(inputObjects, 0); + } + + /// + /// ArrayToTuple is a helper method used to create a tuple for the supplied input array. + /// + /// The first generic type parameter. + /// Input objects used to create a tuple. + /// Start index of the array from which the objects have to considered for the tuple creation. + /// Tuple object. + private static object ArrayToTuple(IList inputObjects, int startIndex) + { + Diagnostics.Assert(inputObjects != null, "inputObjects is null"); + Diagnostics.Assert(inputObjects.Count > 0, "inputObjects is empty"); + + switch (inputObjects.Count - startIndex) + { + case 0: + return null; + case 1: + return Tuple.Create(inputObjects[startIndex]); + case 2: + return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1]); + case 3: + return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2]); + case 4: + return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3]); + case 5: + return Tuple.Create( + inputObjects[startIndex], + inputObjects[startIndex + 1], + inputObjects[startIndex + 2], + inputObjects[startIndex + 3], + inputObjects[startIndex + 4]); + case 6: + return Tuple.Create( + inputObjects[startIndex], + inputObjects[startIndex + 1], + inputObjects[startIndex + 2], + inputObjects[startIndex + 3], + inputObjects[startIndex + 4], + inputObjects[startIndex + 5]); + case 7: + return Tuple.Create( + inputObjects[startIndex], + inputObjects[startIndex + 1], + inputObjects[startIndex + 2], + inputObjects[startIndex + 3], + inputObjects[startIndex + 4], + inputObjects[startIndex + 5], + inputObjects[startIndex + 6]); + case 8: + return Tuple.Create( + inputObjects[startIndex], + inputObjects[startIndex + 1], + inputObjects[startIndex + 2], + inputObjects[startIndex + 3], + inputObjects[startIndex + 4], + inputObjects[startIndex + 5], + inputObjects[startIndex + 6], + inputObjects[startIndex + 7]); + default: + return Tuple.Create( + inputObjects[startIndex], + inputObjects[startIndex + 1], + inputObjects[startIndex + 2], + inputObjects[startIndex + 3], + inputObjects[startIndex + 4], + inputObjects[startIndex + 5], + inputObjects[startIndex + 6], + ArrayToTuple(inputObjects, startIndex + 7)); + } + } + } + + /// + /// Emitted by Group-Object when the NoElement option is true. + /// + public sealed class GroupInfoNoElement : GroupInfo + { + internal GroupInfoNoElement(OrderByPropertyEntry groupValue) : base(groupValue) + { + } + + internal override void Add(PSObject groupValue) + { + Count++; + } + } + + /// + /// Emitted by Group-Object. + /// + [DebuggerDisplay("{Name} ({Count})")] + public class GroupInfo + { + internal GroupInfo(OrderByPropertyEntry groupValue) + { + Group = new Collection(); + this.Add(groupValue.inputObject); + GroupValue = groupValue; + Name = BuildName(groupValue.orderValues); + } + + internal virtual void Add(PSObject groupValue) + { + Group.Add(groupValue); + Count++; + } + + private static string BuildName(List propValues) + { + StringBuilder sb = new(); + foreach (ObjectCommandPropertyValue propValue in propValues) + { + var propValuePropertyValue = propValue?.PropertyValue; + if (propValuePropertyValue != null) + { + if (propValuePropertyValue is ICollection propertyValueItems) + { + sb.Append('{'); + var length = sb.Length; + + foreach (object item in propertyValueItems) + { + sb.Append(CultureInfo.CurrentCulture, $"{item}, "); + } + + sb = sb.Length > length ? sb.Remove(sb.Length - 2, 2) : sb; + sb.Append("}, "); + } + else + { + sb.Append(CultureInfo.CurrentCulture, $"{propValuePropertyValue}, "); + } + } + } + + return sb.Length >= 2 ? sb.Remove(sb.Length - 2, 2).ToString() : string.Empty; + } + + /// + /// Gets the values of the group. + /// + public ArrayList Values + { + get + { + ArrayList values = new(); + foreach (ObjectCommandPropertyValue propValue in GroupValue.orderValues) + { + values.Add(propValue.PropertyValue); + } + + return values; + } + } + + /// + /// Gets the number of objects in the group. + /// + public int Count { get; internal set; } + + /// + /// Gets the list of objects in this group. + /// + public Collection Group { get; } + + /// + /// Gets the name of the group. + /// + public string Name { get; } + + /// + /// Gets the OrderByPropertyEntry used to build this group object. + /// + internal OrderByPropertyEntry GroupValue { get; } + } + + /// + /// Group-Object implementation. + /// + [Cmdlet(VerbsData.Group, "Object", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096619", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(Hashtable), typeof(GroupInfo))] + public class GroupObjectCommand : ObjectBase + { + #region tracer + + /// + /// An instance of the PSTraceSource class used for trace output. + /// + [TraceSource("GroupObjectCommand", "Class that has group base implementation")] + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("GroupObjectCommand", "Class that has group base implementation"); + + #endregion tracer + + #region Command Line Switches + + /// + /// Gets or sets the NoElement parameter indicating of the groups should be flattened. + /// + /// + [Parameter] + public SwitchParameter NoElement { get; set; } + + /// + /// Gets or sets the AsHashTable parameter. + /// + /// + [Parameter(ParameterSetName = "HashTable")] + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HashTable")] + [Alias("AHT")] + public SwitchParameter AsHashTable { get; set; } + + /// + /// Gets or sets the AsString parameter. + /// + [Parameter(ParameterSetName = "HashTable")] + public SwitchParameter AsString { get; set; } + + private readonly List _groups = new(); + private readonly OrderByProperty _orderByProperty = new(); + private readonly Dictionary _tupleToGroupInfoMappingDictionary = new(); + private readonly List _entriesToOrder = new(); + private OrderByPropertyComparer _orderByPropertyComparer; + private bool _hasProcessedFirstInputObject; + private bool _hasDifferentValueTypes; + private Type[] _propertyTypesCandidate; + + #endregion + + #region utils + + /// + /// Utility function called by Group-Object to create Groups. + /// + /// Input object that needs to be grouped. + /// True if we are not accumulating objects. + /// List containing Groups. + /// Dictionary used to keep track of the groups with hash of the property values being the key. + /// The Comparer to be used while comparing to check if new group has to be created. + private static void DoGrouping( + OrderByPropertyEntry currentObjectEntry, + bool noElement, + List groups, + Dictionary groupInfoDictionary, + OrderByPropertyComparer orderByPropertyComparer) + { + var currentObjectOrderValues = currentObjectEntry.orderValues; + if (currentObjectOrderValues != null && currentObjectOrderValues.Count > 0) + { + object currentTupleObject = PSTuple.ArrayToTuple(currentObjectOrderValues); + + if (groupInfoDictionary.TryGetValue(currentTupleObject, out var currentGroupInfo)) + { + // add this inputObject to an existing group + currentGroupInfo.Add(currentObjectEntry.inputObject); + } + else + { + bool isCurrentItemGrouped = false; + + for (int groupsIndex = 0; groupsIndex < groups.Count; groupsIndex++) + { + // Check if the current input object can be converted to one of the already known types + // by looking up in the type to GroupInfo mapping. + if (orderByPropertyComparer.Compare(groups[groupsIndex].GroupValue, currentObjectEntry) == 0) + { + groups[groupsIndex].Add(currentObjectEntry.inputObject); + isCurrentItemGrouped = true; + break; + } + } + + if (!isCurrentItemGrouped) + { + // create a new group + s_tracer.WriteLine("Create a new group: {0}", currentObjectOrderValues); + GroupInfo newObjGrp = noElement ? new GroupInfoNoElement(currentObjectEntry) : new GroupInfo(currentObjectEntry); + groups.Add(newObjGrp); + + groupInfoDictionary.Add(currentTupleObject, newObjGrp); + } + } + } + } + + /// + /// Utility function called by Group-Object to create Groups. + /// + /// Input object that needs to be grouped. + /// True if we are not accumulating objects. + /// List containing Groups. + /// Dictionary used to keep track of the groups with hash of the property values being the key. + /// The Comparer to be used while comparing to check if new group has to be created. + private static void DoOrderedGrouping( + OrderByPropertyEntry currentObjectEntry, + bool noElement, + List groups, + Dictionary groupInfoDictionary, + OrderByPropertyComparer orderByPropertyComparer) + { + var currentObjectOrderValues = currentObjectEntry.orderValues; + if (currentObjectOrderValues != null && currentObjectOrderValues.Count > 0) + { + object currentTupleObject = PSTuple.ArrayToTuple(currentObjectOrderValues); + + if (groupInfoDictionary.TryGetValue(currentTupleObject, out var currentGroupInfo)) + { + // add this inputObject to an existing group + currentGroupInfo.Add(currentObjectEntry.inputObject); + } + else + { + bool isCurrentItemGrouped = false; + + if (groups.Count > 0) + { + var lastGroup = groups[groups.Count - 1]; + + // Check if the current input object can be converted to one of the already known types + // by looking up in the type to GroupInfo mapping. + if (orderByPropertyComparer.Compare(lastGroup.GroupValue, currentObjectEntry) == 0) + { + lastGroup.Add(currentObjectEntry.inputObject); + isCurrentItemGrouped = true; + } + } + + if (!isCurrentItemGrouped) + { + // create a new group + s_tracer.WriteLine("Create a new group: {0}", currentObjectOrderValues); + GroupInfo newObjGrp = noElement + ? new GroupInfoNoElement(currentObjectEntry) + : new GroupInfo(currentObjectEntry); + + groups.Add(newObjGrp); + + groupInfoDictionary.Add(currentTupleObject, newObjGrp); + } + } + } + } + + private void WriteNonTerminatingError(Exception exception, string resourceIdAndErrorId, ErrorCategory category) + { + Exception ex = new(StringUtil.Format(resourceIdAndErrorId), exception); + WriteError(new ErrorRecord(ex, resourceIdAndErrorId, category, null)); + } + + #endregion utils + + /// + /// Process every input object to group them. + /// + protected override void ProcessRecord() + { + if (InputObject != null && InputObject != AutomationNull.Value) + { + OrderByPropertyEntry currentEntry; + + if (!_hasProcessedFirstInputObject) + { + Property ??= OrderByProperty.GetDefaultKeyPropertySet(InputObject); + + _orderByProperty.ProcessExpressionParameter(this, Property); + + if (AsString && !AsHashTable) + { + ArgumentException ex = new(UtilityCommonStrings.GroupObjectWithHashTable); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, AsString); + ThrowTerminatingError(er); + } + + if (AsHashTable && !AsString && (Property != null && (Property.Length > 1 || _orderByProperty.MshParameterList.Count > 1))) + { + ArgumentException ex = new(UtilityCommonStrings.GroupObjectSingleProperty); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property); + ThrowTerminatingError(er); + } + + currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); + bool[] ascending = new bool[currentEntry.orderValues.Count]; + for (int index = 0; index < currentEntry.orderValues.Count; index++) + { + ascending[index] = true; + } + + _orderByPropertyComparer = new OrderByPropertyComparer(ascending, _cultureInfo, CaseSensitive); + + _hasProcessedFirstInputObject = true; + } + else + { + currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); + } + + _entriesToOrder.Add(currentEntry); + + var currentEntryOrderValues = currentEntry.orderValues; + if (!_hasDifferentValueTypes) + { + UpdateOrderPropertyTypeInfo(currentEntryOrderValues); + } + } + } + + private void UpdateOrderPropertyTypeInfo(List currentEntryOrderValues) + { + if (_propertyTypesCandidate == null) + { + _propertyTypesCandidate = currentEntryOrderValues.Select(static c => PSObject.Base(c.PropertyValue)?.GetType()).ToArray(); + return; + } + + if (_propertyTypesCandidate.Length != currentEntryOrderValues.Count) + { + _hasDifferentValueTypes = true; + return; + } + + // check all the types we group on. + // if we find more than one set of types, _hasDifferentValueTypes is set to true, + // and we are forced to take a slower code path when we group our objects + for (int i = 0; i < _propertyTypesCandidate.Length; i++) + { + var candidateType = _propertyTypesCandidate[i]; + var propertyType = PSObject.Base(currentEntryOrderValues[i].PropertyValue)?.GetType(); + if (propertyType == null) + { + // we ignore properties without values. We can always compare against null. + continue; + } + + // if we haven't gotten a type for a property yet, update it when we do get a value + if (propertyType != candidateType) + { + if (candidateType == null) + { + _propertyTypesCandidate[i] = propertyType; + } + else + { + _hasDifferentValueTypes = true; + break; + } + } + } + } + + /// + /// Completes the processing of the gathered group objects. + /// + protected override void EndProcessing() + { + if (!_hasDifferentValueTypes) + { + // using OrderBy to get stable sort. + // fast path when we only have the same object types to group + foreach (var entry in _entriesToOrder.Order(_orderByPropertyComparer)) + { + DoOrderedGrouping(entry, NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer); + if (Stopping) + { + return; + } + } + } + else + { + foreach (var entry in _entriesToOrder) + { + DoGrouping(entry, NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer); + if (Stopping) + { + return; + } + } + } + + s_tracer.WriteLine(_groups.Count); + if (_groups.Count > 0) + { + if (AsHashTable.IsPresent) + { + StringComparer comparer = CaseSensitive.IsPresent + ? StringComparer.CurrentCulture + : StringComparer.CurrentCultureIgnoreCase; + var hashtable = new Hashtable(comparer); + try + { + if (AsString) + { + foreach (GroupInfo grp in _groups) + { + hashtable.Add(grp.Name, grp.Group); + } + } + else + { + foreach (GroupInfo grp in _groups) + { + hashtable.Add(PSObject.Base(grp.Values[0]), grp.Group); + } + } + } + catch (ArgumentException e) + { + WriteNonTerminatingError(e, UtilityCommonStrings.InvalidOperation, ErrorCategory.InvalidArgument); + return; + } + + WriteObject(hashtable); + } + else + { + WriteObject(_groups, true); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..d01d144caca5bcd9600348d9dd9471eea011081b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -0,0 +1,3139 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Management.Automation.Remoting; +using System.Management.Automation.Runspaces; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + using PowerShell = System.Management.Automation.PowerShell; + + /// + /// This class implements Export-PSSession cmdlet. + /// Spec: TBD. + /// + [Cmdlet(VerbsData.Export, "PSSession", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096604")] + [OutputType(typeof(FileInfo))] + public sealed class ExportPSSessionCommand : ImplicitRemotingCommandBase + { + /// + /// Version of the script generator used (by this Export-PSSession cmdlet) to generate psm1 and psd1 files. + /// Generated script checks this version to see if it needs to be regenerated. There are 2 situations where this is needed + /// 1. the script needs to be regenerated because a bug fix made previous versions incompatible with the rest of the system (i.e. with ObjectModelWrapper). + /// 2. ths script needs to be regenerated because a security vulnerability was found inside generated code (there is no way to service generated code, but we can service the dll that reports the version that the generated script checks against). + /// + public static Version VersionOfScriptGenerator { get { return ImplicitRemotingCodeGenerator.VersionOfScriptWriter; } } + + #region Parameters + + /// + /// Mandatory file name to write to. + /// + [Parameter(Mandatory = true, Position = 1)] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "ModuleName")] + public string OutputModule { get; set; } + + /// + /// Property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return new SwitchParameter(_force); + } + + set + { + _force = value.IsPresent; + } + } + + private bool _force; + + /// + /// Encoding optional flag. + /// + [Parameter] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + #endregion Parameters + + #region Implementation + + private const string getChildItemScript = @" + param($path) + Get-ChildItem -LiteralPath $path + "; + + private const string copyItemScript = @" + param($sourcePath, $destinationPath) + Copy-Item -Recurse $sourcePath\\* -Destination $destinationPath\\ + Remove-item $sourcePath -Recurse -Force + "; + + private void DisplayDirectory(List generatedFiles) + { + ScriptBlock script = this.Context.Engine.ParseScriptBlock(getChildItemScript, false); + Collection results = script.Invoke(new object[] { generatedFiles.ToArray() }); + foreach (PSObject o in results) + { + this.WriteObject(o); + } + } + + /// + /// Performs initialization of cmdlet execution. + /// + protected override void BeginProcessing() + { + // Module and FullyQualifiedModule should not be specified at the same time. + // Throw out terminating error if this is the case. + if (IsModuleSpecified && IsFullyQualifiedModuleSpecified) + { + string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, nameof(Module), nameof(FullyQualifiedModule)); + ErrorRecord error = new(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(error); + } + + DirectoryInfo directory = PathUtils.CreateModuleDirectory(this, this.OutputModule, this.Force.IsPresent); + + // Creating a temporary directory where files will be created. + // Then, copy the files from this location to the location specified in OutputModule + // We are doing this since temporary locations in user directory are more secure. + DirectoryInfo tempDirectory = PathUtils.CreateTemporaryDirectory(); + + Dictionary alias2resolvedCommandName; + List listOfCommandMetadata = this.GetRemoteCommandMetadata(out alias2resolvedCommandName); + List listOfFormatData = this.GetRemoteFormatData(); + + List generatedFiles = GenerateProxyModule( + tempDirectory, + Path.GetFileName(directory.FullName), + Encoding, + _force, + listOfCommandMetadata, + alias2resolvedCommandName, + listOfFormatData + ); + + ScriptBlock script = this.Context.Engine.ParseScriptBlock(copyItemScript, false); + script.Invoke(new object[] { tempDirectory, directory }); + + this.DisplayDirectory(new List { directory.FullName }); + } + + #endregion Methods + } + + /// + /// This class implements Import-PSSession cmdlet. + /// Spec: http://cmdletdesigner/SpecViewer/Default.aspx?Project=PowerShell&Cmdlet=Import-Command . + /// + [Cmdlet(VerbsData.Import, "PSSession", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096712")] + [OutputType(typeof(PSModuleInfo))] + public sealed class ImportPSSessionCommand : ImplicitRemotingCommandBase + { + #region Hooking runspace closed event into module cleanup + + private const string runspaceStateChangedScript = @"& { + if ('Closed' -eq $eventArgs.RunspaceStateInfo.State) + { + $sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier) + Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue + + $moduleInfo = $event.MessageData + Remove-Module -ModuleInfo $moduleInfo -Force -ErrorAction SilentlyContinue + + Remove-Item -LiteralPath $moduleInfo.ModuleBase -Recurse -Force -ErrorAction SilentlyContinue + $moduleInfo = $null + } +} + "; + + private const string unregisterEventCleanUpScript = @" + $sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier) + Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue + + if ($null -ne $previousScript) + { + & $previousScript $args + } + "; + + private void RegisterModuleCleanUp(PSModuleInfo moduleInfo) + { + if (moduleInfo == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(moduleInfo)); + } + + // Note: we are using this.Context.Events to make sure that the event handler + // is executing on the pipeline thread (for thread-safety) + + string sourceIdentifier = StringUtil.Format(ImplicitRemotingStrings.EventSourceIdentifier, this.Session.InstanceId, this.ModuleGuid); + PSEventSubscriber eventSubscriber = this.Context.Events.SubscribeEvent( + this.Session.Runspace, + "StateChanged", + sourceIdentifier, + PSObject.AsPSObject(moduleInfo), + this.Context.Engine.ParseScriptBlock(runspaceStateChangedScript, false), + true, false); + + // + // hook into moduleInfo.OnRemove to remove the handler when the module goes away + // + + ScriptBlock newScript = this.Context.Engine.ParseScriptBlock(unregisterEventCleanUpScript, false); + newScript = newScript.GetNewClosure(); // create a separate scope for variables set below + newScript.Module.SessionState.PSVariable.Set("eventSubscriber", eventSubscriber); + newScript.Module.SessionState.PSVariable.Set("previousScript", moduleInfo.OnRemove); + + moduleInfo.OnRemove = newScript; + } + + #endregion + + #region Creating and importing the module + + private const string importModuleScript = @" + param($name, $session, $prefix, $disableNameChecking) + Import-Module -Name $name -Alias * -Function * -Prefix $prefix -DisableNameChecking:$disableNameChecking -PassThru -ArgumentList @($session) + "; + + private PSModuleInfo CreateModule(string manifestFile) + { + ScriptBlock script = this.Context.Engine.ParseScriptBlock(importModuleScript, false); + Collection results = script.Invoke(manifestFile, this.Session, this.Prefix, _disableNameChecking); + Dbg.Assert(results != null, "Import-Module should always succeed"); + Dbg.Assert(results.Count == 1, "Import-Module should always succeed"); + Dbg.Assert(results[0].BaseObject is PSModuleInfo, "Import-Module should always succeed"); + return (PSModuleInfo)(results[0].BaseObject); + } + + #endregion + + #region Extra parameters + + /// + /// This parameter specified a prefix used to modify names of imported commands. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public new string Prefix + { + get { return base.Prefix; } + + set { base.Prefix = value; } + } + + /// + /// Disable warnings on cmdlet and function names that have non-standard verbs + /// or non-standard characters in the noun. + /// Also disable security related checks against command and parameter names. + /// + [Parameter] + public SwitchParameter DisableNameChecking + { + get { return _disableNameChecking; } + + set { _disableNameChecking = value; } + } + + private bool _disableNameChecking; + + #endregion + + /// + /// Performs initialization of cmdlet execution. + /// + protected override void BeginProcessing() + { + // Module and FullyQualifiedModule should not be specified at the same time. + // Throw out terminating error if this is the case. + if (IsModuleSpecified && IsFullyQualifiedModuleSpecified) + { + string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, nameof(Module), nameof(FullyQualifiedModule)); + ErrorRecord error = new(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(error); + } + + DirectoryInfo moduleDirectory = PathUtils.CreateTemporaryDirectory(); + + Dictionary alias2resolvedCommandName; + List listOfCommandMetadata = this.GetRemoteCommandMetadata(out alias2resolvedCommandName); + List listOfFormatData = this.GetRemoteFormatData(); + + List generatedFiles = this.GenerateProxyModule( + moduleDirectory, + Path.GetFileName(moduleDirectory.FullName), + Encoding.Unicode, + false, + listOfCommandMetadata, + alias2resolvedCommandName, + listOfFormatData); + + string manifestFile = null; + foreach (string file in generatedFiles) + { + if (Path.GetExtension(file).Equals(".psd1", StringComparison.OrdinalIgnoreCase)) + { + manifestFile = file; + } + } + + Dbg.Assert(manifestFile != null, "A psd1 file should always be generated"); + + PSModuleInfo moduleInfo = this.CreateModule(manifestFile); + this.RegisterModuleCleanUp(moduleInfo); + + this.WriteObject(moduleInfo); + } + } + + /// + /// Base class for implicit remoting cmdlets. + /// + public class ImplicitRemotingCommandBase : PSCmdlet + { + internal const string ImplicitRemotingKey = "ImplicitRemoting"; + internal const string ImplicitRemotingHashKey = "Hash"; + internal const string ImplicitRemotingCommandsToSkipKey = "CommandsToSkip"; + + #region Constructor + + internal ImplicitRemotingCommandBase() + { + this.CommandName = new string[] { "*" }; + _commandParameterSpecified = false; + + this.FormatTypeName = new string[] { "*" }; + _formatTypeNamesSpecified = false; + } + + #endregion + + #region Common cmdlet parameters + + #region related to Get-Command + + /// + /// Gets or sets the path(s) or name(s) of the commands to retrieve. + /// + [Parameter(Position = 2)] + [Alias("Name")] + public string[] CommandName + { + get + { + return _commandNameParameter; + } + + set + { + _commandNameParameter = value; + _commandParameterSpecified = true; + _commandNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings( + _commandNameParameter, + WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); + } + } + + private string[] _commandNameParameter; + private Collection _commandNamePatterns; // initialized to default value in the constructor + + /// + /// Allows shadowing and/or overwriting of existing local/client commands. + /// + [Parameter] + public SwitchParameter AllowClobber { get; set; } = new SwitchParameter(false); + + /// + /// The parameter that all additional arguments get bound to. These arguments are used + /// when retrieving dynamic parameters from cmdlets that support them. + /// + [Parameter] + [AllowNull] + [AllowEmptyCollection] + [Alias("Args")] + public object[] ArgumentList + { + get + { + return _commandArgs; + } + + set + { + _commandArgs = value; + _commandParameterSpecified = true; + } + } + + private object[] _commandArgs; + + /// + /// Gets or sets the type of the command to get. + /// + [Parameter] + [Alias("Type")] + public CommandTypes CommandType + { + get + { + return _commandType; + } + + set + { + _commandType = value; + _commandParameterSpecified = true; + } + } + + private CommandTypes _commandType = CommandTypes.All & (~(CommandTypes.Application | CommandTypes.Script | CommandTypes.ExternalScript)); + + /// + /// Gets or sets the PSSnapin parameter to the cmdlet. + /// + [Parameter] + [Alias("PSSnapin")] + [ValidateNotNull] + public string[] Module + { + get + { + return _PSSnapins; + } + + set + { + value ??= Array.Empty(); + + _PSSnapins = value; + _commandParameterSpecified = true; + IsModuleSpecified = true; + } + } + + private string[] _PSSnapins = Array.Empty(); + internal bool IsModuleSpecified = false; + /// + /// Gets or sets the FullyQualifiedModule parameter to the cmdlet. + /// + [Parameter] + [ValidateNotNull] + public ModuleSpecification[] FullyQualifiedModule + { + get + { + return _moduleSpecifications; + } + + set + { + if (value != null) + { + _moduleSpecifications = value; + } + + _commandParameterSpecified = true; + IsFullyQualifiedModuleSpecified = true; + } + } + + private ModuleSpecification[] _moduleSpecifications = Array.Empty(); + internal bool IsFullyQualifiedModuleSpecified = false; + + private bool _commandParameterSpecified; // initialized to default value in the constructor + + #endregion related to Get-Command + + #region related to F&O + + /// + /// Gets or sets the types for which we should get formatting and output data. + /// + [Parameter(Position = 3)] + public string[] FormatTypeName + { + get + { + return _formatTypeNameParameter; + } + + set + { + _formatTypeNameParameter = value; + _formatTypeNamesSpecified = true; + _formatTypeNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings( + _formatTypeNameParameter, + WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); + } + } + + private string[] _formatTypeNameParameter; // initialized to default value in the constructor + private Collection _formatTypeNamePatterns; + private bool _formatTypeNamesSpecified; // initialized to default value in the constructor + + #endregion + + #region Related to modules + + /// + /// This parameter specified a prefix used to modify names of imported commands. + /// + internal string Prefix { get; set; } = string.Empty; + + /// + /// Gets or sets the certificate with which to sign the format file and psm1 file. + /// + [Parameter] + public X509Certificate2 Certificate { get; set; } + + #endregion + + /// + /// The PSSession object describing the remote runspace + /// using which the specified cmdlet operation will be performed. + /// + [Parameter(Mandatory = true, Position = 0)] + [ValidateNotNull] + public PSSession Session { get; set; } + + #endregion Parameters + + #region Localized errors and messages + + internal ErrorDetails GetErrorDetails(string errorId, params object[] args) + { + if (string.IsNullOrEmpty(errorId)) + { + throw PSTraceSource.NewArgumentNullException(nameof(errorId)); + } + + return new ErrorDetails( + typeof(ImplicitRemotingCommandBase).GetTypeInfo().Assembly, + "Microsoft.PowerShell.Commands.Utility.resources.ImplicitRemotingStrings", + errorId, + args); + } + + private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() + { + const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; + + ErrorDetails details = this.GetErrorDetails(errorId); + + ErrorRecord errorRecord = new( + new ArgumentException(details.Message), + errorId, + ErrorCategory.InvalidResult, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + const string errorId = "ErrorMalformedDataFromRemoteCommand"; + + ErrorDetails details = this.GetErrorDetails(errorId, commandName); + + ErrorRecord errorRecord = new( + new ArgumentException(details.Message), + errorId, + ErrorCategory.InvalidResult, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames) + { + if (string.IsNullOrEmpty(commandNames)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandNames)); + } + + const string errorId = "ErrorCommandSkippedBecauseOfShadowing"; + + ErrorDetails details = this.GetErrorDetails(errorId, commandNames); + + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.InvalidData, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + const string errorId = "ErrorSkippedNonRequestedCommand"; + + ErrorDetails details = this.GetErrorDetails(errorId, commandName); + + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.ResourceExists, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) + { + if (string.IsNullOrEmpty(typeName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); + } + + const string errorId = "ErrorSkippedNonRequestedTypeDefinition"; + + ErrorDetails details = this.GetErrorDetails(errorId, typeName); + + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.ResourceExists, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + const string errorId = "ErrorSkippedUnsafeCommandName"; + + ErrorDetails details = this.GetErrorDetails(errorId, commandName); + + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.InvalidData, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, string nameType, string name) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + if (string.IsNullOrEmpty(nameType)) + { + throw PSTraceSource.NewArgumentNullException(nameof(nameType)); + } + + Dbg.Assert(nameType.Equals("Alias") || nameType.Equals("ParameterSet") || nameType.Equals("Parameter"), "nameType matches resource names"); + if (string.IsNullOrEmpty(name)) + { + throw PSTraceSource.NewArgumentNullException(nameof(name)); + } + + string errorId = "ErrorSkippedUnsafe" + nameType + "Name"; + + ErrorDetails details = this.GetErrorDetails(errorId, commandName, name); + + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.InvalidData, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeException runtimeException) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + if (runtimeException == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(runtimeException)); + } + + string errorId; + ErrorDetails errorDetails; + ErrorRecord errorRecord; + + // + // handle recognized types of exceptions first + // + if ((runtimeException is RemoteException remoteException) && (remoteException.SerializedRemoteException != null)) + { + if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) + { + errorId = "ErrorRequiredRemoteCommandNotFound"; + errorDetails = this.GetErrorDetails(errorId, this.MyInvocation.MyCommand.Name); + + errorRecord = new ErrorRecord( + new RuntimeException(errorDetails.Message, runtimeException), + errorId, + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = errorDetails; + + return errorRecord; + } + } + + // + // output a generic error message if exception is not recognized + // + errorId = "ErrorFromRemoteCommand"; + errorDetails = this.GetErrorDetails(errorId, commandName, runtimeException.Message); + + errorRecord = new ErrorRecord( + new RuntimeException(errorDetails.Message, runtimeException), + errorId, + ErrorCategory.InvalidResult, + null); + errorRecord.ErrorDetails = errorDetails; + + return errorRecord; + } + + private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) + { + if (string.IsNullOrEmpty(aliasName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(aliasName)); + } + + const string errorId = "ErrorCouldntResolveAlias"; + + ErrorDetails details = this.GetErrorDetails(errorId, aliasName); + + ErrorRecord errorRecord = new( + new ArgumentException(details.Message), + errorId, + ErrorCategory.OperationTimeout, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + const string errorId = "ErrorNoResultsFromRemoteEnd"; + + ErrorDetails details = this.GetErrorDetails(errorId, commandName); + + ErrorRecord errorRecord = new( + new ArgumentException(details.Message), + errorId, + ErrorCategory.InvalidResult, + null); + errorRecord.ErrorDetails = details; + + return errorRecord; + } + + private readonly List _commandsSkippedBecauseOfShadowing = new(); + + private void ReportSkippedCommands() + { + if (_commandsSkippedBecauseOfShadowing.Count != 0) + { + string skippedCommands = string.Join(", ", _commandsSkippedBecauseOfShadowing.ToArray()); + ErrorRecord errorRecord = this.GetErrorCommandSkippedBecauseOfShadowing(skippedCommands); + this.WriteWarning(errorRecord.ErrorDetails.Message); + } + } + + #endregion + + #region Logic to avoid commands we don't want to shadow + + private bool IsCommandNameMatchingParameters(string commandName) + { + if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, _commandNamePatterns, false)) + { + return true; + } + + string nameWithoutExtension = Path.GetFileNameWithoutExtension(commandName); + if (!nameWithoutExtension.Equals(commandName, StringComparison.OrdinalIgnoreCase)) + { + return SessionStateUtilities.MatchesAnyWildcardPattern(nameWithoutExtension, _commandNamePatterns, false); + } + + return false; + } + + private Dictionary _existingCommands; + + private Dictionary ExistingCommands + { + get + { + if (_existingCommands == null) + { + _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); + CommandSearcher searcher = new( + "*", + SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, + CommandTypes.All, + this.Context); + foreach (CommandInfo commandInfo in searcher) + { + _existingCommands[commandInfo.Name] = null; + } + } + + return _existingCommands; + } + } + + private bool IsShadowingExistingCommands(string commandName) + { + commandName = ModuleCmdletBase.AddPrefixToCommandName(commandName, this.Prefix); + + CommandSearcher searcher = new(commandName, SearchResolutionOptions.None, CommandTypes.All, this.Context); + foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(commandName)) + { + if (this.ExistingCommands.ContainsKey(expandedCommandName)) + { + return true; + } + } + + return false; + } + + /// + /// Returns true if command doesn't shadow OR is in the -AllowShadowing parameter. + /// + /// + /// + private bool IsCommandNameAllowedForImport(string commandName) + { + if (string.IsNullOrEmpty(commandName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); + } + + if (this.AllowClobber.IsPresent) + { + return true; + } + + if (IsShadowingExistingCommands(commandName)) + { + _commandsSkippedBecauseOfShadowing.Add(commandName); + return false; + } + else + { + return true; + } + } + + #endregion + + #region Logic to skip commands the server doesn't want to import + + private List CommandSkipListFromServer + { + get + { + // try to get the list from server's application private data + if (_commandSkipListFromServer == null) + { + string[] serverDeclaredListOfCommandsToSkip; + if (PSPrimitiveDictionary.TryPathGet( + this.Session.ApplicationPrivateData, + out serverDeclaredListOfCommandsToSkip, + ImplicitRemotingKey, + ImplicitRemotingCommandsToSkipKey)) + { + _commandSkipListFromServer = new List(); + if (serverDeclaredListOfCommandsToSkip != null) + { + _commandSkipListFromServer.AddRange(serverDeclaredListOfCommandsToSkip); + } + } + } + + // fallback to the default list that hardcodes ... + if (_commandSkipListFromServer == null) + { + _commandSkipListFromServer = new List(); + + // ... A) 5 commands used (some required some not) by implicit remoting + _commandSkipListFromServer.Add("Get-Command"); + _commandSkipListFromServer.Add("Get-FormatData"); + _commandSkipListFromServer.Add("Get-Help"); + _commandSkipListFromServer.Add("Select-Object"); + _commandSkipListFromServer.Add("Measure-Object"); + + // ... B) 2 commands required for 1:1 remoting + _commandSkipListFromServer.Add("Exit-PSSession"); + _commandSkipListFromServer.Add("Out-Default"); + } + + return _commandSkipListFromServer; + } + } + + private List _commandSkipListFromServer; + + private bool IsCommandSkippedByServerDeclaration(string commandName) + { + // skipped = commandName is on the CommandSkipListFromServer and is not on the this.CommandName list + foreach (string commandToSkip in this.CommandSkipListFromServer) + { + if (commandToSkip.Equals(commandName, StringComparison.OrdinalIgnoreCase)) + { + if (this.CommandName != null) + { + foreach (string commandNameParameter in this.CommandName) + { + if (commandName.Equals(commandNameParameter, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + } + + return true; + } + } + + return false; + } + + #endregion + + #region Generic rehydration helpers + + private T ConvertTo(string commandName, object value) + { + return ConvertTo(commandName, value, false); + } + + private T ConvertTo(string commandName, object value, bool nullOk) + { + if (value == null) + { + if (nullOk) + { + return default(T); + } + else + { + this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); + } + } + + T t; + if (!LanguagePrimitives.TryConvertTo(value, out t)) + { + this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); + } + + return t; + } + + private T GetPropertyValue(string commandName, PSObject pso, string propertyName) + { + return GetPropertyValue(commandName, pso, propertyName, false); + } + + private T GetPropertyValue(string commandName, PSObject pso, string propertyName, bool nullOk) + { + PSPropertyInfo property = pso.Properties[propertyName]; + if (property == null) + { + this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); + } + + return ConvertTo(commandName, property.Value, nullOk); + } + + private List RehydrateList(string commandName, PSObject deserializedObject, string propertyName, Func itemRehydrator) + { + Dbg.Assert(deserializedObject != null, "deserializedObject parameter != null"); + + List result = null; + PSPropertyInfo deserializedListProperty = deserializedObject.Properties[propertyName]; + if (deserializedListProperty != null) + { + result = RehydrateList(commandName, deserializedListProperty.Value, itemRehydrator); + } + + return result; + } + + private List RehydrateList(string commandName, object deserializedList, Func itemRehydrator) + { + itemRehydrator ??= (PSObject pso) => ConvertTo(commandName, pso); + + List result = null; + + ArrayList list = ConvertTo(commandName, deserializedList, true); + if (list != null) + { + result = new List(); + foreach (object o in list) + { + PSObject deserializedItem = ConvertTo(commandName, o); + T item = itemRehydrator(deserializedItem); + result.Add(item); + } + } + + return result; + } + + private Dictionary RehydrateDictionary( + string commandName, + PSObject deserializedObject, + string propertyName, + Func valueRehydrator) + { + Dbg.Assert(deserializedObject != null, "deserializedObject parameter != null"); + Dbg.Assert(!string.IsNullOrEmpty(propertyName), "propertyName parameter != null"); + + valueRehydrator ??= (PSObject pso) => ConvertTo(commandName, pso); + + Dictionary result = new(); + PSPropertyInfo deserializedDictionaryProperty = deserializedObject.Properties[propertyName]; + if (deserializedDictionaryProperty != null) + { + Hashtable deserializedDictionary = ConvertTo(commandName, deserializedDictionaryProperty.Value, true); + if (deserializedDictionary != null) + { + foreach (DictionaryEntry deserializedItem in deserializedDictionary) + { + TKey itemKey = ConvertTo(commandName, deserializedItem.Key); + + PSObject deserializedItemValue = ConvertTo(commandName, deserializedItem.Value); + TValue itemValue = valueRehydrator(deserializedItemValue); + + result.Add(itemKey, itemValue); + } + } + } + + return result; + } + + #endregion + + #region CommandInfo-specific rehydration helpers + + /// + /// Validates that a name or identifier is safe to use in generated code + /// (i.e. it can't be used for code injection attacks). + /// + /// Name to validate. + /// if the name is safe; otherwise. + private static bool IsSafeNameOrIdentifier(string name) + { + // '.' is needed for stuff like net.exe + // ':' and '\' are included because they are present in default functions (cd\, C:) + // \p{Ll}\p{Lu}\p{Lt} => letter lower/upper/title-case + // \p{Lo}\p{Nd}\p{Lm} => letter other, digit, letter modifier + // we reject names longer than 100 characters + return !string.IsNullOrEmpty(name) && + Regex.IsMatch(name, CommandMetadata.isSafeNameOrIdentifierRegex, + RegexOptions.CultureInvariant | RegexOptions.Singleline); + } + + /// + /// Validates that a parameter name is safe to use in generated code + /// (i.e. it can't be used for code injection attacks). + /// + /// Parameter name to validate. + /// if the name is safe; otherwise. + private static bool IsSafeParameterName(string parameterName) + { + return IsSafeNameOrIdentifier(parameterName) && !parameterName.Contains(':'); + } + + /// + /// Validates that a type can be safely used as a type constraint + /// (i.e. it doesn't introduce any side effects on the client). + /// + /// Type to validate. + /// if the type is safe; otherwise. + private static bool IsSafeTypeConstraint(Type type) + { + if (type == null) + { + return true; // no type constraint => safe + } + + if (type.IsArray) + { + return IsSafeTypeConstraint(type.GetElementType()); + } + else if (type.Equals(typeof(Hashtable))) + { + return true; + } + else if (type.Equals(typeof(SwitchParameter))) + { + return true; + } + else if (type.Equals(typeof(PSCredential))) + { + return true; + } + else if (type.Equals(typeof(System.Security.SecureString))) + { + return true; + } + else if (KnownTypes.GetTypeSerializationInfo(type) != null) + { + return true; + } + else + { + return false; + } + } + + /// + /// Validates that command metadata returned from the (potentially malicious) server is safe. + /// Writes error messages if necessary. Modifies command metadata to make it safe if necessary. + /// + /// Command metadata to verify. + /// if the command metadata is safe; otherwise. + private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) + { + if (!IsCommandNameMatchingParameters(commandMetadata.Name)) + { + this.WriteError(this.GetErrorSkippedNonRequestedCommand(commandMetadata.Name)); + return false; + } + + if (!IsSafeNameOrIdentifier(commandMetadata.Name)) + { + this.WriteError(this.GetErrorSkippedUnsafeCommandName(commandMetadata.Name)); + return false; + } + + if ((commandMetadata.DefaultParameterSetName != null) && + !IsSafeNameOrIdentifier(commandMetadata.DefaultParameterSetName)) + { + this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + commandMetadata.Name, + "ParameterSet", + commandMetadata.DefaultParameterSetName)); + return false; + } + + Dbg.Assert(commandMetadata.CommandType == null, "CommandType shouldn't get rehydrated"); + Dbg.Assert(!commandMetadata.ImplementsDynamicParameters, "Proxies shouldn't do dynamic parameters"); + + if (commandMetadata.Parameters != null) + { + foreach (ParameterMetadata parameter in commandMetadata.Parameters.Values) + { + Dbg.Assert(parameter.Attributes == null || parameter.Attributes.Count == 0, + "Attributes shouldn't get rehydrated"); + + // sanitize - remove type constraint that are not allowed + if (!IsSafeTypeConstraint(parameter.ParameterType)) + { + parameter.ParameterType = null; + } + + if (!IsSafeParameterName(parameter.Name)) + { + this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + commandMetadata.Name, + "Parameter", + parameter.Name)); + return false; + } + + if (parameter.Aliases != null) + { + foreach (string alias in parameter.Aliases) + { + if (!IsSafeNameOrIdentifier(alias)) + { + this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + commandMetadata.Name, + "Alias", + alias)); + return false; + } + } + } + + if (parameter.ParameterSets != null) + { + foreach (KeyValuePair setPair in parameter.ParameterSets) + { + if (!IsSafeNameOrIdentifier(setPair.Key)) + { + this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + commandMetadata.Name, + "ParameterSet", + setPair.Key)); + return false; + } + + ParameterSetMetadata parameterSet = setPair.Value; + Dbg.Assert(string.IsNullOrEmpty(parameterSet.HelpMessageBaseName), "HelpMessageBaseName shouldn't get rehydrated"); + Dbg.Assert(string.IsNullOrEmpty(parameterSet.HelpMessageResourceId), "HelpMessageResourceId shouldn't get rehydrated"); + } + } + } + } + + return true; + } + + private Type RehydrateParameterType(PSObject deserializedParameterMetadata) + { + bool switchParameter = GetPropertyValue("Get-Command", deserializedParameterMetadata, "SwitchParameter"); + if (switchParameter) + { + return typeof(SwitchParameter); + } + else + { + return typeof(object); + } + } + + private ParameterMetadata RehydrateParameterMetadata(PSObject deserializedParameterMetadata) + { + if (deserializedParameterMetadata == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(deserializedParameterMetadata)); + } + + string name = GetPropertyValue("Get-Command", deserializedParameterMetadata, "Name"); + bool isDynamic = GetPropertyValue("Get-Command", deserializedParameterMetadata, "IsDynamic"); + + Type parameterType = RehydrateParameterType(deserializedParameterMetadata); + List aliases = RehydrateList("Get-Command", deserializedParameterMetadata, "Aliases", null); + + ParameterSetMetadata parameterSetMetadata = new(int.MinValue, 0, null); + Dictionary parameterSets = new(StringComparer.OrdinalIgnoreCase); + parameterSets.Add(ParameterAttribute.AllParameterSets, parameterSetMetadata); + + return new ParameterMetadata( + aliases == null ? new Collection() : new Collection(aliases), + isDynamic, + name, + parameterSets, + parameterType); + } + + private bool IsProxyForCmdlet(Dictionary parameters) + { + // we are not sending CmdletBinding/DefaultParameterSet over the wire anymore + // we need to infer IsProxyForCmdlet from presence of all common parameters + + // need to exclude `ProgressAction` which may not exist for downlevel platforms + bool isDownLevelRemote = Session.Runspace is RemoteRunspace remoteRunspace + && remoteRunspace.ServerVersion is not null + && remoteRunspace.ServerVersion <= new Version(7, 3); + + foreach (string commonParameterName in CommonParameters) + { + if (isDownLevelRemote && commonParameterName == "ProgressAction") + { + continue; + } + + if (!parameters.ContainsKey(commonParameterName)) + { + return false; + } + } + + return true; + } + + private CommandMetadata RehydrateCommandMetadata(PSObject deserializedCommandInfo, out string resolvedCommandName) + { + if (deserializedCommandInfo == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(deserializedCommandInfo)); + } + + string name = GetPropertyValue("Get-Command", deserializedCommandInfo, "Name"); + + CommandTypes commandType = GetPropertyValue("Get-Command", deserializedCommandInfo, "CommandType"); + if (commandType == CommandTypes.Alias) + { + resolvedCommandName = GetPropertyValue("Get-Command", deserializedCommandInfo, "ResolvedCommandName", true); + if (string.IsNullOrEmpty(resolvedCommandName)) + { + this.WriteError(this.GetErrorCouldntResolvedAlias(name)); + } + } + else + { + resolvedCommandName = null; + } + + Dictionary parameters = RehydrateDictionary("Get-Command", deserializedCommandInfo, "Parameters", RehydrateParameterMetadata); + + // add client-side AsJob parameter + parameters.Remove("AsJob"); + ParameterMetadata asJobParameter = new("AsJob", typeof(SwitchParameter)); + parameters.Add(asJobParameter.Name, asJobParameter); + + return new CommandMetadata( + name: name, + commandType: commandType, + isProxyForCmdlet: IsProxyForCmdlet(parameters), + defaultParameterSetName: ParameterAttribute.AllParameterSets, + supportsShouldProcess: false, + confirmImpact: ConfirmImpact.None, + supportsPaging: false, + supportsTransactions: false, + positionalBinding: true, + parameters: parameters); + } + + private static int GetCommandTypePriority(CommandTypes commandType) + { + switch (commandType) + { + case CommandTypes.Alias: + return 10; + + // there is only one function table + case CommandTypes.Filter: + case CommandTypes.Function: + case CommandTypes.Script: + return 20; + + case CommandTypes.Cmdlet: + return 30; + + // application/externalScript order depends on remote $env:path variable + case CommandTypes.Application: + case CommandTypes.ExternalScript: + return 40; + + default: + Dbg.Assert(false, "Unknown value of CommandTypes enumeration"); + return 50; + } + } + + /// + /// Converts remote (deserialized) CommandInfo objects into CommandMetadata equivalents. + /// + /// Dictionary where rehydrated CommandMetadata are going to be stored. + /// Dictionary mapping alias names to resolved command names. + /// Remote (deserialized) CommandInfo object. + /// CommandMetadata equivalents. + private void AddRemoteCommandMetadata( + Dictionary name2commandMetadata, + Dictionary alias2resolvedCommandName, + PSObject remoteCommandInfo) + { + Dbg.Assert(name2commandMetadata != null, "name2commandMetadata parameter != null"); + Dbg.Assert(alias2resolvedCommandName != null, "alias2resolvedCommandName parameter != null"); + Dbg.Assert(remoteCommandInfo != null, "remoteCommandInfo parameter != null"); + + string resolvedCommandName; + CommandMetadata commandMetadata = RehydrateCommandMetadata(remoteCommandInfo, out resolvedCommandName); + if (!IsSafeCommandMetadata(commandMetadata)) + { + return; + } + + if (resolvedCommandName != null && !IsSafeNameOrIdentifier(commandMetadata.Name)) + { + this.WriteError(this.GetErrorSkippedUnsafeCommandName(resolvedCommandName)); + return; + } + + if (IsCommandSkippedByServerDeclaration(commandMetadata.Name)) + { + return; + } + + if (!IsCommandNameAllowedForImport(commandMetadata.Name)) + { + return; + } + + CommandMetadata previousCommandWithSameName; + if (name2commandMetadata.TryGetValue(commandMetadata.Name, out previousCommandWithSameName)) + { + int previousCommandPriority = GetCommandTypePriority(previousCommandWithSameName.WrappedCommandType); + int currentCommandPriority = GetCommandTypePriority(commandMetadata.WrappedCommandType); + if (previousCommandPriority < currentCommandPriority) + { + return; + } + } + + if (resolvedCommandName != null) + { + alias2resolvedCommandName[commandMetadata.Name] = resolvedCommandName; + commandMetadata.Name = resolvedCommandName; + } + + name2commandMetadata[commandMetadata.Name] = commandMetadata; + } + + #endregion + + #region Logic to avoid format data we don't want to shadow + + private bool IsTypeNameMatchingParameters(string name) + { + return SessionStateUtilities.MatchesAnyWildcardPattern(name, _formatTypeNamePatterns, false); + } + + private bool IsSafeTypeDefinition(ExtendedTypeDefinition typeDefinition) + { + if (!IsTypeNameMatchingParameters(typeDefinition.TypeName)) + { + this.WriteError(this.GetErrorSkippedNonRequestedTypeDefinition(typeDefinition.TypeName)); + return false; + } + + return true; + } + + private void AddRemoteTypeDefinition(IList listOfTypeDefinitions, PSObject remoteTypeDefinition) + { + Dbg.Assert(listOfTypeDefinitions != null, "listOfTypeDefinitions parameter != null"); + Dbg.Assert(remoteTypeDefinition != null, "remoteTypeDefinition parameter != null"); + + ExtendedTypeDefinition typeDefinition = ConvertTo("Get-FormatData", remoteTypeDefinition); + if (!IsSafeTypeDefinition(typeDefinition)) + { + return; + } + + listOfTypeDefinitions.Add(typeDefinition); + } + + #endregion + + #region Helpers for executing remote commands + + private bool _assumeMeasureObjectIsAvailable = true; + + private int CountRemoteObjects(PowerShell powerShell) + { + if (!_assumeMeasureObjectIsAvailable) + { + return -1; + } + + try + { + powerShell.AddCommand("Measure-Object"); + + Collection measurements; + using (new PowerShellStopper(this.Context, powerShell)) + { + measurements = powerShell.Invoke(); + } + + if ((measurements == null) || (measurements.Count != 1)) + { + _assumeMeasureObjectIsAvailable = false; + return -1; + } + + PSPropertyInfo countProperty = measurements[0].Properties["Count"]; + if (countProperty == null) + { + _assumeMeasureObjectIsAvailable = false; + return -1; + } + + int count; + if (LanguagePrimitives.TryConvertTo(countProperty.Value, out count)) + { + return count; + } + else + { + _assumeMeasureObjectIsAvailable = false; + return -1; + } + } + catch (RuntimeException) + { + // just return -1 if remote Measure-Object invocation fails for any reason + _assumeMeasureObjectIsAvailable = false; + return -1; + } + } + + internal void DuplicatePowerShellStreams(PowerShell powerShell) + { + foreach (ErrorRecord record in powerShell.Streams.Error.ReadAll()) + { + this.WriteError(record); + } + + foreach (WarningRecord record in powerShell.Streams.Warning.ReadAll()) + { + this.WriteWarning(record.Message); + } + + foreach (VerboseRecord record in powerShell.Streams.Verbose.ReadAll()) + { + this.WriteVerbose(record.Message); + } + + foreach (DebugRecord record in powerShell.Streams.Debug.ReadAll()) + { + this.WriteDebug(record.Message); + } + + foreach (InformationRecord record in powerShell.Streams.Information.ReadAll()) + { + this.WriteInformation(record); + } + } + + #endregion + + #region Executing remote Get-FormatData (and Get-TypeData in the future?) + + private PowerShell BuildPowerShellForGetFormatData() + { + PowerShell powerShell = PowerShell.Create(); + + powerShell.AddCommand("Get-FormatData"); + powerShell.AddParameter("TypeName", this.FormatTypeName); + + // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter + if ((Session.Runspace is RemoteRunspace remoteRunspace) && (remoteRunspace.ServerVersion != null) && + (remoteRunspace.ServerVersion >= new Version(5, 1))) + { + powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); + } + + powerShell.Runspace = Session.Runspace; + + return powerShell; + } + + /// + /// Gets CommandMetadata objects from remote runspace. + /// + /// (rehydrated) CommandMetadata objects. + internal List GetRemoteFormatData() + { + if ((this.FormatTypeName == null) || (this.FormatTypeName.Length == 0) || + (_commandParameterSpecified && !_formatTypeNamesSpecified)) + { + return new List(); + } + + this.WriteProgress(StringUtil.Format(ImplicitRemotingStrings.ProgressStatusGetFormatDataStart), null, null); + + using (PowerShell powerShell = this.BuildPowerShellForGetFormatData()) + { + IAsyncResult asyncResult = null; + try + { + int expectedCount = -1; + using (PowerShell countingPowerShell = this.BuildPowerShellForGetFormatData()) + { + expectedCount = this.CountRemoteObjects(countingPowerShell); + } + + // invoke + using (new PowerShellStopper(this.Context, powerShell)) + { + DateTime startTime = DateTime.UtcNow; + + PSDataCollection asyncOutput = new(); + + // process output and errors as soon as possible + asyncResult = powerShell.BeginInvoke(null, asyncOutput); + int numberOfReceivedObjects = 0; + List result = new(); + foreach (PSObject deserializedFormatData in asyncOutput) + { + AddRemoteTypeDefinition(result, deserializedFormatData); + this.DuplicatePowerShellStreams(powerShell); + this.WriteProgress(startTime, ++numberOfReceivedObjects, expectedCount, ImplicitRemotingStrings.ProgressStatusGetFormatDataProgress); + } + + this.DuplicatePowerShellStreams(powerShell); + powerShell.EndInvoke(asyncResult); + + if ((numberOfReceivedObjects == 0) && (_formatTypeNamesSpecified)) + { + this.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-FormatData")); + } + + return result; + } + } + catch (RuntimeException e) + { + // process terminating errors from remote end + this.ThrowTerminatingError(this.GetErrorFromRemoteCommand("Get-FormatData", e)); + } + } + + // silencing the compiler with the "return" statement + Dbg.Assert(false, "We should never get here"); + return null; + } + + #endregion + + #region Executing remote Get-Command + + private PowerShell BuildPowerShellForGetCommand() + { + PowerShell powerShell = PowerShell.Create(); + + powerShell.AddCommand("Get-Command"); + powerShell.AddParameter("CommandType", this.CommandType); + if (this.CommandName != null) + { + powerShell.AddParameter("Name", this.CommandName); + } + + powerShell.AddParameter(nameof(Module), this.Module); + if (IsFullyQualifiedModuleSpecified) + { + powerShell.AddParameter(nameof(FullyQualifiedModule), this.FullyQualifiedModule); + } + + powerShell.AddParameter("ArgumentList", this.ArgumentList); + + powerShell.Runspace = Session.Runspace; + powerShell.RemotePowerShell.HostCallReceived += HandleHostCallReceived; + return powerShell; + } + + /// + /// + /// + /// + private void HandleHostCallReceived(object sender, RemoteDataEventArgs eventArgs) + { + System.Management.Automation.Runspaces.Internal.ClientRemotePowerShell.ExitHandler(sender, eventArgs); + } + + /// + /// Gets CommandMetadata objects from remote runspace. + /// + /// (rehydrated) CommandMetadata objects. + internal List GetRemoteCommandMetadata(out Dictionary alias2resolvedCommandName) + { + bool isReleaseCandidateBackcompatibilityMode = + this.Session.Runspace.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersion_2_0; + + alias2resolvedCommandName = new Dictionary(StringComparer.OrdinalIgnoreCase); + if ((this.CommandName == null) || (this.CommandName.Length == 0) || + (!_commandParameterSpecified && _formatTypeNamesSpecified)) + { + return new List(); + } + + this.WriteProgress(StringUtil.Format(ImplicitRemotingStrings.ProgressStatusGetCommandStart), null, null); + + using (PowerShell powerShell = this.BuildPowerShellForGetCommand()) + { + powerShell.AddCommand("Select-Object"); + powerShell.AddParameter("Property", new string[] { + "Name", "CommandType", "ResolvedCommandName", "DefaultParameterSet", "CmdletBinding", "Parameters"}); + powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; + + IAsyncResult asyncResult = null; + try + { + int expectedCount = -1; + if (isReleaseCandidateBackcompatibilityMode) + { + using (PowerShell countingPowerShell = this.BuildPowerShellForGetCommand()) + { + expectedCount = this.CountRemoteObjects(countingPowerShell); + } + } + + Dictionary name2commandMetadata = + new(StringComparer.OrdinalIgnoreCase); + + // invoke + using (new PowerShellStopper(this.Context, powerShell)) + { + DateTime startTime = DateTime.UtcNow; + + PSDataCollection asyncOutput = new(); + + // process output and errors as soon as possible + asyncResult = powerShell.BeginInvoke(null, asyncOutput); + int numberOfReceivedObjects = 0; + foreach (PSObject deserializedCommandInfo in asyncOutput) + { + if (!isReleaseCandidateBackcompatibilityMode && expectedCount == -1) + { + expectedCount = RemotingDecoder.GetPropertyValue( + deserializedCommandInfo, + RemoteDataNameStrings.DiscoveryCount); + + continue; + } + + AddRemoteCommandMetadata(name2commandMetadata, alias2resolvedCommandName, deserializedCommandInfo); + this.DuplicatePowerShellStreams(powerShell); + this.WriteProgress(startTime, ++numberOfReceivedObjects, expectedCount, ImplicitRemotingStrings.ProgressStatusGetCommandProgress); + } + + this.DuplicatePowerShellStreams(powerShell); + powerShell.EndInvoke(asyncResult); + + if ((numberOfReceivedObjects == 0) && (_commandParameterSpecified)) + { + this.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-Command")); + } + + return new List(name2commandMetadata.Values); + } + } + catch (RuntimeException e) + { + // process terminating errors from remote end + this.ThrowTerminatingError(this.GetErrorFromRemoteCommand("Get-Command", e)); + } + } + + // silencing the compiler with the "return" statement + Dbg.Assert(false, "We should never get here"); + return null; + } + + #endregion + + #region Reporting progress + + private DateTime _lastTimeProgressWasWritten = DateTime.UtcNow; + + private void WriteProgress(string statusDescription, int? percentComplete, int? secondsRemaining) + { + ProgressRecordType recordType; + if (secondsRemaining.HasValue && secondsRemaining.Value == 0 && + percentComplete.HasValue && percentComplete.Value == 100) + { + recordType = ProgressRecordType.Completed; + } + else + { + recordType = ProgressRecordType.Processing; + } + + if (recordType == ProgressRecordType.Processing) + { + TimeSpan timeSinceProgressWasWrittenLast = DateTime.UtcNow - _lastTimeProgressWasWritten; + if (timeSinceProgressWasWrittenLast < TimeSpan.FromMilliseconds(200)) + { + return; + } + } + + _lastTimeProgressWasWritten = DateTime.UtcNow; + + string activityDescription = StringUtil.Format(ImplicitRemotingStrings.ProgressActivity); + ProgressRecord progressRecord = new( + 1905347799, // unique id for ImplicitRemoting (I just picked a random number) + activityDescription, + statusDescription); + + if (percentComplete.HasValue) + { + progressRecord.PercentComplete = percentComplete.Value; + } + + if (secondsRemaining.HasValue) + { + progressRecord.SecondsRemaining = secondsRemaining.Value; + } + + progressRecord.RecordType = recordType; + + this.WriteProgress(progressRecord); + } + + private void WriteProgress(DateTime startTime, int currentCount, int expectedCount, string resourceId) + { + Dbg.Assert(currentCount > 0, "Progress shouldn't be written before 1 result is received"); + + string message = StringUtil.Format(resourceId, currentCount); + if (expectedCount <= 0) + { + this.WriteProgress(message, null, null); + } + else + { + double percentComplete = (double)currentCount / expectedCount; + int? secondsRemaining = ProgressRecord.GetSecondsRemaining(startTime, percentComplete); + + this.WriteProgress(message, (int)(100.0 * percentComplete), secondsRemaining); + } + } + + #endregion + + #region Generating a proxy module + + internal Guid ModuleGuid { get; } = Guid.NewGuid(); + + /// + /// Generates a proxy module in the given directory. + /// + /// Base directory for the module. + /// FileName prefix for module files. + /// Encoding of generated files. + /// Whether to overwrite files. + /// Remote commands to generate proxies for. + /// Dictionary mapping alias names to resolved command names. + /// Remote format data to generate format.ps1xml for. + /// Paths to generated files. + internal List GenerateProxyModule( + DirectoryInfo moduleRootDirectory, + string moduleNamePrefix, + Encoding encoding, + bool force, + List listOfCommandMetadata, + Dictionary alias2resolvedCommandName, + List listOfFormatData) + { + if (_commandsSkippedBecauseOfShadowing.Count != 0) + { + this.ReportSkippedCommands(); + + if (listOfCommandMetadata.Count == 0) + { + ErrorRecord error = this.GetErrorNoCommandsImportedBecauseOfSkipping(); + this.ThrowTerminatingError(error); + } + } + + ImplicitRemotingCodeGenerator codeGenerator = new( + this.Session, + this.ModuleGuid, + this.MyInvocation); + + List generatedFiles = codeGenerator.GenerateProxyModule( + moduleRootDirectory, + moduleNamePrefix, + encoding, + force, + listOfCommandMetadata, + alias2resolvedCommandName, + listOfFormatData, + Certificate); + + this.WriteProgress(StringUtil.Format(ImplicitRemotingStrings.ProgressStatusCompleted), 100, 0); + + return generatedFiles; + } + + #endregion + } + + internal sealed class ImplicitRemotingCodeGenerator + { + internal static readonly Version VersionOfScriptWriter = new(1, 0); + + #region Constructor and shared private data + + private readonly PSSession _remoteRunspaceInfo; + private readonly Guid _moduleGuid; + private readonly InvocationInfo _invocationInfo; + + internal ImplicitRemotingCodeGenerator( + PSSession remoteRunspaceInfo, + Guid moduleGuid, + InvocationInfo invocationInfo) + { + Dbg.Assert(remoteRunspaceInfo != null, "Caller should validate remoteRunspaceInfo != null"); + Dbg.Assert(moduleGuid != Guid.Empty, "Caller should validate moduleGuid is not empty"); + Dbg.Assert(invocationInfo != null, "Caller should validate invocationInfo != null"); + + _remoteRunspaceInfo = remoteRunspaceInfo; + _moduleGuid = moduleGuid; + _invocationInfo = invocationInfo; + } + + #endregion + + #region Code generation helpers + + /// + /// Gets a connection URI associated with the remote runspace. + /// + /// Connection URI associated with the remote runspace. + private string GetConnectionString() + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo connectionInfo) + { + return connectionInfo.ConnectionUri.ToString(); + } + + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) + { + return vmConnectionInfo.ComputerName; + } + + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) + { + return containerConnectionInfo.ComputerName; + } + + /* + wsman will also work with something that Uri.IsWellFormedUriString fails on: + http://[0000:0000:0000:0000:0000:0000:0000:0001]/wsman + Dbg.Assert( + Uri.IsWellFormedUriString(connectionString, UriKind.Absolute), + "GetConnectionString() should return only well formed uri strings"); + */ + return null; + } + + private static string EscapeFunctionNameForRemoteHelp(string name) + { + if (name == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(name)); + } + + StringBuilder result = new(name.Length); + foreach (char c in name) + { + if (!"\"'`$".Contains(c) + && !char.IsControl(c) + && !char.IsWhiteSpace(c)) + { + result.Append(c); + } + } + + return result.ToString(); + } + + private const string SectionSeparator = @" +############################################################################## +"; + + private static void GenerateSectionSeparator(TextWriter writer) + { + writer.Write(SectionSeparator); + } + + #endregion + + #region Generating manifest for proxy module + + private const string ManifestTemplate = @" +@{{ + GUID = '{0}' + Description = '{1}' + ModuleToProcess = @('{2}') + FormatsToProcess = @('{3}') + + ModuleVersion = '1.0' + + PrivateData = @{{ + ImplicitRemoting = $true + }} +}} + "; + + private void GenerateManifest(TextWriter writer, string psm1fileName, string formatPs1xmlFileName) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + GenerateTopComment(writer); + + writer.Write( + ManifestTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(_moduleGuid.ToString()), + CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ProxyModuleDescription, this.GetConnectionString())), + CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(psm1fileName)), + CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(formatPs1xmlFileName))); + } + + #endregion + + #region Generating header of a proxy module + + private const string TopCommentTemplate = @" +<# + # {0} + # {1} + # {2} + # {3} + #> + "; + + private void GenerateTopComment(TextWriter writer) + { + writer.Write( + TopCommentTemplate, + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderTitle)), + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderDate, DateTime.Now.ToString(CultureInfo.CurrentCulture))), + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderCommand, _invocationInfo.MyCommand.Name)), + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderCommandLine, _invocationInfo.Line))); + } + + private const string HeaderTemplate = @" +param( + <# {0} #> + [System.Management.Automation.Runspaces.PSSession] $PSSessionOverride, + [System.Management.Automation.Remoting.PSSessionOption] $PSSessionOptionOverride +) + +$script:__psImplicitRemoting_versionOfScriptGenerator = {1} +if ($script:__psImplicitRemoting_versionOfScriptGenerator.Major -ne {2}) +{{ + throw '{3}' +}} + +$script:WriteHost = $executionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:WriteWarning = $executionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:WriteInformation = $executionContext.InvokeCommand.GetCommand('Write-Information', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:GetPSSession = $executionContext.InvokeCommand.GetCommand('Get-PSSession', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:NewPSSession = $executionContext.InvokeCommand.GetCommand('New-PSSession', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:ConnectPSSession = $executionContext.InvokeCommand.GetCommand('Connect-PSSession', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:NewObject = $executionContext.InvokeCommand.GetCommand('New-Object', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:RemovePSSession = $executionContext.InvokeCommand.GetCommand('Remove-PSSession', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:InvokeCommand = $executionContext.InvokeCommand.GetCommand('Invoke-Command', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:SetItem = $executionContext.InvokeCommand.GetCommand('Set-Item', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:ImportCliXml = $executionContext.InvokeCommand.GetCommand('Import-CliXml', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:NewPSSessionOption = $executionContext.InvokeCommand.GetCommand('New-PSSessionOption', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:JoinPath = $executionContext.InvokeCommand.GetCommand('Join-Path', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:ExportModuleMember = $executionContext.InvokeCommand.GetCommand('Export-ModuleMember', [System.Management.Automation.CommandTypes]::Cmdlet) +$script:SetAlias = $executionContext.InvokeCommand.GetCommand('Set-Alias', [System.Management.Automation.CommandTypes]::Cmdlet) + +$script:MyModule = $MyInvocation.MyCommand.ScriptBlock.Module + "; + + private void GenerateModuleHeader(TextWriter writer) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + // In Win8, we are no longer loading all assemblies by default. + // So we need to use the fully qualified name when accessing a type in that assembly + Type type = typeof(ExportPSSessionCommand); + string asmName = type.Assembly.GetName().Name; + string versionOfScriptGenerator = $"[{type.FullName}, {asmName}]::VersionOfScriptGenerator"; + GenerateTopComment(writer); + writer.Write( + HeaderTemplate, + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderRunspaceOverrideParameter)), + versionOfScriptGenerator, + ImplicitRemotingCodeGenerator.VersionOfScriptWriter, + CodeGeneration.EscapeSingleQuotedStringContent(string.Format(null, PathUtilsStrings.ExportPSSession_ScriptGeneratorVersionMismatch, "Export-PSSession"))); + } + + #endregion + + #region Generating helper functions of a proxy module + + #region Write-PSImplicitRemotingMessage + + private const string HelperFunctionsWriteMessage = @" +function Write-PSImplicitRemotingMessage +{ + param( + [Parameter(Mandatory = $true, Position = 0)] + [string] + $message) + + try { & $script:WriteHost -Object $message -ErrorAction SilentlyContinue } catch { } +} +"; + + private static void GenerateHelperFunctionsWriteMessage(TextWriter writer) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + writer.Write(HelperFunctionsWriteMessage); + } + + #endregion + + #region Set-PSImplicitRemotingSession + + private const string HelperFunctionsSetImplicitRunspaceTemplate = @" +$script:PSSession = $null + +function Get-PSImplicitRemotingModuleName {{ $myInvocation.MyCommand.ScriptBlock.File }} + +function Set-PSImplicitRemotingSession +{{ + param( + [Parameter(Mandatory = $true, Position = 0)] + [AllowNull()] + [Management.Automation.Runspaces.PSSession] + $PSSession, + + [Parameter(Mandatory = $false, Position = 1)] + [bool] $createdByModule = $false) + + if ($null -ne $PSSession) + {{ + $script:PSSession = $PSSession + + if ($createdByModule -and ($null -ne $script:PSSession)) + {{ + $moduleName = Get-PSImplicitRemotingModuleName + $script:PSSession.Name = '{0}' -f $moduleName + + $oldCleanUpScript = $script:MyModule.OnRemove + $removePSSessionCommand = $script:RemovePSSession + $script:MyModule.OnRemove = {{ + & $removePSSessionCommand -Session $PSSession -ErrorAction SilentlyContinue + if ($oldCleanUpScript) + {{ + & $oldCleanUpScript $args + }} + }}.GetNewClosure() + }} + }} +}} + +if ($PSSessionOverride) {{ Set-PSImplicitRemotingSession $PSSessionOverride }} +"; + + private static void GenerateHelperFunctionsSetImplicitRunspace(TextWriter writer) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + string runspaceNameTemplate = StringUtil.Format(ImplicitRemotingStrings.ProxyRunspaceNameTemplate); + + writer.Write( + HelperFunctionsSetImplicitRunspaceTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(runspaceNameTemplate)); + } + + #endregion + + #region Get-PSImplicitRemotingSessionOption + + private const string HelperFunctionsGetSessionOptionTemplate = @" +function Get-PSImplicitRemotingSessionOption +{{ + if ($null -ne $PSSessionOptionOverride) + {{ + return $PSSessionOptionOverride + }} + else + {{ + return $({0}) + }} +}} +"; + + private void GenerateHelperFunctionsGetSessionOption(TextWriter writer) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + writer.Write( + HelperFunctionsGetSessionOptionTemplate, + GenerateNewPSSessionOption()); + } + + private PSPrimitiveDictionary GetApplicationArguments() + { + RemoteRunspace remoteRunspace = _remoteRunspaceInfo.Runspace as RemoteRunspace; + + Dbg.Assert(remoteRunspace != null, "PSSessionInfo should refer to a *remote* runspace"); + Dbg.Assert(remoteRunspace.RunspacePool != null, "All remote runspaces are implemented using a runspace pool"); + Dbg.Assert(remoteRunspace.RunspacePool != null, "All remote runspace pools have an internal implementation helper"); + + return remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.ApplicationArguments; + } + + private string GenerateNewPSSessionOption() + { + StringBuilder result = new("& $script:NewPSSessionOption "); + + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is RunspaceConnectionInfo runspaceConnectionInfo) + { + result.Append(null, $"-Culture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())}' "); + result.Append(null, $"-UICulture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())}' "); + + result.Append(null, $"-CancelTimeOut {runspaceConnectionInfo.CancelTimeout} "); + result.Append(null, $"-IdleTimeOut {runspaceConnectionInfo.IdleTimeout} "); + result.Append(null, $"-OpenTimeOut {runspaceConnectionInfo.OpenTimeout} "); + result.Append(null, $"-OperationTimeOut {runspaceConnectionInfo.OperationTimeout} "); + } + + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo) + { + if (!wsmanConnectionInfo.UseCompression) + { + result.Append("-NoCompression "); + } + + if (wsmanConnectionInfo.NoEncryption) + { + result.Append("-NoEncryption "); + } + + if (wsmanConnectionInfo.NoMachineProfile) + { + result.Append("-NoMachineProfile "); + } + + if (wsmanConnectionInfo.UseUTF16) + { + result.Append("-UseUTF16 "); + } + + if (wsmanConnectionInfo.SkipCACheck) + { + result.Append("-SkipCACheck "); + } + + if (wsmanConnectionInfo.SkipCNCheck) + { + result.Append("-SkipCNCheck "); + } + + if (wsmanConnectionInfo.SkipRevocationCheck) + { + result.Append("-SkipRevocationCheck "); + } + + if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) + { + result.Append(CultureInfo.InvariantCulture, $"-MaximumReceivedDataSizePerCommand {wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value} "); + } + + if (wsmanConnectionInfo.MaximumReceivedObjectSize.HasValue) + { + result.Append(CultureInfo.InvariantCulture, $"-MaximumReceivedObjectSize {wsmanConnectionInfo.MaximumReceivedObjectSize.Value} "); + } + + result.Append(CultureInfo.InvariantCulture, $"-MaximumRedirection {wsmanConnectionInfo.MaximumConnectionRedirectionCount} "); + + result.Append(CultureInfo.InvariantCulture, $"-ProxyAccessType {wsmanConnectionInfo.ProxyAccessType} "); + result.Append(CultureInfo.InvariantCulture, $"-ProxyAuthentication {wsmanConnectionInfo.ProxyAuthentication} "); + result.Append(this.GenerateProxyCredentialParameter(wsmanConnectionInfo)); + } + + PSPrimitiveDictionary applicationArguments = GetApplicationArguments(); + if (applicationArguments != null) + { + result.Append("-ApplicationArguments $("); + result.Append("& $script:ImportCliXml -Path $("); + result.Append("& $script:JoinPath -Path $PSScriptRoot -ChildPath ApplicationArguments.xml"); + result.Append(')'); + result.Append(") "); + } + + return result.ToString(); + } + + // index 0 - dialog title + // index 1 - dialog body + // index 2 - user name + // index 3 - target name (eventually passed to native CredUIPromptForCredentials as pszTargetName) + private const string ProxyCredentialParameterTemplate = + "-ProxyCredential ( $host.UI.PromptForCredential( '{0}', '{1}', '{2}', '{3}' ) ) "; + + private string GenerateProxyCredentialParameter(WSManConnectionInfo wsmanConnectionInfo) + { + if ((wsmanConnectionInfo == null) || (wsmanConnectionInfo.ProxyCredential == null)) + { + return string.Empty; + } + else + { + return string.Format( + CultureInfo.InvariantCulture, + ProxyCredentialParameterTemplate, + /* 0 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CredentialRequestTitle)), + /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ProxyCredentialRequestBody, this.GetConnectionString())), + /* 2 */ CodeGeneration.EscapeSingleQuotedStringContent(wsmanConnectionInfo.ProxyCredential.UserName), + /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.ComputerName + @"\httpproxy")); + } + } + + #endregion + + #region Get-PSImplicitRemotingSession + + // index 0 - remote runspace id + // index 1 - message template for new runspace + // index 2 - expression for getting a new runspace + // index 3 - message when no runspace is available + // index 4 - implicit remoting hash + // index 5 - message for mismatched implicit remoting hash + // index 6 - key for implicit remoting private data + // index 7 - key for implicit remoting hash + private const string HelperFunctionsGetImplicitRunspaceTemplate = @" +function Get-PSImplicitRemotingSession +{{ + param( + [Parameter(Mandatory = $true, Position = 0)] + [string] + $commandName + ) + + $savedImplicitRemotingHash = '{4}' + + if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened')) + {{ + Set-PSImplicitRemotingSession ` + (& $script:GetPSSession ` + -InstanceId {0} ` + -ErrorAction SilentlyContinue ) + }} + + if (($null -ne $script:PSSession) -and ($script:PSSession.Runspace.RunspaceStateInfo.State -eq 'Disconnected')) + {{ + # If we are handed a disconnected session, try re-connecting it before creating a new session. + Set-PSImplicitRemotingSession ` + (& $script:ConnectPSSession ` + -Session $script:PSSession ` + -ErrorAction SilentlyContinue) + }} + + if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened')) + {{ + Write-PSImplicitRemotingMessage ('{1}' -f $commandName) + + Set-PSImplicitRemotingSession ` + -CreatedByModule $true ` + -PSSession ( {2} ) + + if ($savedImplicitRemotingHash -ne '') + {{ + $newImplicitRemotingHash = [string]($script:PSSession.ApplicationPrivateData.{6}.{7}) + if ($newImplicitRemotingHash -ne $savedImplicitRemotingHash) + {{ + & $script:WriteWarning -Message '{5}' + }} + }} + + {8} + }} + + if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened')) + {{ + throw '{3}' + }} + + return [Management.Automation.Runspaces.PSSession]$script:PSSession +}} +"; + + private void GenerateHelperFunctionsGetImplicitRunspace(TextWriter writer) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + string hashString; + PSPrimitiveDictionary.TryPathGet( + _remoteRunspaceInfo.ApplicationPrivateData, + out hashString, + ImplicitRemotingCommandBase.ImplicitRemotingKey, + ImplicitRemotingCommandBase.ImplicitRemotingHashKey); + hashString ??= string.Empty; + + writer.Write( + HelperFunctionsGetImplicitRunspaceTemplate, + /* 0 */ _remoteRunspaceInfo.InstanceId, + /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CreateNewRunspaceMessageTemplate)), + /* 2 */ this.GenerateNewRunspaceExpression(), + /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ErrorNoRunspaceForThisModule)), + /* 4 */ CodeGeneration.EscapeSingleQuotedStringContent(hashString), + /* 5 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.WarningMismatchedImplicitRemotingHash)), + /* 6 */ ImplicitRemotingCommandBase.ImplicitRemotingKey, + /* 7 */ ImplicitRemotingCommandBase.ImplicitRemotingHashKey, + /* 8 */ this.GenerateReimportingOfModules()); + } + + private const string ReimportTemplate = @" + try {{ + & $script:InvokeCommand -Session $script:PSSession -ScriptBlock {{ + Get-Module -ListAvailable -Name '{0}' | Import-Module + }} -ErrorAction SilentlyContinue + }} catch {{ }} +"; + + private string GenerateReimportingOfModules() + { + StringBuilder result = new(); + + if (_invocationInfo.BoundParameters.ContainsKey(nameof(Module))) + { + string[] moduleNames = (string[])_invocationInfo.BoundParameters[nameof(Module)]; + foreach (string moduleName in moduleNames) + { + result.AppendFormat( + CultureInfo.InvariantCulture, + ReimportTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(moduleName)); + } + } + + return result.ToString(); + } + + #endregion + + #region New-Runspace expression + + // index 0 - connection uri (escaped for inclusion in single quoted string) + // index 1 - shell name (escaped for inclusion in single quoted string) + // index 2 - credential (empty string or parameter + value from $host.UI.PromptForCredential) + // index 3 - certificate thumbprint (empty string or full parameter + value) + // wsman specific: + // index 4 - authentication mechanism (empty string of full parameter + value) + // index 5 - allow redirection + private const string NewRunspaceTemplate = @" + $( + & $script:NewPSSession ` + {0} -ConfigurationName '{1}' ` + -SessionOption (Get-PSImplicitRemotingSessionOption) ` + {2} ` + {3} ` + {4} ` + {5} ` + ) +"; + + // index 0 - "-VMId " (VMId is used instead of VMName due to its uniqueness) + // index 1 - VM credential + // index 2 - "-ConfigurationName " or empty string + private const string NewVMRunspaceTemplate = @" + $( + & $script:NewPSSession ` + {0} ` + {1} ` + {2} ` + ) +"; + + // index 0 - "-ContainerId " + // index 1 - "-RunAsAdministrator" or empty string + // index 2 - "-ConfigurationName " or empty string + private const string NewContainerRunspaceTemplate = @" + $( + & $script:NewPSSession ` + {0} ` + {1} ` + {2} ` + ) +"; + + private string GenerateNewRunspaceExpression() + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) + { + string vmConfigurationName = vmConnectionInfo.ConfigurationName; + return string.Format( + CultureInfo.InvariantCulture, + NewVMRunspaceTemplate, + /* 0 */ this.GenerateConnectionStringForNewRunspace(), + /* 1 */ this.GenerateCredentialParameter(), + /* 2 */ string.IsNullOrEmpty(vmConfigurationName) ? string.Empty : string.Concat("-ConfigurationName ", vmConfigurationName)); + } + else + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) + { + string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; + return string.Format( + CultureInfo.InvariantCulture, + NewContainerRunspaceTemplate, + /* 0 */ this.GenerateConnectionStringForNewRunspace(), + /* 1 */ containerConnectionInfo.ContainerProc.RunAsAdmin ? "-RunAsAdministrator" : string.Empty, + /* 2 */ string.IsNullOrEmpty(containerConfigurationName) ? string.Empty : string.Concat("-ConfigurationName ", containerConfigurationName)); + } + else + { + return string.Format( + CultureInfo.InvariantCulture, + NewRunspaceTemplate, + /* 0 */ this.GenerateConnectionStringForNewRunspace(), + /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.ConfigurationName), + /* 2 */ this.GenerateCredentialParameter(), + /* 3 */ this.GenerateCertificateThumbprintParameter(), + /* 4 */ this.GenerateAuthenticationMechanismParameter(), + /* 5 */ this.GenerateAllowRedirectionParameter()); + } + } + } + + private const string ComputerNameParameterTemplate = @"-ComputerName '{0}' ` + -ApplicationName '{1}' {2} {3} "; + + private const string VMIdParameterTemplate = @"-VMId '{0}' "; + private const string ContainerIdParameterTemplate = @"-ContainerId '{0}' "; + + /// + /// This is needed to work with Default Port DCR change from WSMan. See BUG + /// 542726. If http/https is specified in the connectionURI and no port is + /// specified then defaults for http/https (80/443) are applied. But WSMan + /// by default listens on 5985/5986. To overcome this, this function + /// creates a -ComputerName parameter set or -ConnectionUri parameter + /// set depending on the situation. + /// + /// + private string GenerateConnectionStringForNewRunspace() + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo connectionInfo) + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) + { + return string.Format(CultureInfo.InvariantCulture, + VMIdParameterTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(vmConnectionInfo.VMGuid.ToString())); + } + + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) + { + return string.Format(CultureInfo.InvariantCulture, + ContainerIdParameterTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(containerConnectionInfo.ContainerProc.ContainerId)); + } + + return null; + } + + if (connectionInfo.UseDefaultWSManPort) + { + bool isSSLSpecified; + WSManConnectionInfo.GetConnectionString(connectionInfo.ConnectionUri, out isSSLSpecified); + return string.Format(CultureInfo.InvariantCulture, + ComputerNameParameterTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(connectionInfo.ComputerName), + CodeGeneration.EscapeSingleQuotedStringContent(connectionInfo.AppName), + connectionInfo.UseDefaultWSManPort ? + string.Empty : + string.Create(CultureInfo.InvariantCulture, $"-Port {connectionInfo.Port} "), + isSSLSpecified ? "-useSSL" : string.Empty); + } + else + { + string connectionString = CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString()); + return string.Create(CultureInfo.InvariantCulture, $"-connectionUri '{connectionString}'"); + } + } + + private string GenerateAllowRedirectionParameter() + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo wsmanConnectionInfo) + { + return string.Empty; + } + + if (wsmanConnectionInfo.MaximumConnectionRedirectionCount != 0) + { + return "-AllowRedirection"; + } + else + { + return string.Empty; + } + } + + private const string AuthenticationMechanismParameterTemplate = "-Authentication {0}"; + + private string GenerateAuthenticationMechanismParameter() + { + // comment in newrunspacecommand.cs says that -CertificateThumbprint + // and AuthenticationMechanism are mutually exclusive + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint != null) + { + return string.Empty; + } + + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo wsmanConnectionInfo) + { + return string.Empty; + } + + return string.Format( + CultureInfo.InvariantCulture, + AuthenticationMechanismParameterTemplate, + wsmanConnectionInfo.AuthenticationMechanism.ToString()); + } + + // index 0 - dialog title + // index 1 - dialog body + // index 2 - user name + // index 3 - target name (eventually passed to native CredUIPromptForCredentials as pszTargetName) + private const string CredentialParameterTemplate = + "-Credential ( $host.UI.PromptForCredential( '{0}', '{1}', '{2}', '{3}' ) )"; + + private string GenerateCredentialParameter() + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.Credential == null) + { + return string.Empty; + } + else + { + return string.Format( + CultureInfo.InvariantCulture, + CredentialParameterTemplate, + /* 0 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CredentialRequestTitle)), + /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CredentialRequestBody, this.GetConnectionString())), + /* 2 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.Runspace.ConnectionInfo.Credential.UserName), + /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.ComputerName)); + } + } + + private const string CertificateThumbprintParameterTemplate = "-CertificateThumbprint '{0}'"; + + private string GenerateCertificateThumbprintParameter() + { + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint == null) + { + return string.Empty; + } + else + { + return string.Format( + CultureInfo.InvariantCulture, + CertificateThumbprintParameterTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint)); + } + } + + #endregion + + #region Get-ClientSideParameters + + private const string HelperFunctionsModifyParameters = @" +function Modify-PSImplicitRemotingParameters +{ + param( + [Parameter(Mandatory = $true, Position = 0)] + [hashtable] + $clientSideParameters, + + [Parameter(Mandatory = $true, Position = 1)] + $PSBoundParameters, + + [Parameter(Mandatory = $true, Position = 2)] + [string] + $parameterName, + + [Parameter()] + [switch] + $leaveAsRemoteParameter) + + if ($PSBoundParameters.ContainsKey($parameterName)) + { + $clientSideParameters.Add($parameterName, $PSBoundParameters[$parameterName]) + if (-not $leaveAsRemoteParameter) { + $null = $PSBoundParameters.Remove($parameterName) + } + } +} + +function Get-PSImplicitRemotingClientSideParameters +{ + param( + [Parameter(Mandatory = $true, Position = 1)] + $PSBoundParameters, + + [Parameter(Mandatory = $true, Position = 2)] + $proxyForCmdlet) + + $clientSideParameters = @{} + + $parametersToLeaveRemote = 'ErrorAction', 'WarningAction', 'InformationAction', 'ProgressAction' + + Modify-PSImplicitRemotingParameters $clientSideParameters $PSBoundParameters 'AsJob' + if ($proxyForCmdlet) + { + foreach($parameter in [System.Management.Automation.Cmdlet]::CommonParameters) + { + if($parametersToLeaveRemote -contains $parameter) + { + Modify-PSImplicitRemotingParameters $clientSideParameters $PSBoundParameters $parameter -LeaveAsRemoteParameter + } + else + { + Modify-PSImplicitRemotingParameters $clientSideParameters $PSBoundParameters $parameter + } + } + } + + return $clientSideParameters +} +"; + + private static void GenerateHelperFunctionsClientSideParameters(TextWriter writer) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + writer.Write(HelperFunctionsModifyParameters); + } + + #endregion + + private void GenerateHelperFunctions(TextWriter writer) + { + GenerateSectionSeparator(writer); + GenerateHelperFunctionsWriteMessage(writer); + this.GenerateHelperFunctionsGetSessionOption(writer); + GenerateHelperFunctionsSetImplicitRunspace(writer); + this.GenerateHelperFunctionsGetImplicitRunspace(writer); + GenerateHelperFunctionsClientSideParameters(writer); + } + + #endregion + + #region Generating proxy commands + + // index 0 - name of the command escaped for inclusion inside a single-quoted string + // index 1 - name of the command escaped for help comment + // index 2 - not used + // index 3 - param declaration + // index 4 - not used + // index 5 - remote help category + // index 6 - process block + // index 7 - end block + // index 8 - whether or not this is a proxy for a cmdlet-bound command (i.e. should common parameters get special handling) + private const string CommandProxyTemplate = @" +& $script:SetItem 'function:script:{0}' ` +{{ + param( + {3}) + + Begin {{ + try {{ + $positionalArguments = & $script:NewObject collections.arraylist + foreach ($parameterName in $PSBoundParameters.BoundPositionally) + {{ + $null = $positionalArguments.Add( $PSBoundParameters[$parameterName] ) + $null = $PSBoundParameters.Remove($parameterName) + }} + + $positionalArguments.AddRange($args) + + $clientSideParameters = Get-PSImplicitRemotingClientSideParameters $PSBoundParameters ${8} + + $scriptCmd = {{ + & $script:InvokeCommand ` + @clientSideParameters ` + -HideComputerName ` + -Session (Get-PSImplicitRemotingSession -CommandName '{0}') ` + -Arg ('{0}', $PSBoundParameters, $positionalArguments) ` + -Script {{ param($name, $boundParams, $unboundParams) & $name @boundParams @unboundParams }} ` + }} + + $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) + $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext) + }} catch {{ + throw + }} + }} + + Process {{ {6} }} + + End {{ {7} }} + + # .ForwardHelpTargetName {1} + # .ForwardHelpCategory {5} + # .RemoteHelpRunspace PSSession +}} + "; + + private static void GenerateCommandProxy(TextWriter writer, CommandMetadata commandMetadata) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + string functionNameForString = CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name); + string functionNameForHelp = EscapeFunctionNameForRemoteHelp(commandMetadata.Name); + writer.Write( + CommandProxyTemplate, + /* 0 */ functionNameForString, + /* 1 */ functionNameForHelp, + /* 2 */ commandMetadata.GetDecl(), + /* 3 */ commandMetadata.GetParamBlock(), + /* 4 */ null /* not used */, + /* 5 */ commandMetadata.WrappedCommandType, + /* 6 */ ProxyCommand.GetProcess(commandMetadata), + /* 7 */ ProxyCommand.GetEnd(commandMetadata), + /* 8 */ commandMetadata.WrappedAnyCmdlet); + } + + private static void GenerateCommandProxy(TextWriter writer, IEnumerable listOfCommandMetadata) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + if (listOfCommandMetadata == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); + } + + GenerateSectionSeparator(writer); + foreach (CommandMetadata commandMetadata in listOfCommandMetadata) + { + GenerateCommandProxy(writer, commandMetadata); + } + } + + #endregion + + #region Generating export declaration of a proxy module + + private const string ExportFunctionsTemplate = @" +& $script:ExportModuleMember -Function {0} + "; + + private static void GenerateExportDeclaration(TextWriter writer, IEnumerable listOfCommandMetadata) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + if (listOfCommandMetadata == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); + } + + GenerateSectionSeparator(writer); + + List listOfCommandNames = GetListOfCommandNames(listOfCommandMetadata); + string exportString = GenerateArrayString(listOfCommandNames); + writer.Write(ExportFunctionsTemplate, exportString); + } + + private static List GetListOfCommandNames(IEnumerable listOfCommandMetadata) + { + if (listOfCommandMetadata == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); + } + + List listOfCommandNames = new(); + foreach (CommandMetadata commandMetadata in listOfCommandMetadata) + { + listOfCommandNames.Add(commandMetadata.Name); + } + + return listOfCommandNames; + } + + private static string GenerateArrayString(IEnumerable listOfStrings) + { + if (listOfStrings == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(listOfStrings)); + } + + StringBuilder arrayString = new(); + foreach (string s in listOfStrings) + { + if (arrayString.Length != 0) + { + arrayString.Append(", "); + } + + arrayString.Append('\''); + arrayString.Append(CodeGeneration.EscapeSingleQuotedStringContent(s)); + arrayString.Append('\''); + } + + arrayString.Insert(0, "@("); + arrayString.Append(')'); + + return arrayString.ToString(); + } + + #endregion + + #region Generating aliases + + private const string SetAliasTemplate = @" +& $script:SetAlias -Name '{0}' -Value '{1}' -Force -Scope script + "; + + private const string ExportAliasesTemplate = @" +& $script:ExportModuleMember -Alias {0} + "; + + private static void GenerateAliases(TextWriter writer, Dictionary alias2resolvedCommandName) + { + GenerateSectionSeparator(writer); + + foreach (KeyValuePair pair in alias2resolvedCommandName) + { + string aliasName = pair.Key; + string resolvedCommandName = pair.Value; + + writer.Write( + SetAliasTemplate, + CodeGeneration.EscapeSingleQuotedStringContent(aliasName), + CodeGeneration.EscapeSingleQuotedStringContent(resolvedCommandName)); + } + + string exportString = GenerateArrayString(alias2resolvedCommandName.Keys); + writer.Write(ExportAliasesTemplate, exportString); + } + + #endregion + + #region Generating format.ps1xml file + + private static void GenerateFormatFile(TextWriter writer, List listOfFormatData) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(writer)); + } + + if (listOfFormatData == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(listOfFormatData)); + } + + XmlWriterSettings settings = new(); + settings.CloseOutput = false; + settings.ConformanceLevel = ConformanceLevel.Document; + settings.Encoding = writer.Encoding; + settings.Indent = true; + using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings)) + { + FormatXmlWriter.WriteToXml(xmlWriter, listOfFormatData, false); + } + } + + #endregion + + /// + /// Generates a proxy module in the given directory. + /// + /// Base directory for the module. + /// Filename prefix for module files. + /// Encoding of generated files. + /// Whether to overwrite files. + /// Remote commands to generate proxies for. + /// Dictionary mapping alias names to resolved command names. + /// Remote format data to generate format.ps1xml for. + /// Certificate with which to sign the format files. + /// Path to the created files. + internal List GenerateProxyModule( + DirectoryInfo moduleRootDirectory, + string fileNamePrefix, + Encoding encoding, + bool force, + List listOfCommandMetadata, + Dictionary alias2resolvedCommandName, + List listOfFormatData, + X509Certificate2 certificate) + { + List result = new(); + + Dbg.Assert(moduleRootDirectory != null, "Caller should validate moduleRootDirectory != null"); + Dbg.Assert(Directory.Exists(moduleRootDirectory.FullName), "Caller should validate moduleRootDirectory exists"); + Dbg.Assert(encoding != null, "Caller should validate encoding != null"); + + string baseName = Path.Combine(moduleRootDirectory.FullName, fileNamePrefix); + FileMode fileMode = force ? FileMode.OpenOrCreate : FileMode.CreateNew; + + result.Add(baseName + ".psm1"); + FileStream psm1 = new( + baseName + ".psm1", + fileMode, + FileAccess.Write, + FileShare.None); + using (TextWriter writer = new StreamWriter(psm1, encoding)) + { + listOfCommandMetadata ??= new List(); + + GenerateModuleHeader(writer); + GenerateHelperFunctions(writer); + GenerateCommandProxy(writer, listOfCommandMetadata); + GenerateExportDeclaration(writer, listOfCommandMetadata); + GenerateAliases(writer, alias2resolvedCommandName); + psm1.SetLength(psm1.Position); + } + + result.Add(baseName + ".format.ps1xml"); + FileStream formatPs1xml = new( + baseName + ".format.ps1xml", + fileMode, + FileAccess.Write, + FileShare.None); + using (TextWriter writer = new StreamWriter(formatPs1xml, encoding)) + { + listOfFormatData ??= new List(); + + GenerateFormatFile(writer, listOfFormatData); + formatPs1xml.SetLength(formatPs1xml.Position); + } + // Sign psm1 file and format file + // If certificate is passed, sign the file + // If certificate is not passed and executionPolicy is set to Restricted/AllSigned, output error + // Since we will anyway be erroring out during Import-Module, it is better to fail fast + ExecutionPolicy executionPolicy = SecuritySupport.GetExecutionPolicy(Utils.DefaultPowerShellShellID); + if (executionPolicy == ExecutionPolicy.Restricted || executionPolicy == ExecutionPolicy.AllSigned) + { + if (certificate == null) + { + string message = ImplicitRemotingStrings.CertificateNeeded; + throw new PSInvalidOperationException(message); + } + else + { + string currentFile = baseName + ".psm1"; + try + { + SignatureHelper.SignFile(SigningOption.Default, currentFile, certificate, string.Empty, null); + currentFile = baseName + ".format.ps1xml"; + SignatureHelper.SignFile(SigningOption.Default, currentFile, certificate, string.Empty, null); + } + catch (Exception e) + { + string message = StringUtil.Format(ImplicitRemotingStrings.InvalidSigningOperation, currentFile); + throw new PSInvalidOperationException(message, e); + } + } + } + + result.Add(baseName + ".psd1"); + FileInfo manifestFile = new(baseName + ".psd1"); + FileStream psd1 = new( + manifestFile.FullName, + fileMode, + FileAccess.Write, + FileShare.None); + using (TextWriter writer = new StreamWriter(psd1, encoding)) + { + GenerateManifest(writer, baseName + ".psm1", baseName + ".format.ps1xml"); + psd1.SetLength(psd1.Position); + } + + PSPrimitiveDictionary applicationArguments = GetApplicationArguments(); + if (applicationArguments != null) + { + string applicationArgumentsFile = Path.Combine(moduleRootDirectory.FullName, "ApplicationArguments.xml"); + result.Add(applicationArgumentsFile); + + using (var stream = new FileStream(applicationArgumentsFile, FileMode.Create, FileAccess.Write, FileShare.Read)) + using (var xmlWriter = XmlWriter.Create(stream)) + { + Serializer serializer = new(xmlWriter); + serializer.Serialize(applicationArguments); + serializer.Done(); + } + } + + return result; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs new file mode 100644 index 0000000000000000000000000000000000000000..c4e423ffd1d497b1e219b1a310faae333a3ddb85 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -0,0 +1,407 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Security; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "import-localizeddata" cmdlet. + /// + [Cmdlet(VerbsData.Import, "LocalizedData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096710")] + public sealed class ImportLocalizedData : PSCmdlet + { + #region Parameters + + /// + /// The path from which to import the aliases. + /// + [Parameter(Position = 0)] + [Alias("Variable")] + [ValidateNotNullOrEmpty] + public string BindingVariable + { + get + { + return _bindingVariable; + } + + set + { + _bindingVariable = value; + } + } + + private string _bindingVariable; + + /// + /// The scope to import the aliases to. + /// + [Parameter(Position = 1)] + public string UICulture + { + get + { + return _uiculture; + } + + set + { + _uiculture = value; + } + } + + private string _uiculture; + + /// + /// The scope to import the aliases to. + /// + [Parameter] + public string BaseDirectory + { + get + { + return _baseDirectory; + } + + set + { + _baseDirectory = value; + } + } + + private string _baseDirectory; + + /// + /// The scope to import the aliases to. + /// + [Parameter] + public string FileName + { + get + { + return _fileName; + } + + set + { + _fileName = value; + } + } + + private string _fileName; + + /// + /// The command allowed in the data file. If unspecified, then ConvertFrom-StringData is allowed. + /// + [Parameter] + [ValidateTrustedData] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + public string[] SupportedCommand + { + get + { + return _commandsAllowed; + } + + set + { + _setSupportedCommand = true; + _commandsAllowed = value; + } + } + + private string[] _commandsAllowed = new string[] { "ConvertFrom-StringData" }; + private bool _setSupportedCommand = false; + + #endregion Parameters + + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + string path = GetFilePath(); + + if (path == null) + { + return; + } + + if (!File.Exists(path)) + { + InvalidOperationException ioe = + PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.FileNotExist, + path); + WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, path)); + return; + } + + // Prevent additional commands in ConstrainedLanguage mode + if (_setSupportedCommand && Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + { + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + NotSupportedException nse = + PSTraceSource.NewNotSupportedException( + ImportLocalizedDataStrings.CannotDefineSupportedCommand); + ThrowTerminatingError( + new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: ImportLocalizedDataStrings.WDACLogTitle, + message: ImportLocalizedDataStrings.WDACLogMessage, + fqid: "SupportedCommandsDisabled", + dropIntoDebugger: true); + } + + string script = GetScript(path); + if (script == null) + { + return; + } + + try + { + var scriptBlock = Context.Engine.ParseScriptBlock(script, false); + scriptBlock.CheckRestrictedLanguage(SupportedCommand, null, false); + object result; + PSLanguageMode oldLanguageMode = Context.LanguageMode; + Context.LanguageMode = PSLanguageMode.RestrictedLanguage; + try + { + result = scriptBlock.InvokeReturnAsIs(); + if (result == AutomationNull.Value) + { + result = null; + } + } + finally + { + Context.LanguageMode = oldLanguageMode; + } + + if (_bindingVariable != null) + { + VariablePath variablePath = new(_bindingVariable); + if (variablePath.IsUnscopedVariable) + { + variablePath = variablePath.CloneAndSetLocal(); + } + + if (string.IsNullOrEmpty(variablePath.UnqualifiedPath)) + { + InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.IncorrectVariableName, _bindingVariable); + WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.InvalidArgument, + _bindingVariable)); + return; + } + + SessionStateScope scope = null; + PSVariable variable = SessionState.Internal.GetVariableItem(variablePath, out scope); + + if (variable == null) + { + variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None); + Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal); + } + else + { + variable.Value = result; + + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + { + // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in + // a module scope, if it's necessary. + ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(variable, scope, Context.EngineSessionState); + } + } + } + + // If binding variable is null, write the object to stream + else + { + WriteObject(result); + } + } + catch (RuntimeException e) + { + PSInvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(e, + ImportLocalizedDataStrings.ErrorLoadingDataFile, + path, + e.Message); + + throw ioe; + } + + return; + } + + private string GetFilePath() + { + if (string.IsNullOrEmpty(_fileName)) + { + if (InvocationExtent == null || string.IsNullOrEmpty(InvocationExtent.File)) + { + throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.NotCalledFromAScriptFile); + } + } + + string dir = _baseDirectory; + + if (string.IsNullOrEmpty(dir)) + { + if (InvocationExtent != null && !string.IsNullOrEmpty(InvocationExtent.File)) + { + dir = Path.GetDirectoryName(InvocationExtent.File); + } + else + { + dir = "."; + } + } + + dir = PathUtils.ResolveFilePath(dir, this); + + string fileName = _fileName; + if (string.IsNullOrEmpty(fileName)) + { + fileName = InvocationExtent.File; + } + else + { + if (!string.IsNullOrEmpty(Path.GetDirectoryName(fileName))) + { + throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.FileNameParameterCannotHavePath); + } + } + + fileName = Path.GetFileNameWithoutExtension(fileName); + + CultureInfo culture; + if (_uiculture == null) + { + culture = CultureInfo.CurrentUICulture; + } + else + { + try + { + culture = CultureInfo.GetCultureInfo(_uiculture); + } + catch (ArgumentException) + { + throw PSTraceSource.NewArgumentException("Culture"); + } + } + + List cultureList = new List { culture }; + if (_uiculture == null && culture.Name != "en-US") + { + // .NET 4.8 presents en-US as a parent of any current culture when accessed via the CurrentUICulture + // property. + // + // This feature is not present when GetCultureInfo is called, therefore this fallback change only + // applies when the UICulture parameter is not supplied. + cultureList.Add(CultureInfo.GetCultureInfo("en-US")); + } + + string filePath; + string fullFileName = fileName + ".psd1"; + foreach (CultureInfo cultureToTest in cultureList) + { + CultureInfo currentCulture = cultureToTest; + while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name)) + { + filePath = Path.Combine(dir, currentCulture.Name, fullFileName); + + if (File.Exists(filePath)) + { + return filePath; + } + + currentCulture = currentCulture.Parent; + } + } + + filePath = Path.Combine(dir, fullFileName); + + if (File.Exists(filePath)) + { + return filePath; + } + + InvalidOperationException ioe = + PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.CannotFindPsd1File, + fullFileName, + Path.Combine(dir, culture.Name) + ); + WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, + Path.Combine(dir, culture.Name, fullFileName))); + return null; + } + + private string GetScript(string filePath) + { + InvalidOperationException ioe = null; + try + { + // 197751: WR BUG BASH: Powershell: localized text display as garbage + // leaving the encoding to be decided by the StreamReader. StreamReader + // will read the preamble and decide proper encoding. + using (FileStream scriptStream = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (StreamReader scriptReader = new(scriptStream)) + { + return scriptReader.ReadToEnd(); + } + } + catch (ArgumentException e) + { + ioe = PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.ErrorOpeningFile, + filePath, + e.Message); + } + catch (IOException e) + { + ioe = PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.ErrorOpeningFile, + filePath, + e.Message); + } + catch (NotSupportedException e) + { + ioe = PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.ErrorOpeningFile, + filePath, + e.Message); + } + catch (UnauthorizedAccessException e) + { + ioe = PSTraceSource.NewInvalidOperationException( + ImportLocalizedDataStrings.ErrorOpeningFile, + filePath, + e.Message); + } + + WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.OpenError, filePath)); + return null; + } + + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..657d00b4fc547919b200fcf9f93c376008b3ece1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -0,0 +1,484 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "import-alias" cmdlet. + /// + [Cmdlet(VerbsData.Import, "Alias", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097125")] + [OutputType(typeof(AliasInfo))] + public class ImportAliasCommand : PSCmdlet + { + #region Statics + + private const string LiteralPathParameterSetName = "ByLiteralPath"; + + #endregion + + #region Parameters + + /// + /// The path from which to import the aliases. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + public string Path { get; set; } + + /// + /// The literal path from which to import the aliases. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = LiteralPathParameterSetName)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return Path; + } + + set + { + Path = value; + } + } + + /// + /// The scope to import the aliases to. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + /// + /// If set to true, the alias that is set is passed to the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThru; + } + + set + { + _passThru = value; + } + } + + private bool _passThru; + + /// + /// If set to true and an existing alias of the same name exists + /// and is ReadOnly, the alias will be overwritten. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + #endregion Parameters + + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + Collection importedAliases = GetAliasesFromFile(this.ParameterSetName.Equals(LiteralPathParameterSetName, + StringComparison.OrdinalIgnoreCase)); + + CommandOrigin origin = MyInvocation.CommandOrigin; + + foreach (AliasInfo alias in importedAliases) + { + // If not force, then see if the alias already exists + + // NTRAID#Windows Out Of Band Releases-906910-2006/03/17-JonN + string action = AliasCommandStrings.ImportAliasAction; + + string target = StringUtil.Format(AliasCommandStrings.ImportAliasTarget, alias.Name, alias.Definition); + + if (!ShouldProcess(target, action)) + continue; + + if (!Force) + { + AliasInfo existingAlias = null; + if (string.IsNullOrEmpty(Scope)) + { + existingAlias = SessionState.Internal.GetAlias(alias.Name); + } + else + { + existingAlias = SessionState.Internal.GetAliasAtScope(alias.Name, Scope); + } + + if (existingAlias != null) + { + // Write an error for aliases that aren't visible... + try + { + SessionState.ThrowIfNotVisible(origin, existingAlias); + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + // Only report the error once... + continue; + } + + // Since the alias already exists, write an error. + + SessionStateException aliasExists = + new( + alias.Name, + SessionStateCategory.Alias, + "AliasAlreadyExists", + SessionStateStrings.AliasAlreadyExists, + ErrorCategory.ResourceExists); + + WriteError( + new ErrorRecord( + aliasExists.ErrorRecord, + aliasExists)); + continue; + } + + if (VerifyShadowingExistingCommandsAndWriteError(alias.Name)) + { + continue; + } + } + + // Set the alias in the specified scope or the + // current scope. + + AliasInfo result = null; + + try + { + if (string.IsNullOrEmpty(Scope)) + { + result = SessionState.Internal.SetAliasItem(alias, Force, MyInvocation.CommandOrigin); + } + else + { + result = SessionState.Internal.SetAliasItemAtScope(alias, Scope, Force, MyInvocation.CommandOrigin); + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + continue; + } + catch (PSArgumentOutOfRangeException argOutOfRange) + { + WriteError( + new ErrorRecord( + argOutOfRange.ErrorRecord, + argOutOfRange)); + continue; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + continue; + } + + // Write the alias to the pipeline if PassThru was specified + + if (PassThru && result != null) + { + WriteObject(result); + } + } + } + + private Dictionary _existingCommands; + + private Dictionary ExistingCommands + { + get + { + if (_existingCommands == null) + { + _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); + CommandSearcher searcher = new( + "*", + SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, + CommandTypes.All ^ CommandTypes.Alias, + this.Context); + + foreach (CommandInfo commandInfo in searcher) + { + _existingCommands[commandInfo.Name] = commandInfo.CommandType; + } + + // Also add commands from the analysis cache + foreach (CommandInfo commandInfo in System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands("*", this.Context, this.MyInvocation.CommandOrigin)) + { + if (!_existingCommands.ContainsKey(commandInfo.Name)) + { + _existingCommands[commandInfo.Name] = commandInfo.CommandType; + } + } + } + + return _existingCommands; + } + } + + private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName) + { + CommandSearcher searcher = new(aliasName, SearchResolutionOptions.None, CommandTypes.All ^ CommandTypes.Alias, this.Context); + foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(aliasName)) + { + CommandTypes commandTypeOfExistingCommand; + if (this.ExistingCommands.TryGetValue(expandedCommandName, out commandTypeOfExistingCommand)) + { + // Since the alias already exists, write an error. + SessionStateException aliasExists = + new( + aliasName, + SessionStateCategory.Alias, + "AliasAlreadyExists", + SessionStateStrings.AliasWithCommandNameAlreadyExists, + ErrorCategory.ResourceExists, + commandTypeOfExistingCommand); + + WriteError( + new ErrorRecord( + aliasExists.ErrorRecord, + aliasExists)); + return true; + } + } + + return false; + } + + private Collection GetAliasesFromFile(bool isLiteralPath) + { + Collection result = new(); + + string filePath = null; + using (StreamReader reader = OpenFile(out filePath, isLiteralPath)) + { + CSVHelper csvHelper = new(','); + + long lineNumber = 0; + string line = null; + while ((line = reader.ReadLine()) != null) + { + ++lineNumber; + + // Ignore blank lines + if (line.Length == 0) + { + continue; + } + + // Ignore lines that only contain whitespace + if (OnlyContainsWhitespace(line)) + { + continue; + } + + // Ignore comment lines + if (line[0] == '#') + { + continue; + } + + Collection values = csvHelper.ParseCsv(line); + + if (values.Count != 4) + { + string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, lineNumber); + + FormatException formatException = + new(message); + + ErrorRecord errorRecord = + new( + formatException, + "ImportAliasFileFormatError", + ErrorCategory.ReadError, + filePath); + + errorRecord.ErrorDetails = new ErrorDetails(message); + + ThrowTerminatingError(errorRecord); + } + + ScopedItemOptions options = ScopedItemOptions.None; + + try + { + options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), values[3], true); + } + catch (ArgumentException argException) + { + string message = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, lineNumber); + + ErrorRecord errorRecord = + new( + argException, + "ImportAliasOptionsError", + ErrorCategory.ReadError, + filePath); + + errorRecord.ErrorDetails = new ErrorDetails(message); + WriteError(errorRecord); + continue; + } + + AliasInfo newAlias = + new( + values[0], + values[1], + Context, + options); + + if (!string.IsNullOrEmpty(values[2])) + { + newAlias.Description = values[2]; + } + + result.Add(newAlias); + } + + reader.Dispose(); + } + + return result; + } + + private StreamReader OpenFile(out string filePath, bool isLiteralPath) + { + StreamReader result = null; + + filePath = null; + ProviderInfo provider = null; + Collection paths = null; + + if (isLiteralPath) + { + paths = new Collection(); + PSDriveInfo drive; + paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.Path, out provider, out drive)); + } + else + { + // first resolve the path + paths = SessionState.Path.GetResolvedProviderPathFromPSPath(this.Path, out provider); + } + + // We can only export aliases to the file system + if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) + { + throw + PSTraceSource.NewNotSupportedException( + AliasCommandStrings.ImportAliasFromFileSystemOnly, + this.Path, + provider.FullName); + } + + // We can only write to a single file at a time. + if (paths.Count != 1) + { + throw + PSTraceSource.NewNotSupportedException( + AliasCommandStrings.ImportAliasPathResolvedToMultiple, + this.Path); + } + + filePath = paths[0]; + + try + { + FileStream file = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + result = new StreamReader(file); + } + catch (IOException ioException) + { + ThrowFileOpenError(ioException, filePath); + } + catch (SecurityException securityException) + { + ThrowFileOpenError(securityException, filePath); + } + catch (UnauthorizedAccessException unauthorizedAccessException) + { + ThrowFileOpenError(unauthorizedAccessException, filePath); + } + + return result; + } + + private void ThrowFileOpenError(Exception e, string pathWithError) + { + string message = + StringUtil.Format(AliasCommandStrings.ImportAliasFileOpenFailed, pathWithError, e.Message); + + ErrorRecord errorRecord = new( + e, + "FileOpenFailure", + ErrorCategory.OpenError, + pathWithError); + + errorRecord.ErrorDetails = new ErrorDetails(message); + this.ThrowTerminatingError(errorRecord); + } + + private static bool OnlyContainsWhitespace(string line) + { + bool result = true; + + foreach (char c in line) + { + if (char.IsWhiteSpace(c) && c != '\n' && c != '\r') + { + continue; + } + + result = false; + break; + } + + return result; + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs new file mode 100644 index 0000000000000000000000000000000000000000..5661df24fa9a2b2ce0f7688e6dbbfc327e0b30b7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Management.Automation.Language; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Import-PowerShellDataFile command. + /// + [Cmdlet(VerbsData.Import, "PowerShellDataFile", DefaultParameterSetName = "ByPath", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=623621", RemotingCapability = RemotingCapability.None)] + public class ImportPowerShellDataFileCommand : PSCmdlet + { + private bool _isLiteralPath; + + /// + /// Path specified, using globbing to resolve. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Path { get; set; } + + /// + /// Specifies a path to one or more locations, without globbing. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get { return _isLiteralPath ? Path : null; } + + set { _isLiteralPath = true; Path = value; } + } + + /// + /// Gets or sets switch that determines if built-in limits are applied to the data. + /// + [Parameter] + public SwitchParameter SkipLimitCheck { get; set; } + + /// + /// For each path, resolve it, parse it and write all hashtables to the output stream. + /// + protected override void ProcessRecord() + { + foreach (var path in Path) + { + var resolved = PathUtils.ResolveFilePath(path, this, _isLiteralPath); + if (!string.IsNullOrEmpty(resolved) && System.IO.File.Exists(resolved)) + { + Token[] tokens; + ParseError[] errors; + var ast = Parser.ParseFile(resolved, out tokens, out errors); + if (errors.Length > 0) + { + WriteInvalidDataFileError(resolved, "CouldNotParseAsPowerShellDataFile"); + } + else + { + var data = ast.Find(static a => a is HashtableAst, false); + if (data != null) + { + WriteObject(data.SafeGetValue(SkipLimitCheck)); + } + else + { + WriteInvalidDataFileError(resolved, "CouldNotParseAsPowerShellDataFileNoHashtableRoot"); + } + } + } + else + { + WritePathNotFoundError(path); + } + } + } + + private void WritePathNotFoundError(string path) + { + const string errorId = "PathNotFound"; + const ErrorCategory errorCategory = ErrorCategory.InvalidArgument; + var errorMessage = string.Format(UtilityCommonStrings.PathDoesNotExist, path); + var exception = new ArgumentException(errorMessage); + var errorRecord = new ErrorRecord(exception, errorId, errorCategory, path); + WriteError(errorRecord); + } + + private void WriteInvalidDataFileError(string resolvedPath, string errorId) + { + const ErrorCategory errorCategory = ErrorCategory.InvalidData; + var errorMessage = string.Format(UtilityCommonStrings.CouldNotParseAsPowerShellDataFile, resolvedPath); + var exception = new InvalidOperationException(errorMessage); + var errorRecord = new ErrorRecord(exception, errorId, errorCategory, resolvedPath); + WriteError(errorRecord); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..acbffeb66f4621a7805e018462650ff864003231 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Security; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class implementing Invoke-Expression. + /// + [Cmdlet(VerbsLifecycle.Invoke, "Expression", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097030")] + public sealed + class + InvokeExpressionCommand : PSCmdlet + { + #region parameters + + /// + /// Command to execute. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [ValidateTrustedData] + public string Command { get; set; } + + #endregion parameters + + /// + /// For each record, execute it, and push the results into the success stream. + /// + protected override void ProcessRecord() + { + Diagnostics.Assert(Command != null, "Command is null"); + + ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command); + + // If the runspace has ever been in ConstrainedLanguage, lock down this + // invocation as well - it is too easy for the command to be negatively influenced + // by malicious input (such as ReadOnly + Constant variables) + if (Context.HasRunspaceEverUsedConstrainedLanguageMode) + { + myScriptBlock.LanguageMode = PSLanguageMode.ConstrainedLanguage; + } + + if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: UtilityCommonStrings.IEXWDACLogTitle, + message: UtilityCommonStrings.IEXWDACLogMessage, + fqid: "InvokeExpressionCmdletConstrained", + dropIntoDebugger: true); + } + + var emptyArray = Array.Empty(); + myScriptBlock.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: AutomationNull.Value, + input: emptyArray, + scriptThis: AutomationNull.Value, + args: emptyArray); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs new file mode 100644 index 0000000000000000000000000000000000000000..80a04b07f173d551e75e8f74ec0812ecc81e0dcc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -0,0 +1,274 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Text; + +namespace Microsoft.PowerShell.Commands.Utility +{ + /// + /// Join-Object implementation. + /// + [Cmdlet(VerbsCommon.Join, "String", RemotingCapability = RemotingCapability.None, DefaultParameterSetName = "default")] + [OutputType(typeof(string))] + public sealed class JoinStringCommand : PSCmdlet + { + /// A bigger default to not get re-allocations in common use cases. + private const int DefaultOutputStringCapacity = 256; + + private readonly StringBuilder _outputBuilder = new(DefaultOutputStringCapacity); + private CultureInfo _cultureInfo = CultureInfo.InvariantCulture; + private string _separator; + private char _quoteChar; + private bool _firstInputObject = true; + + /// + /// Gets or sets the property name or script block to use as the value to join. + /// + [Parameter(Position = 0)] + [ArgumentCompleter(typeof(PropertyNameCompleter))] + public PSPropertyExpression Property { get; set; } + + /// + /// Gets or sets the delimiter to join the output with. + /// + [Parameter(Position = 1)] + [ArgumentCompleter(typeof(SeparatorArgumentCompleter))] + [AllowEmptyString] + public string Separator + { + get => _separator ?? LanguagePrimitives.ConvertTo(GetVariableValue("OFS")); + set => _separator = value; + } + + /// + /// Gets or sets text to include before the joined input text. + /// + [Parameter] + [Alias("op")] + public string OutputPrefix { get; set; } + + /// + /// Gets or sets text to include after the joined input text. + /// + [Parameter] + [Alias("os")] + public string OutputSuffix { get; set; } + + /// + /// Gets or sets if the output items should we wrapped in single quotes. + /// + [Parameter(ParameterSetName = "SingleQuote")] + public SwitchParameter SingleQuote { get; set; } + + /// + /// Gets or sets if the output items should we wrapped in double quotes. + /// + [Parameter(ParameterSetName = "DoubleQuote")] + public SwitchParameter DoubleQuote { get; set; } + + /// + /// Gets or sets a format string that is applied to each input object. + /// + [Parameter(ParameterSetName = "Format")] + [ArgumentCompleter(typeof(FormatStringArgumentCompleter))] + public string FormatString { get; set; } + + /// + /// Gets or sets if the current culture should be used with formatting instead of the invariant culture. + /// + [Parameter] + public SwitchParameter UseCulture { get; set; } + + /// + /// Gets or sets the input object to join into text. + /// + [Parameter(ValueFromPipeline = true)] + public PSObject[] InputObject { get; set; } + + /// + protected override void BeginProcessing() + { + _quoteChar = SingleQuote ? '\'' : DoubleQuote ? '"' : char.MinValue; + _outputBuilder.Append(OutputPrefix); + if (UseCulture) + { + _cultureInfo = CultureInfo.CurrentCulture; + } + } + + /// + protected override void ProcessRecord() + { + if (InputObject != null) + { + foreach (PSObject inputObject in InputObject) + { + if (inputObject != null && inputObject != AutomationNull.Value) + { + var inputValue = Property == null + ? inputObject + : Property.GetValues(inputObject, false, true).FirstOrDefault()?.Result; + + // conversion to string always succeeds. + if (!LanguagePrimitives.TryConvertTo(inputValue, _cultureInfo, out var stringValue)) + { + throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", ExtendedTypeSystem.InvalidCastCannotRetrieveString, null); + } + + if (_firstInputObject) + { + _firstInputObject = false; + } + else + { + _outputBuilder.Append(Separator); + } + + if (_quoteChar != char.MinValue) + { + _outputBuilder.Append(_quoteChar); + _outputBuilder.Append(stringValue); + _outputBuilder.Append(_quoteChar); + } + else if (string.IsNullOrEmpty(FormatString)) + { + _outputBuilder.Append(stringValue); + } + else + { + _outputBuilder.AppendFormat(_cultureInfo, FormatString, inputValue); + } + } + } + } + } + + /// + protected override void EndProcessing() + { + _outputBuilder.Append(OutputSuffix); + WriteObject(_outputBuilder.ToString()); + } + } + + /// + /// Provides completion for the Separator parameter of the Join-String cmdlet. + /// + public sealed class SeparatorArgumentCompleter : IArgumentCompleter + { + private const string NewLineText = +#if UNIX + "`n"; +#else + "`r`n"; +#endif + + private static readonly CompletionHelpers.CompletionDisplayInfoMapper SeparatorDisplayInfoMapper = separator => separator switch + { + "," => ( + ToolTip: TabCompletionStrings.SeparatorCommaToolTip, + ListItemText: "Comma"), + ", " => ( + ToolTip: TabCompletionStrings.SeparatorCommaSpaceToolTip, + ListItemText: "Comma-Space"), + ";" => ( + ToolTip: TabCompletionStrings.SeparatorSemiColonToolTip, + ListItemText: "Semi-Colon"), + "; " => ( + ToolTip: TabCompletionStrings.SeparatorSemiColonSpaceToolTip, + ListItemText: "Semi-Colon-Space"), + "-" => ( + ToolTip: TabCompletionStrings.SeparatorDashToolTip, + ListItemText: "Dash"), + " " => ( + ToolTip: TabCompletionStrings.SeparatorSpaceToolTip, + ListItemText: "Space"), + NewLineText => ( + ToolTip: StringUtil.Format(TabCompletionStrings.SeparatorNewlineToolTip, NewLineText), + ListItemText: "Newline"), + _ => ( + ToolTip: separator, + ListItemText: separator), + }; + + private static readonly IReadOnlyList s_separatorValues = new List(capacity: 7) + { + ",", + ", ", + ";", + "; ", + NewLineText, + "-", + " ", + }; + + /// + /// Returns completion results for Separator parameter. + /// + /// The command name. + /// The parameter name. + /// The word to complete. + /// The command AST. + /// The fake bound parameters. + /// List of Completion Results. + public IEnumerable CompleteArgument( + string commandName, + string parameterName, + string wordToComplete, + CommandAst commandAst, + IDictionary fakeBoundParameters) + => CompletionHelpers.GetMatchingResults( + wordToComplete, + possibleCompletionValues: s_separatorValues, + displayInfoMapper: SeparatorDisplayInfoMapper, + resultType: CompletionResultType.ParameterValue); + } + + /// + /// Provides completion for the FormatString parameter of the Join-String cmdlet. + /// + public sealed class FormatStringArgumentCompleter : IArgumentCompleter + { + private static readonly IReadOnlyList s_formatStringValues = new List(capacity: 4) + { + "[{0}]", + "{0:N2}", +#if UNIX + "`n `${0}", + "`n [string] `${0}", +#else + "`r`n `${0}", + "`r`n [string] `${0}", +#endif + }; + + /// + /// Returns completion results for FormatString parameter. + /// + /// The command name. + /// The parameter name. + /// The word to complete. + /// The command AST. + /// The fake bound parameters. + /// List of Completion Results. + public IEnumerable CompleteArgument( + string commandName, + string parameterName, + string wordToComplete, + CommandAst commandAst, + IDictionary fakeBoundParameters) + => CompletionHelpers.GetMatchingResults( + wordToComplete, + possibleCompletionValues: s_formatStringValues, + matchStrategy: CompletionHelpers.WildcardPatternEscapeMatch); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs new file mode 100644 index 0000000000000000000000000000000000000000..7c2a7ac65f46d00b2090d8e611a64afd7aa49448 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; + +namespace Microsoft.PowerShell.Commands; + +/// +/// Thrown during evaluation of when an attempt +/// to resolve a $ref or $dynamicRef fails. +/// +internal sealed class JsonSchemaReferenceResolutionException : Exception +{ + /// + /// Initializes a new instance of the class. + /// + /// + /// The exception that is the cause of the current exception, or a null reference + /// (Nothing in Visual Basic) if no inner exception is specified. + /// + public JsonSchemaReferenceResolutionException(Exception innerException) + : base(message: null, innerException) + { + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..cd18f33c41df06c506193b9b495526715f8d7663 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -0,0 +1,314 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Concurrent; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; + +using Microsoft.PowerShell.MarkdownRender; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class for implementing Set-MarkdownOption cmdlet. + /// + [Cmdlet( + VerbsCommon.Set, "MarkdownOption", + DefaultParameterSetName = IndividualSetting, + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006265")] + [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo))] + public class SetMarkdownOptionCommand : PSCmdlet + { + /// + /// Gets or sets the VT100 escape sequence for Header Level 1. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Header1Color { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for Header Level 2. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Header2Color { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for Header Level 3. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Header3Color { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for Header Level 4. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Header4Color { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for Header Level 5. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Header5Color { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for Header Level 6. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Header6Color { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for code block background. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string Code { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for image alt text foreground. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string ImageAltTextForegroundColor { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for link foreground. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string LinkForegroundColor { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for italics text foreground. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string ItalicsForegroundColor { get; set; } + + /// + /// Gets or sets the VT100 escape sequence for bold text foreground. + /// + [ValidatePattern(@"^\[*[0-9;]*?m{1}")] + [Parameter(ParameterSetName = IndividualSetting)] + public string BoldForegroundColor { get; set; } + + /// + /// Gets or sets the switch to PassThru the values set. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + + /// + /// Gets or sets the Theme. + /// + [ValidateNotNullOrEmpty] + [Parameter(ParameterSetName = ThemeParamSet, Mandatory = true)] + [ValidateSet(DarkThemeName, LightThemeName)] + public string Theme { get; set; } + + /// + /// Gets or sets InputObject. + /// + [ValidateNotNullOrEmpty] + [Parameter(ParameterSetName = InputObjectParamSet, Mandatory = true, ValueFromPipeline = true, Position = 0)] + public PSObject InputObject { get; set; } + + private const string IndividualSetting = "IndividualSetting"; + private const string InputObjectParamSet = "InputObject"; + private const string ThemeParamSet = "Theme"; + private const string LightThemeName = "Light"; + private const string DarkThemeName = "Dark"; + + /// + /// Override EndProcessing. + /// + protected override void EndProcessing() + { + PSMarkdownOptionInfo mdOptionInfo = null; + + switch (ParameterSetName) + { + case ThemeParamSet: + mdOptionInfo = new PSMarkdownOptionInfo(); + if (string.Equals(Theme, LightThemeName, StringComparison.OrdinalIgnoreCase)) + { + mdOptionInfo.SetLightTheme(); + } + else if (string.Equals(Theme, DarkThemeName, StringComparison.OrdinalIgnoreCase)) + { + mdOptionInfo.SetDarkTheme(); + } + + break; + + case InputObjectParamSet: + object baseObj = InputObject.BaseObject; + mdOptionInfo = baseObj as PSMarkdownOptionInfo; + + if (mdOptionInfo == null) + { + var errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); + + ErrorRecord errorRecord = new( + new ArgumentException(errorMessage), + "InvalidObject", + ErrorCategory.InvalidArgument, + InputObject); + } + + break; + + case IndividualSetting: + mdOptionInfo = new PSMarkdownOptionInfo(); + SetOptions(mdOptionInfo); + break; + } + + var setOption = PSMarkdownOptionInfoCache.Set(this.CommandInfo, mdOptionInfo); + + if (PassThru.IsPresent) + { + WriteObject(setOption); + } + } + + private void SetOptions(PSMarkdownOptionInfo mdOptionInfo) + { + if (!string.IsNullOrEmpty(Header1Color)) + { + mdOptionInfo.Header1 = Header1Color; + } + + if (!string.IsNullOrEmpty(Header2Color)) + { + mdOptionInfo.Header2 = Header2Color; + } + + if (!string.IsNullOrEmpty(Header3Color)) + { + mdOptionInfo.Header3 = Header3Color; + } + + if (!string.IsNullOrEmpty(Header4Color)) + { + mdOptionInfo.Header4 = Header4Color; + } + + if (!string.IsNullOrEmpty(Header5Color)) + { + mdOptionInfo.Header5 = Header5Color; + } + + if (!string.IsNullOrEmpty(Header6Color)) + { + mdOptionInfo.Header6 = Header6Color; + } + + if (!string.IsNullOrEmpty(Code)) + { + mdOptionInfo.Code = Code; + } + + if (!string.IsNullOrEmpty(ImageAltTextForegroundColor)) + { + mdOptionInfo.Image = ImageAltTextForegroundColor; + } + + if (!string.IsNullOrEmpty(LinkForegroundColor)) + { + mdOptionInfo.Link = LinkForegroundColor; + } + + if (!string.IsNullOrEmpty(ItalicsForegroundColor)) + { + mdOptionInfo.EmphasisItalics = ItalicsForegroundColor; + } + + if (!string.IsNullOrEmpty(BoldForegroundColor)) + { + mdOptionInfo.EmphasisBold = BoldForegroundColor; + } + } + } + + /// + /// Implements the cmdlet for getting the Markdown options that are set. + /// + [Cmdlet( + VerbsCommon.Get, "MarkdownOption", + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006371")] + [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo))] + public class GetMarkdownOptionCommand : PSCmdlet + { + private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; + + /// + /// Override EndProcessing. + /// + protected override void EndProcessing() + { + WriteObject(PSMarkdownOptionInfoCache.Get(this.CommandInfo)); + } + } + + /// + /// The class manages whether we should use a module scope variable or concurrent dictionary for storing the set PSMarkdownOptions. + /// When we have a moduleInfo available we use the module scope variable. + /// In case of built-in modules, they are loaded as snapins when we are hosting PowerShell. + /// We use runspace Id as the key for the concurrent dictionary to have the functionality of separate settings per runspace. + /// Force loading the module does not unload the nested modules and hence we cannot use IModuleAssemblyCleanup to remove items from the dictionary. + /// Because of these reason, we continue using module scope variable when moduleInfo is available. + /// + internal static class PSMarkdownOptionInfoCache + { + private static readonly ConcurrentDictionary markdownOptionInfoCache; + + private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; + + static PSMarkdownOptionInfoCache() + { + markdownOptionInfoCache = new ConcurrentDictionary(); + } + + internal static PSMarkdownOptionInfo Get(CommandInfo command) + { + // If we have the moduleInfo then store are module scope variable + if (command.Module != null) + { + return command.Module.SessionState.PSVariable.GetValue(MarkdownOptionInfoVariableName, new PSMarkdownOptionInfo()) as PSMarkdownOptionInfo; + } + + // If we don't have a moduleInfo, like in PowerShell hosting scenarios, use a concurrent dictionary. + if (markdownOptionInfoCache.TryGetValue(Runspace.DefaultRunspace.InstanceId, out PSMarkdownOptionInfo cachedOption)) + { + // return the cached options for the runspaceId + return cachedOption; + } + else + { + // no option cache so cache and return the default PSMarkdownOptionInfo + var newOptionInfo = new PSMarkdownOptionInfo(); + return markdownOptionInfoCache.GetOrAdd(Runspace.DefaultRunspace.InstanceId, newOptionInfo); + } + } + + internal static PSMarkdownOptionInfo Set(CommandInfo command, PSMarkdownOptionInfo optionInfo) + { + // If we have the moduleInfo then store are module scope variable + if (command.Module != null) + { + command.Module.SessionState.PSVariable.Set(MarkdownOptionInfoVariableName, optionInfo); + return optionInfo; + } + + // If we don't have a moduleInfo, like in PowerShell hosting scenarios with modules loaded as snapins, use a concurrent dictionary. + return markdownOptionInfoCache.AddOrUpdate(Runspace.DefaultRunspace.InstanceId, optionInfo, (key, oldvalue) => optionInfo); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs new file mode 100644 index 0000000000000000000000000000000000000000..262fd44b30f14de65cef421b89d5136ab6033f05 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -0,0 +1,2105 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Text; +using System.Text.RegularExpressions; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Context information about a match. + /// + public sealed class MatchInfoContext : ICloneable + { + internal MatchInfoContext() + { + } + + /// + /// Gets or sets the lines found before a match. + /// + public string[] PreContext { get; set; } + + /// + /// Gets or sets the lines found after a match. + /// + public string[] PostContext { get; set; } + + /// + /// Gets or sets the lines found before a match. Does not include + /// overlapping context and thus can be used to + /// display contiguous match regions. + /// + public string[] DisplayPreContext { get; set; } + + /// + /// Gets or sets the lines found after a match. Does not include + /// overlapping context and thus can be used to + /// display contiguous match regions. + /// + public string[] DisplayPostContext { get; set; } + + /// + /// Produce a deep copy of this object. + /// + /// A new object that is a copy of this instance. + public object Clone() + { + return new MatchInfoContext() + { + PreContext = (string[])PreContext?.Clone(), + PostContext = (string[])PostContext?.Clone(), + DisplayPreContext = (string[])DisplayPreContext?.Clone(), + DisplayPostContext = (string[])DisplayPostContext?.Clone() + }; + } + } + + /// + /// The object returned by select-string representing the result of a match. + /// + public class MatchInfo + { + private static readonly string s_inputStream = "InputStream"; + + /// + /// Gets or sets a value indicating whether the match was done ignoring case. + /// + /// True if case was ignored. + public bool IgnoreCase { get; set; } + + /// + /// Gets or sets the number of the matching line. + /// + /// The number of the matching line. + public ulong LineNumber { get; set; } + + /// + /// Gets or sets the text of the matching line. + /// + /// The text of the matching line. + public string Line { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether the matched portion of the string is highlighted. + /// + /// Whether the matched portion of the string is highlighted with the negative VT sequence. + private readonly bool _emphasize; + + /// + /// Stores the starting index of each match within the line. + /// + private readonly IReadOnlyList _matchIndexes; + + /// + /// Stores the length of each match within the line. + /// + private readonly IReadOnlyList _matchLengths; + + /// + /// Initializes a new instance of the class with emphasis disabled. + /// + public MatchInfo() + { + this._emphasize = false; + } + + /// + /// Initializes a new instance of the class with emphasized matched text. + /// Used when virtual terminal sequences are supported. + /// + /// Sets the matchIndexes. + /// Sets the matchLengths. + public MatchInfo(IReadOnlyList matchIndexes, IReadOnlyList matchLengths) + { + this._emphasize = true; + this._matchIndexes = matchIndexes; + this._matchLengths = matchLengths; + } + + /// + /// Gets the base name of the file containing the matching line. + /// + /// + /// It will be the string "InputStream" if the object came from the input stream. + /// This is a readonly property calculated from the path . + /// + /// The file name. + public string Filename + { + get + { + if (!_pathSet) + { + return s_inputStream; + } + + return _filename ??= System.IO.Path.GetFileName(_path); + } + } + + private string _filename; + + /// + /// Gets or sets the full path of the file containing the matching line. + /// + /// + /// It will be "InputStream" if the object came from the input stream. + /// + /// The path name. + public string Path + { + get => _pathSet ? _path : s_inputStream; + set + { + _path = value; + _pathSet = true; + } + } + + private string _path = s_inputStream; + + private bool _pathSet; + + /// + /// Gets or sets the pattern that was used in the match. + /// + /// The pattern string. + public string Pattern { get; set; } + + /// + /// Gets or sets context for the match, or null if -context was not specified. + /// + public MatchInfoContext Context { get; set; } + + /// + /// Returns the path of the matching file truncated relative to the parameter. + /// + /// + /// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo + /// the routine would return bar\baz.c . + /// + /// The directory base the truncation on. + /// The relative path that was produced. + public string RelativePath(string directory) + { + if (!_pathSet) + { + return this.Path; + } + + string relPath = _path; + if (!string.IsNullOrEmpty(directory)) + { + if (relPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase)) + { + int offset = directory.Length; + if (offset < relPath.Length) + { + if (directory[offset - 1] == '\\' || directory[offset - 1] == '/') + { + relPath = relPath.Substring(offset); + } + else if (relPath[offset] == '\\' || relPath[offset] == '/') + { + relPath = relPath.Substring(offset + 1); + } + } + } + } + + return relPath; + } + + private const string MatchFormat = "{0}{1}:{2}:{3}"; + private const string SimpleFormat = "{0}{1}"; + + // Prefixes used by formatting: Match and Context prefixes + // are used when context-tracking is enabled, otherwise + // the empty prefix is used. + private const string MatchPrefix = "> "; + private const string ContextPrefix = " "; + private const string EmptyPrefix = ""; + + /// + /// Returns the string representation of this object. The format + /// depends on whether a path has been set for this object or not. + /// + /// + /// If the path component is set, as would be the case when matching + /// in a file, ToString() would return the path, line number and line text. + /// If path is not set, then just the line text is presented. + /// + /// The string representation of the match object. + public override string ToString() + { + return ToString(null); + } + + /// + /// Returns the string representation of the match object same format as ToString() + /// but trims the path to be relative to the argument. + /// + /// Directory to use as the root when calculating the relative path. + /// The string representation of the match object. + public string ToString(string directory) + { + return ToString(directory, Line); + } + + /// + /// Returns the string representation of the match object with the matched line passed + /// in as and trims the path to be relative to + /// the argument. + /// + /// Directory to use as the root when calculating the relative path. + /// Line that the match occurs in. + /// The string representation of the match object. + private string ToString(string directory, string line) + { + string displayPath = (directory != null) ? RelativePath(directory) : _path; + + // Just return a single line if the user didn't + // enable context-tracking. + if (Context == null) + { + return FormatLine(line, this.LineNumber, displayPath, EmptyPrefix); + } + + // Otherwise, render the full context. + List lines = new(Context.DisplayPreContext.Length + Context.DisplayPostContext.Length + 1); + + ulong displayLineNumber = this.LineNumber - (ulong)Context.DisplayPreContext.Length; + foreach (string contextLine in Context.DisplayPreContext) + { + lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix)); + } + + lines.Add(FormatLine(line, displayLineNumber++, displayPath, MatchPrefix)); + + foreach (string contextLine in Context.DisplayPostContext) + { + lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix)); + } + + return string.Join(System.Environment.NewLine, lines.ToArray()); + } + + /// + /// Returns the string representation of the match object same format as ToString() + /// and inverts the color of the matched text if virtual terminal is supported. + /// + /// Directory to use as the root when calculating the relative path. + /// The string representation of the match object with matched text inverted. + public string ToEmphasizedString(string directory) + { + if (!_emphasize) + { + return ToString(directory); + } + + return ToString(directory, EmphasizeLine()); + } + + /// + /// Surrounds the matched text with virtual terminal sequences to invert it's color. Used in ToEmphasizedString. + /// + /// The matched line with matched text inverted. + private string EmphasizeLine() + { + string invertColorsVT100 = PSStyle.Instance.Reverse; + string resetVT100 = PSStyle.Instance.Reset; + + char[] chars = new char[(_matchIndexes.Count * (invertColorsVT100.Length + resetVT100.Length)) + Line.Length]; + int lineIndex = 0; + int charsIndex = 0; + for (int i = 0; i < _matchIndexes.Count; i++) + { + // Adds characters before match + Line.CopyTo(lineIndex, chars, charsIndex, _matchIndexes[i] - lineIndex); + charsIndex += _matchIndexes[i] - lineIndex; + lineIndex = _matchIndexes[i]; + + // Adds opening vt sequence + invertColorsVT100.CopyTo(0, chars, charsIndex, invertColorsVT100.Length); + charsIndex += invertColorsVT100.Length; + + // Adds characters being emphasized + Line.CopyTo(lineIndex, chars, charsIndex, _matchLengths[i]); + lineIndex += _matchLengths[i]; + charsIndex += _matchLengths[i]; + + // Adds closing vt sequence + resetVT100.CopyTo(0, chars, charsIndex, resetVT100.Length); + charsIndex += resetVT100.Length; + } + + // Adds remaining characters in line + Line.CopyTo(lineIndex, chars, charsIndex, Line.Length - lineIndex); + + return new string(chars); + } + + /// + /// Formats a line for use in ToString. + /// + /// The line to format. + /// The line number to display. + /// The file path, formatted for display. + /// The match prefix. + /// The formatted line as a string. + private string FormatLine(string lineStr, ulong displayLineNumber, string displayPath, string prefix) + { + return _pathSet + ? StringUtil.Format(MatchFormat, prefix, displayPath, displayLineNumber, lineStr) + : StringUtil.Format(SimpleFormat, prefix, lineStr); + } + + /// + /// Gets or sets a list of all Regex matches on the matching line. + /// + public Match[] Matches { get; set; } = Array.Empty(); + + /// + /// Create a deep copy of this MatchInfo instance. + /// + /// A new object that is a copy of this instance. + internal MatchInfo Clone() + { + // Just do a shallow copy and then deep-copy the + // fields that need it. + MatchInfo clone = (MatchInfo)this.MemberwiseClone(); + + if (clone.Context != null) + { + clone.Context = (MatchInfoContext)clone.Context.Clone(); + } + + // Regex match objects are immutable, so we can get away + // with just copying the array. + clone.Matches = (Match[])clone.Matches.Clone(); + + return clone; + } + } + + /// + /// A cmdlet to search through strings and files for particular patterns. + /// + [Cmdlet(VerbsCommon.Select, "String", DefaultParameterSetName = ParameterSetFile, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097119")] + [OutputType(typeof(bool), typeof(MatchInfo), ParameterSetName = new[] { ParameterSetFile, ParameterSetObject, ParameterSetLiteralFile })] + [OutputType(typeof(string), ParameterSetName = new[] { ParameterSetFileRaw, ParameterSetObjectRaw, ParameterSetLiteralFileRaw })] + public sealed class SelectStringCommand : PSCmdlet + { + private const string ParameterSetFile = "File"; + private const string ParameterSetFileRaw = "FileRaw"; + private const string ParameterSetObject = "Object"; + private const string ParameterSetObjectRaw = "ObjectRaw"; + private const string ParameterSetLiteralFile = "LiteralFile"; + private const string ParameterSetLiteralFileRaw = "LiteralFileRaw"; + + /// + /// A generic circular buffer. + /// + /// The type of items that are buffered. + private sealed class CircularBuffer : ICollection + { + // Ring of items + private readonly T[] _items; + + // Current length, as opposed to the total capacity + // Current start of the list. Starts at 0, but may + // move forwards or wrap around back to 0 due to + // rotation. + private int _firstIndex; + + /// + /// Initializes a new instance of the class. + /// + /// The maximum capacity of the buffer. + /// If is negative. + public CircularBuffer(int capacity) + { + ArgumentOutOfRangeException.ThrowIfNegative(capacity); + + _items = new T[capacity]; + Clear(); + } + + /// + /// Gets the maximum capacity of the buffer. If more items + /// are added than the buffer has capacity for, then + /// older items will be removed from the buffer with + /// a first-in, first-out policy. + /// + public int Capacity => _items.Length; + + /// + /// Whether or not the buffer is at capacity. + /// + public bool IsFull => Count == Capacity; + + /// + /// Convert from a 0-based index to a buffer index which + /// has been properly offset and wrapped. + /// + /// The index to wrap. + /// If is out of range. + /// + /// The actual index that + /// maps to. + /// + private int WrapIndex(int zeroBasedIndex) + { + if (Capacity == 0 || zeroBasedIndex < 0) + { + throw new ArgumentOutOfRangeException(nameof(zeroBasedIndex)); + } + + return (zeroBasedIndex + _firstIndex) % Capacity; + } + + #region IEnumerable implementation. + public IEnumerator GetEnumerator() + { + for (int i = 0; i < Count; i++) + { + yield return _items[WrapIndex(i)]; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)GetEnumerator(); + } + #endregion + + #region ICollection implementation + public int Count { get; private set; } + + public bool IsReadOnly => false; + + /// + /// Adds an item to the buffer. If the buffer is already + /// full, the oldest item in the list will be removed, + /// and the new item added at the logical end of the list. + /// + /// The item to add. + public void Add(T item) + { + if (Capacity == 0) + { + return; + } + + int itemIndex; + + if (IsFull) + { + itemIndex = _firstIndex; + _firstIndex = (_firstIndex + 1) % Capacity; + } + else + { + itemIndex = _firstIndex + Count; + Count++; + } + + _items[itemIndex] = item; + } + + public void Clear() + { + _firstIndex = 0; + Count = 0; + } + + public bool Contains(T item) + { + throw new NotImplementedException(); + } + + public void CopyTo(T[] array, int arrayIndex) + { + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); + + if (Count > (array.Length - arrayIndex)) + { + throw new ArgumentException("arrayIndex"); + } + + // Iterate through the buffer in correct order. + foreach (T item in this) + { + array[arrayIndex++] = item; + } + } + + public bool Remove(T item) + { + throw new NotImplementedException(); + } + #endregion + + /// + /// Create an array of the items in the buffer. Items + /// will be in the same order they were added. + /// + /// The new array. + public T[] ToArray() + { + T[] result = new T[Count]; + CopyTo(result, 0); + return result; + } + + /// + /// Access an item in the buffer. Indexing is based off + /// of the order items were added, rather than any + /// internal ordering the buffer may be maintaining. + /// + /// The index of the item to access. + /// The buffered item at index . + public T this[int index] + { + get + { + if (!(index >= 0 && index < Count)) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + + return _items[WrapIndex(index)]; + } + } + } + + /// + /// An interface to a context tracking algorithm. + /// + private interface IContextTracker + { + /// + /// Gets matches with completed context information + /// that are ready to be emitted into the pipeline. + /// + IList EmitQueue { get; } + + /// + /// Track a non-matching line for context. + /// + /// The line to track. + void TrackLine(string line); + + /// + /// Track a matching line. + /// + /// The line to track. + void TrackMatch(MatchInfo match); + + /// + /// Track having reached the end of the file, + /// giving the tracker a chance to process matches with + /// incomplete context information. + /// + void TrackEOF(); + } + + /// + /// A state machine to track display context for each match. + /// + private sealed class DisplayContextTracker : IContextTracker + { + private enum ContextState + { + InitialState, + CollectPre, + CollectPost, + } + + private ContextState _contextState = ContextState.InitialState; + private readonly int _preContext; + private readonly int _postContext; + + // The context leading up to the match. + private readonly CircularBuffer _collectedPreContext; + + // The context after the match. + private readonly List _collectedPostContext; + + // Current match info we are tracking postcontext for. + // At any given time, if set, this value will not be + // in the emitQueue but will be the next to be added. + private MatchInfo _matchInfo = null; + + /// + /// Initializes a new instance of the class. + /// + /// How much preContext to collect at most. + /// How much postContext to collect at most. + public DisplayContextTracker(int preContext, int postContext) + { + _preContext = preContext; + _postContext = postContext; + + _collectedPreContext = new CircularBuffer(preContext); + _collectedPostContext = new List(postContext); + _emitQueue = new List(); + Reset(); + } + + #region IContextTracker implementation + public IList EmitQueue => _emitQueue; + + private readonly List _emitQueue; + + // Track non-matching line + public void TrackLine(string line) + { + switch (_contextState) + { + case ContextState.InitialState: + break; + case ContextState.CollectPre: + _collectedPreContext.Add(line); + break; + case ContextState.CollectPost: + // We're not done collecting post-context. + _collectedPostContext.Add(line); + + if (_collectedPostContext.Count >= _postContext) + { + // Now we're done. + UpdateQueue(); + } + + break; + } + } + + // Track matching line + public void TrackMatch(MatchInfo match) + { + // Update the queue in case we were in the middle + // of collecting postcontext for an older match... + if (_contextState == ContextState.CollectPost) + { + UpdateQueue(); + } + + // Update the current matchInfo. + _matchInfo = match; + + // If postContext is set, then we need to hold + // onto the match for a while and gather context. + // Otherwise, immediately move the match onto the queue + // and let UpdateQueue update our state instead. + if (_postContext > 0) + { + _contextState = ContextState.CollectPost; + } + else + { + UpdateQueue(); + } + } + + // Track having reached the end of the file. + public void TrackEOF() + { + // If we're in the middle of collecting postcontext, we + // already have a match and it's okay to queue it up + // early since there are no more lines to track context + // for. + if (_contextState == ContextState.CollectPost) + { + UpdateQueue(); + } + } + #endregion + + /// + /// Moves matchInfo, if set, to the emitQueue and + /// resets the tracking state. + /// + private void UpdateQueue() + { + if (_matchInfo != null) + { + _emitQueue.Add(_matchInfo); + + if (_matchInfo.Context != null) + { + _matchInfo.Context.DisplayPreContext = _collectedPreContext.ToArray(); + _matchInfo.Context.DisplayPostContext = _collectedPostContext.ToArray(); + } + + Reset(); + } + } + + // Reset tracking state. Does not reset the emit queue. + private void Reset() + { + _contextState = (_preContext > 0) + ? ContextState.CollectPre + : ContextState.InitialState; + _collectedPreContext.Clear(); + _collectedPostContext.Clear(); + _matchInfo = null; + } + } + + /// + /// A class to track logical context for each match. + /// + /// + /// The difference between logical and display context is + /// that logical context includes as many context lines + /// as possible for a given match, up to the specified + /// limit, including context lines which overlap between + /// matches and other matching lines themselves. Display + /// context, on the other hand, is designed to display + /// a possibly-continuous set of matches by excluding + /// overlapping context (lines will only appear once) + /// and other matching lines (since they will appear + /// as their own match entries.). + /// + private sealed class LogicalContextTracker : IContextTracker + { + // A union: string | MatchInfo. Needed since + // context lines could be either proper matches + // or non-matching lines. + private sealed class ContextEntry + { + public readonly string Line; + public readonly MatchInfo Match; + + public ContextEntry(string line) + { + Line = line; + } + + public ContextEntry(MatchInfo match) + { + Match = match; + } + + public override string ToString() => Match?.Line ?? Line; + } + + // Whether or not early entries found + // while still filling up the context buffer + // have been added to the emit queue. + // Used by UpdateQueue. + private bool _hasProcessedPreEntries; + + private readonly int _preContext; + private readonly int _postContext; + + // A circular buffer tracking both precontext and postcontext. + // + // Essentially, the buffer is separated into regions: + // | prectxt region (older entries, length = precontext) | + // | match region (length = 1) | + // | postctxt region (newer entries, length = postcontext) | + // + // When context entries containing a match reach the "middle" + // (the position between the pre/post context regions) + // of this buffer, and the buffer is full, we will know + // enough context to populate the Context properties of the + // match. At that point, we will add the match object + // to the emit queue. + private readonly CircularBuffer _collectedContext; + + /// + /// Initializes a new instance of the class. + /// + /// How much preContext to collect at most. + /// How much postContext to collect at most. + public LogicalContextTracker(int preContext, int postContext) + { + _preContext = preContext; + _postContext = postContext; + _collectedContext = new CircularBuffer(preContext + postContext + 1); + _emitQueue = new List(); + } + + #region IContextTracker implementation + public IList EmitQueue => _emitQueue; + + private readonly List _emitQueue; + + public void TrackLine(string line) + { + ContextEntry entry = new(line); + _collectedContext.Add(entry); + UpdateQueue(); + } + + public void TrackMatch(MatchInfo match) + { + ContextEntry entry = new(match); + _collectedContext.Add(entry); + UpdateQueue(); + } + + public void TrackEOF() + { + // If the buffer is already full, + // check for any matches with incomplete + // postcontext and add them to the emit queue. + // These matches can be identified by being past + // the "middle" of the context buffer (still in + // the postcontext region. + // + // If the buffer isn't full, then nothing will have + // ever been emitted and everything is still waiting + // on postcontext. So process the whole buffer. + int startIndex = _collectedContext.IsFull ? _preContext + 1 : 0; + EmitAllInRange(startIndex, _collectedContext.Count - 1); + } + #endregion + + /// + /// Add all matches found in the specified range + /// to the emit queue, collecting as much context + /// as possible up to the limits specified in the constructor. + /// + /// + /// The range is inclusive; the entries at + /// startIndex and endIndex will both be checked. + /// + /// The beginning of the match range. + /// The ending of the match range. + private void EmitAllInRange(int startIndex, int endIndex) + { + for (int i = startIndex; i <= endIndex; i++) + { + MatchInfo match = _collectedContext[i].Match; + if (match != null) + { + int preStart = Math.Max(i - _preContext, 0); + int postLength = Math.Min(_postContext, _collectedContext.Count - i - 1); + Emit(match, preStart, i - preStart, i + 1, postLength); + } + } + } + + /// + /// Add match(es) found in the match region to the + /// emit queue. Should be called every time an entry + /// is added to the context buffer. + /// + private void UpdateQueue() + { + // Are we at capacity and thus have enough postcontext? + // Is there a match in the "middle" of the buffer + // that we know the pre/post context for? + // + // If this is the first time we've reached full capacity, + // hasProcessedPreEntries will not be set, and we + // should go through the entire context, because it might + // have entries that never collected enough + // precontext. Otherwise, we should just look at the + // middle region. + if (_collectedContext.IsFull) + { + if (_hasProcessedPreEntries) + { + // Only process a potential match with exactly + // enough pre and post-context. + EmitAllInRange(_preContext, _preContext); + } + else + { + // Some of our early entries may not + // have enough precontext. Process them too. + EmitAllInRange(0, _preContext); + _hasProcessedPreEntries = true; + } + } + } + + /// + /// Collects context from the specified ranges. Populates + /// the specified match with the collected context + /// and adds it to the emit queue. + /// + /// + /// Context ranges must be within the bounds of the context buffer. + /// + /// The match to operate on. + /// The start index of the preContext range. + /// The length of the preContext range. + /// The start index of the postContext range. + /// The length of the postContext range. + private void Emit(MatchInfo match, int preStartIndex, int preLength, int postStartIndex, int postLength) + { + if (match.Context != null) + { + match.Context.PreContext = CopyContext(preStartIndex, preLength); + match.Context.PostContext = CopyContext(postStartIndex, postLength); + } + + _emitQueue.Add(match); + } + + /// + /// Collects context from the specified ranges. + /// + /// + /// The range must be within the bounds of the context buffer. + /// + /// The index to start at. + /// The length of the range. + /// String representation of the collected context at the specified range. + private string[] CopyContext(int startIndex, int length) + { + string[] result = new string[length]; + + for (int i = 0; i < length; i++) + { + result[i] = _collectedContext[startIndex + i].ToString(); + } + + return result; + } + } + + /// + /// A class to track both logical and display contexts. + /// + private sealed class ContextTracker : IContextTracker + { + private readonly IContextTracker _displayTracker; + private readonly IContextTracker _logicalTracker; + + /// + /// Initializes a new instance of the class. + /// + /// How much preContext to collect at most. + /// How much postContext to collect at most. + public ContextTracker(int preContext, int postContext) + { + _displayTracker = new DisplayContextTracker(preContext, postContext); + _logicalTracker = new LogicalContextTracker(preContext, postContext); + EmitQueue = new List(); + } + + #region IContextTracker implementation + public IList EmitQueue { get; } + + public void TrackLine(string line) + { + _displayTracker.TrackLine(line); + _logicalTracker.TrackLine(line); + UpdateQueue(); + } + + public void TrackMatch(MatchInfo match) + { + _displayTracker.TrackMatch(match); + _logicalTracker.TrackMatch(match); + UpdateQueue(); + } + + public void TrackEOF() + { + _displayTracker.TrackEOF(); + _logicalTracker.TrackEOF(); + UpdateQueue(); + } + #endregion + + /// + /// Update the emit queue based on the wrapped trackers. + /// + private void UpdateQueue() + { + // Look for completed matches in the logical + // tracker's queue. Since the logical tracker + // will try to collect as much context as + // possible, the display tracker will have either + // already finished collecting its context for the + // match or will have completed it at the same + // time as the logical tracker, so we can + // be sure the matches will have both logical + // and display context already populated. + foreach (MatchInfo match in _logicalTracker.EmitQueue) + { + EmitQueue.Add(match); + } + + _logicalTracker.EmitQueue.Clear(); + _displayTracker.EmitQueue.Clear(); + } + } + + /// + /// ContextTracker that does not work for the case when pre- and post context is 0. + /// + private sealed class NoContextTracker : IContextTracker + { + private readonly IList _matches = new List(1); + + IList IContextTracker.EmitQueue => _matches; + + void IContextTracker.TrackLine(string line) + { + } + + void IContextTracker.TrackMatch(MatchInfo match) => _matches.Add(match); + + void IContextTracker.TrackEOF() + { + } + } + + /// + /// Gets or sets a culture name. + /// + [Parameter] + [ValidateSet(typeof(ValidateMatchStringCultureNamesGenerator))] + [ValidateNotNull] + public string Culture + { + get + { + switch (_stringComparison) + { + case StringComparison.Ordinal: + case StringComparison.OrdinalIgnoreCase: + { + return OrdinalCultureName; + } + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + { + return InvariantCultureName; + } + + case StringComparison.CurrentCulture: + case StringComparison.CurrentCultureIgnoreCase: + { + return CurrentCultureName; + } + + default: + { + break; + } + } + + return _cultureName; + } + + set + { + _cultureName = value; + InitCulture(); + } + } + + internal const string OrdinalCultureName = "Ordinal"; + internal const string InvariantCultureName = "Invariant"; + internal const string CurrentCultureName = "Current"; + + private string _cultureName = CultureInfo.CurrentCulture.Name; + private StringComparison _stringComparison = StringComparison.CurrentCultureIgnoreCase; + private CompareOptions _compareOptions = CompareOptions.IgnoreCase; + + private delegate int CultureInfoIndexOf(string source, string value, int startIndex, int count, CompareOptions options); + + private CultureInfoIndexOf _cultureInfoIndexOf = CultureInfo.CurrentCulture.CompareInfo.IndexOf; + + private void InitCulture() + { + _stringComparison = default; + + switch (_cultureName) + { + case OrdinalCultureName: + { + _stringComparison = CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + _compareOptions = CaseSensitive ? CompareOptions.Ordinal : CompareOptions.OrdinalIgnoreCase; + _cultureInfoIndexOf = CultureInfo.InvariantCulture.CompareInfo.IndexOf; + break; + } + + case InvariantCultureName: + { + _stringComparison = CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + _compareOptions = CaseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase; + _cultureInfoIndexOf = CultureInfo.InvariantCulture.CompareInfo.IndexOf; + break; + } + + case CurrentCultureName: + { + _stringComparison = CaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; + _compareOptions = CaseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase; + _cultureInfoIndexOf = CultureInfo.CurrentCulture.CompareInfo.IndexOf; + break; + } + + default: + { + var _cultureInfo = CultureInfo.GetCultureInfo(_cultureName); + _compareOptions = CaseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase; + _cultureInfoIndexOf = _cultureInfo.CompareInfo.IndexOf; + break; + } + } + } + + /// + /// Gets or sets the current pipeline object. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = ParameterSetObject)] + [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = ParameterSetObjectRaw)] + [AllowNull] + [AllowEmptyString] + public PSObject InputObject + { + get => _inputObject; + set => _inputObject = LanguagePrimitives.IsNull(value) ? PSObject.AsPSObject(string.Empty) : value; + } + + private PSObject _inputObject = AutomationNull.Value; + + /// + /// Gets or sets the patterns to find. + /// + [Parameter(Mandatory = true, Position = 0)] + public string[] Pattern { get; set; } + + private Regex[] _regexPattern; + + /// + /// Gets or sets files to read from. + /// Globbing is done on these. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetFile)] + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetFileRaw)] + [FileinfoToString] + public string[] Path { get; set; } + + /// + /// Gets or sets literal files to read from. + /// Globbing is not done on these. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetLiteralFile)] + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetLiteralFileRaw)] + [FileinfoToString] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get => Path; + set + { + Path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath; + + /// + /// Gets or sets a value indicating if only string values containing matched lines should be returned. + /// If not (default) return MatchInfo (or bool objects, when Quiet is passed). + /// + [Parameter(Mandatory = true, ParameterSetName = ParameterSetObjectRaw)] + [Parameter(Mandatory = true, ParameterSetName = ParameterSetFileRaw)] + [Parameter(Mandatory = true, ParameterSetName = ParameterSetLiteralFileRaw)] + public SwitchParameter Raw { get; set; } + + /// + /// Gets or sets a value indicating if a pattern string should be matched literally. + /// If not (default) search using pattern as a Regular Expression. + /// + [Parameter] + public SwitchParameter SimpleMatch { get; set; } + + /// + /// Gets or sets a value indicating if the search is case sensitive.If true, then do case-sensitive searches. + /// + [Parameter] + public SwitchParameter CaseSensitive { get; set; } + + /// + /// Gets or sets a value indicating if the cmdlet will stop processing at the first successful match and + /// return true. If both List and Quiet parameters are given, an exception is thrown. + /// + [Parameter(ParameterSetName = ParameterSetObject)] + [Parameter(ParameterSetName = ParameterSetFile)] + [Parameter(ParameterSetName = ParameterSetLiteralFile)] + public SwitchParameter Quiet { get; set; } + + /// + /// Gets or sets a value indicating if matching files should be listed. + /// This is the Unix functionality this switch is intended to mimic; + /// the actual action of this option is to stop after the first match + /// is found and returned from any particular file. + /// + [Parameter] + public SwitchParameter List { get; set; } + + /// + /// Gets or sets a value indicating if highlighting should be disabled. + /// + [Parameter] + public SwitchParameter NoEmphasis { get; set; } + + /// + /// Gets or sets files to include. Files matching + /// one of these (if specified) are included. + /// + /// Invalid wildcard pattern was specified. + [Parameter] + [ValidateNotNullOrEmpty] + public string[] Include + { + get => _includeStrings; + set + { + // null check is not needed (because of ValidateNotNullOrEmpty), + // but we have to include it to silence OACR + _includeStrings = value ?? throw PSTraceSource.NewArgumentNullException(nameof(value)); + + _include = new WildcardPattern[_includeStrings.Length]; + for (int i = 0; i < _includeStrings.Length; i++) + { + _include[i] = WildcardPattern.Get(_includeStrings[i], WildcardOptions.IgnoreCase); + } + } + } + + private string[] _includeStrings; + + private WildcardPattern[] _include; + + /// + /// Gets or sets files to exclude. Files matching + /// one of these (if specified) are excluded. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string[] Exclude + { + get => _excludeStrings; + set + { + // null check is not needed (because of ValidateNotNullOrEmpty), + // but we have to include it to silence OACR + _excludeStrings = value ?? throw PSTraceSource.NewArgumentNullException("value"); + + _exclude = new WildcardPattern[_excludeStrings.Length]; + for (int i = 0; i < _excludeStrings.Length; i++) + { + _exclude[i] = WildcardPattern.Get(_excludeStrings[i], WildcardOptions.IgnoreCase); + } + } + } + + private string[] _excludeStrings; + + private WildcardPattern[] _exclude; + + /// + /// Gets or sets a value indicating whether to only show lines which do not match. + /// Equivalent to grep -v/findstr -v. + /// + [Parameter] + public SwitchParameter NotMatch { get; set; } + + /// + /// Gets or sets a value indicating whether the Matches property of MatchInfo should be set + /// to the result of calling System.Text.RegularExpressions.Regex.Matches() on + /// the corresponding line. + /// Has no effect if -SimpleMatch is also specified. + /// + [Parameter] + public SwitchParameter AllMatches { get; set; } + + /// + /// Gets or sets the text encoding to process each file as. + /// + [Parameter] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + /// + /// Gets or sets the number of context lines to collect. If set to a + /// single integer value N, collects N lines each of pre- + /// and post- context. If set to a 2-tuple B,A, collects B + /// lines of pre- and A lines of post- context. + /// If set to a list with more than 2 elements, the + /// excess elements are ignored. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [ValidateCount(1, 2)] + [ValidateRange(0, int.MaxValue)] + public new int[] Context + { + get => _context; + set + { + // null check is not needed (because of ValidateNotNullOrEmpty), + // but we have to include it to silence OACR + _context = value ?? throw PSTraceSource.NewArgumentNullException("value"); + + if (_context.Length == 1) + { + _preContext = _context[0]; + _postContext = _context[0]; + } + else if (_context.Length >= 2) + { + _preContext = _context[0]; + _postContext = _context[1]; + } + } + } + + private int[] _context; + + private int _preContext = 0; + + private int _postContext = 0; + + // When we are in Raw mode or pre- and postcontext are zero, use the _noContextTracker, since we will not be needing trackedLines. + private IContextTracker GetContextTracker() => (Raw || (_preContext == 0 && _postContext == 0)) + ? _noContextTracker + : new ContextTracker(_preContext, _postContext); + + // This context tracker is only used for strings which are piped + // directly into the cmdlet. File processing doesn't need + // to track state between calls to ProcessRecord, and so + // allocates its own tracker. The reason we can't + // use a single global tracker for both is that in the case of + // a mixed list of strings and FileInfo, the context tracker + // would get reset after each file. + private IContextTracker _globalContextTracker; + + private IContextTracker _noContextTracker; + + /// + /// This is used to handle the case were we're done processing input objects. + /// If true, process record will just return. + /// + private bool _doneProcessing; + + private ulong _inputRecordNumber; + + /// + /// Read command line parameters. + /// + protected override void BeginProcessing() + { + if (this.MyInvocation.BoundParameters.ContainsKey(nameof(Culture)) && !this.MyInvocation.BoundParameters.ContainsKey(nameof(SimpleMatch))) + { + InvalidOperationException exception = new(MatchStringStrings.CannotSpecifyCultureWithoutSimpleMatch); + ErrorRecord errorRecord = new(exception, "CannotSpecifyCultureWithoutSimpleMatch", ErrorCategory.InvalidData, null); + this.ThrowTerminatingError(errorRecord); + } + + InitCulture(); + + string suppressVt = Environment.GetEnvironmentVariable("__SuppressAnsiEscapeSequences"); + if (!string.IsNullOrEmpty(suppressVt)) + { + NoEmphasis = true; + } + + if (!SimpleMatch) + { + RegexOptions regexOptions = CaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase; + _regexPattern = new Regex[Pattern.Length]; + for (int i = 0; i < Pattern.Length; i++) + { + try + { + _regexPattern[i] = new Regex(Pattern[i], regexOptions); + } + catch (Exception e) + { + this.ThrowTerminatingError(BuildErrorRecord(MatchStringStrings.InvalidRegex, Pattern[i], e.Message, "InvalidRegex", e)); + throw; + } + } + } + + _noContextTracker = new NoContextTracker(); + _globalContextTracker = GetContextTracker(); + } + + private readonly List _inputObjectFileList = new(1) { string.Empty }; + + /// + /// Process the input. + /// + /// Regular expression parsing error, path error. + /// A file cannot be found. + /// A file cannot be found. + protected override void ProcessRecord() + { + if (_doneProcessing) + { + return; + } + + // We may only have directories when we have resolved wildcards + var expandedPathsMaybeDirectory = false; + List expandedPaths = null; + if (Path != null) + { + expandedPaths = ResolveFilePaths(Path, _isLiteralPath); + if (expandedPaths == null) + { + return; + } + + expandedPathsMaybeDirectory = true; + } + else + { + if (_inputObject.BaseObject is FileInfo fileInfo) + { + _inputObjectFileList[0] = fileInfo.FullName; + expandedPaths = _inputObjectFileList; + } + } + + if (expandedPaths != null) + { + foreach (var filename in expandedPaths) + { + if (expandedPathsMaybeDirectory && Directory.Exists(filename)) + { + continue; + } + + var foundMatch = ProcessFile(filename); + if (Quiet && foundMatch) + { + return; + } + } + + // No results in any files. + if (Quiet) + { + var res = List ? null : Boxed.False; + WriteObject(res); + } + } + else + { + // Set the line number in the matched object to be the record number + _inputRecordNumber++; + + bool matched; + MatchInfo result; + MatchInfo matchInfo = null; + if (_inputObject.BaseObject is string line) + { + matched = DoMatch(line, out result); + } + else + { + matchInfo = _inputObject.BaseObject as MatchInfo; + object objectToCheck = matchInfo ?? (object)_inputObject; + matched = DoMatch(objectToCheck, out result, out line); + } + + if (matched) + { + // Don't re-write the line number if it was already set... + if (matchInfo == null) + { + result.LineNumber = _inputRecordNumber; + } + + // doMatch will have already set the pattern and line text... + _globalContextTracker.TrackMatch(result); + } + else + { + _globalContextTracker.TrackLine(line); + } + + // Emit any queued up objects... + if (FlushTrackerQueue(_globalContextTracker)) + { + // If we're in quiet mode, go ahead and stop processing + // now. + if (Quiet) + { + _doneProcessing = true; + } + } + } + } + + /// + /// Process a file which was either specified on the + /// command line or passed in as a FileInfo object. + /// + /// The file to process. + /// True if a match was found; otherwise false. + private bool ProcessFile(string filename) + { + var contextTracker = GetContextTracker(); + + bool foundMatch = false; + + // Read the file one line at a time... + try + { + // see if the file is one the include exclude list... + if (!MeetsIncludeExcludeCriteria(filename)) + { + return false; + } + + using (FileStream fs = new(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + using (StreamReader sr = new(fs, Encoding)) + { + string line; + ulong lineNo = 0; + + // Read and display lines from the file until the end of + // the file is reached. + while ((line = sr.ReadLine()) != null) + { + lineNo++; + + if (DoMatch(line, out MatchInfo result)) + { + result.Path = filename; + result.LineNumber = lineNo; + contextTracker.TrackMatch(result); + } + else + { + contextTracker.TrackLine(line); + } + + // Flush queue of matches to emit. + if (contextTracker.EmitQueue.Count > 0) + { + foundMatch = true; + + // If -list or -quiet was specified, we only want to emit the first match + // for each file so record the object to emit and stop processing + // this file. It's done this way so the file is closed before emitting + // the result so the downstream cmdlet can actually manipulate the file + // that was found. + if (Quiet || List) + { + break; + } + + FlushTrackerQueue(contextTracker); + } + } + } + } + + // Check for any remaining matches. This could be caused + // by breaking out of the loop early for quiet or list + // mode, or by reaching EOF before we collected all + // our postcontext. + contextTracker.TrackEOF(); + if (FlushTrackerQueue(contextTracker)) + { + foundMatch = true; + } + } + catch (System.NotSupportedException nse) + { + WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, nse.Message, "ProcessingFile", nse)); + } + catch (System.IO.IOException ioe) + { + WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, ioe.Message, "ProcessingFile", ioe)); + } + catch (System.Security.SecurityException se) + { + WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, se.Message, "ProcessingFile", se)); + } + catch (System.UnauthorizedAccessException uae) + { + WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, uae.Message, "ProcessingFile", uae)); + } + + return foundMatch; + } + + /// + /// Emit any objects which have been queued up, and clear the queue. + /// + /// The context tracker to operate on. + /// Whether or not any objects were emitted. + private bool FlushTrackerQueue(IContextTracker contextTracker) + { + // Do we even have any matches to emit? + if (contextTracker.EmitQueue.Count < 1) + { + return false; + } + + if (Raw) + { + foreach (MatchInfo match in contextTracker.EmitQueue) + { + WriteObject(match.Line); + } + } + else if (Quiet && !List) + { + WriteObject(true); + } + else if (List) + { + WriteObject(contextTracker.EmitQueue[0]); + } + else + { + foreach (MatchInfo match in contextTracker.EmitQueue) + { + WriteObject(match); + } + } + + contextTracker.EmitQueue.Clear(); + return true; + } + + /// + /// Complete processing. Emits any objects which have been queued up + /// due to -context tracking. + /// + protected override void EndProcessing() + { + // Check for a leftover match that was still tracking context. + _globalContextTracker.TrackEOF(); + if (!_doneProcessing) + { + FlushTrackerQueue(_globalContextTracker); + } + } + + private bool DoMatch(string operandString, out MatchInfo matchResult) + { + return DoMatchWorker(operandString, null, out matchResult); + } + + private bool DoMatch(object operand, out MatchInfo matchResult, out string operandString) + { + MatchInfo matchInfo = operand as MatchInfo; + if (matchInfo != null) + { + // We're operating in filter mode. Match + // against the provided MatchInfo's line. + // If the user has specified context tracking, + // inform them that it is not allowed in filter + // mode and disable it. Also, reset the global + // context tracker used for processing pipeline + // objects to use the new settings. + operandString = matchInfo.Line; + + if (_preContext > 0 || _postContext > 0) + { + _preContext = 0; + _postContext = 0; + _globalContextTracker = new ContextTracker(_preContext, _postContext); + WarnFilterContext(); + } + } + else + { + operandString = (string)LanguagePrimitives.ConvertTo(operand, typeof(string), CultureInfo.InvariantCulture); + } + + return DoMatchWorker(operandString, matchInfo, out matchResult); + } + + /// + /// Check the operand and see if it matches, if this.quiet is not set, then + /// return a partially populated MatchInfo object with Line, Pattern, IgnoreCase set. + /// + /// The result of converting operand to a string. + /// The input object in filter mode. + /// The match info object - this will be null if this.quiet is set. + /// True if the input object matched. + private bool DoMatchWorker(string operandString, MatchInfo matchInfo, out MatchInfo matchResult) + { + bool gotMatch = false; + Match[] matches = null; + int patternIndex = 0; + matchResult = null; + + List indexes = null; + List lengths = null; + + bool shouldEmphasize = !NoEmphasis && Host.UI.SupportsVirtualTerminal; + + // If Emphasize is set and VT is supported, + // the lengths and starting indexes of regex matches + // need to be passed in to the matchInfo object. + if (shouldEmphasize) + { + indexes = new List(); + lengths = new List(); + } + + if (!SimpleMatch) + { + while (patternIndex < Pattern.Length) + { + Regex r = _regexPattern[patternIndex]; + + // Only honor allMatches if notMatch is not set, + // since it's a fairly expensive operation and + // notMatch takes precedent over allMatch. + if (AllMatches && !NotMatch) + { + MatchCollection mc = r.Matches(operandString); + if (mc.Count > 0) + { + matches = new Match[mc.Count]; + ((ICollection)mc).CopyTo(matches, 0); + + if (shouldEmphasize) + { + foreach (Match match in matches) + { + indexes.Add(match.Index); + lengths.Add(match.Length); + } + } + + gotMatch = true; + } + } + else + { + Match match = r.Match(operandString); + gotMatch = match.Success; + + if (match.Success) + { + if (shouldEmphasize) + { + indexes.Add(match.Index); + lengths.Add(match.Length); + } + + matches = new Match[] { match }; + } + } + + if (gotMatch) + { + break; + } + + patternIndex++; + } + } + else + { + while (patternIndex < Pattern.Length) + { + string pat = Pattern[patternIndex]; + + int index = _cultureInfoIndexOf(operandString, pat, 0, operandString.Length, _compareOptions); + if (index >= 0) + { + if (shouldEmphasize) + { + indexes.Add(index); + lengths.Add(pat.Length); + } + + gotMatch = true; + break; + } + + patternIndex++; + } + } + + if (NotMatch) + { + gotMatch = !gotMatch; + + // If notMatch was specified with multiple + // patterns, then *none* of the patterns + // matched and any pattern could be picked + // to report in MatchInfo. However, that also + // means that patternIndex will have been + // incremented past the end of the pattern array. + // So reset it to select the first pattern. + patternIndex = 0; + } + + if (gotMatch) + { + // if we were passed a MatchInfo object as the operand, + // we're operating in filter mode. + if (matchInfo != null) + { + // If the original MatchInfo was tracking context, + // we need to copy it and disable display context, + // since we can't guarantee it will be displayed + // correctly when filtered. + if (matchInfo.Context != null) + { + matchResult = matchInfo.Clone(); + matchResult.Context.DisplayPreContext = Array.Empty(); + matchResult.Context.DisplayPostContext = Array.Empty(); + } + else + { + // Otherwise, just pass the object as is. + matchResult = matchInfo; + } + + return true; + } + + // otherwise construct and populate a new MatchInfo object + matchResult = shouldEmphasize + ? new MatchInfo(indexes, lengths) + : new MatchInfo(); + matchResult.IgnoreCase = !CaseSensitive; + matchResult.Line = operandString; + matchResult.Pattern = Pattern[patternIndex]; + + if (_preContext > 0 || _postContext > 0) + { + matchResult.Context = new MatchInfoContext(); + } + + // Matches should be an empty list, rather than null, + // in the cases of notMatch and simpleMatch. + matchResult.Matches = matches ?? Array.Empty(); + + return true; + } + + return false; + } + + /// + /// Get a list or resolved file paths. + /// + /// The filePaths to resolve. + /// True if the wildcard resolution should not be attempted. + /// The resolved (absolute) paths. + private List ResolveFilePaths(string[] filePaths, bool isLiteralPath) + { + List allPaths = new(); + + foreach (string path in filePaths) + { + Collection resolvedPaths; + ProviderInfo provider; + if (isLiteralPath) + { + resolvedPaths = new Collection(); + string resolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path, out provider, out _); + resolvedPaths.Add(resolvedPath); + } + else + { + resolvedPaths = GetResolvedProviderPathFromPSPath(path, out provider); + } + + if (!provider.NameEquals(base.Context.ProviderNames.FileSystem)) + { + // "The current provider ({0}) cannot open a file" + WriteError(BuildErrorRecord(MatchStringStrings.FileOpenError, provider.FullName, "ProcessingFile", null)); + continue; + } + + allPaths.AddRange(resolvedPaths); + } + + return allPaths; + } + + private static ErrorRecord BuildErrorRecord(string messageId, string argument, string errorId, Exception innerException) + { + return BuildErrorRecord(messageId, new object[] { argument }, errorId, innerException); + } + + private static ErrorRecord BuildErrorRecord(string messageId, string arg0, string arg1, string errorId, Exception innerException) + { + return BuildErrorRecord(messageId, new object[] { arg0, arg1 }, errorId, innerException); + } + + private static ErrorRecord BuildErrorRecord(string messageId, object[] arguments, string errorId, Exception innerException) + { + string fmtedMsg = StringUtil.Format(messageId, arguments); + ArgumentException e = new(fmtedMsg, innerException); + return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null); + } + + private void WarnFilterContext() + { + string msg = MatchStringStrings.FilterContextWarning; + WriteWarning(msg); + } + + /// + /// Magic class that works around the limitations on ToString() for FileInfo. + /// + private sealed class FileinfoToStringAttribute : ArgumentTransformationAttribute + { + public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) + { + object result = inputData; + + if (result is PSObject mso) + { + result = mso.BaseObject; + } + + FileInfo fileInfo; + + // Handle an array of elements... + if (result is IList argList) + { + object[] resultList = new object[argList.Count]; + + for (int i = 0; i < argList.Count; i++) + { + object element = argList[i]; + + mso = element as PSObject; + if (mso != null) + { + element = mso.BaseObject; + } + + fileInfo = element as FileInfo; + resultList[i] = fileInfo?.FullName ?? element; + } + + return resultList; + } + + // Handle the singleton case... + fileInfo = result as FileInfo; + if (fileInfo != null) + { + return fileInfo.FullName; + } + + return inputData; + } + } + + /// + /// Check whether the supplied name meets the include/exclude criteria. + /// That is - it's on the include list if there is one and not on + /// the exclude list if there was one of those. + /// + /// The filename to test. + /// True if the filename is acceptable. + private bool MeetsIncludeExcludeCriteria(string filename) + { + bool ok = false; + + // see if the file is on the include list... + if (_include != null) + { + foreach (WildcardPattern patternItem in _include) + { + if (patternItem.IsMatch(filename)) + { + ok = true; + break; + } + } + } + else + { + ok = true; + } + + if (!ok) + { + return false; + } + + // now see if it's on the exclude list... + if (_exclude != null) + { + foreach (WildcardPattern patternItem in _exclude) + { + if (patternItem.IsMatch(filename)) + { + ok = false; + break; + } + } + } + + return ok; + } + } + + /// + /// Get list of valid culture names for ValidateSet attribute. + /// + public class ValidateMatchStringCultureNamesGenerator : IValidateSetValuesGenerator + { + string[] IValidateSetValuesGenerator.GetValidValues() + { + var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); + var result = new List(cultures.Length + 3); + result.Add(SelectStringCommand.OrdinalCultureName); + result.Add(SelectStringCommand.InvariantCultureName); + result.Add(SelectStringCommand.CurrentCultureName); + foreach (var cultureInfo in cultures) + { + result.Add(cultureInfo.Name); + } + + return result.ToArray(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..1e741758270d6a72f537d7f32c2a337269a130c9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -0,0 +1,995 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class output by Measure-Object. + /// + public abstract class MeasureInfo + { + /// + /// Property name. + /// + public string Property { get; set; } + } + + /// + /// Class output by Measure-Object. + /// + public sealed class GenericMeasureInfo : MeasureInfo + { + /// + /// Initializes a new instance of the class. + /// + public GenericMeasureInfo() + { + Average = Sum = Maximum = Minimum = StandardDeviation = null; + } + + /// + /// Keeping track of number of objects with a certain property. + /// + public int Count { get; set; } + + /// + /// The average of property values. + /// + public double? Average { get; set; } + + /// + /// The sum of property values. + /// + public double? Sum { get; set; } + + /// + /// The max of property values. + /// + public double? Maximum { get; set; } + + /// + /// The min of property values. + /// + public double? Minimum { get; set; } + + /// + /// The Standard Deviation of property values. + /// + public double? StandardDeviation { get; set; } + } + + /// + /// Class output by Measure-Object. + /// + /// + /// This class is created to make 'Measure-Object -MAX -MIN' work with ANYTHING that supports 'CompareTo'. + /// GenericMeasureInfo class is shipped with PowerShell V2. Fixing this bug requires, changing the type of + /// Maximum and Minimum properties which would be a breaking change. Hence created a new class to not + /// have an appcompat issues with PS V2. + /// + public sealed class GenericObjectMeasureInfo : MeasureInfo + { + /// + /// Initializes a new instance of the class. + /// Default ctor. + /// + public GenericObjectMeasureInfo() + { + Average = Sum = StandardDeviation = null; + Maximum = Minimum = null; + } + + /// + /// Keeping track of number of objects with a certain property. + /// + public int Count { get; set; } + + /// + /// The average of property values. + /// + public double? Average { get; set; } + + /// + /// The sum of property values. + /// + public double? Sum { get; set; } + + /// + /// The max of property values. + /// + public object Maximum { get; set; } + + /// + /// The min of property values. + /// + public object Minimum { get; set; } + + /// + /// The Standard Deviation of property values. + /// + public double? StandardDeviation { get; set; } + } + + /// + /// Class output by Measure-Object. + /// + public sealed class TextMeasureInfo : MeasureInfo + { + /// + /// Initializes a new instance of the class. + /// Default ctor. + /// + public TextMeasureInfo() + { + Lines = Words = Characters = null; + } + + /// + /// Keeping track of number of objects with a certain property. + /// + public int? Lines { get; set; } + + /// + /// The average of property values. + /// + public int? Words { get; set; } + + /// + /// The sum of property values. + /// + public int? Characters { get; set; } + } + + /// + /// Measure object cmdlet. + /// + [Cmdlet(VerbsDiagnostic.Measure, "Object", DefaultParameterSetName = GenericParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096617", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(GenericMeasureInfo), typeof(TextMeasureInfo), typeof(GenericObjectMeasureInfo))] + public sealed class MeasureObjectCommand : PSCmdlet + { + /// + /// Dictionary to be used by Measure-Object implementation. + /// Keys are strings. Keys are compared with OrdinalIgnoreCase. + /// + /// Value type. + private sealed class MeasureObjectDictionary : Dictionary + where TValue : new() + { + /// + /// Initializes a new instance of the class. + /// Default ctor. + /// + internal MeasureObjectDictionary() : base(StringComparer.OrdinalIgnoreCase) + { + } + + /// + /// Attempt to look up the value associated with the + /// the specified key. If a value is not found, associate + /// the key with a new value created via the value type's + /// default constructor. + /// + /// The key to look up. + /// + /// The existing value, or a newly-created value. + /// + public TValue EnsureEntry(string key) + { + TValue val; + if (!TryGetValue(key, out val)) + { + val = new TValue(); + this[key] = val; + } + + return val; + } + } + + /// + /// Convenience class to track statistics without having + /// to maintain two sets of MeasureInfo and constantly checking + /// what mode we're in. + /// + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] + private sealed class Statistics + { + // Common properties + internal int count = 0; + + // Generic/Numeric statistics + internal double sum = 0.0; + internal double sumPrevious = 0.0; + internal double variance = 0.0; + internal object max = null; + internal object min = null; + + // Text statistics + internal int characters = 0; + internal int words = 0; + internal int lines = 0; + } + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public MeasureObjectCommand() + : base() + { + } + + #region Command Line Switches + + #region Common parameters in both sets + + /// + /// Incoming object. + /// + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// Properties to be examined. + /// + /// + [ValidateNotNullOrEmpty] + [Parameter(Position = 0)] + public PSPropertyExpression[] Property { get; set; } + + #endregion Common parameters in both sets + + /// + /// Set to true if Standard Deviation is to be returned. + /// + [Parameter(ParameterSetName = GenericParameterSet)] + public SwitchParameter StandardDeviation + { + get + { + return _measureStandardDeviation; + } + + set + { + _measureStandardDeviation = value; + } + } + + private bool _measureStandardDeviation; + + /// + /// Set to true is Sum is to be returned. + /// + /// + [Parameter(ParameterSetName = GenericParameterSet)] + public SwitchParameter Sum + { + get + { + return _measureSum; + } + + set + { + _measureSum = value; + } + } + + private bool _measureSum; + + /// + /// Gets or sets the value indicating if all statistics should be returned. + /// + /// + [Parameter(ParameterSetName = GenericParameterSet)] + public SwitchParameter AllStats + { + get + { + return _allStats; + } + + set + { + _allStats = value; + } + } + + private bool _allStats; + + /// + /// Set to true is Average is to be returned. + /// + /// + [Parameter(ParameterSetName = GenericParameterSet)] + public SwitchParameter Average + { + get + { + return _measureAverage; + } + + set + { + _measureAverage = value; + } + } + + private bool _measureAverage; + + /// + /// Set to true is Max is to be returned. + /// + /// + [Parameter(ParameterSetName = GenericParameterSet)] + public SwitchParameter Maximum + { + get + { + return _measureMax; + } + + set + { + _measureMax = value; + } + } + + private bool _measureMax; + + /// + /// Set to true is Min is to be returned. + /// + /// + [Parameter(ParameterSetName = GenericParameterSet)] + public SwitchParameter Minimum + { + get + { + return _measureMin; + } + + set + { + _measureMin = value; + } + } + + private bool _measureMin; + + #region TextMeasure ParameterSet + /// + /// + /// + [Parameter(ParameterSetName = TextParameterSet)] + public SwitchParameter Line + { + get + { + return _measureLines; + } + + set + { + _measureLines = value; + } + } + + private bool _measureLines = false; + + /// + /// + /// + [Parameter(ParameterSetName = TextParameterSet)] + public SwitchParameter Word + { + get + { + return _measureWords; + } + + set + { + _measureWords = value; + } + } + + private bool _measureWords = false; + + /// + /// + /// + [Parameter(ParameterSetName = TextParameterSet)] + public SwitchParameter Character + { + get + { + return _measureCharacters; + } + + set + { + _measureCharacters = value; + } + } + + private bool _measureCharacters = false; + + /// + /// + /// + [Parameter(ParameterSetName = TextParameterSet)] + public SwitchParameter IgnoreWhiteSpace + { + get + { + return _ignoreWhiteSpace; + } + + set + { + _ignoreWhiteSpace = value; + } + } + + private bool _ignoreWhiteSpace; + + #endregion TextMeasure ParameterSet + #endregion Command Line Switches + + /// + /// Which parameter set the Cmdlet is in. + /// + private bool IsMeasuringGeneric + { + get + { + return string.Equals(ParameterSetName, GenericParameterSet, StringComparison.Ordinal); + } + } + + /// + /// Does the begin part of the cmdlet. + /// + protected override void BeginProcessing() + { + // Sets all other generic parameters to true to get all statistics. + if (_allStats) + { + _measureSum = _measureStandardDeviation = _measureAverage = _measureMax = _measureMin = true; + } + + // finally call the base class. + base.BeginProcessing(); + } + + /// + /// Collect data about each record that comes in. + /// Side effects: Updates totalRecordCount. + /// + protected override void ProcessRecord() + { + if (InputObject == null || InputObject == AutomationNull.Value) + { + return; + } + + _totalRecordCount++; + + if (Property == null) + AnalyzeValue(null, InputObject.BaseObject); + else + AnalyzeObjectProperties(InputObject); + } + + /// + /// Analyze an object on a property-by-property basis instead + /// of as a simple value. + /// Side effects: Updates statistics. + /// + /// The object to analyze. + private void AnalyzeObjectProperties(PSObject inObj) + { + // Keep track of which properties are counted for an + // input object so that repeated properties won't be + // counted twice. + MeasureObjectDictionary countedProperties = new(); + + // First iterate over the user-specified list of + // properties... + foreach (var expression in Property) + { + List resolvedNames = expression.ResolveNames(inObj); + if (resolvedNames == null || resolvedNames.Count == 0) + { + // Insert a blank entry so we can track + // property misses in EndProcessing. + if (!expression.HasWildCardCharacters) + { + string propertyName = expression.ToString(); + _statistics.EnsureEntry(propertyName); + } + + continue; + } + + // Each property value can potentially refer + // to multiple properties via globbing. Iterate over + // the actual property names. + foreach (PSPropertyExpression resolvedName in resolvedNames) + { + string propertyName = resolvedName.ToString(); + // skip duplicated properties + if (countedProperties.ContainsKey(propertyName)) + { + continue; + } + + List tempExprRes = resolvedName.GetValues(inObj); + if (tempExprRes == null || tempExprRes.Count == 0) + { + // Shouldn't happen - would somehow mean + // that the property went away between when + // we resolved it and when we tried to get its + // value. + continue; + } + + AnalyzeValue(propertyName, tempExprRes[0].Result); + + // Remember resolved propertyNames that have been counted + countedProperties[propertyName] = null; + } + } + } + + /// + /// Analyze a value for generic/text statistics. + /// Side effects: Updates statistics. May set nonNumericError. + /// + /// The property this value corresponds to. + /// The value to analyze. + private void AnalyzeValue(string propertyName, object objValue) + { + propertyName ??= thisObject; + + Statistics stat = _statistics.EnsureEntry(propertyName); + + // Update common properties. + stat.count++; + + if (_measureCharacters || _measureWords || _measureLines) + { + string strValue = (objValue == null) ? string.Empty : objValue.ToString(); + AnalyzeString(strValue, stat); + } + + if (_measureAverage || _measureSum || _measureStandardDeviation) + { + double numValue = 0.0; + if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) + { + _nonNumericError = true; + ErrorRecord errorRecord = new( + PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), + "NonNumericInputObject", + ErrorCategory.InvalidType, + objValue); + WriteError(errorRecord); + return; + } + + AnalyzeNumber(numValue, stat); + } + + // Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo + if (_measureMin) + { + stat.min = Compare(objValue, stat.min, true); + } + + if (_measureMax) + { + stat.max = Compare(objValue, stat.max, false); + } + } + + /// + /// Compare is a helper function used to find the min/max between the supplied input values. + /// + /// + /// Current input value. + /// + /// + /// Current minimum or maximum value in the statistics. + /// + /// + /// Indicates if minimum or maximum value has to be found. + /// If true is passed in then the minimum of the two values would be returned. + /// If false is passed in then maximum of the two values will be returned. + /// + private static object Compare(object objValue, object statMinOrMaxValue, bool isMin) + { + object currentValue = objValue; + object statValue = statMinOrMaxValue; + + double temp; + currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo(objValue, out temp)) ? temp : currentValue; + statValue = ((statValue != null) && LanguagePrimitives.TryConvertTo(statValue, out temp)) ? temp : statValue; + + if (currentValue != null && statValue != null && !currentValue.GetType().Equals(statValue.GetType())) + { + currentValue = PSObject.AsPSObject(currentValue).ToString(); + statValue = PSObject.AsPSObject(statValue).ToString(); + } + + if (statValue == null) + { + return objValue; + } + + int comparisonResult = LanguagePrimitives.Compare(statValue, currentValue, ignoreCase: false, CultureInfo.CurrentCulture); + return (isMin ? comparisonResult : -comparisonResult) > 0 + ? objValue + : statMinOrMaxValue; + } + + /// + /// Class contains util static functions. + /// + private static class TextCountUtilities + { + /// + /// Count chars in inStr. + /// + /// String whose chars are counted. + /// True to discount white space. + /// Number of chars in inStr. + internal static int CountChar(string inStr, bool ignoreWhiteSpace) + { + if (string.IsNullOrEmpty(inStr)) + { + return 0; + } + + if (!ignoreWhiteSpace) + { + return inStr.Length; + } + + int len = 0; + foreach (char c in inStr) + { + if (!char.IsWhiteSpace(c)) + { + len++; + } + } + + return len; + } + + /// + /// Count words in inStr. + /// + /// String whose words are counted. + /// Number of words in inStr. + internal static int CountWord(string inStr) + { + if (string.IsNullOrEmpty(inStr)) + { + return 0; + } + + int wordCount = 0; + bool wasAWhiteSpace = true; + foreach (char c in inStr) + { + if (char.IsWhiteSpace(c)) + { + wasAWhiteSpace = true; + } + else + { + if (wasAWhiteSpace) + { + wordCount++; + } + + wasAWhiteSpace = false; + } + } + + return wordCount; + } + + /// + /// Count lines in inStr. + /// + /// String whose lines are counted. + /// Number of lines in inStr. + internal static int CountLine(string inStr) + { + if (string.IsNullOrEmpty(inStr)) + { + return 0; + } + + int numberOfLines = 0; + foreach (char c in inStr) + { + if (c == '\n') + { + numberOfLines++; + } + } + // 'abc\nd' has two lines + // but 'abc\n' has one line + if (inStr[inStr.Length - 1] != '\n') + { + numberOfLines++; + } + + return numberOfLines; + } + } + + /// + /// Update text statistics. + /// + /// The text to analyze. + /// The Statistics object to update. + private void AnalyzeString(string strValue, Statistics stat) + { + if (_measureCharacters) + stat.characters += TextCountUtilities.CountChar(strValue, _ignoreWhiteSpace); + if (_measureWords) + stat.words += TextCountUtilities.CountWord(strValue); + if (_measureLines) + stat.lines += TextCountUtilities.CountLine(strValue); + } + + /// + /// Update number statistics. + /// + /// The number to analyze. + /// The Statistics object to update. + private void AnalyzeNumber(double numValue, Statistics stat) + { + if (_measureSum || _measureAverage || _measureStandardDeviation) + { + stat.sumPrevious = stat.sum; + stat.sum += numValue; + } + + if (_measureStandardDeviation && stat.count > 1) + { + // Based off of iterative method of calculating variance on + // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm + double avgPrevious = stat.sumPrevious / (stat.count - 1); + stat.variance *= (stat.count - 2.0) / (stat.count - 1); + stat.variance += (numValue - avgPrevious) * (numValue - avgPrevious) / stat.count; + } + } + + /// + /// WriteError when a property is not found. + /// + /// The missing property. + /// The error ID to write. + private void WritePropertyNotFoundError(string propertyName, string errorId) + { + Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); + ErrorRecord errorRecord = new( + PSTraceSource.NewArgumentException(propertyName), + errorId, + ErrorCategory.ObjectNotFound, + null); + errorRecord.ErrorDetails = new ErrorDetails( + this, "MeasureObjectStrings", "PropertyNotFound", propertyName); + WriteError(errorRecord); + } + + /// + /// Output collected statistics. + /// Side effects: Updates statistics. Writes objects to stream. + /// + protected override void EndProcessing() + { + // Fix for 917114: If Property is not set, + // and we aren't passed any records at all, + // output 0s to emulate wc behavior. + if (_totalRecordCount == 0 && Property == null) + { + _statistics.EnsureEntry(thisObject); + } + + foreach (string propertyName in _statistics.Keys) + { + Statistics stat = _statistics[propertyName]; + if (stat.count == 0 && Property != null) + { + if (Context.IsStrictVersion(2)) + { + string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; + WritePropertyNotFoundError(propertyName, errorId); + } + + continue; + } + + MeasureInfo mi = null; + if (IsMeasuringGeneric) + { + double temp; + if ((stat.min == null || LanguagePrimitives.TryConvertTo(stat.min, out temp)) && + (stat.max == null || LanguagePrimitives.TryConvertTo(stat.max, out temp))) + { + mi = CreateGenericMeasureInfo(stat, true); + } + else + { + mi = CreateGenericMeasureInfo(stat, false); + } + } + else + mi = CreateTextMeasureInfo(stat); + + // Set common properties. + if (Property != null) + mi.Property = propertyName; + + WriteObject(mi); + } + } + + /// + /// Create a MeasureInfo object for generic stats. + /// + /// The statistics to use. + /// + /// A new GenericMeasureInfo object. + private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGenericMeasureInfo) + { + double? sum = null; + double? average = null; + double? StandardDeviation = null; + object max = null; + object min = null; + + if (!_nonNumericError) + { + if (_measureSum) + sum = stat.sum; + + if (_measureAverage && stat.count > 0) + average = stat.sum / stat.count; + + if (_measureStandardDeviation) + { + StandardDeviation = Math.Sqrt(stat.variance); + } + } + + if (_measureMax) + { + if (shouldUseGenericMeasureInfo && (stat.max != null)) + { + double temp; + LanguagePrimitives.TryConvertTo(stat.max, out temp); + max = temp; + } + else + { + max = stat.max; + } + } + + if (_measureMin) + { + if (shouldUseGenericMeasureInfo && (stat.min != null)) + { + double temp; + LanguagePrimitives.TryConvertTo(stat.min, out temp); + min = temp; + } + else + { + min = stat.min; + } + } + + if (shouldUseGenericMeasureInfo) + { + GenericMeasureInfo gmi = new(); + gmi.Count = stat.count; + gmi.Sum = sum; + gmi.Average = average; + gmi.StandardDeviation = StandardDeviation; + if (max != null) + { + gmi.Maximum = (double)max; + } + + if (min != null) + { + gmi.Minimum = (double)min; + } + + return gmi; + } + else + { + GenericObjectMeasureInfo gomi = new(); + gomi.Count = stat.count; + gomi.Sum = sum; + gomi.Average = average; + gomi.Maximum = max; + gomi.Minimum = min; + + return gomi; + } + } + + /// + /// Create a MeasureInfo object for text stats. + /// + /// The statistics to use. + /// A new TextMeasureInfo object. + private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) + { + TextMeasureInfo tmi = new(); + + if (_measureCharacters) + tmi.Characters = stat.characters; + if (_measureWords) + tmi.Words = stat.words; + if (_measureLines) + tmi.Lines = stat.lines; + + return tmi; + } + + /// + /// The observed statistics keyed by property name. + /// If Property is not set, then the key used will be the value of thisObject. + /// + private readonly MeasureObjectDictionary _statistics = new(); + + /// + /// Whether or not a numeric conversion error occurred. + /// If true, then average/sum/standard deviation will not be output. + /// + private bool _nonNumericError = false; + + /// + /// The total number of records encountered. + /// + private int _totalRecordCount = 0; + + /// + /// Parameter set name for measuring objects. + /// + private const string GenericParameterSet = "GenericMeasure"; + + /// + /// Parameter set name for measuring text. + /// + private const string TextParameterSet = "TextMeasure"; + + /// + /// Key that statistics are stored under when Property is not set. + /// + private const string thisObject = "$_"; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..0ea312f2963debf27deab349dccb99eb7d0f019b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -0,0 +1,551 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Management.Automation.Security; +using System.Reflection; +using System.Runtime.InteropServices; +#if !UNIX +using System.Threading; +#endif + +using Dbg = System.Management.Automation.Diagnostics; + +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// Create a new .net object + [Cmdlet(VerbsCommon.New, "Object", DefaultParameterSetName = netSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096620")] + public sealed class NewObjectCommand : PSCmdlet + { + #region parameters + + /// the number + [Parameter(ParameterSetName = netSetName, Mandatory = true, Position = 0)] + [ValidateTrustedData] + public string TypeName { get; set; } + +#if !UNIX + private Guid _comObjectClsId = Guid.Empty; + /// + /// The ProgID of the Com object. + /// + [Parameter(ParameterSetName = "Com", Mandatory = true, Position = 0)] + [ValidateTrustedData] + public string ComObject { get; set; } +#endif + + /// + /// The parameters for the constructor. + /// + /// + [Parameter(ParameterSetName = netSetName, Mandatory = false, Position = 1)] + [ValidateTrustedData] + [Alias("Args")] + public object[] ArgumentList { get; set; } + + /// + /// True if we should have an error when Com objects will use an interop assembly. + /// + [Parameter(ParameterSetName = "Com")] + public SwitchParameter Strict { get; set; } + + // Updated from Hashtable to IDictionary to support the work around ordered hashtables. + /// + /// Gets the properties to be set. + /// + [Parameter] + [ValidateTrustedData] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public IDictionary Property { get; set; } + + #endregion parameters + + #region private + private object CallConstructor(Type type, ConstructorInfo[] constructors, object[] args) + { + object result = null; + try + { + result = DotNetAdapter.ConstructorInvokeDotNet(type, constructors, args); + } + catch (MethodException e) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "ConstructorInvokedThrowException", + ErrorCategory.InvalidOperation, null)); + } + // let other exceptions propagate + return result; + } + + private void CreateMemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType) + { + string message = StringUtil.Format(NewObjectStrings.MemberNotFound, null, property.Key.ToString(), ParameterSet2ResourceString(ParameterSetName)); + + ThrowTerminatingError( + new ErrorRecord( + new InvalidOperationException(message), + "InvalidOperationException", + ErrorCategory.InvalidOperation, + null)); + } + + private void CreateMemberSetValueError(SetValueException e) + { + Exception ex = new(StringUtil.Format(NewObjectStrings.InvalidValue, e)); + ThrowTerminatingError( + new ErrorRecord(ex, "SetValueException", ErrorCategory.InvalidData, null)); + } + + private static string ParameterSet2ResourceString(string parameterSet) + { + if (parameterSet.Equals(netSetName, StringComparison.OrdinalIgnoreCase)) + { + return ".NET"; + } + else if (parameterSet.Equals("Com", StringComparison.OrdinalIgnoreCase)) + { + return "COM"; + } + else + { + Dbg.Assert(false, "Should never get here - unknown parameter set"); + return parameterSet; + } + } + + #endregion private + + #region Overrides + /// Create the object + protected override void BeginProcessing() + { + Type type = null; + PSArgumentException mshArgE = null; + + if (string.Equals(ParameterSetName, netSetName, StringComparison.Ordinal)) + { + object _newObject = null; + try + { + type = LanguagePrimitives.ConvertTo(TypeName, typeof(Type), CultureInfo.InvariantCulture) as Type; + } + catch (Exception e) + { + // these complications in Exception handling are aim to make error messages better. + if (e is InvalidCastException || e is ArgumentException) + { + if (e.InnerException != null && e.InnerException is TypeResolver.AmbiguousTypeException) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "AmbiguousTypeReference", + ErrorCategory.InvalidType, + targetObject: null)); + } + + mshArgE = PSTraceSource.NewArgumentException( + "TypeName", + NewObjectStrings.TypeNotFound, + TypeName); + + ThrowTerminatingError( + new ErrorRecord( + mshArgE, + "TypeNotFound", + ErrorCategory.InvalidType, + targetObject: null)); + } + + throw; + } + + Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true"); + + if (type.IsByRefLike) + { + ThrowTerminatingError( + new ErrorRecord( + PSTraceSource.NewInvalidOperationException( + NewObjectStrings.CannotInstantiateBoxedByRefLikeType, + type), + nameof(NewObjectStrings.CannotInstantiateBoxedByRefLikeType), + ErrorCategory.InvalidOperation, + targetObject: null)); + } + + switch (Context.LanguageMode) + { + case PSLanguageMode.ConstrainedLanguage: + if (!CoreTypes.Contains(type)) + { + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), + "CannotCreateTypeConstrainedLanguage", + ErrorCategory.PermissionDenied, + targetObject: null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: NewObjectStrings.TypeWDACLogTitle, + message: StringUtil.Format(NewObjectStrings.TypeWDACLogMessage, type.FullName), + fqid: "NewObjectCmdletCannotCreateType", + dropIntoDebugger: true); + } + break; + + case PSLanguageMode.NoLanguage: + case PSLanguageMode.RestrictedLanguage: + if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce + && !CoreTypes.Contains(type)) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException( + string.Format(NewObjectStrings.CannotCreateTypeLanguageMode, Context.LanguageMode.ToString())), + nameof(NewObjectStrings.CannotCreateTypeLanguageMode), + ErrorCategory.PermissionDenied, + targetObject: null)); + } + break; + } + + // WinRT does not support creating instances of attribute & delegate WinRT types. + if (WinRTHelper.IsWinRTType(type) && ((typeof(System.Attribute)).IsAssignableFrom(type) || (typeof(System.Delegate)).IsAssignableFrom(type))) + { + ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType), + "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null)); + } + + if (ArgumentList == null || ArgumentList.Length == 0) + { + ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes); + if (ci != null && ci.IsPublic) + { + _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, Array.Empty()); + if (_newObject != null && Property != null) + { + // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2 + _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); + } + + WriteObject(_newObject); + return; + } + else if (type.IsValueType) + { + // This is for default parameterless struct ctor which is not returned by + // Type.GetConstructor(System.Type.EmptyTypes). + try + { + _newObject = Activator.CreateInstance(type); + if (_newObject != null && Property != null) + { + // Win8:649519 + _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); + } + } + catch (TargetInvocationException e) + { + ThrowTerminatingError( + new ErrorRecord( + e.InnerException ?? e, + "ConstructorCalledThrowException", + ErrorCategory.InvalidOperation, null)); + } + + WriteObject(_newObject); + return; + } + } + else + { + ConstructorInfo[] ctorInfos = type.GetConstructors(); + + if (ctorInfos.Length != 0) + { + _newObject = CallConstructor(type, ctorInfos, ArgumentList); + if (_newObject != null && Property != null) + { + // Win8:649519 + _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); + } + + WriteObject(_newObject); + return; + } + } + + mshArgE = PSTraceSource.NewArgumentException( + "TypeName", NewObjectStrings.CannotFindAppropriateCtor, TypeName); + ThrowTerminatingError( + new ErrorRecord( + mshArgE, + "CannotFindAppropriateCtor", + ErrorCategory.ObjectNotFound, null)); + } +#if !UNIX + else // Parameterset -Com + { + int result = NewObjectNativeMethods.CLSIDFromProgID(ComObject, out _comObjectClsId); + + // If we're in ConstrainedLanguage, do additional restrictions + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + { + bool isAllowed = false; + + // If it's a system-wide lockdown, we may allow additional COM types + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); + if (systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) + { + isAllowed = (result >= 0) && SystemPolicy.IsClassInApprovedList(_comObjectClsId); + } + + if (!isAllowed) + { + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), + "CannotCreateComTypeConstrainedLanguage", + ErrorCategory.PermissionDenied, + targetObject: null)); + return; + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: NewObjectStrings.ComWDACLogTitle, + message: StringUtil.Format(NewObjectStrings.ComWDACLogMessage, ComObject ?? string.Empty), + fqid: "NewObjectCmdletCannotCreateCOM", + dropIntoDebugger: true); + } + } + + object comObject = CreateComObject(); + string comObjectTypeName = comObject.GetType().FullName; + if (!comObjectTypeName.Equals("System.__ComObject")) + { + mshArgE = PSTraceSource.NewArgumentException( + "TypeName", NewObjectStrings.ComInteropLoaded, comObjectTypeName); + WriteVerbose(mshArgE.Message); + if (Strict) + { + WriteError(new ErrorRecord( + mshArgE, + "ComInteropLoaded", + ErrorCategory.InvalidArgument, comObject)); + } + } + + if (comObject != null && Property != null) + { + // Win8:649519 + comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); + } + + WriteObject(comObject); + } +#endif + } + + #endregion Overrides + +#if !UNIX + #region Com + + private object SafeCreateInstance(Type t) + { + object result = null; + try + { + result = Activator.CreateInstance(t); + } + // Does not catch InvalidComObjectException because ComObject is obtained from GetTypeFromProgID + catch (ArgumentException e) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "CannotNewNonRuntimeType", + ErrorCategory.InvalidOperation, null)); + } + catch (NotSupportedException e) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "CannotNewTypeBuilderTypedReferenceArgIteratorRuntimeArgumentHandle", + ErrorCategory.InvalidOperation, null)); + } + catch (MethodAccessException e) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "CtorAccessDenied", + ErrorCategory.PermissionDenied, null)); + } + catch (MissingMethodException e) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "NoPublicCtorMatch", + ErrorCategory.InvalidOperation, null)); + } + catch (MemberAccessException e) + { + ThrowTerminatingError( + new ErrorRecord( + e, + "CannotCreateAbstractClass", + ErrorCategory.InvalidOperation, null)); + } + catch (COMException e) + { + if (e.HResult == RPC_E_CHANGED_MODE) + { + throw; + } + + ThrowTerminatingError( + new ErrorRecord( + e, + "NoCOMClassIdentified", + ErrorCategory.ResourceUnavailable, null)); + } + + return result; + } + + private sealed class ComCreateInfo + { + public object objectCreated; + public bool success; + public Exception e; + } + + private ComCreateInfo createInfo; + + private void STAComCreateThreadProc(object createstruct) + { + ComCreateInfo info = (ComCreateInfo)createstruct; + try + { + Type type = Type.GetTypeFromCLSID(_comObjectClsId); + if (type == null) + { + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( + "ComObject", + NewObjectStrings.CannotLoadComObjectType, + ComObject); + + info.e = mshArgE; + info.success = false; + return; + } + + info.objectCreated = SafeCreateInstance(type); + info.success = true; + } + catch (Exception e) + { + info.e = e; + info.success = false; + } + } + + private object CreateComObject() + { + try + { + Type type = Marshal.GetTypeFromCLSID(_comObjectClsId); + if (type == null) + { + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( + "ComObject", + NewObjectStrings.CannotLoadComObjectType, + ComObject); + + ThrowTerminatingError( + new ErrorRecord( + mshArgE, + "CannotLoadComObjectType", + ErrorCategory.InvalidType, + targetObject: null)); + } + + return SafeCreateInstance(type); + } + catch (COMException e) + { + // Check Error Code to see if Error is because of Com apartment Mismatch. + if (e.HResult == RPC_E_CHANGED_MODE) + { + createInfo = new ComCreateInfo(); + + Thread thread = new(new ParameterizedThreadStart(STAComCreateThreadProc)); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(createInfo); + + thread.Join(); + + if (createInfo.success) + { + return createInfo.objectCreated; + } + + ThrowTerminatingError( + new ErrorRecord(createInfo.e, "NoCOMClassIdentified", + ErrorCategory.ResourceUnavailable, null)); + } + else + { + ThrowTerminatingError( + new ErrorRecord( + e, + "NoCOMClassIdentified", + ErrorCategory.ResourceUnavailable, null)); + } + + return null; + } + } + + #endregion Com +#endif + + // HResult code '-2147417850' - Cannot change thread mode after it is set. + private const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106); + private const string netSetName = "Net"; + } + + /// + /// Native methods for dealing with COM objects. + /// + internal static class NewObjectNativeMethods + { + /// Return Type: HRESULT->LONG->int + [DllImport(PinvokeDllNames.CLSIDFromProgIDDllName)] + internal static extern int CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..8ae43a6e4fda8de01f71b911421af0cd4d18f2c4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "new-alias" cmdlet. + /// + [Cmdlet(VerbsCommon.New, "Alias", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097022")] + [OutputType(typeof(AliasInfo))] + public class NewAliasCommand : WriteAliasCommandBase + { + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + // If not force, then see if the alias already exists + + if (!Force) + { + AliasInfo existingAlias = null; + if (string.IsNullOrEmpty(Scope)) + { + existingAlias = SessionState.Internal.GetAlias(Name); + } + else + { + existingAlias = SessionState.Internal.GetAliasAtScope(Name, Scope); + } + + if (existingAlias != null) + { + // Throw if alias exists and is private... + SessionState.ThrowIfNotVisible(this.CommandOrigin, existingAlias); + + // Since the alias already exists, write an error. + + SessionStateException aliasExists = + new( + Name, + SessionStateCategory.Alias, + "AliasAlreadyExists", + SessionStateStrings.AliasAlreadyExists, + ErrorCategory.ResourceExists); + + WriteError( + new ErrorRecord( + aliasExists.ErrorRecord, + aliasExists)); + return; + } + } + + // Create the alias info + + AliasInfo newAlias = + new( + Name, + Value, + Context, + Option); + + newAlias.Description = Description; + + string action = + AliasCommandStrings.NewAliasAction; + + string target = + StringUtil.Format(AliasCommandStrings.NewAliasTarget, Name, Value); + + if (ShouldProcess(target, action)) + { + // Set the alias in the specified scope or the + // current scope. + + AliasInfo result = null; + + try + { + if (string.IsNullOrEmpty(Scope)) + { + result = SessionState.Internal.SetAliasItem(newAlias, Force, MyInvocation.CommandOrigin); + } + else + { + result = SessionState.Internal.SetAliasItemAtScope(newAlias, Scope, Force, MyInvocation.CommandOrigin); + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + return; + } + catch (PSArgumentOutOfRangeException argOutOfRange) + { + WriteError( + new ErrorRecord( + argOutOfRange.ErrorRecord, + argOutOfRange)); + return; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + return; + } + + // Write the alias to the pipeline if PassThru was specified + + if (PassThru && result != null) + { + WriteObject(result); + } + } + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..1e46241b2d89cce8556e0155f5a065fc7a8e8baa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Generates a new event notification. + /// + [Cmdlet(VerbsCommon.New, "Event", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096708")] + [OutputType(typeof(PSEventArgs))] + public class NewEventCommand : PSCmdlet + { + #region parameters + + /// + /// Adds an event to the event queue. + /// + [Parameter(Position = 0, Mandatory = true)] + public string SourceIdentifier + { + get + { + return _sourceIdentifier; + } + + set + { + _sourceIdentifier = value; + } + } + + private string _sourceIdentifier = null; + + /// + /// Data relating to this event. + /// + [Parameter(Position = 1)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public PSObject Sender + { + get + { + return _sender; + } + + set + { + _sender = value; + } + } + + private PSObject _sender = null; + + /// + /// Data relating to this event. + /// + [Parameter(Position = 2)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public PSObject[] EventArguments + { + get + { + return _eventArguments; + } + + set + { + if (_eventArguments != null) + { + _eventArguments = value; + } + } + } + + private PSObject[] _eventArguments = Array.Empty(); + + /// + /// Data relating to this event. + /// + [Parameter(Position = 3)] + public PSObject MessageData + { + get + { + return _messageData; + } + + set + { + _messageData = value; + } + } + + private PSObject _messageData = null; + + #endregion parameters + + /// + /// Add the event to the event queue. + /// + protected override void EndProcessing() + { + object[] baseEventArgs = null; + + // Get the BaseObject from the event arguments + if (_eventArguments != null) + { + baseEventArgs = new object[_eventArguments.Length]; + int loopCounter = 0; + foreach (PSObject eventArg in _eventArguments) + { + if (eventArg != null) + baseEventArgs[loopCounter] = eventArg.BaseObject; + + loopCounter++; + } + } + + object messageSender = null; + if (_sender != null) + { + messageSender = _sender.BaseObject; + } + + // And then generate the event + WriteObject(Events.GenerateEvent(_sourceIdentifier, messageSender, baseEventArgs, _messageData, true, false)); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..0e466f86d3f35f02f9ef3d8783bac652d1bf7546 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "new-guid" cmdlet. + /// + [Cmdlet(VerbsCommon.New, "Guid", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097130")] + [OutputType(typeof(Guid))] + public class NewGuidCommand : PSCmdlet + { + /// + /// Gets or sets a value indicating that the cmdlet should return a Guid structure whose value is all zeros. + /// + [Parameter(ParameterSetName = "Empty")] + public SwitchParameter Empty { get; set; } + + /// + /// Gets or sets the value to be converted to a Guid. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "InputObject")] + [System.Diagnostics.CodeAnalysis.AllowNull] + public string InputObject { get; set; } + + /// + /// Returns a Guid. + /// + protected override void ProcessRecord() + { + Guid? guid = null; + + if (ParameterSetName is "InputObject") + { + try + { + guid = new(InputObject); + } + catch (Exception ex) + { + ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidArgument, null); + WriteError(error); + } + } + else + { + guid = Empty.ToBool() ? Guid.Empty : Guid.NewGuid(); + } + + WriteObject(guid); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..93b3eb209af158539e7a0dac9c80921c88ce4d1a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "New-TemporaryFile" cmdlet. + /// + [Cmdlet(VerbsCommon.New, "TemporaryFile", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097032")] + [OutputType(typeof(System.IO.FileInfo))] + public class NewTemporaryFileCommand : Cmdlet + { + /// + /// Returns a TemporaryFile. + /// + protected override void EndProcessing() + { + string filePath = null; + string tempPath = Path.GetTempPath(); + if (ShouldProcess(tempPath)) + { + try + { + filePath = Path.GetTempFileName(); + } + catch (IOException ioException) + { + ThrowTerminatingError( + new ErrorRecord( + ioException, + "NewTemporaryFileWriteError", + ErrorCategory.WriteError, + tempPath)); + return; + } + + if (!string.IsNullOrEmpty(filePath)) + { + FileInfo file = new(filePath); + WriteObject(file); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..a5d784da9bb591e12a6946894961a5aa49420338 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the new-timespan command. + /// + [Cmdlet(VerbsCommon.New, "TimeSpan", DefaultParameterSetName = "Date", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096709", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(TimeSpan))] + public sealed class NewTimeSpanCommand : PSCmdlet + { + #region parameters + + /// + /// This parameter indicates the date the time span begins; + /// it is used if two times are being compared. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Date")] + [Alias("LastWriteTime")] + public DateTime Start + { + get + { + return _start; + } + + set + { + _start = value; + _startSpecified = true; + } + } + + private DateTime _start; + private bool _startSpecified; + + /// + /// This parameter indicates the end of a time span. It is used if two + /// times are being compared. If one of the times is not specified, + /// the current system time is used. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "Date")] + public DateTime End + { + get + { + return _end; + } + + set + { + _end = value; + _endSpecified = true; + } + } + + private DateTime _end; + private bool _endSpecified = false; + + /// + /// Allows the user to override the day. + /// + [Parameter(ParameterSetName = "Time")] + public int Days { get; set; } + + /// + /// Allows the user to override the hour. + /// + [Parameter(ParameterSetName = "Time")] + public int Hours { get; set; } + + /// + /// Allows the user to override the minute. + /// + [Parameter(ParameterSetName = "Time")] + public int Minutes { get; set; } + + /// + /// Allows the user to override the second. + /// + [Parameter(ParameterSetName = "Time")] + public int Seconds { get; set; } + + /// + /// Allows the user to override the millisecond. + /// + [Parameter(ParameterSetName = "Time")] + public int Milliseconds { get; set; } + + #endregion + + #region methods + + /// + /// Calculate and write out the appropriate timespan. + /// + protected override void ProcessRecord() + { + // initially set start and end time to be equal + DateTime startTime = DateTime.Now; + DateTime endTime = startTime; + TimeSpan result; + + switch (ParameterSetName) + { + case "Date": + if (_startSpecified) + { + startTime = Start; + } + + if (_endSpecified) + { + endTime = End; + } + + result = endTime.Subtract(startTime); + break; + + case "Time": + result = new TimeSpan(Days, Hours, Minutes, Seconds, Milliseconds); + break; + + default: + Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); + return; + } + + WriteObject(result); + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs new file mode 100644 index 0000000000000000000000000000000000000000..13b0234a02b4196fff8e14fb6ca86a6a476dae43 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections; +using System.Globalization; +using System.Management.Automation; + +#endregion + +namespace Microsoft.PowerShell.Commands +{ + #region PSObject Comparer + + /// + /// Keeps the property value of inputObject. Because the value of a non-existing property is null, + /// isExistingProperty is needed to distinguish whether a property exists and its value is null or + /// the property does not exist at all. + /// + internal sealed class ObjectCommandPropertyValue + { + private ObjectCommandPropertyValue() { } + + internal ObjectCommandPropertyValue(object propVal) + { + PropertyValue = propVal; + IsExistingProperty = true; + } + + /// + /// Initializes a new instance of the class. + /// + /// Property Value. + /// Indicates if the Property value comparison has to be case sensitive or not. + /// Culture Info of the Property Value. + internal ObjectCommandPropertyValue(object propVal, bool isCaseSensitive, CultureInfo cultureInfo) + : this(propVal) + { + _caseSensitive = isCaseSensitive; + this.cultureInfo = cultureInfo; + } + + internal object PropertyValue { get; } + + internal bool IsExistingProperty { get; } + + /// + /// Indicates if the Property Value comparison has to be Case sensitive or not. + /// + internal SwitchParameter CaseSensitive + { + get { return _caseSensitive; } + } + + /// + /// Gets the Culture Info of the Property Value. + /// + internal CultureInfo Culture + { + get + { + return cultureInfo; + } + } + + internal static readonly ObjectCommandPropertyValue NonExistingProperty = new(); + internal static readonly ObjectCommandPropertyValue ExistingNullProperty = new(null); + private readonly bool _caseSensitive; + internal CultureInfo cultureInfo = null; + + /// + /// Provides an Equals implementation. + /// + /// Input Object. + /// True if both the objects are same or else returns false. + public override bool Equals(object inputObject) + { + if (inputObject is not ObjectCommandPropertyValue objectCommandPropertyValueObject) + { + return false; + } + + object baseObject = PSObject.Base(PropertyValue); + object inComingbaseObjectPropertyValue = PSObject.Base(objectCommandPropertyValueObject.PropertyValue); + + if (baseObject is IComparable) + { + var success = LanguagePrimitives.TryCompare(baseObject, inComingbaseObjectPropertyValue, CaseSensitive, Culture, out int result); + return success && result == 0; + } + + if (baseObject == null && inComingbaseObjectPropertyValue == null) + { + return true; + } + + if (baseObject != null && inComingbaseObjectPropertyValue != null) + { + return baseObject.ToString().Equals(inComingbaseObjectPropertyValue.ToString(), StringComparison.OrdinalIgnoreCase); + } + + // One of the property values being compared is null. + return false; + } + + /// + /// Provides a GetHashCode() implementation. + /// + /// Hashcode in the form of an integer. + public override int GetHashCode() + { + if (PropertyValue == null) + { + return 0; + } + + object baseObject = PSObject.Base(PropertyValue); + if (baseObject == null) + { + return 0; + } + + if (baseObject is IComparable) + { + return baseObject.GetHashCode(); + } + else + { + return baseObject.ToString().GetHashCode(); + } + } + } + + /// + /// ObjectCommandComparer class. + /// + internal sealed class ObjectCommandComparer : IComparer + { + /// + /// Initializes a new instance of the class. + /// Constructor that doesn't set any private field. + /// Necessary because compareTo can compare two objects by calling + /// ((ICompare)obj1).CompareTo(obj2) without using a key. + /// + internal ObjectCommandComparer(bool ascending, CultureInfo cultureInfo, bool caseSensitive) + { + _ascendingOrder = ascending; + _cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; + _caseSensitive = caseSensitive; + } + + private static bool IsValueNull(object value) + { + object val = PSObject.Base(value); + return (val == null); + } + + internal int Compare(ObjectCommandPropertyValue first, ObjectCommandPropertyValue second) + { + if (first.IsExistingProperty && second.IsExistingProperty) + { + return Compare(first.PropertyValue, second.PropertyValue); + } + // if first.IsExistingProperty, !second.IsExistingProperty; otherwise the + // first branch if would return. Regardless of key orders non existing property + // will be considered greater than others + if (first.IsExistingProperty) + { + return -1; + } + // vice versa for the previous branch + if (second.IsExistingProperty) + { + return 1; + } + // both are nonexisting + return 0; + } + + /// + /// Main method that will compare first and second by their keys considering case and order. + /// + /// + /// First object to extract value. + /// + /// + /// Second object to extract value. + /// + /// + /// 0 if they are the same, less than 0 if first is smaller, more than 0 if first is greater. + /// + public int Compare(object first, object second) + { + // This method will never throw exceptions, two null + // objects are considered the same + if (IsValueNull(first) && IsValueNull(second)) + { + return 0; + } + + if (first is PSObject firstMsh) + { + first = firstMsh.BaseObject; + } + + if (second is PSObject secondMsh) + { + second = secondMsh.BaseObject; + } + + if (!LanguagePrimitives.TryCompare(first, second, !_caseSensitive, _cultureInfo, out int result)) + { + // Note that this will occur if the objects do not support + // IComparable. We fall back to comparing as strings. + + // being here means the first object doesn't support ICompare + string firstString = PSObject.AsPSObject(first).ToString(); + string secondString = PSObject.AsPSObject(second).ToString(); + + result = _cultureInfo.CompareInfo.Compare(firstString, secondString, _caseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase); + } + + return _ascendingOrder ? result : -result; + } + + private readonly CultureInfo _cultureInfo = null; + + private readonly bool _ascendingOrder = true; + + private readonly bool _caseSensitive = false; + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..596bbcaafc6b3313ef809d2c5bf2db6697affcc6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -0,0 +1,730 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Definitions for hash table keys. + /// + internal static class SortObjectParameterDefinitionKeys + { + internal const string AscendingEntryKey = "ascending"; + internal const string DescendingEntryKey = "descending"; + } + + /// + /// + internal sealed class SortObjectExpressionParameterDefinition : CommandParameterDefinition + { + protected override void SetEntries() + { + this.hashEntries.Add(new ExpressionEntryDefinition(false)); + this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.AscendingEntryKey)); + this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.DescendingEntryKey)); + } + } + + /// + /// + internal sealed class GroupObjectExpressionParameterDefinition : CommandParameterDefinition + { + protected override void SetEntries() + { + this.hashEntries.Add(new ExpressionEntryDefinition(true)); + } + } + + /// + /// Base Cmdlet for cmdlets which deal with raw objects. + /// + public class ObjectCmdletBase : PSCmdlet + { + #region Parameters + /// + /// + /// + [Parameter] + [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "The CultureNumber is only used if the property has been set with a hex string starting with 0x")] + public string Culture + { + get + { + return _cultureInfo?.ToString(); + } + + set + { + if (string.IsNullOrEmpty(value)) + { + _cultureInfo = null; + return; + } + + int cultureNumber; + string trimmedValue = value.Trim(); + if (trimmedValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { + if ((trimmedValue.Length > 2) && + int.TryParse(trimmedValue.AsSpan(2), NumberStyles.AllowHexSpecifier, + CultureInfo.CurrentCulture, out cultureNumber)) + { + _cultureInfo = new CultureInfo(cultureNumber); + return; + } + } + else if (int.TryParse(trimmedValue, NumberStyles.AllowThousands, + CultureInfo.CurrentCulture, out cultureNumber)) + { + _cultureInfo = new CultureInfo(cultureNumber); + return; + } + + _cultureInfo = new CultureInfo(value); + } + } + + internal CultureInfo _cultureInfo = null; + + /// + /// + /// + [Parameter] + public SwitchParameter CaseSensitive + { + get { return _caseSensitive; } + + set { _caseSensitive = value; } + } + + private bool _caseSensitive; + #endregion Parameters + } + + /// + /// Base Cmdlet for object cmdlets that deal with Grouping, Sorting and Comparison. + /// + public abstract class ObjectBase : ObjectCmdletBase + { + #region Parameters + + /// + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// Gets or Sets the Properties that would be used for Grouping, Sorting and Comparison. + /// + [Parameter(Position = 0)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public object[] Property { get; set; } + + #endregion Parameters + } + + /// + /// Base Cmdlet for object cmdlets that deal with Ordering and Comparison. + /// + public class OrderObjectBase : ObjectBase + { + #region Internal Properties + + /// + /// Specifies sorting order. + /// + internal SwitchParameter DescendingOrder + { + get { return !_ascending; } + + set { _ascending = !value; } + } + + private bool _ascending = true; + + internal List InputObjects { get; } = new List(); + + /// + /// CultureInfo converted from the Culture Cmdlet parameter. + /// + internal CultureInfo ConvertedCulture + { + get + { + return _cultureInfo; + } + } + + #endregion Internal Properties + + /// + /// Simply accumulates the incoming objects. + /// + protected override void ProcessRecord() + { + if (InputObject != null && InputObject != AutomationNull.Value) + { + InputObjects.Add(InputObject); + } + } + } + + internal sealed class OrderByProperty + { + #region Internal properties + + /// + /// A logical matrix where each row is an input object and its property values specified by Properties. + /// + internal List OrderMatrix { get; } + + internal OrderByPropertyComparer Comparer { get; } + + internal List MshParameterList + { + get + { + return _mshParameterList; + } + } + #endregion Internal properties + + #region Utils + // These are made static for Measure-Object's GroupBy parameter that measure the outputs of Group-Object + // However, Measure-Object differs from Group-Object and Sort-Object considerably that it should not + // be built on the same base class, i.e., this class. Moreover, Measure-Object's Property parameter is + // a string array and allows wildcard. + // Yes, the Cmdlet is needed. It's used to get the TerminatingErrorContext, WriteError and WriteDebug. + + #region process PSPropertyExpression and MshParameter + + private static void ProcessExpressionParameter( + List inputObjects, + PSCmdlet cmdlet, + object[] expr, + out List mshParameterList) + { + mshParameterList = null; + TerminatingErrorContext invocationContext = new(cmdlet); + // compare-object and group-object use the same definition here + ParameterProcessor processor = cmdlet is SortObjectCommand ? + new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : + new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); + + if (expr == null && inputObjects != null && inputObjects.Count > 0) + { + expr = GetDefaultKeyPropertySet(inputObjects[0]); + } + + if (expr != null) + { + List unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); + mshParameterList = ExpandExpressions(inputObjects, unexpandedParameterList); + } + // NOTE: if no parameters are passed, we will look at the default keys of the first + // incoming object + } + + internal void ProcessExpressionParameter( + PSCmdlet cmdlet, + object[] expr) + { + TerminatingErrorContext invocationContext = new(cmdlet); + // compare-object and group-object use the same definition here + ParameterProcessor processor = cmdlet is SortObjectCommand ? + new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : + new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); + + if (expr != null) + { + if (_unexpandedParameterList == null) + { + _unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); + + foreach (MshParameter unexpandedParameter in _unexpandedParameterList) + { + PSPropertyExpression mshExpression = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); + if (!mshExpression.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings + { + _mshParameterList.Add(unexpandedParameter); + } + else + { + _unExpandedParametersWithWildCardPattern ??= new List(); + + _unExpandedParametersWithWildCardPattern.Add(unexpandedParameter); + } + } + } + } + } + + // Expand a list of (possibly wildcarded) expressions into resolved expressions that + // match property names on the incoming objects. + private static List ExpandExpressions(List inputObjects, List unexpandedParameterList) + { + List expandedParameterList = new(); + + if (unexpandedParameterList != null) + { + foreach (MshParameter unexpandedParameter in unexpandedParameterList) + { + PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); + if (!ex.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings + { + expandedParameterList.Add(unexpandedParameter); + } + else + { + SortedDictionary expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase); + if (inputObjects != null) + { + foreach (object inputObject in inputObjects) + { + if (inputObject == null) + { + continue; + } + + foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject))) + { + expandedPropertyNames[resolvedName.ToString()] = resolvedName; + } + } + } + + foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values) + { + MshParameter expandedParameter = new(); + expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); + expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; + + expandedParameterList.Add(expandedParameter); + } + } + } + } + + return expandedParameterList; + } + + // Expand a list of (possibly wildcarded) expressions into resolved expressions that + // match property names on the incoming objects. + private static void ExpandExpressions(PSObject inputObject, List UnexpandedParametersWithWildCardPattern, List expandedParameterList) + { + if (UnexpandedParametersWithWildCardPattern != null) + { + foreach (MshParameter unexpandedParameter in UnexpandedParametersWithWildCardPattern) + { + PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); + + SortedDictionary expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase); + if (inputObject == null) + { + continue; + } + + foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject))) + { + expandedPropertyNames[resolvedName.ToString()] = resolvedName; + } + + foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values) + { + MshParameter expandedParameter = new(); + expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); + expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; + + expandedParameterList.Add(expandedParameter); + } + } + } + } + + internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) + { + PSMemberSet standardNames = mshObj.PSStandardMembers; + if (standardNames == null) + { + return null; + } + + if (standardNames.Members["DefaultKeyPropertySet"] is not PSPropertySet defaultKeys) + { + return null; + } + + string[] props = new string[defaultKeys.ReferencedPropertyNames.Count]; + defaultKeys.ReferencedPropertyNames.CopyTo(props, 0); + return props; + } + + #endregion process PSPropertyExpression and MshParameter + + internal static List CreateOrderMatrix( + PSCmdlet cmdlet, + List inputObjects, + List mshParameterList + ) + { + List orderMatrixToCreate = new(); + for (int index = 0; index < inputObjects.Count; index++) + { + PSObject so = inputObjects[index]; + if (so == null || so == AutomationNull.Value) + continue; + List evaluationErrors = new(); + List propertyNotFoundMsgs = new(); + OrderByPropertyEntry result = + OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs, originalIndex: index); + foreach (ErrorRecord err in evaluationErrors) + { + cmdlet.WriteError(err); + } + + foreach (string debugMsg in propertyNotFoundMsgs) + { + cmdlet.WriteDebug(debugMsg); + } + + orderMatrixToCreate.Add(result); + } + + return orderMatrixToCreate; + } + + private static bool isOrderEntryKeyDefined(object orderEntryKey) + { + return orderEntryKey != null && orderEntryKey != AutomationNull.Value; + } + + private static OrderByPropertyComparer CreateComparer( + List orderMatrix, + List mshParameterList, + bool ascending, + CultureInfo cultureInfo, + bool caseSensitive) + { + if (orderMatrix == null || orderMatrix.Count == 0) + { + return null; + } + + bool?[] ascendingOverrides = null; + if (mshParameterList != null && mshParameterList.Count != 0) + { + ascendingOverrides = new bool?[mshParameterList.Count]; + for (int k = 0; k < ascendingOverrides.Length; k++) + { + object ascendingVal = mshParameterList[k].GetEntry( + SortObjectParameterDefinitionKeys.AscendingEntryKey); + object descendingVal = mshParameterList[k].GetEntry( + SortObjectParameterDefinitionKeys.DescendingEntryKey); + bool isAscendingDefined = isOrderEntryKeyDefined(ascendingVal); + bool isDescendingDefined = isOrderEntryKeyDefined(descendingVal); + if (!isAscendingDefined && !isDescendingDefined) + { + // if neither ascending nor descending is defined + ascendingOverrides[k] = null; + } + else if (isAscendingDefined && isDescendingDefined && + (bool)ascendingVal == (bool)descendingVal) + { + // if both ascending and descending defined but their values conflict + // they are ignored. + ascendingOverrides[k] = null; + } + else if (isAscendingDefined) + { + ascendingOverrides[k] = (bool)ascendingVal; + } + else + { + ascendingOverrides[k] = !(bool)descendingVal; + } + } + } + + OrderByPropertyComparer comparer = + OrderByPropertyComparer.CreateComparer(orderMatrix, ascending, + ascendingOverrides, cultureInfo, caseSensitive); + + return comparer; + } + + internal OrderByProperty( + PSCmdlet cmdlet, + List inputObjects, + object[] expr, + bool ascending, + CultureInfo cultureInfo, + bool caseSensitive + ) + { + Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); + + ProcessExpressionParameter(inputObjects, cmdlet, expr, out _mshParameterList); + OrderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList); + Comparer = CreateComparer(OrderMatrix, _mshParameterList, ascending, cultureInfo, caseSensitive); + } + + /// + /// Initializes a new instance of the class. + /// + internal OrderByProperty() + { + _mshParameterList = new List(); + OrderMatrix = new List(); + } + + /// + /// Utility function used to create OrderByPropertyEntry for the supplied input object. + /// + /// PSCmdlet. + /// Input Object. + /// Indicates if the Property value comparisons need to be case sensitive or not. + /// Culture Info that needs to be used for comparison. + /// OrderByPropertyEntry for the supplied InputObject. + internal OrderByPropertyEntry CreateOrderByPropertyEntry( + PSCmdlet cmdlet, + PSObject inputObject, + bool isCaseSensitive, + CultureInfo cultureInfo) + { + Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); + + if (_unExpandedParametersWithWildCardPattern != null) + { + ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList); + } + + List evaluationErrors = new(); + List propertyNotFoundMsgs = new(); + OrderByPropertyEntry result = + OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo); + foreach (ErrorRecord err in evaluationErrors) + { + cmdlet.WriteError(err); + } + + foreach (string debugMsg in propertyNotFoundMsgs) + { + cmdlet.WriteDebug(debugMsg); + } + + return result; + } + + #endregion Utils + + // list of processed parameters obtained from the Expression array + private readonly List _mshParameterList = null; + + // list of unprocessed parameters obtained from the Expression array. + private List _unexpandedParameterList = null; + + // list of unprocessed parameters with wild card patterns. + private List _unExpandedParametersWithWildCardPattern = null; + } + + internal static class OrderByPropertyEntryEvaluationHelper + { + internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List mshParameterList, + List errors, List propertyNotFoundMsgs, bool isCaseSensitive = false, CultureInfo cultureInfo = null, int originalIndex = -1) + { + Diagnostics.Assert(errors != null, "errors cannot be null!"); + Diagnostics.Assert(propertyNotFoundMsgs != null, "propertyNotFoundMsgs cannot be null!"); + OrderByPropertyEntry entry = new(); + entry.inputObject = inputObject; + entry.originalIndex = originalIndex; + + if (mshParameterList == null || mshParameterList.Count == 0) + { + // we do not have a property to evaluate, we sort on $_ + entry.orderValues.Add(new ObjectCommandPropertyValue(inputObject, isCaseSensitive, cultureInfo)); + entry.comparable = true; + return entry; + } + + // we need to compute the properties + foreach (MshParameter p in mshParameterList) + { + string propertyNotFoundMsg = null; + EvaluateSortingExpression(p, inputObject, entry.orderValues, errors, out propertyNotFoundMsg, ref entry.comparable); + if (!string.IsNullOrEmpty(propertyNotFoundMsg)) + { + propertyNotFoundMsgs.Add(propertyNotFoundMsg); + } + } + + return entry; + } + + private static void EvaluateSortingExpression( + MshParameter p, + PSObject inputObject, + List orderValues, + List errors, + out string propertyNotFoundMsg, + ref bool comparable) + { + // NOTE: we assume globbing was not allowed in input + PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; + + // get the values, but do not expand aliases + List expressionResults = ex.GetValues(inputObject, false, true); + + if (expressionResults.Count == 0) + { + // we did not get any result out of the expression: + // we enter a null as a place holder + orderValues.Add(ObjectCommandPropertyValue.NonExistingProperty); + propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, ex.ToString()); + return; + } + + propertyNotFoundMsg = null; + // we obtained some results, enter them into the list + foreach (PSPropertyExpressionResult r in expressionResults) + { + if (r.Exception == null) + { + orderValues.Add(new ObjectCommandPropertyValue(r.Result)); + } + else + { + ErrorRecord errorRecord = new( + r.Exception, + "ExpressionEvaluation", + ErrorCategory.InvalidResult, + inputObject); + errors.Add(errorRecord); + orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty); + } + + comparable = true; + } + } + } + + /// + /// This is the row of the OrderMatrix. + /// + internal sealed class OrderByPropertyEntry + { + internal PSObject inputObject = null; + internal List orderValues = new(); + // The originalIndex field was added to enable stable heap-sorts (Top N/Bottom N) + internal int originalIndex = -1; + + // The comparable field enables faster identification of uncomparable data + internal bool comparable = false; + } + + internal sealed class OrderByPropertyComparer : IComparer + { + internal OrderByPropertyComparer(bool[] ascending, CultureInfo cultureInfo, bool caseSensitive) + { + _propertyComparers = new ObjectCommandComparer[ascending.Length]; + for (int k = 0; k < ascending.Length; k++) + { + _propertyComparers[k] = new ObjectCommandComparer(ascending[k], cultureInfo, caseSensitive); + } + } + + public int Compare(OrderByPropertyEntry firstEntry, OrderByPropertyEntry secondEntry) + { + // we have to take into consideration that some vectors + // might be shorter than others + int order = 0; + for (int k = 0; k < _propertyComparers.Length; k++) + { + ObjectCommandPropertyValue firstValue = (k < firstEntry.orderValues.Count) ? + firstEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; + ObjectCommandPropertyValue secondValue = (k < secondEntry.orderValues.Count) ? + secondEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; + order = _propertyComparers[k].Compare(firstValue, secondValue); + + if (order != 0) + return order; + } + + return order; + } + + internal static OrderByPropertyComparer CreateComparer(List orderMatrix, bool ascendingFlag, bool?[] ascendingOverrides, CultureInfo cultureInfo, bool caseSensitive) + { + if (orderMatrix.Count == 0) + return null; + + // create a comparer able to handle a vector of N entries, + // where N is the max number of entries + int maxEntries = 0; + foreach (OrderByPropertyEntry entry in orderMatrix) + { + if (entry.orderValues.Count > maxEntries) + maxEntries = entry.orderValues.Count; + } + + if (maxEntries == 0) + return null; + + bool[] ascending = new bool[maxEntries]; + for (int k = 0; k < maxEntries; k++) + { + if (ascendingOverrides != null && ascendingOverrides[k].HasValue) + { + ascending[k] = ascendingOverrides[k].Value; + } + else + { + ascending[k] = ascendingFlag; + } + } + + // NOTE: the size of the boolean array will determine the max width of the + // vectors to check + return new OrderByPropertyComparer(ascending, cultureInfo, caseSensitive); + } + + private readonly ObjectCommandComparer[] _propertyComparers = null; + } + + internal sealed class IndexedOrderByPropertyComparer : IComparer + { + internal IndexedOrderByPropertyComparer(OrderByPropertyComparer orderByPropertyComparer) + { + _orderByPropertyComparer = orderByPropertyComparer; + } + + public int Compare(OrderByPropertyEntry lhs, OrderByPropertyEntry rhs) + { + // Non-comparable items always fall after comparable items + if (lhs.comparable != rhs.comparable) + { + return lhs.comparable.CompareTo(rhs.comparable) * -1; + } + + int result = _orderByPropertyComparer.Compare(lhs, rhs); + // When items are identical according to the internal comparison, compare by index + // to preserve the original order + if (result == 0) + { + return lhs.originalIndex.CompareTo(rhs.originalIndex); + } + // Otherwise, return the default comparison results + return result; + } + + private readonly OrderByPropertyComparer _orderByPropertyComparer = null; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..d3dfd30f9e5551a0c649da51bd8c9663fee32d89 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Base class for Get/Set-PSBreakpoint. + /// + public abstract class PSBreakpointAccessorCommandBase : PSBreakpointCommandBase + { + #region strings + + internal const string CommandParameterSetName = "Command"; + internal const string LineParameterSetName = "Line"; + internal const string VariableParameterSetName = "Variable"; + + #endregion strings + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..61d7236977d91797590e8e5d8013d33bd2c66b7e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Base class for PSBreakpoint cmdlets. + /// + public abstract class PSBreakpointCommandBase : PSCmdlet + { + #region parameters + + /// + /// Gets or sets the runspace where the breakpoints will be used. + /// + [Parameter] + [ValidateNotNull] + [Runspace] + public virtual Runspace Runspace { get; set; } + + #endregion parameters + + #region overrides + + /// + /// Identifies the default runspace. + /// + protected override void BeginProcessing() + { + Runspace ??= Context.CurrentRunspace; + } + + #endregion overrides + + #region protected methods + + /// + /// Write the given breakpoint out to the pipeline, decorated with the runspace instance id if appropriate. + /// + /// The breakpoint to write to the pipeline. + protected virtual void ProcessBreakpoint(Breakpoint breakpoint) + { + if (Runspace != Context.CurrentRunspace) + { + var pso = new PSObject(breakpoint); + pso.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, Runspace.InstanceId)); + WriteObject(pso); + } + else + { + WriteObject(breakpoint); + } + } + + #endregion protected methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..f186fbe1baa53068967d50b56ebe99ad24d4d43d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Base class for Enable/Disable/Remove-PSBreakpoint. + /// + public abstract class PSBreakpointUpdaterCommandBase : PSBreakpointCommandBase + { + #region strings + + internal const string BreakpointParameterSetName = "Breakpoint"; + internal const string IdParameterSetName = "Id"; + + #endregion strings + + #region parameters + + /// + /// Gets or sets the breakpoint to enable. + /// + [Parameter(ParameterSetName = BreakpointParameterSetName, ValueFromPipeline = true, Position = 0, Mandatory = true)] + [ValidateNotNull] + public Breakpoint[] Breakpoint { get; set; } + + /// + /// Gets or sets the Id of the breakpoint to enable. + /// + [Parameter(ParameterSetName = IdParameterSetName, ValueFromPipelineByPropertyName = true, Position = 0, Mandatory = true)] + [ValidateNotNull] + public int[] Id { get; set; } + + /// + /// Gets or sets the runspace where the breakpoints will be used. + /// + [Parameter(ParameterSetName = IdParameterSetName, ValueFromPipelineByPropertyName = true)] + [Alias("RunspaceId")] + [Runspace] + public override Runspace Runspace { get; set; } + + #endregion parameters + + #region overrides + + /// + /// Gathers the list of breakpoints to process and calls ProcessBreakpoints. + /// + protected override void ProcessRecord() + { + if (ParameterSetName.Equals(BreakpointParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + foreach (Breakpoint breakpoint in Breakpoint) + { + if (ShouldProcessInternal(breakpoint.ToString()) && + TryGetRunspace(breakpoint)) + { + ProcessBreakpoint(breakpoint); + } + } + } + else + { + Debug.Assert( + ParameterSetName.Equals(IdParameterSetName, StringComparison.OrdinalIgnoreCase), + $"There should be no other parameter sets besides '{BreakpointParameterSetName}' and '{IdParameterSetName}'."); + + foreach (int id in Id) + { + Breakpoint breakpoint; + if (TryGetBreakpoint(id, out breakpoint) && + ShouldProcessInternal(breakpoint.ToString())) + { + ProcessBreakpoint(breakpoint); + } + } + } + } + + #endregion overrides + + #region private data + + private readonly Dictionary runspaces = new(); + + #endregion private data + + #region private methods + + private bool TryGetRunspace(Breakpoint breakpoint) + { + // Breakpoints retrieved from another runspace will have a RunspaceId note property of type Guid on them. + var pso = new PSObject(breakpoint); + var runspaceInstanceIdProperty = pso.Properties[RemotingConstants.RunspaceIdNoteProperty]; + if (runspaceInstanceIdProperty == null) + { + Runspace = Context.CurrentRunspace; + return true; + } + + Debug.Assert(runspaceInstanceIdProperty.TypeNameOfValue.Equals("System.Guid", StringComparison.OrdinalIgnoreCase), "Instance ids must be GUIDs."); + + var runspaceInstanceId = (Guid)runspaceInstanceIdProperty.Value; + if (runspaces.ContainsKey(runspaceInstanceId)) + { + Runspace = runspaces[runspaceInstanceId]; + return true; + } + + var matchingRunspaces = GetRunspaceUtils.GetRunspacesByInstanceId(new[] { runspaceInstanceId }); + if (matchingRunspaces.Count != 1) + { + WriteError( + new ErrorRecord( + new ArgumentException(StringUtil.Format(Debugger.RunspaceInstanceIdNotFound, runspaceInstanceId)), + "PSBreakpoint:RunspaceInstanceIdNotFound", + ErrorCategory.InvalidArgument, + null)); + return false; + } + + Runspace = runspaces[runspaceInstanceId] = matchingRunspaces[0]; + return true; + } + + private bool TryGetBreakpoint(int id, out Breakpoint breakpoint) + { + breakpoint = Runspace.Debugger.GetBreakpoint(id); + + if (breakpoint == null) + { + WriteError( + new ErrorRecord( + new ArgumentException(StringUtil.Format(Debugger.BreakpointIdNotFound, id)), + "PSBreakpoint:BreakpointIdNotFound", + ErrorCategory.InvalidArgument, + null)); + return false; + } + + return true; + } + + private bool ShouldProcessInternal(string target) + { + // ShouldProcess should be called only if the WhatIf or Confirm parameters are passed in explicitly. + // It should *not* be called if we are in a nested debug prompt and the current running command was + // run with -WhatIf or -Confirm, because this prevents the user from adding/removing breakpoints inside + // a debugger stop. + if (MyInvocation.BoundParameters.ContainsKey("WhatIf") || + MyInvocation.BoundParameters.ContainsKey("Confirm")) + { + return ShouldProcess(target); + } + + return true; + } + + #endregion private methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..3fabe75de24faacac9a6fe3220f323140f7bb3cb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Security; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Retrieves input from the host virtual console and writes it to the pipeline output. + /// + [Cmdlet(VerbsCommunications.Read, "Host", DefaultParameterSetName = "AsString", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096610")] + [OutputType(typeof(string), typeof(SecureString))] + public sealed class ReadHostCommand : PSCmdlet + { + /// + /// Initializes a new instance of the class. + /// + public + ReadHostCommand() + { + // empty, provided per design guidelines. + } + + #region Parameters + + /// + /// The objects to display on the host before collecting input. + /// + [Parameter(Position = 0, ValueFromRemainingArguments = true)] + [AllowNull] + public + object + Prompt + { + get + { + return _prompt; + } + + set + { + _prompt = value; + } + } + + /// + /// Gets or sets to no echo the input as is typed. If set then the cmdlet returns a secure string. + /// + [Parameter(ParameterSetName = "AsSecureString")] + public + SwitchParameter + AsSecureString + { + get + { + return _safe; + } + + set + { + _safe = value; + } + } + + /// + /// Gets or sets whether the console will echo the input as is typed. If set then the cmdlet returns a regular string. + /// + [Parameter(ParameterSetName = "AsString")] + public + SwitchParameter + MaskInput + { + get; + set; + } + #endregion Parameters + + #region Cmdlet Overrides + + /// + /// Write the prompt, then collect a line of input from the host, then output it to the output stream. + /// + protected override void BeginProcessing() + { + PSHostUserInterface ui = Host.UI; + string promptString; + + if (_prompt != null) + { + IEnumerator e = LanguagePrimitives.GetEnumerator(_prompt); + if (e != null) + { + StringBuilder sb = new(); + + while (e.MoveNext()) + { + // The current object might itself be a collection, like a string array, as in read/console "foo","bar","baz" + // If it is, then the PSObject ToString() will take care of it. We could go on unwrapping collections + // forever, but it's a pretty common use case to see a varags confused with an array. + + string element = (string)LanguagePrimitives.ConvertTo(e.Current, typeof(string), CultureInfo.InvariantCulture); + + if (!string.IsNullOrEmpty(element)) + { + // Prepend a space if the stringbuilder isn't empty... + // We could consider using $OFS here but that's probably more + // effort than is really needed... + if (sb.Length > 0) + sb.Append(' '); + sb.Append(element); + } + } + + promptString = sb.ToString(); + } + else + { + promptString = (string)LanguagePrimitives.ConvertTo(_prompt, typeof(string), CultureInfo.InvariantCulture); + } + + FieldDescription fd = new(promptString); + if (AsSecureString || MaskInput) + { + fd.SetParameterType(typeof(SecureString)); + } + else + { + fd.SetParameterType(typeof(string)); + } + + Collection fdc = new(); + fdc.Add(fd); + + Dictionary result = Host.UI.Prompt(string.Empty, string.Empty, fdc); + // Result can be null depending on the host implementation. One typical + // example of a null return is for a canceled dialog. + if (result != null) + { + foreach (PSObject o in result.Values) + { + if (MaskInput && o?.BaseObject is SecureString secureString) + { + WriteObject(Utils.GetStringFromSecureString(secureString)); + } + else + { + WriteObject(o); + } + } + } + } + else + { + object result; + if (AsSecureString || MaskInput) + { + result = Host.UI.ReadLineAsSecureString(); + } + else + { + result = Host.UI.ReadLine(); + } + + if (MaskInput) + { + WriteObject(Utils.GetStringFromSecureString((SecureString)result)); + } + else + { + WriteObject(result); + } + } + } + + #endregion Cmdlet Overrides + + private object _prompt = null; + private bool _safe = false; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..d4e7dc784c1858d955b722b002fdaa72a2480def --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Registers for an event on an object. + /// + [Cmdlet(VerbsLifecycle.Register, "ObjectEvent", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096714")] + [OutputType(typeof(PSEventJob))] + public class RegisterObjectEventCommand : ObjectEventRegistrationBase + { + #region parameters + + /// + /// The object on which to subscribe. + /// + [Parameter(Mandatory = true, Position = 0)] + public PSObject InputObject + { + get + { + return _inputObject; + } + + set + { + _inputObject = value; + } + } + + private PSObject _inputObject = null; + + /// + /// The event name to subscribe. + /// + [Parameter(Mandatory = true, Position = 1)] + public string EventName + { + get + { + return _eventName; + } + + set + { + _eventName = value; + } + } + + private string _eventName = null; + + #endregion parameters + + /// + /// Returns the object that generates events to be monitored. + /// + protected override object GetSourceObject() + { + return _inputObject; + } + + /// + /// Returns the event name to be monitored on the input object. + /// + protected override string GetSourceObjectEventName() + { + return _eventName; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..6e4ced907605495bbad2aa70ab9852ce951f801c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Registers for an event coming from the engine. + /// + [Cmdlet(VerbsLifecycle.Register, "EngineEvent", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097128")] + [OutputType(typeof(PSEventJob))] + public class RegisterEngineEventCommand : ObjectEventRegistrationBase + { + /// + /// Parameter for an identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 100)] + public new string SourceIdentifier + { + get + { + return base.SourceIdentifier; + } + + set + { + base.SourceIdentifier = value; + } + } + + /// + /// Returns the object that generates events to be monitored. + /// + protected override object GetSourceObject() + { + // If it's not a forwarded event, the user must specify + // an action + if ( + (Action == null) && + (!(bool)Forward) + ) + { + ErrorRecord errorRecord = new( + new ArgumentException(EventingStrings.ActionMandatoryForLocal), + "ACTION_MANDATORY_FOR_LOCAL", + ErrorCategory.InvalidArgument, + null); + + ThrowTerminatingError(errorRecord); + } + + return null; + } + + /// + /// Returns the event name to be monitored on the input object. + /// + protected override string GetSourceObjectEventName() + { + return null; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs new file mode 100644 index 0000000000000000000000000000000000000000..de324b33fb860f61ce6eadb10c0e6fdb7803f5d9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Remove-PSBreakpoint. + /// + [Cmdlet(VerbsCommon.Remove, "PSBreakpoint", SupportsShouldProcess = true, DefaultParameterSetName = BreakpointParameterSetName, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097134")] + public class RemovePSBreakpointCommand : PSBreakpointUpdaterCommandBase + { + #region overrides + + /// + /// Removes the given breakpoint. + /// + protected override void ProcessBreakpoint(Breakpoint breakpoint) + { + Runspace.Debugger.RemoveBreakpoint(breakpoint); + } + + #endregion overrides + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..15c48efd8472c035bc93653f149e1bdedcae4146 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "Remove-Alias" cmdlet. + /// + [Cmdlet(VerbsCommon.Remove, "Alias", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2097127")] + [Alias("ral")] + public class RemoveAliasCommand : PSCmdlet + { + #region Parameters + + /// + /// The alias name to remove. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Name { get; set; } + + /// + /// The scope parameter for the command determines which scope the alias is removed from. + /// + [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + /// + /// If set to true and an existing alias of the same name exists + /// and is ReadOnly, it will still be deleted. + /// + [Parameter] + public SwitchParameter Force { get; set; } + + #endregion Parameters + + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + foreach (string aliasName in Name) + { + AliasInfo existingAlias = null; + if (string.IsNullOrEmpty(Scope)) + { + existingAlias = SessionState.Internal.GetAlias(aliasName); + } + else + { + existingAlias = SessionState.Internal.GetAliasAtScope(aliasName, Scope); + } + + if (existingAlias != null) + { + SessionState.Internal.RemoveAlias(aliasName, Force); + } + else + { + ItemNotFoundException notAliasFound = new(StringUtil.Format(AliasCommandStrings.NoAliasFound, "name", aliasName)); + ErrorRecord error = new(notAliasFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, aliasName); + WriteError(error); + } + } + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..4b8ade4a94a297f68c7d57c722ff1f349861d018 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Removes an event from the event queue. + /// + [Cmdlet(VerbsCommon.Remove, "Event", SupportsShouldProcess = true, DefaultParameterSetName = "BySource", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096715")] + public class RemoveEventCommand : PSCmdlet + { + #region parameters + + /// + /// A source identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "BySource")] + public string SourceIdentifier + { + get + { + return _sourceIdentifier; + } + + set + { + _sourceIdentifier = value; + + if (value != null) + { + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + } + } + } + + private string _sourceIdentifier = null; + + /// + /// An identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByIdentifier")] + public int EventIdentifier + { + get + { + return _eventIdentifier; + } + + set + { + _eventIdentifier = value; + } + } + + private int _eventIdentifier = -1; + + #endregion parameters + + private WildcardPattern _matchPattern; + + /// + /// Remove the event from the queue. + /// + protected override void ProcessRecord() + { + // Go through all the received events and write them to the output + // pipeline + bool foundMatch = false; + + lock (Events.ReceivedEvents.SyncRoot) + { + PSEventArgsCollection currentEvents = Events.ReceivedEvents; + + for (int eventCounter = currentEvents.Count; eventCounter > 0; eventCounter--) + { + PSEventArgs currentEvent = currentEvents[eventCounter - 1]; + + // If they specified a event identifier and we don't match, continue + if ((_sourceIdentifier != null) && + (!_matchPattern.IsMatch(currentEvent.SourceIdentifier))) + { + continue; + } + + // If they specified a TimeGenerated and we don't match, continue + if ((_eventIdentifier >= 0) && + (currentEvent.EventIdentifier != _eventIdentifier)) + { + continue; + } + + foundMatch = true; + if (ShouldProcess( + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + EventingStrings.EventResource, + currentEvent.SourceIdentifier), + EventingStrings.Remove)) + { + currentEvents.RemoveAt(eventCounter - 1); + } + } + } + + // Generate an error if we couldn't find the subscription identifier, + // and no globbing was done. + if ((_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && + (!foundMatch)) + { + ErrorRecord errorRecord = new( + new ArgumentException( + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + EventingStrings.SourceIdentifierNotFound, _sourceIdentifier)), + "INVALID_SOURCE_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + + WriteError(errorRecord); + } + else if ((_eventIdentifier >= 0) && (!foundMatch)) + { + ErrorRecord errorRecord = new( + new ArgumentException( + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + EventingStrings.EventIdentifierNotFound, _eventIdentifier)), + "INVALID_EVENT_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + + WriteError(errorRecord); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs new file mode 100644 index 0000000000000000000000000000000000000000..696813449cbbd0cdc4c411172d53bb64ef43743e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable 1634, 1691 +#pragma warning disable 56506 + +using Microsoft.PowerShell.Commands; + +namespace System.Management.Automation.Runspaces +{ + /// + /// Defines the attribute used to designate a cmdlet parameter as one that + /// should accept runspaces. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] + public sealed class RunspaceAttribute : ArgumentTransformationAttribute + { + /// + /// Transforms the input data to a Runspace. + /// + /// + /// The engine APIs for the context under which the transformation is being + /// made. + /// + /// + /// If a string, the transformation uses the input as the runspace name. + /// If an int, the transformation uses the input as the runspace ID. + /// If a guid, the transformation uses the input as the runspace GUID. + /// If already a Runspace, the transform does nothing. + /// + /// A runspace object representing the inputData. + public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) + { + if (engineIntrinsics?.Host?.UI == null) + { + throw PSTraceSource.NewArgumentNullException("engineIntrinsics"); + } + + if (inputData == null) + { + return null; + } + + // Try to coerce the input as a runspace + Runspace runspace = LanguagePrimitives.FromObjectAs(inputData); + if (runspace != null) + { + return runspace; + } + + // Try to coerce the runspace if the user provided a string, int, or guid + switch (inputData) + { + case string name: + var runspacesByName = GetRunspaceUtils.GetRunspacesByName(new[] { name }); + if (runspacesByName.Count == 1) + { + return runspacesByName[0]; + } + + break; + + case int id: + var runspacesById = GetRunspaceUtils.GetRunspacesById(new[] { id }); + if (runspacesById.Count == 1) + { + return runspacesById[0]; + } + + break; + + case Guid guid: + var runspacesByGuid = GetRunspaceUtils.GetRunspacesByInstanceId(new[] { guid }); + if (runspacesByGuid.Count == 1) + { + return runspacesByGuid[0]; + } + + break; + + default: + // Non-convertible type + break; + } + + // If we couldn't get a single runspace, return the inputData + return inputData; + } + + /// + /// Gets a flag indicating whether or not null optional parameters are transformed. + /// + public override bool TransformNullOptionalParameters { get { return false; } } + } +} + +#pragma warning restore 56506 diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..e0b0bff07c5ffe8169c21d4ba85503510ebc3164 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -0,0 +1,837 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class SelectObjectExpressionParameterDefinition : CommandParameterDefinition + { + protected override void SetEntries() + { + this.hashEntries.Add(new ExpressionEntryDefinition()); + this.hashEntries.Add(new NameEntryDefinition()); + } + } + + /// + /// + [Cmdlet(VerbsCommon.Select, "Object", DefaultParameterSetName = "DefaultParameter", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096716", RemotingCapability = RemotingCapability.None)] + public sealed class SelectObjectCommand : PSCmdlet + { + #region Command Line Switches + + /// + /// + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// + /// + [Parameter(Position = 0, ParameterSetName = "DefaultParameter")] + [Parameter(Position = 0, ParameterSetName = "SkipLastParameter")] + public object[] Property { get; set; } + + /// + /// + /// + [Parameter(ParameterSetName = "DefaultParameter")] + [Parameter(ParameterSetName = "SkipLastParameter")] + public string[] ExcludeProperty { get; set; } + + /// + /// + /// + [Parameter(ParameterSetName = "DefaultParameter")] + [Parameter(ParameterSetName = "SkipLastParameter")] + public string ExpandProperty { get; set; } + + /// + /// + /// + [Parameter] + public SwitchParameter Unique + { + get { return _unique; } + + set { _unique = value; } + } + + private bool _unique; + + /// + /// Gets or sets case insensitive switch for string comparison. + /// Used in combination with Unique switch parameter. + /// + [Parameter] + public SwitchParameter CaseInsensitive { get; set; } + + /// + /// + /// + [Parameter(ParameterSetName = "DefaultParameter")] + // NTRAID#Windows Out Of Band Releases-927878-2006/03/02 + // Allow zero + [ValidateRange(0, int.MaxValue)] + public int Last + { + get { return _last; } + + set { _last = value; _firstOrLastSpecified = true; } + } + + private int _last = 0; + + /// + /// + /// + [Parameter(ParameterSetName = "DefaultParameter")] + // NTRAID#Windows Out Of Band Releases-927878-2006/03/02 + // Allow zero + [ValidateRange(0, int.MaxValue)] + public int First + { + get { return _first; } + + set { _first = value; _firstOrLastSpecified = true; } + } + + private int _first = 0; + private bool _firstOrLastSpecified; + + /// + /// Skips the specified number of items from top when used with First, from end when used with Last or SkipLast. + /// + /// + [Parameter(ParameterSetName = "DefaultParameter")] + [Parameter(ParameterSetName = "SkipLastParameter")] + [ValidateRange(0, int.MaxValue)] + public int Skip { get; set; } + + /// + /// Skip the specified number of items from end. + /// + [Parameter(ParameterSetName = "SkipLastParameter")] + [ValidateRange(0, int.MaxValue)] + public int SkipLast { get; set; } + + /// + /// With this switch present, the cmdlet won't "short-circuit" + /// (i.e. won't stop upstream cmdlets after it knows that no further objects will be emitted downstream). + /// + [Parameter(ParameterSetName = "DefaultParameter")] + [Parameter(ParameterSetName = "IndexParameter")] + public SwitchParameter Wait { get; set; } + + /// + /// Used to display the object at the specified index. + /// + /// + [Parameter(ParameterSetName = "IndexParameter")] + [ValidateRange(0, int.MaxValue)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] Index + { + get + { + return _index; + } + + set + { + _index = value; + _indexSpecified = true; + _isIncludeIndex = true; + Array.Sort(_index); + } + } + + /// + /// Used to display all objects at the specified indices. + /// + /// + [Parameter(ParameterSetName = "SkipIndexParameter")] + [ValidateRange(0, int.MaxValue)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public int[] SkipIndex + { + get + { + return _index; + } + + set + { + _index = value; + _indexSpecified = true; + _isIncludeIndex = false; + Array.Sort(_index); + } + } + + private int[] _index; + private bool _indexSpecified; + private bool _isIncludeIndex; + + #endregion + + private SelectObjectQueue _selectObjectQueue; + + private sealed class SelectObjectQueue : Queue + { + internal SelectObjectQueue(int first, int last, int skip, int skipLast, bool firstOrLastSpecified) + { + _first = first; + _last = last; + _skip = skip; + _skipLast = skipLast; + _firstOrLastSpecified = firstOrLastSpecified; + } + + public bool AllRequestedObjectsProcessed + { + get + { + return _firstOrLastSpecified && _last == 0 && _first != 0 && _streamedObjectCount >= _first; + } + } + + public new void Enqueue(PSObject obj) + { + if (_last > 0 && this.Count >= (_last + _skip) && _first == 0) + { + base.Dequeue(); + } + else if (_last > 0 && this.Count >= _last && _first != 0) + { + base.Dequeue(); + } + + base.Enqueue(obj); + } + + public PSObject StreamingDequeue() + { + // if skip parameter is not mentioned or there are no more objects to skip + if (_skip == 0) + { + if (_skipLast > 0) + { + // We are going to skip some items from end, but it's okay to process + // the early input objects once we have more items in queue than the + // specified 'skipLast' value. + if (this.Count > _skipLast) + { + return Dequeue(); + } + } + else + { + if (_streamedObjectCount < _first || !_firstOrLastSpecified) + { + Diagnostics.Assert(this.Count > 0, "Streaming an empty queue"); + _streamedObjectCount++; + return Dequeue(); + } + + if (_last == 0) + { + Dequeue(); + } + } + } + else + { + // if last parameter is not mentioned,remove the objects and decrement the skip + if (_last == 0) + { + Dequeue(); + _skip--; + } + else if (_first != 0) + { + _skip--; + Dequeue(); + } + } + + return null; + } + + private int _streamedObjectCount; + private readonly int _first; + private readonly int _last; + private int _skip; + private readonly int _skipLast; + private readonly bool _firstOrLastSpecified; + } + + /// + /// List of processed parameters obtained from the Expression array. + /// + private List _propertyMshParameterList; + + /// + /// Singleton list of process parameters obtained from ExpandProperty. + /// + private List _expandMshParameterList; + + private PSPropertyExpressionFilter _exclusionFilter; + + private sealed class UniquePSObjectHelper + { + internal UniquePSObjectHelper(PSObject o, int notePropertyCount) + { + WrittenObject = o; + NotePropertyCount = notePropertyCount; + } + + internal readonly PSObject WrittenObject; + + internal int NotePropertyCount { get; } + } + + private List _uniques = null; + + private void ProcessExpressionParameter() + { + TerminatingErrorContext invocationContext = new(this); + ParameterProcessor processor = + new(new SelectObjectExpressionParameterDefinition()); + if ((Property != null) && (Property.Length != 0)) + { + // Build property list taking into account the wildcards and @{name=;expression=} + + _propertyMshParameterList = processor.ProcessParameters(Property, invocationContext); + } + else + { + // Property don't exist + _propertyMshParameterList = new List(); + } + + if (!string.IsNullOrEmpty(ExpandProperty)) + { + _expandMshParameterList = processor.ProcessParameters(new string[] { ExpandProperty }, invocationContext); + } + + if (ExcludeProperty != null) + { + _exclusionFilter = new PSPropertyExpressionFilter(ExcludeProperty); + // ExcludeProperty implies -Property * for better UX + if ((Property == null) || (Property.Length == 0)) + { + Property = new object[] { "*" }; + _propertyMshParameterList = processor.ProcessParameters(Property, invocationContext); + } + } + } + + private void ProcessObject(PSObject inputObject) + { + if ((Property == null || Property.Length == 0) && string.IsNullOrEmpty(ExpandProperty)) + { + FilteredWriteObject(inputObject, new List()); + return; + } + + // If property parameter is mentioned + List matchedProperties = new(); + foreach (MshParameter p in _propertyMshParameterList) + { + ProcessParameter(p, inputObject, matchedProperties); + } + + if (string.IsNullOrEmpty(ExpandProperty)) + { + PSObject result = new(); + if (matchedProperties.Count != 0) + { + HashSet propertyNames = new(StringComparer.OrdinalIgnoreCase); + + foreach (PSNoteProperty noteProperty in matchedProperties) + { + try + { + if (!propertyNames.Contains(noteProperty.Name)) + { + propertyNames.Add(noteProperty.Name); + result.Properties.Add(noteProperty); + } + else + { + WriteAlreadyExistingPropertyError(noteProperty.Name, inputObject, + "AlreadyExistingUserSpecifiedPropertyNoExpand"); + } + } + catch (ExtendedTypeSystemException) + { + WriteAlreadyExistingPropertyError(noteProperty.Name, inputObject, + "AlreadyExistingUserSpecifiedPropertyNoExpand"); + } + } + } + + FilteredWriteObject(result, matchedProperties); + } + else + { + ProcessExpandParameter(_expandMshParameterList[0], inputObject, matchedProperties); + } + } + + private void ProcessParameter(MshParameter p, PSObject inputObject, List result) + { + string name = p.GetEntry(NameEntryDefinition.NameEntryKey) as string; + + PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; + List expressionResults = new(); + foreach (PSPropertyExpression resolvedName in ex.ResolveNames(inputObject)) + { + if (_exclusionFilter == null || !_exclusionFilter.IsMatch(resolvedName)) + { + List tempExprResults = resolvedName.GetValues(inputObject); + if (tempExprResults == null) + { + continue; + } + + foreach (PSPropertyExpressionResult mshExpRes in tempExprResults) + { + expressionResults.Add(mshExpRes); + } + } + } + + // allow 'Select-Object -Property noexist-name' to return a PSObject with property noexist-name, + // unless noexist-name itself contains wildcards + if (expressionResults.Count == 0 && !ex.HasWildCardCharacters) + { + expressionResults.Add(new PSPropertyExpressionResult(null, ex, null)); + } + + // if we have an expansion, renaming is not acceptable + else if (!string.IsNullOrEmpty(name) && expressionResults.Count > 1) + { + string errorMsg = SelectObjectStrings.RenamingMultipleResults; + ErrorRecord errorRecord = new( + new InvalidOperationException(errorMsg), + "RenamingMultipleResults", + ErrorCategory.InvalidOperation, + inputObject); + WriteError(errorRecord); + return; + } + + foreach (PSPropertyExpressionResult r in expressionResults) + { + // filter the exclusions, if any + if (_exclusionFilter != null && _exclusionFilter.IsMatch(r.ResolvedExpression)) + continue; + + PSNoteProperty mshProp; + if (string.IsNullOrEmpty(name)) + { + string resolvedExpressionName = r.ResolvedExpression.ToString(); + if (string.IsNullOrEmpty(resolvedExpressionName)) + { + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( + "Property", + SelectObjectStrings.EmptyScriptBlockAndNoName); + ThrowTerminatingError( + new ErrorRecord( + mshArgE, + "EmptyScriptBlockAndNoName", + ErrorCategory.InvalidArgument, null)); + } + + mshProp = new PSNoteProperty(resolvedExpressionName, r.Result); + } + else + { + mshProp = new PSNoteProperty(name, r.Result); + } + + result.Add(mshProp); + } + } + + private void ProcessExpandParameter(MshParameter p, PSObject inputObject, + List matchedProperties) + { + PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; + List expressionResults = ex.GetValues(inputObject); + + if (expressionResults.Count == 0) + { + ErrorRecord errorRecord = new( + PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.PropertyNotFound, ExpandProperty), + "ExpandPropertyNotFound", + ErrorCategory.InvalidArgument, + inputObject); + throw new SelectObjectException(errorRecord); + } + + if (expressionResults.Count > 1) + { + ErrorRecord errorRecord = new( + PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.MutlipleExpandProperties, ExpandProperty), + "MutlipleExpandProperties", + ErrorCategory.InvalidArgument, + inputObject); + throw new SelectObjectException(errorRecord); + } + + PSPropertyExpressionResult r = expressionResults[0]; + if (r.Exception == null) + { + // ignore the property value if it's null + if (r.Result == null) + { + return; + } + + System.Collections.IEnumerable results = LanguagePrimitives.GetEnumerable(r.Result); + if (results == null) + { + // add NoteProperties if there is any + // If r.Result is a base object, we don't want to associate the NoteProperty + // directly with it. We want the NoteProperty to be associated only with this + // particular PSObject, so that when the user uses the base object else where, + // its members remain the same as before the Select-Object command run. + PSObject expandedObject = PSObject.AsPSObject(r.Result, true); + AddNoteProperties(expandedObject, inputObject, matchedProperties); + + FilteredWriteObject(expandedObject, matchedProperties); + return; + } + + foreach (object expandedValue in results) + { + // ignore the element if it's null + if (expandedValue == null) + { + continue; + } + + // add NoteProperties if there is any + // If expandedValue is a base object, we don't want to associate the NoteProperty + // directly with it. We want the NoteProperty to be associated only with this + // particular PSObject, so that when the user uses the base object else where, + // its members remain the same as before the Select-Object command run. + PSObject expandedObject = PSObject.AsPSObject(expandedValue, true); + AddNoteProperties(expandedObject, inputObject, matchedProperties); + + FilteredWriteObject(expandedObject, matchedProperties); + } + } + else + { + ErrorRecord errorRecord = new( + r.Exception, + "PropertyEvaluationExpand", + ErrorCategory.InvalidResult, + inputObject); + throw new SelectObjectException(errorRecord); + } + } + + private void AddNoteProperties(PSObject expandedObject, PSObject inputObject, IEnumerable matchedProperties) + { + foreach (PSNoteProperty noteProperty in matchedProperties) + { + try + { + if (expandedObject.Properties[noteProperty.Name] != null) + { + WriteAlreadyExistingPropertyError(noteProperty.Name, inputObject, "AlreadyExistingUserSpecifiedPropertyExpand"); + } + else + { + expandedObject.Properties.Add(noteProperty); + } + } + catch (ExtendedTypeSystemException) + { + WriteAlreadyExistingPropertyError(noteProperty.Name, inputObject, "AlreadyExistingUserSpecifiedPropertyExpand"); + } + } + } + + private void WriteAlreadyExistingPropertyError(string name, object inputObject, string errorId) + { + ErrorRecord errorRecord = new( + PSTraceSource.NewArgumentException("Property", SelectObjectStrings.AlreadyExistingProperty, name), + errorId, + ErrorCategory.InvalidOperation, + inputObject); + WriteError(errorRecord); + } + + private void FilteredWriteObject(PSObject obj, List addedNoteProperties) + { + Diagnostics.Assert(obj != null, "This command should never write null"); + + if (!_unique) + { + if (obj != AutomationNull.Value) + { + SetPSCustomObject(obj, newPSObject: addedNoteProperties.Count > 0); + WriteObject(obj); + } + + return; + } + // if only unique is mentioned + else if ((_unique)) + { + bool isObjUnique = true; + foreach (UniquePSObjectHelper uniqueObj in _uniques) + { + ObjectCommandComparer comparer = new( + ascending: true, + CultureInfo.CurrentCulture, + caseSensitive: !CaseInsensitive.IsPresent); + + if ((comparer.Compare(obj.BaseObject, uniqueObj.WrittenObject.BaseObject) == 0) && + (uniqueObj.NotePropertyCount == addedNoteProperties.Count)) + { + bool found = true; + foreach (PSNoteProperty note in addedNoteProperties) + { + PSMemberInfo prop = uniqueObj.WrittenObject.Properties[note.Name]; + if (prop == null || comparer.Compare(prop.Value, note.Value) != 0) + { + found = false; + break; + } + } + + if (found) + { + isObjUnique = false; + break; + } + } + else + { + continue; + } + } + + if (isObjUnique) + { + SetPSCustomObject(obj, newPSObject: addedNoteProperties.Count > 0); + _uniques.Add(new UniquePSObjectHelper(obj, addedNoteProperties.Count)); + } + } + } + + private void SetPSCustomObject(PSObject psObj, bool newPSObject) + { + if (psObj.ImmediateBaseObject is PSCustomObject) + { + var typeName = "Selected." + InputObject.BaseObject.GetType().ToString(); + if (newPSObject || !psObj.TypeNames.Contains(typeName)) + { + psObj.TypeNames.Insert(0, typeName); + } + } + } + + private void ProcessObjectAndHandleErrors(PSObject pso) + { + Diagnostics.Assert(pso != null, "Caller should verify pso != null"); + + try + { + ProcessObject(pso); + } + catch (SelectObjectException e) + { + WriteError(e.ErrorRecord); + } + } + + /// + /// + protected override void BeginProcessing() + { + ProcessExpressionParameter(); + + if (_unique) + { + _uniques = new List(); + } + + _selectObjectQueue = new SelectObjectQueue(_first, _last, Skip, SkipLast, _firstOrLastSpecified); + } + + /// + /// Handles processing of InputObject. + /// + protected override void ProcessRecord() + { + if (InputObject != AutomationNull.Value && InputObject != null) + { + if (_indexSpecified) + { + ProcessIndexed(); + } + else + { + _selectObjectQueue.Enqueue(InputObject); + PSObject streamingInputObject = _selectObjectQueue.StreamingDequeue(); + if (streamingInputObject != null) + { + ProcessObjectAndHandleErrors(streamingInputObject); + } + + if (_selectObjectQueue.AllRequestedObjectsProcessed && !this.Wait) + { + this.EndProcessing(); + throw new StopUpstreamCommandsException(this); + } + } + } + } + + /// + /// The index of the active index filter. + /// + private int _currentFilterIndex; + + /// + /// The index of the object being processed. + /// + private int _currentObjectIndex; + + /// + /// Handles processing of InputObject if -Index or -SkipIndex is specified. + /// + private void ProcessIndexed() + { + if (_isIncludeIndex) + { + if (_currentFilterIndex < _index.Length) + { + int nextIndexToOutput = _index[_currentFilterIndex]; + if (_currentObjectIndex == nextIndexToOutput) + { + ProcessObjectAndHandleErrors(InputObject); + while ((_currentFilterIndex < _index.Length) && (_index[_currentFilterIndex] == nextIndexToOutput)) + { + _currentFilterIndex++; + } + } + } + + if (!Wait && _currentFilterIndex >= _index.Length) + { + EndProcessing(); + throw new StopUpstreamCommandsException(this); + } + + _currentObjectIndex++; + } + else + { + if (_currentFilterIndex < _index.Length) + { + int nextIndexToSkip = _index[_currentFilterIndex]; + if (_currentObjectIndex != nextIndexToSkip) + { + ProcessObjectAndHandleErrors(InputObject); + } + else + { + while ((_currentFilterIndex < _index.Length) && (_index[_currentFilterIndex] == nextIndexToSkip)) + { + _currentFilterIndex++; + } + } + } + else + { + ProcessObjectAndHandleErrors(InputObject); + } + + _currentObjectIndex++; + } + } + + /// + /// Completes the processing of Input. + /// + protected override void EndProcessing() + { + // We can skip this part for 'IndexParameter' and 'SkipLastParameter' sets because: + // 1. 'IndexParameter' set doesn't use selectObjectQueue. + // 2. 'SkipLastParameter' set should have processed all valid input in the ProcessRecord. + if (ParameterSetName == "DefaultParameter") + { + if (_first != 0) + { + while ((_selectObjectQueue.Count > 0)) + { + ProcessObjectAndHandleErrors(_selectObjectQueue.Dequeue()); + } + } + else + { + while ((_selectObjectQueue.Count > 0)) + { + int lenQueue = _selectObjectQueue.Count; + if (lenQueue > Skip) + { + ProcessObjectAndHandleErrors(_selectObjectQueue.Dequeue()); + } + else + { + break; + } + } + } + } + + if (_uniques != null) + { + foreach (UniquePSObjectHelper obj in _uniques) + { + if (obj.WrittenObject == null || obj.WrittenObject == AutomationNull.Value) + { + continue; + } + + WriteObject(obj.WrittenObject); + } + } + } + } + + /// + /// Used only internally for select-object. + /// + [SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "This exception is internal and never thrown by any public API")] + [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This exception is internal and never thrown by any public API")] + [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = "This exception is internal and never thrown by any public API")] + internal sealed class SelectObjectException : SystemException + { + internal ErrorRecord ErrorRecord { get; } + + internal SelectObjectException(ErrorRecord errorRecord) + { + ErrorRecord = errorRecord; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..2598d953496298e8616e394ab69d2b9ae624b741 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -0,0 +1,403 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Net.Mail; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + #region SendMailMessage + /// + /// Implementation for the Send-MailMessage command. + /// + [Obsolete("This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage at this time. See https://aka.ms/SendMailMessage for more information.")] + [Cmdlet(VerbsCommunications.Send, "MailMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097115")] + public sealed class SendMailMessage : PSCmdlet + { + #region Command Line Parameters + + /// + /// Gets or sets the files names to be attached to the email. + /// If the filename specified can not be found, then the relevant error + /// message should be thrown. + /// + [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("PsPath")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Attachments { get; set; } + + /// + /// Gets or sets the address collection that contains the + /// blind carbon copy (BCC) recipients for the e-mail message. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Bcc { get; set; } + + /// + /// Gets or sets the body (content) of the message. + /// + [Parameter(Position = 2, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string Body { get; set; } + + /// + /// Gets or sets the value indicating whether the mail message body is in Html. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Alias("BAH")] + public SwitchParameter BodyAsHtml { get; set; } + + /// + /// Gets or sets the encoding used for the content of the body and also the subject. + /// This is set to ASCII to ensure there are no problems with any email server. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Alias("BE")] + [ValidateNotNullOrEmpty] + [ArgumentEncodingCompletions] + [ArgumentToEncodingTransformation] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.ASCII; + + /// + /// Gets or sets the address collection that contains the + /// carbon copy (CC) recipients for the e-mail message. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cc")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Cc { get; set; } + + /// + /// Gets or sets the delivery notifications options for the e-mail message. The various + /// options available for this parameter are None, OnSuccess, OnFailure, Delay and Never. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Alias("DNO")] + [ValidateNotNullOrEmpty] + public DeliveryNotificationOptions DeliveryNotificationOption { get; set; } + + /// + /// Gets or sets the from address for this e-mail message. The default value for + /// this parameter is the email address of the currently logged on user. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public string From { get; set; } + + /// + /// Gets or sets the name of the Host used to send the email. This host name will be assigned + /// to the Powershell variable PSEmailServer, if this host can not reached an appropriate error. + /// message will be displayed. + /// + [Parameter(Position = 3, ValueFromPipelineByPropertyName = true)] + [Alias("ComputerName")] + [ValidateNotNullOrEmpty] + public string SmtpServer { get; set; } + + /// + /// Gets or sets the priority of the email message. The valid values for this are Normal, High and Low. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + public MailPriority Priority { get; set; } + + /// + /// Gets or sets the Reply-To field for this e-mail message. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public string[] ReplyTo { get; set; } + + /// + /// Gets or sets the subject of the email message. + /// + [Parameter(Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] + [Alias("sub")] + public string Subject { get; set; } + + /// + /// Gets or sets the To address for this e-mail message. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] To { get; set; } + + /// + /// Gets or sets the credential for this e-mail message. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Credential] + [ValidateNotNullOrEmpty] + public PSCredential Credential { get; set; } + + /// + /// Gets or sets if Secured layer is required or not. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public SwitchParameter UseSsl { get; set; } + + /// + /// Gets or sets the Port to be used on the server. + /// + /// + /// Value must be greater than zero. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, int.MaxValue)] + public int Port { get; set; } + + #endregion + + #region Private variables and methods + + // Instantiate a new instance of MailMessage + private readonly MailMessage _mMailMessage = new(); + + private SmtpClient _mSmtpClient = null; + + /// + /// Add the input addresses which are either string or hashtable to the MailMessage. + /// It returns true if the from parameter has more than one value. + /// + /// + /// + private void AddAddressesToMailMessage(object address, string param) + { + string[] objEmailAddresses = address as string[]; + foreach (string strEmailAddress in objEmailAddresses) + { + try + { + switch (param) + { + case "to": + { + _mMailMessage.To.Add(new MailAddress(strEmailAddress)); + break; + } + case "cc": + { + _mMailMessage.CC.Add(new MailAddress(strEmailAddress)); + break; + } + case "bcc": + { + _mMailMessage.Bcc.Add(new MailAddress(strEmailAddress)); + break; + } + case "replyTo": + { + _mMailMessage.ReplyToList.Add(new MailAddress(strEmailAddress)); + break; + } + } + } + catch (FormatException e) + { + ErrorRecord er = new(e, "FormatException", ErrorCategory.InvalidType, null); + WriteError(er); + continue; + } + } + } + + #endregion + + #region Overrides + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + try + { + // Set the sender address of the mail message + _mMailMessage.From = new MailAddress(From); + } + catch (FormatException e) + { + ErrorRecord er = new(e, "FormatException", ErrorCategory.InvalidType, From); + ThrowTerminatingError(er); + } + + // Set the recipient address of the mail message + AddAddressesToMailMessage(To, "to"); + + // Set the BCC address of the mail message + if (Bcc != null) + { + AddAddressesToMailMessage(Bcc, "bcc"); + } + + // Set the CC address of the mail message + if (Cc != null) + { + AddAddressesToMailMessage(Cc, "cc"); + } + + // Set the Reply-To address of the mail message + if (ReplyTo != null) + { + AddAddressesToMailMessage(ReplyTo, "replyTo"); + } + + // Set the delivery notification + _mMailMessage.DeliveryNotificationOptions = DeliveryNotificationOption; + + // Set the subject of the mail message + _mMailMessage.Subject = Subject; + + // Set the body of the mail message + _mMailMessage.Body = Body; + + // Set the subject and body encoding + _mMailMessage.SubjectEncoding = Encoding; + _mMailMessage.BodyEncoding = Encoding; + + // Set the format of the mail message body as HTML + _mMailMessage.IsBodyHtml = BodyAsHtml; + + // Set the priority of the mail message to normal + _mMailMessage.Priority = Priority; + + // Get the PowerShell environment variable + // globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer + PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer); + + if (SmtpServer == null && globalEmailServer != null) + { + SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture); + } + + if (string.IsNullOrEmpty(SmtpServer)) + { + ErrorRecord er = new(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null); + this.ThrowTerminatingError(er); + } + + if (Port == 0) + { + _mSmtpClient = new SmtpClient(SmtpServer); + } + else + { + _mSmtpClient = new SmtpClient(SmtpServer, Port); + } + + if (UseSsl) + { + _mSmtpClient.EnableSsl = true; + } + + if (Credential != null) + { + _mSmtpClient.UseDefaultCredentials = false; + _mSmtpClient.Credentials = Credential.GetNetworkCredential(); + } + else if (!UseSsl) + { + _mSmtpClient.UseDefaultCredentials = true; + } + } + + /// + /// ProcessRecord override. + /// + protected override void ProcessRecord() + { + // Add the attachments + if (Attachments != null) + { + string filepath = string.Empty; + foreach (string attachFile in Attachments) + { + try + { + filepath = PathUtils.ResolveFilePath(attachFile, this); + } + catch (ItemNotFoundException e) + { + // NOTE: This will throw + PathUtils.ReportFileOpenFailure(this, filepath, e); + } + + Attachment mailAttachment = new(filepath); + _mMailMessage.Attachments.Add(mailAttachment); + } + } + } + + /// + /// EndProcessing override. + /// + protected override void EndProcessing() + { + try + { + // Send the mail message + _mSmtpClient.Send(_mMailMessage); + } + catch (SmtpFailedRecipientsException ex) + { + ErrorRecord er = new(ex, "SmtpFailedRecipientsException", ErrorCategory.InvalidOperation, _mSmtpClient); + WriteError(er); + } + catch (SmtpException ex) + { + if (ex.InnerException != null) + { + ErrorRecord er = new(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); + WriteError(er); + } + else + { + ErrorRecord er = new(ex, "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); + WriteError(er); + } + } + catch (InvalidOperationException ex) + { + ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _mSmtpClient); + WriteError(er); + } + catch (System.Security.Authentication.AuthenticationException ex) + { + ErrorRecord er = new(ex, "AuthenticationException", ErrorCategory.InvalidOperation, _mSmtpClient); + WriteError(er); + } + finally + { + _mSmtpClient.Dispose(); + + // If we don't dispose the attachments, the sender can't modify or use the files sent. + _mMailMessage.Attachments.Dispose(); + } + } + + #endregion + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs new file mode 100644 index 0000000000000000000000000000000000000000..ccf17652c79fb21a4416923773627042e4735387 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Set-PSBreakpoint command. + /// + [Cmdlet(VerbsCommon.Set, "PSBreakpoint", DefaultParameterSetName = LineParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096623")] + [OutputType(typeof(CommandBreakpoint), ParameterSetName = new string[] { CommandParameterSetName })] + [OutputType(typeof(LineBreakpoint), ParameterSetName = new string[] { LineParameterSetName })] + [OutputType(typeof(VariableBreakpoint), ParameterSetName = new string[] { VariableParameterSetName })] + public class SetPSBreakpointCommand : PSBreakpointAccessorCommandBase + { + #region parameters + + /// + /// Gets or sets the action to take when hitting this breakpoint. + /// + [Parameter(ParameterSetName = CommandParameterSetName)] + [Parameter(ParameterSetName = LineParameterSetName)] + [Parameter(ParameterSetName = VariableParameterSetName)] + public ScriptBlock Action { get; set; } + + /// + /// Gets or sets the column to set the breakpoint on. + /// + [Parameter(Position = 2, ParameterSetName = LineParameterSetName)] + [ValidateRange(1, int.MaxValue)] + public int Column { get; set; } + + /// + /// Gets or sets the command(s) to set the breakpoint on. + /// + [Alias("C")] + [Parameter(ParameterSetName = CommandParameterSetName, Mandatory = true)] + public string[] Command { get; set; } + + /// + /// Gets or sets the line to set the breakpoint on. + /// + [Parameter(Position = 1, ParameterSetName = LineParameterSetName, Mandatory = true)] + public int[] Line { get; set; } + + /// + /// Gets or sets the script to set the breakpoint on. + /// + [Parameter(ParameterSetName = CommandParameterSetName, Position = 0)] + [Parameter(ParameterSetName = LineParameterSetName, Mandatory = true, Position = 0)] + [Parameter(ParameterSetName = VariableParameterSetName, Position = 0)] + [ValidateNotNull] + public string[] Script { get; set; } + + /// + /// Gets or sets the variables to set the breakpoint(s) on. + /// + [Alias("V")] + [Parameter(ParameterSetName = VariableParameterSetName, Mandatory = true)] + public string[] Variable { get; set; } + + /// + /// Gets or sets the access type for variable breakpoints to break on. + /// + [Parameter(ParameterSetName = VariableParameterSetName)] + public VariableAccessMode Mode { get; set; } = VariableAccessMode.Write; + + #endregion parameters + + #region overrides + + /// + /// Verifies that debugging is supported. + /// + protected override void BeginProcessing() + { + // Call the base method to ensure Runspace is initialized properly. + base.BeginProcessing(); + + // Check whether we are executing on a remote session and if so + // whether the RemoteScript debug option is selected. + if (this.Context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost && + ((this.Context.CurrentRunspace == null) || (this.Context.CurrentRunspace.Debugger == null) || + ((this.Context.CurrentRunspace.Debugger.DebugMode & DebugModes.RemoteScript) != DebugModes.RemoteScript) && + (this.Context.CurrentRunspace.Debugger.DebugMode != DebugModes.None))) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(Debugger.RemoteDebuggerNotSupportedInHost), + "SetPSBreakpoint:RemoteDebuggerNotSupported", + ErrorCategory.NotImplemented, + null)); + } + + // If we're in ConstrainedLanguage mode and the system is not in lockdown mode, + // don't allow breakpoints as we can't protect that boundary. + // This covers the case where the debugger could modify variables in a trusted + // script block. So debugging is supported in Constrained language mode only if + // the system is also in lock down mode. + if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && + (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() != + System.Management.Automation.Security.SystemEnforcementMode.Enforce)) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(Debugger.RemoteDebuggerNotSupported), + "CannotSetBreakpointInconsistentLanguageMode", + ErrorCategory.PermissionDenied, + Context.LanguageMode)); + } + } + + /// + /// Set a new breakpoint. + /// + protected override void ProcessRecord() + { + // If there is a script, resolve its path + Collection scripts = new(); + + if (Script != null) + { + foreach (string script in Script) + { + Collection scriptPaths = SessionState.Path.GetResolvedPSPathFromPSPath(script); + + for (int i = 0; i < scriptPaths.Count; i++) + { + string providerPath = scriptPaths[i].ProviderPath; + + if (!File.Exists(providerPath)) + { + WriteError( + new ErrorRecord( + new ArgumentException(StringUtil.Format(Debugger.FileDoesNotExist, providerPath)), + "NewPSBreakpoint:FileDoesNotExist", + ErrorCategory.InvalidArgument, + null)); + + continue; + } + + string extension = Path.GetExtension(providerPath); + + if (!extension.Equals(".ps1", StringComparison.OrdinalIgnoreCase) && !extension.Equals(".psm1", StringComparison.OrdinalIgnoreCase)) + { + WriteError( + new ErrorRecord( + new ArgumentException(StringUtil.Format(Debugger.WrongExtension, providerPath)), + "NewPSBreakpoint:WrongExtension", + ErrorCategory.InvalidArgument, + null)); + continue; + } + + scripts.Add(Path.GetFullPath(providerPath)); + } + } + } + + // If it is a command breakpoint... + if (ParameterSetName.Equals(CommandParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + for (int i = 0; i < Command.Length; i++) + { + if (scripts.Count > 0) + { + foreach (string path in scripts) + { + ProcessBreakpoint( + Runspace.Debugger.SetCommandBreakpoint(Command[i], Action, path)); + } + } + else + { + ProcessBreakpoint( + Runspace.Debugger.SetCommandBreakpoint(Command[i], Action, path: null)); + } + } + } + // If it is a variable breakpoint... + else if (ParameterSetName.Equals(VariableParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + for (int i = 0; i < Variable.Length; i++) + { + if (scripts.Count > 0) + { + foreach (string path in scripts) + { + ProcessBreakpoint( + Runspace.Debugger.SetVariableBreakpoint(Variable[i], Mode, Action, path)); + } + } + else + { + ProcessBreakpoint( + Runspace.Debugger.SetVariableBreakpoint(Variable[i], Mode, Action, path: null)); + } + } + } + // Else it is the default parameter set (Line breakpoint)... + else + { + Debug.Assert(ParameterSetName.Equals(LineParameterSetName, StringComparison.OrdinalIgnoreCase)); + + for (int i = 0; i < Line.Length; i++) + { + if (Line[i] < 1) + { + WriteError( + new ErrorRecord( + new ArgumentException(Debugger.LineLessThanOne), + "SetPSBreakpoint:LineLessThanOne", + ErrorCategory.InvalidArgument, + null)); + + continue; + } + + foreach (string path in scripts) + { + ProcessBreakpoint( + Runspace.Debugger.SetLineBreakpoint(path, Line[i], Column, Action)); + } + } + } + } + + #endregion overrides + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..6c0007fa2a2e1e2b7ccc02b15e78ec1c7ca20cdc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The implementation of the "set-alias" cmdlet. + /// + [Cmdlet(VerbsCommon.Set, "Alias", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096625")] + [OutputType(typeof(AliasInfo))] + public class SetAliasCommand : WriteAliasCommandBase + { + #region Command code + + /// + /// The main processing loop of the command. + /// + protected override void ProcessRecord() + { + // Create the alias info + + AliasInfo aliasToSet = + new( + Name, + Value, + Context, + Option); + + aliasToSet.Description = Description; + + string action = AliasCommandStrings.SetAliasAction; + + string target = StringUtil.Format(AliasCommandStrings.SetAliasTarget, Name, Value); + + if (ShouldProcess(target, action)) + { + // Set the alias in the specified scope or the + // current scope. + + AliasInfo result = null; + + try + { + if (string.IsNullOrEmpty(Scope)) + { + result = SessionState.Internal.SetAliasItem(aliasToSet, Force, MyInvocation.CommandOrigin); + } + else + { + result = SessionState.Internal.SetAliasItemAtScope(aliasToSet, Scope, Force, MyInvocation.CommandOrigin); + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + return; + } + + // Write the alias to the pipeline if PassThru was specified + + if (PassThru && result != null) + { + WriteObject(result); + } + } + } + #endregion Command code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..5dfe40fa9d452581ae27def899b3db48d05cd58d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable 1634, 1691 + +using System; +using System.ComponentModel; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Runtime.InteropServices; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the set-date command. + /// + [Cmdlet(VerbsCommon.Set, "Date", DefaultParameterSetName = "Date", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097133")] + [OutputType(typeof(DateTime))] + public sealed class SetDateCommand : PSCmdlet + { + #region parameters + + /// + /// Allows user to override the date/time object that will be processed. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Date", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public DateTime Date { get; set; } + + /// + /// Allows a use to specify a timespan with which to apply to the current time. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Adjust", ValueFromPipelineByPropertyName = true)] + [AllowNull] + public TimeSpan Adjust { get; set; } + + /// + /// This option determines the default output format used to display the object set-date emits. + /// + [Parameter] + public DisplayHintType DisplayHint { get; set; } = DisplayHintType.DateTime; + + #endregion + + #region methods + + /// + /// Set the date. + /// + protected override void ProcessRecord() + { + DateTime dateToUse; + + switch (ParameterSetName) + { + case "Date": + dateToUse = Date; + break; + + case "Adjust": + dateToUse = DateTime.Now.Add(Adjust); + break; + + default: + Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); + goto case "Date"; + } + + if (ShouldProcess(dateToUse.ToString())) + { +#if UNIX + // We are not validating the native call here. + // We just want to be sure that we're using the value the user provided us. + if (Dbg.Internal.InternalTestHooks.SetDate) + { + WriteObject(dateToUse); + } + else if (!Platform.NonWindowsSetDate(dateToUse)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } +#else + // build up the SystemTime struct to pass to SetSystemTime + NativeMethods.SystemTime systemTime = new(); + systemTime.Year = (ushort)dateToUse.Year; + systemTime.Month = (ushort)dateToUse.Month; + systemTime.Day = (ushort)dateToUse.Day; + systemTime.Hour = (ushort)dateToUse.Hour; + systemTime.Minute = (ushort)dateToUse.Minute; + systemTime.Second = (ushort)dateToUse.Second; + systemTime.Milliseconds = (ushort)dateToUse.Millisecond; +#pragma warning disable 56523 + if (Dbg.Internal.InternalTestHooks.SetDate) + { + WriteObject(systemTime); + } + else + { + if (!NativeMethods.SetLocalTime(ref systemTime)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + // MSDN says to call this twice to account for changes + // between DST + if (!NativeMethods.SetLocalTime(ref systemTime)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + } +#pragma warning restore 56523 +#endif + } + + // output DateTime object wrapped in an PSObject with DisplayHint attached + PSObject outputObj = new(dateToUse); + PSNoteProperty note = new("DisplayHint", DisplayHint); + outputObj.Properties.Add(note); + + // If we've turned on the SetDate test hook, don't emit the output object here because we emitted it earlier. + if (!Dbg.Internal.InternalTestHooks.SetDate) + { + WriteObject(outputObj); + } + } + + #endregion + + #region nativemethods + + internal static class NativeMethods + { + [StructLayout(LayoutKind.Sequential)] + public struct SystemTime + { + public ushort Year; + public ushort Month; + public ushort DayOfWeek; + public ushort Day; + public ushort Hour; + public ushort Minute; + public ushort Second; + public ushort Milliseconds; + } + + [DllImport(PinvokeDllNames.SetLocalTimeDllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetLocalTime(ref SystemTime systime); + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..60b05807d489df2ac8c841fdef90599edd467d2d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -0,0 +1,644 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Management.Automation; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Show-Command displays a GUI for a cmdlet, or for all cmdlets if no specific cmdlet is specified. + /// + [Cmdlet(VerbsCommon.Show, "Command", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109589")] + public class ShowCommandCommand : PSCmdlet, IDisposable + { + #region Private Fields + /// + /// Set to true when ProcessRecord is reached, since it will always open a window. + /// + private bool _hasOpenedWindow; + + /// + /// Determines if the command should be sent to the pipeline as a string instead of run. + /// + private bool _passThrough; + + /// + /// Uses ShowCommandProxy to invoke WPF GUI object. + /// + private ShowCommandProxy _showCommandProxy; + + /// + /// Data container for all cmdlets. This is populated when show-command is called with no command name. + /// + private List _commands; + + /// + /// List of modules that have been loaded indexed by module name. + /// + private Dictionary _importedModules; + + /// + /// Record the EndProcessing error. + /// + private PSDataCollection _errors = new(); + + /// + /// Field used for the NoCommonParameter parameter. + /// + private SwitchParameter _noCommonParameter; + + /// + /// Object used for ShowCommand with a command name that holds the view model created for the command. + /// + private object _commandViewModelObj; + #endregion + + #region Input Cmdlet Parameter + /// + /// Gets or sets the command name. + /// + [Parameter(Position = 0)] + [Alias("CommandName")] + public string Name { get; set; } + + /// + /// Gets or sets the Width. + /// + [Parameter] + [ValidateRange(300, int.MaxValue)] + public double Height { get; set; } + + /// + /// Gets or sets the Width. + /// + [Parameter] + [ValidateRange(300, int.MaxValue)] + public double Width { get; set; } + + /// + /// Gets or sets a value indicating Common Parameters should not be displayed. + /// + [Parameter] + public SwitchParameter NoCommonParameter + { + get { return _noCommonParameter; } + + set { _noCommonParameter = value; } + } + + /// + /// Gets or sets a value indicating errors should not cause a message window to be displayed. + /// + [Parameter] + public SwitchParameter ErrorPopup { get; set; } + + /// + /// Gets or sets a value indicating the command should be sent to the pipeline as a string instead of run. + /// + [Parameter] + public SwitchParameter PassThru + { + get { return _passThrough; } + + set { _passThrough = value; } + } + #endregion + + #region Public and Protected Methods + /// + /// Executes a PowerShell script, writing the output objects to the pipeline. + /// + /// Script to execute. + public void RunScript(string script) + { + if (_showCommandProxy == null || string.IsNullOrEmpty(script)) + { + return; + } + + if (_passThrough) + { + this.WriteObject(script); + return; + } + + if (ErrorPopup) + { + this.RunScriptSilentlyAndWithErrorHookup(script); + return; + } + + if (_showCommandProxy.HasHostWindow) + { + if (!_showCommandProxy.SetPendingISECommand(script)) + { + this.RunScriptSilentlyAndWithErrorHookup(script); + } + + return; + } + + // Don't send newline at end as PSReadLine shows it rather than executing + if (!ConsoleInputWithNativeMethods.AddToConsoleInputBuffer(script, newLine: false)) + { + this.WriteDebug(FormatAndOut_out_gridview.CannotWriteToConsoleInputBuffer); + this.RunScriptSilentlyAndWithErrorHookup(script); + } + } + + /// + /// Dispose method in IDisposable. + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Initialize a proxy instance for show-command. + /// + protected override void BeginProcessing() + { + _showCommandProxy = new ShowCommandProxy(this); + + if (_showCommandProxy.ScreenHeight < this.Height) + { + ErrorRecord error = new( + new NotSupportedException(string.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)), + "PARAMETER_DATA_ERROR", + ErrorCategory.InvalidData, + null); + this.ThrowTerminatingError(error); + } + + if (_showCommandProxy.ScreenWidth < this.Width) + { + ErrorRecord error = new( + new NotSupportedException(string.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)), + "PARAMETER_DATA_ERROR", + ErrorCategory.InvalidData, + null); + this.ThrowTerminatingError(error); + } + } + + /// + /// ProcessRecord with or without CommandName. + /// + protected override void ProcessRecord() + { + if (Name == null) + { + _hasOpenedWindow = this.CanProcessRecordForAllCommands(); + } + else + { + _hasOpenedWindow = this.CanProcessRecordForOneCommand(); + } + } + + /// + /// Optionally displays errors in a message. + /// + protected override void EndProcessing() + { + if (!_hasOpenedWindow) + { + return; + } + + // We wait until the window is loaded and then activate it + // to work around the console window gaining activation somewhere + // in the end of ProcessRecord, which causes the keyboard focus + // (and use oif tab key to focus controls) to go away from the window + _showCommandProxy.WindowLoaded.WaitOne(); + _showCommandProxy.ActivateWindow(); + + this.WaitForWindowClosedOrHelpNeeded(); + this.RunScript(_showCommandProxy.GetScript()); + + if (_errors.Count == 0 || !ErrorPopup) + { + return; + } + + StringBuilder errorString = new(); + + for (int i = 0; i < _errors.Count; i++) + { + if (i != 0) + { + errorString.AppendLine(); + } + + ErrorRecord error = _errors[i]; + errorString.Append(error.Exception.Message); + } + + _showCommandProxy.ShowErrorString(errorString.ToString()); + } + + /// + /// StopProcessing is called close the window when user press Ctrl+C in the command prompt. + /// + protected override void StopProcessing() + { + _showCommandProxy.CloseWindow(); + } + + #endregion + + #region Private Methods + /// + /// Runs the script in a new PowerShell instance and hooks up error stream to potentially display error popup. + /// This method has the inconvenience of not showing to the console user the script being executed. + /// + /// Script to be run. + private void RunScriptSilentlyAndWithErrorHookup(string script) + { + // errors are not created here, because there is a field for it used in the final pop up + PSDataCollection output = new(); + + output.DataAdded += this.Output_DataAdded; + _errors.DataAdded += this.Error_DataAdded; + + System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); + ps.Streams.Error = _errors; + + ps.Commands.AddScript(script); + + ps.Invoke(null, output, null); + } + + /// + /// Issues an error when this.commandName was not found. + /// + private void IssueErrorForNoCommand() + { + InvalidOperationException errorException = new( + string.Format( + CultureInfo.CurrentUICulture, + FormatAndOut_out_gridview.CommandNotFound, + Name)); + this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, Name)); + } + + /// + /// Issues an error when there is more than one command matching this.commandName. + /// + private void IssueErrorForMoreThanOneCommand() + { + InvalidOperationException errorException = new( + string.Format( + CultureInfo.CurrentUICulture, + FormatAndOut_out_gridview.MoreThanOneCommand, + Name, + "Show-Command")); + this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, Name)); + } + + /// + /// Called from CommandProcessRecord to run the command that will get the CommandInfo and list of modules. + /// + /// Command to be retrieved. + /// List of loaded modules. + private void GetCommandInfoAndModules(out CommandInfo command, out Dictionary modules) + { + command = null; + modules = null; + string commandText = _showCommandProxy.GetShowCommandCommand(Name, true); + + Collection commandResults = this.InvokeCommand.InvokeScript(commandText); + + object[] commandObjects = (object[])commandResults[0].BaseObject; + object[] moduleObjects = (object[])commandResults[1].BaseObject; + if (commandResults == null || moduleObjects == null || commandObjects.Length == 0) + { + this.IssueErrorForNoCommand(); + return; + } + + if (commandObjects.Length > 1) + { + this.IssueErrorForMoreThanOneCommand(); + } + + command = ((PSObject)commandObjects[0]).BaseObject as CommandInfo; + if (command == null) + { + this.IssueErrorForNoCommand(); + return; + } + + if (command.CommandType == CommandTypes.Alias) + { + commandText = _showCommandProxy.GetShowCommandCommand(command.Definition, false); + commandResults = this.InvokeCommand.InvokeScript(commandText); + if (commandResults == null || commandResults.Count != 1) + { + this.IssueErrorForNoCommand(); + return; + } + + command = (CommandInfo)commandResults[0].BaseObject; + } + + modules = _showCommandProxy.GetImportedModulesDictionary(moduleObjects); + } + + /// + /// ProcessRecord when a command name is specified. + /// + /// True if there was no exception processing this record. + private bool CanProcessRecordForOneCommand() + { + CommandInfo commandInfo; + this.GetCommandInfoAndModules(out commandInfo, out _importedModules); + Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a terminating error/exception"); + + try + { + _commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.Contains('\\')); + _showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough); + } + catch (TargetInvocationException ti) + { + this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, Name)); + return false; + } + + return true; + } + + /// + /// ProcessRecord when a command name is not specified. + /// + /// True if there was no exception processing this record. + private bool CanProcessRecordForAllCommands() + { + Collection rawCommands = this.InvokeCommand.InvokeScript(_showCommandProxy.GetShowAllModulesCommand()); + + _commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); + _importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); + + try + { + _showCommandProxy.ShowAllModulesWindow(_importedModules, _commands, _noCommonParameter.ToBool(), _passThrough); + } + catch (TargetInvocationException ti) + { + this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, Name)); + return false; + } + + return true; + } + + /// + /// Waits until the window has been closed answering HelpNeeded events. + /// + private void WaitForWindowClosedOrHelpNeeded() + { + while (true) + { + int which = WaitHandle.WaitAny(new WaitHandle[] { _showCommandProxy.WindowClosed, _showCommandProxy.HelpNeeded, _showCommandProxy.ImportModuleNeeded }); + + if (which == 0) + { + break; + } + + if (which == 1) + { + Collection helpResults = this.InvokeCommand.InvokeScript(_showCommandProxy.GetHelpCommand(_showCommandProxy.CommandNeedingHelp)); + _showCommandProxy.DisplayHelp(helpResults); + continue; + } + + Diagnostics.Assert(which == 2, "which is 0,1 or 2 and 0 and 1 have been eliminated in the ifs above"); + string commandToRun = _showCommandProxy.GetImportModuleCommand(_showCommandProxy.ParentModuleNeedingImportModule); + Collection rawCommands; + try + { + rawCommands = this.InvokeCommand.InvokeScript(commandToRun); + } + catch (RuntimeException e) + { + _showCommandProxy.ImportModuleFailed(e); + continue; + } + + _commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); + _importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); + _showCommandProxy.ImportModuleDone(_importedModules, _commands); + continue; + } + } + + /// + /// Writes the output of a script being run into the pipeline. + /// + /// Output collection. + /// Output event. + private void Output_DataAdded(object sender, DataAddedEventArgs e) + { + this.WriteObject(((PSDataCollection)sender)[e.Index]); + } + + /// + /// Writes the errors of a script being run into the pipeline. + /// + /// Error collection. + /// Error event. + private void Error_DataAdded(object sender, DataAddedEventArgs e) + { + this.WriteError(((PSDataCollection)sender)[e.Index]); + } + + /// + /// Implements IDisposable logic. + /// + /// True if being called from Dispose. + private void Dispose(bool isDisposing) + { + if (isDisposing) + { + if (_errors != null) + { + _errors.Dispose(); + _errors = null; + } + } + } + #endregion + + /// + /// Wraps interop code for console input buffer. + /// + internal static class ConsoleInputWithNativeMethods + { + /// + /// Constant used in calls to GetStdHandle. + /// + internal const int STD_INPUT_HANDLE = -10; + + /// + /// Adds a string to the console input buffer. + /// + /// String to add to console input buffer. + /// True to add Enter after the string. + /// True if it was successful in adding all characters to console input buffer. + internal static bool AddToConsoleInputBuffer(string str, bool newLine) + { + IntPtr handle = ConsoleInputWithNativeMethods.GetStdHandle(ConsoleInputWithNativeMethods.STD_INPUT_HANDLE); + if (handle == IntPtr.Zero) + { + return false; + } + + uint strLen = (uint)str.Length; + + ConsoleInputWithNativeMethods.INPUT_RECORD[] records = new ConsoleInputWithNativeMethods.INPUT_RECORD[strLen + (newLine ? 1 : 0)]; + + for (int i = 0; i < strLen; i++) + { + ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref records[i], str[i]); + } + + uint written; + if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, records, strLen, out written) || written != strLen) + { + // I do not know of a case where written is not going to be strlen. Maybe for some character that + // is not supported in the console. The API suggests this can happen, + // so we handle it by returning false + return false; + } + + // Enter is written separately, because if this is a command, and one of the characters in the command was not written + // (written != strLen) it is desireable to fail (return false) before typing enter and running the command + if (newLine) + { + ConsoleInputWithNativeMethods.INPUT_RECORD[] enterArray = new ConsoleInputWithNativeMethods.INPUT_RECORD[1]; + ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref enterArray[0], (char)13); + + written = 0; + if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, enterArray, 1, out written)) + { + // I don't think this will happen + return false; + } + + Diagnostics.Assert(written == 1, "only Enter is being added and it is a supported character"); + } + + return true; + } + + /// + /// Gets the console handle. + /// + /// Which console handle to get. + /// The console handle. + [DllImport("kernel32.dll", SetLastError = true)] + internal static extern IntPtr GetStdHandle(int nStdHandle); + + /// + /// Writes to the console input buffer. + /// + /// Console handle. + /// Inputs to be written. + /// Number of inputs to be written. + /// Returned number of inputs actually written. + /// 0 if the function fails. + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool WriteConsoleInput( + IntPtr hConsoleInput, + INPUT_RECORD[] lpBuffer, + uint nLength, + out uint lpNumberOfEventsWritten); + + /// + /// A record to be added to the console buffer. + /// + internal struct INPUT_RECORD + { + /// + /// The proper event type for a KeyEvent KEY_EVENT_RECORD. + /// + internal const int KEY_EVENT = 0x0001; + + /// + /// Input buffer event type. + /// + internal ushort EventType; + + /// + /// The actual event. The original structure is a union of many others, but this is the largest of them. + /// And we don't need other kinds of events. + /// + internal KEY_EVENT_RECORD KeyEvent; + + /// + /// Sets the necessary fields of for a KeyDown event for the + /// + /// Input record to be set. + /// Character to set the record with. + internal static void SetInputRecord(ref INPUT_RECORD inputRecord, char character) + { + inputRecord.EventType = INPUT_RECORD.KEY_EVENT; + inputRecord.KeyEvent.bKeyDown = true; + inputRecord.KeyEvent.UnicodeChar = character; + } + } + + /// + /// Type of INPUT_RECORD which is a key. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct KEY_EVENT_RECORD + { + /// + /// True for key down and false for key up, but only needed if wVirtualKeyCode is used. + /// + internal bool bKeyDown; + + /// + /// Repeat count. + /// + internal ushort wRepeatCount; + + /// + /// Virtual key code. + /// + internal ushort wVirtualKeyCode; + + /// + /// Virtual key scan code. + /// + internal ushort wVirtualScanCode; + + /// + /// Character in input. If this is specified, wVirtualKeyCode, and others don't need to be. + /// + internal char UnicodeChar; + + /// + /// State of keys like Shift and control. + /// + internal uint dwControlKeyState; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..e2ba41fb3fc8d6414b82aee4e23c93337c45eba4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands.ShowCommandExtension +{ + /// + /// Implements a facade around CommandInfo and its deserialized counterpart. + /// + public class ShowCommandCommandInfo + { + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandCommandInfo(CommandInfo other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Name; + this.ModuleName = other.ModuleName; + this.CommandType = other.CommandType; + this.Definition = other.Definition; + + // In a runspace with restricted security settings we catch + // PSSecurityException when accessing ParameterSets because + // ExternalScript commands may be evaluated. + try + { + this.ParameterSets = + other.ParameterSets + .Select(static x => new ShowCommandParameterSetInfo(x)) + .ToList() + .AsReadOnly(); + } + catch (PSSecurityException) + { + // Since we can't access the parameter sets of this command, + // populate the ParameterSets property with an empty list + // so that consumers don't trip on a null value. + this.ParameterSets = new List().AsReadOnly(); + } + catch (ParseException) + { + // Could not parse the given command so don't continue initializing it + this.ParameterSets = new List().AsReadOnly(); + } + + if (other.Module != null) + { + this.Module = new ShowCommandModuleInfo(other.Module); + } + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandCommandInfo(PSObject other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Members["Name"].Value as string; + this.ModuleName = other.Members["ModuleName"].Value as string; + this.Definition = other.Members["Definition"].Value as string; + this.ParameterSets = other.Members["ParameterSets"].Value as ICollection; + if (this.ParameterSets != null) + { + // Simple case - the objects are still live because they came from in-proc. Just cast them back + this.CommandType = (CommandTypes)(other.Members["CommandType"].Value); + this.Module = other.Members["Module"].Value as ShowCommandModuleInfo; + } + else + { + // Objects came in their deserialized form - recreate the object graph + this.CommandType = (CommandTypes)((other.Members["CommandType"].Value as PSObject).BaseObject); + + var parameterSets = (other.Members["ParameterSets"].Value as PSObject).BaseObject as System.Collections.ArrayList; + this.ParameterSets = GetObjectEnumerable(parameterSets).Cast().Select(static x => new ShowCommandParameterSetInfo(x)).ToList().AsReadOnly(); + + if (other.Members["Module"]?.Value is PSObject) + { + this.Module = new ShowCommandModuleInfo(other.Members["Module"].Value as PSObject); + } + } + } + + /// + /// Builds a strongly typed IEnumerable{object} out of an IEnumerable. + /// + /// + /// The object to enumerate. + /// + internal static IEnumerable GetObjectEnumerable(System.Collections.IEnumerable enumerable) + { + foreach (object obj in enumerable) + { + yield return obj; + } + } + + /// + /// A string representing the definition of the command. + /// + public string Name { get; } + + /// + /// A string representing module the command belongs to. + /// + public string ModuleName { get; } + + /// + /// A reference to the module the command came from. + /// + public ShowCommandModuleInfo Module { get; } + + /// + /// An enumeration of the command types this command belongs to. + /// + public CommandTypes CommandType { get; } + + /// + /// A string representing the definition of the command. + /// + public string Definition { get; } + + /// + /// A string representing the definition of the command. + /// + public ICollection ParameterSets { get; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..f31bc93525d622e5d3f16a1cf774fd68b8f740fa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands.ShowCommandExtension +{ + /// + /// Implements a facade around PSModuleInfo and its deserialized counterpart. + /// + public class ShowCommandModuleInfo + { + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandModuleInfo(PSModuleInfo other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Name; + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandModuleInfo(PSObject other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Members["Name"].Value as string; + } + + /// + /// Gets the name of this module. + /// + public string Name { get; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..9bf79c5bd76cd2cff189f4597a909541e8446db0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands.ShowCommandExtension +{ + /// + /// Implements a facade around ShowCommandParameterInfo and its deserialized counterpart. + /// + public class ShowCommandParameterInfo + { + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandParameterInfo(CommandParameterInfo other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Name; + this.IsMandatory = other.IsMandatory; + this.ValueFromPipeline = other.ValueFromPipeline; + this.ParameterType = new ShowCommandParameterType(other.ParameterType); + this.Position = other.Position; + + var validateSetAttribute = other.Attributes.Where(static x => typeof(ValidateSetAttribute).IsAssignableFrom(x.GetType())).Cast().LastOrDefault(); + if (validateSetAttribute != null) + { + this.HasParameterSet = true; + this.ValidParamSetValues = validateSetAttribute.ValidValues; + } + } + + /// + /// Initializes a new instance of the class. + /// Creates an instance of the ShowCommandParameterInfo class based on a PSObject object. + /// + /// + /// The object to wrap. + /// + public ShowCommandParameterInfo(PSObject other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Members["Name"].Value as string; + this.IsMandatory = (bool)(other.Members["IsMandatory"].Value); + this.ValueFromPipeline = (bool)(other.Members["ValueFromPipeline"].Value); + this.HasParameterSet = (bool)(other.Members["HasParameterSet"].Value); + this.ParameterType = new ShowCommandParameterType(other.Members["ParameterType"].Value as PSObject); + this.Position = (int)(other.Members["Position"].Value); + if (this.HasParameterSet) + { + this.ValidParamSetValues = ShowCommandCommandInfo.GetObjectEnumerable((other.Members["ValidParamSetValues"].Value as PSObject).BaseObject as System.Collections.ArrayList).Cast().ToList(); + } + } + + /// + /// Gets the name of the parameter. + /// + public string Name { get; } + + /// + /// True if the parameter is dynamic, or false otherwise. + /// + public bool IsMandatory { get; } + + /// + /// Gets whether the parameter can take values from the incoming pipeline object. + /// + public bool ValueFromPipeline { get; } + + /// + /// Gets the type of the parameter. + /// + public ShowCommandParameterType ParameterType { get; } + + /// + /// The possible values of this parameter. + /// + public IList ValidParamSetValues { get; } + + /// + /// Gets whether the parameter has a parameter set. + /// + public bool HasParameterSet { get; } + + /// + /// Gets the position in which the parameter can be specified on the command line + /// if not named. If the returned value is int.MinValue then the parameter must be named. + /// + public int Position { get; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..c5ec1c74c089fc5337505a0c02899aafd03487ea --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands.ShowCommandExtension +{ + /// + /// Implements a facade around CommandParameterSetInfo and its deserialized counterpart. + /// + public class ShowCommandParameterSetInfo + { + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandParameterSetInfo(CommandParameterSetInfo other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Name; + this.IsDefault = other.IsDefault; + this.Parameters = other.Parameters.Select(static x => new ShowCommandParameterInfo(x)).ToArray(); + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandParameterSetInfo(PSObject other) + { + ArgumentNullException.ThrowIfNull(other); + + this.Name = other.Members["Name"].Value as string; + this.IsDefault = (bool)(other.Members["IsDefault"].Value); + var parameters = (other.Members["Parameters"].Value as PSObject).BaseObject as System.Collections.ArrayList; + this.Parameters = ShowCommandCommandInfo.GetObjectEnumerable(parameters).Cast().Select(static x => new ShowCommandParameterInfo(x)).ToArray(); + } + + /// + /// Gets the name of the parameter set. + /// + public string Name { get; } + + /// + /// Gets whether the parameter set is the default parameter set. + /// + public bool IsDefault { get; } + + /// + /// Gets the parameter information for the parameters in this parameter set. + /// + public ICollection Parameters { get; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs new file mode 100644 index 0000000000000000000000000000000000000000..01da285a1d709c175aa1892690dd51d01d0467f8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands.ShowCommandExtension +{ + /// + /// Implements a facade around ShowCommandParameterInfo and its deserialized counterpart. + /// + public class ShowCommandParameterType + { + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandParameterType(Type other) + { + ArgumentNullException.ThrowIfNull(other); + + this.FullName = other.FullName; + if (other.IsEnum) + { + this.EnumValues = new ArrayList(Enum.GetValues(other)); + } + + if (other.IsArray) + { + this.ElementType = new ShowCommandParameterType(other.GetElementType()); + } + + object[] attributes = other.GetCustomAttributes(typeof(FlagsAttribute), true); + this.HasFlagAttribute = attributes.Length != 0; + this.ImplementsDictionary = typeof(IDictionary).IsAssignableFrom(other); + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The object to wrap. + /// + public ShowCommandParameterType(PSObject other) + { + ArgumentNullException.ThrowIfNull(other); + + this.IsEnum = (bool)(other.Members["IsEnum"].Value); + this.FullName = other.Members["FullName"].Value as string; + this.IsArray = (bool)(other.Members["IsArray"].Value); + this.HasFlagAttribute = (bool)(other.Members["HasFlagAttribute"].Value); + this.ImplementsDictionary = (bool)(other.Members["ImplementsDictionary"].Value); + + if (this.IsArray) + { + this.ElementType = new ShowCommandParameterType(other.Members["ElementType"].Value as PSObject); + } + + if (this.IsEnum) + { + this.EnumValues = (other.Members["EnumValues"].Value as PSObject).BaseObject as ArrayList; + } + } + + /// + /// The full name of the outermost type. + /// + public string FullName { get; } + + /// + /// Whether or not this type is an enum. + /// + public bool IsEnum { get; } + + /// + /// Whether or not this type is an dictionary. + /// + public bool ImplementsDictionary { get; } + + /// + /// Whether or not this enum has a flag attribute. + /// + public bool HasFlagAttribute { get; } + + /// + /// Whether or not this type is an array type. + /// + public bool IsArray { get; } + + /// + /// Gets the inner type, if this corresponds to an array type. + /// + public ShowCommandParameterType ElementType { get; } + + /// + /// Whether or not this type is a string. + /// + public bool IsString + { + get + { + return string.Equals(this.FullName, "System.String", StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// Whether or not this type is an script block. + /// + public bool IsScriptBlock + { + get + { + return string.Equals(this.FullName, "System.Management.Automation.ScriptBlock", StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// Whether or not this type is a bool. + /// + public bool IsBoolean + { + get + { + return string.Equals(this.FullName, "System.Management.Automation.ScriptBlock", StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// Whether or not this type is a switch parameter. + /// + public bool IsSwitch + { + get + { + return string.Equals(this.FullName, "System.Management.Automation.SwitchParameter", StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// If this is an enum value, return the list of potential values. + /// + public ArrayList EnumValues { get; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..ab8909bb590bcef1ad5919481a2ae57ed8de64f0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Threading; + +using Microsoft.PowerShell.Commands.ShowCommandExtension; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Help show-command create WPF object and invoke WPF windows with the + /// Microsoft.PowerShell.Commands.ShowCommandInternal.ShowCommandHelperhelp type defined in Microsoft.PowerShell.GraphicalHost.dll. + /// + internal sealed class ShowCommandProxy + { + private const string ShowCommandHelperName = "Microsoft.PowerShell.Commands.ShowCommandInternal.ShowCommandHelper"; + + private readonly ShowCommandCommand _cmdlet; + + private readonly GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; + + internal ShowCommandProxy(ShowCommandCommand cmdlet) + { + _cmdlet = cmdlet; + _graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(cmdlet, ShowCommandProxy.ShowCommandHelperName); + } + + internal void ShowAllModulesWindow(Dictionary importedModules, IEnumerable commands, bool noCommonParameter, bool passThrough) + { + _graphicalHostReflectionWrapper.CallMethod("ShowAllModulesWindow", _cmdlet, importedModules, commands, noCommonParameter, _cmdlet.Width, _cmdlet.Height, passThrough); + } + + internal void ShowCommandWindow(object commandViewModelObj, bool passThrough) + { + _graphicalHostReflectionWrapper.CallMethod("ShowCommandWindow", _cmdlet, commandViewModelObj, _cmdlet.Width, _cmdlet.Height, passThrough); + } + + internal void CloseWindow() + { + _graphicalHostReflectionWrapper.CallMethod("CloseWindow"); + } + + internal string GetScript() + { + return (string)_graphicalHostReflectionWrapper.CallMethod("GetScript"); + } + + internal void ShowErrorString(string error) + { + _graphicalHostReflectionWrapper.CallMethod("ShowErrorString", error); + } + + internal bool SetPendingISECommand(string command) + { + return (bool)_graphicalHostReflectionWrapper.CallMethod("SetPendingISECommand", command); + } + + internal object GetCommandViewModel(ShowCommandCommandInfo command, bool noCommonParameter, Dictionary importedModules, bool moduleQualify) + { + return _graphicalHostReflectionWrapper.CallStaticMethod("GetCommandViewModel", command, noCommonParameter, importedModules, moduleQualify); + } + + internal string GetShowCommandCommand(string commandName, bool includeAliasAndModules) + { + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetShowCommandCommand", commandName, includeAliasAndModules); + } + + internal string GetShowAllModulesCommand() + { + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetShowAllModulesCommand", false, true); + } + + internal Dictionary GetImportedModulesDictionary(object[] moduleObjects) + { + return (Dictionary)_graphicalHostReflectionWrapper.CallStaticMethod("GetImportedModulesDictionary", new object[] { moduleObjects }); + } + + internal List GetCommandList(object[] commandObjects) + { + return (List)_graphicalHostReflectionWrapper.CallStaticMethod("GetCommandList", new object[] { commandObjects }); + } + + internal bool HasHostWindow + { + get + { + return (bool)_graphicalHostReflectionWrapper.GetPropertyValue("HasHostWindow"); + } + } + + internal AutoResetEvent WindowClosed + { + get + { + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("WindowClosed"); + } + } + + internal AutoResetEvent HelpNeeded + { + get + { + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("HelpNeeded"); + } + } + + internal AutoResetEvent ImportModuleNeeded + { + get + { + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("ImportModuleNeeded"); + } + } + + internal AutoResetEvent WindowLoaded + { + get + { + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("WindowLoaded"); + } + } + + internal string CommandNeedingHelp + { + get + { + return (string)_graphicalHostReflectionWrapper.GetPropertyValue("CommandNeedingHelp"); + } + } + + internal string ParentModuleNeedingImportModule + { + get + { + return (string)_graphicalHostReflectionWrapper.GetPropertyValue("ParentModuleNeedingImportModule"); + } + } + + internal void DisplayHelp(Collection helpResults) + { + _graphicalHostReflectionWrapper.CallMethod("DisplayHelp", helpResults); + } + + internal string GetImportModuleCommand(string module) + { + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetImportModuleCommand", module, false, true); + } + + internal string GetHelpCommand(string command) + { + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetHelpCommand", command); + } + + internal void ImportModuleDone(Dictionary importedModules, IEnumerable commands) + { + _graphicalHostReflectionWrapper.CallMethod("ImportModuleDone", importedModules, commands); + } + + internal void ImportModuleFailed(Exception reason) + { + _graphicalHostReflectionWrapper.CallMethod("ImportModuleFailed", reason); + } + + internal void ActivateWindow() + { + _graphicalHostReflectionWrapper.CallMethod("ActivateWindow"); + } + + internal double ScreenWidth + { + get + { + return (double)_graphicalHostReflectionWrapper.GetStaticPropertyValue("ScreenWidth"); + } + } + + internal double ScreenHeight + { + get + { + return (double)_graphicalHostReflectionWrapper.GetStaticPropertyValue("ScreenHeight"); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..3f40ec3439e79dd2bec4c7e3cccf1c322f3e6772 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -0,0 +1,230 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.MarkdownRender; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Show the VT100EncodedString or Html property of on console or show. + /// VT100EncodedString will be displayed on console. + /// Html will be displayed in default browser. + /// + [Cmdlet( + VerbsCommon.Show, "Markdown", + DefaultParameterSetName = "Path", + HelpUri = "https://go.microsoft.com/fwlink/?linkid=2102329")] + [OutputType(typeof(string))] + public class ShowMarkdownCommand : PSCmdlet + { + /// + /// Gets or sets InputObject of type Microsoft.PowerShell.MarkdownRender.MarkdownInfo to display. + /// + [ValidateNotNullOrEmpty] + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "InputObject")] + public PSObject InputObject { get; set; } + + /// + /// Gets or sets path to markdown file(s) to display. + /// + [ValidateNotNullOrEmpty] + [Parameter(Position = 0, Mandatory = true, + ValueFromPipelineByPropertyName = true, ParameterSetName = "Path")] + public string[] Path { get; set; } + + /// + /// Gets or sets the literal path parameter to markdown files(s) to display. + /// + [Parameter(ParameterSetName = "LiteralPath", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get { return Path; } + + set { Path = value; } + } + + /// + /// Gets or sets the switch to view Html in default browser. + /// + [Parameter] + public SwitchParameter UseBrowser { get; set; } + + private System.Management.Automation.PowerShell _powerShell; + + /// + /// Override BeginProcessing. + /// + protected override void BeginProcessing() + { + _powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); + } + + /// + /// Override ProcessRecord. + /// + protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case "InputObject": + if (InputObject.BaseObject is MarkdownInfo markdownInfo) + { + ProcessMarkdownInfo(markdownInfo); + } + else + { + ConvertFromMarkdown("InputObject", InputObject.BaseObject); + } + + break; + + case "Path": + case "LiteralPath": + ConvertFromMarkdown(ParameterSetName, Path); + break; + + default: + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ConvertMarkdownStrings.InvalidParameterSet, ParameterSetName)); + } + } + + /// + /// Process markdown as path. + /// + /// Name of parameter to pass to `ConvertFrom-Markdown`. + /// Value of parameter. + private void ConvertFromMarkdown(string parameter, object input) + { + _powerShell.AddCommand("Microsoft.PowerShell.Utility\\ConvertFrom-Markdown").AddParameter(parameter, input); + if (!UseBrowser) + { + _powerShell.AddParameter("AsVT100EncodedString"); + } + + Collection output = _powerShell.Invoke(); + + if (_powerShell.HadErrors) + { + foreach (ErrorRecord errorRecord in _powerShell.Streams.Error) + { + WriteError(errorRecord); + } + } + + foreach (MarkdownInfo result in output) + { + ProcessMarkdownInfo(result); + } + } + + /// + /// Process markdown as input objects. + /// + /// Markdown object to process. + private void ProcessMarkdownInfo(MarkdownInfo markdownInfo) + { + if (UseBrowser) + { + var html = markdownInfo.Html; + + if (!string.IsNullOrEmpty(html)) + { + string tmpFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + ".html"); + + try + { + using (var writer = new StreamWriter(new FileStream(tmpFilePath, FileMode.Create, FileAccess.Write, FileShare.Write))) + { + writer.Write(html); + } + } + catch (Exception e) + { + var errorRecord = new ErrorRecord( + e, + "ErrorWritingTempFile", + ErrorCategory.WriteError, + tmpFilePath); + + WriteError(errorRecord); + return; + } + + if (InternalTestHooks.ShowMarkdownOutputBypass) + { + WriteObject(html); + return; + } + + try + { + ProcessStartInfo startInfo = new(); + startInfo.FileName = tmpFilePath; + startInfo.UseShellExecute = true; + Process.Start(startInfo); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord( + e, + "ErrorLaunchingDefaultApplication", + ErrorCategory.InvalidOperation, + targetObject: null); + + WriteError(errorRecord); + return; + } + } + else + { + string errorMessage = StringUtil.Format(ConvertMarkdownStrings.MarkdownInfoInvalid, "Html"); + var errorRecord = new ErrorRecord( + new InvalidDataException(errorMessage), + "HtmlIsNullOrEmpty", + ErrorCategory.InvalidData, + html); + + WriteError(errorRecord); + } + } + else + { + var vt100String = markdownInfo.VT100EncodedString; + + if (!string.IsNullOrEmpty(vt100String)) + { + WriteObject(vt100String); + } + else + { + string errorMessage = StringUtil.Format(ConvertMarkdownStrings.MarkdownInfoInvalid, "VT100EncodedString"); + var errorRecord = new ErrorRecord( + new InvalidDataException(errorMessage), + "VT100EncodedStringIsNullOrEmpty", + ErrorCategory.InvalidData, + vt100String); + + WriteError(errorRecord); + } + } + } + + /// + /// Override EndProcessing. + /// + protected override void EndProcessing() + { + _powerShell?.Dispose(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..365a669c1861e750c5b7c088d77e417accd9f71b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs @@ -0,0 +1,274 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// + [Cmdlet("Sort", + "Object", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097038", + DefaultParameterSetName = "Default", + RemotingCapability = RemotingCapability.None)] + public sealed class SortObjectCommand : OrderObjectBase + { + #region Command Line Switches + + /// + /// Gets or sets a value indicating whether a stable sort is required. + /// + /// + /// + /// Items that are duplicates according to the sort algorithm will appear + /// in the same relative order in a stable sort. + /// + [Parameter(ParameterSetName = "Default")] + public SwitchParameter Stable { get; set; } + + /// + /// Gets or sets a value indicating whether the sort order is descending. + /// + [Parameter] + public SwitchParameter Descending + { + get { return DescendingOrder; } + + set { DescendingOrder = value; } + } + + /// + /// Gets or sets a value indicating whether the sort filters out any duplicate objects. + /// + /// + [Parameter] + public SwitchParameter Unique { get; set; } + + #endregion + + /// + /// Gets or sets the number of items to return in a Top N sort. + /// + [Parameter(ParameterSetName = "Top", Mandatory = true)] + [ValidateRange(1, int.MaxValue)] + public int Top { get; set; } + + /// + /// Gets or sets the number of items to return in a Bottom N sort. + /// + [Parameter(ParameterSetName = "Bottom", Mandatory = true)] + [ValidateRange(1, int.MaxValue)] + public int Bottom { get; set; } + + /// + /// Moves unique entries to the front of the list. + /// + private int MoveUniqueEntriesToFront(List sortedData, OrderByPropertyComparer comparer) + { + // If we have sorted data then we know we have at least one unique item + int uniqueCount = sortedData.Count > 0 ? 1 : 0; + + // Move the first of each unique entry to the front of the list + for (int uniqueItemIndex = 0, nextUniqueItemIndex = 1; uniqueItemIndex < sortedData.Count && uniqueCount != Top; uniqueItemIndex++, nextUniqueItemIndex++) + { + // Identify the index of the next unique item + while (nextUniqueItemIndex < sortedData.Count && comparer.Compare(sortedData[uniqueItemIndex], sortedData[nextUniqueItemIndex]) == 0) + { + nextUniqueItemIndex++; + } + + // If there are no more unique items, break + if (nextUniqueItemIndex == sortedData.Count) + { + break; + } + + // Move the next unique item forward and increment the unique item counter + sortedData[uniqueItemIndex + 1] = sortedData[nextUniqueItemIndex]; + uniqueCount++; + } + + return uniqueCount; + } + + /// + /// Sort unsorted OrderByPropertyEntry data using a full sort. + /// + private int FullSort(List dataToSort, OrderByPropertyComparer comparer) + { + // Track how many items in the list are sorted + int sortedItemCount = dataToSort.Count; + + // Future: It may be worth comparing List.Sort with SortedSet when handling unique + // records in case SortedSet is faster (SortedSet was not an option in earlier + // versions of PowerShell). + dataToSort.Sort(comparer); + + if (Unique) + { + // Move unique entries to the front of the list (this is significantly faster + // than removing them) + sortedItemCount = MoveUniqueEntriesToFront(dataToSort, comparer); + } + + return sortedItemCount; + } + + /// + /// Sort unsorted OrderByPropertyEntry data using an indexed min-/max-heap sort. + /// + private int Heapify(List dataToSort, OrderByPropertyComparer orderByPropertyComparer) + { + // Instantiate the Heapify comparer, which takes index into account for sort stability + var comparer = new IndexedOrderByPropertyComparer(orderByPropertyComparer); + + // Identify how many items will be in the heap and the current number of items + int heapCount = 0; + int heapCapacity = Stable ? int.MaxValue + : Top > 0 ? Top : Bottom; + + // Identify the comparator (the value all comparisons will be made against based on whether we're + // doing a Top N or Bottom N sort) + // Note: All comparison results in the loop below are performed related to the value of the + // comparator. OrderByPropertyComparer.Compare will return -1 to indicate that the lhs is smaller + // if an ascending sort is being executed, or -1 to indicate that the lhs is larger if a descending + // sort is being executed. The comparator will be -1 if we're executing a Top N sort, or 1 if we're + // executing a Bottom N sort. These two pairs of states allow us to perform the proper comparison + // regardless of whether we're executing an ascending or descending Top N or Bottom N sort. This + // allows us to build a min-heap or max-heap for each of these sorts with the exact same logic. + // Min-heap: used for faster processing of a top N descending sort and a bottom N ascending sort + // Max-heap: used for faster processing of a top N ascending sort and a bottom N descending sort + int comparator = Top > 0 ? -1 : 1; + + // For unique sorts, use a sorted set to avoid adding unique items to the heap + SortedSet uniqueSet = Unique ? new SortedSet(orderByPropertyComparer) : null; + + // Tracking the index is necessary so that unsortable items can be output at the end, in the order + // in which they were received. + for (int dataIndex = 0, discardedDuplicates = 0; dataIndex + discardedDuplicates < dataToSort.Count; dataIndex++) + { + // Min-heap: if the heap is full and the root item is larger than the entry, discard the entry + // Max-heap: if the heap is full and the root item is smaller than the entry, discard the entry + if (heapCount == heapCapacity && comparer.Compare(dataToSort[0], dataToSort[dataIndex]) == comparator) + { + continue; + } + + // If we're doing a unique sort and the entry is not unique, discard the duplicate entry + if (Unique && !uniqueSet.Add(dataToSort[dataIndex + discardedDuplicates])) + { + discardedDuplicates++; + dataIndex--; + continue; + } + + // Shift next non-duplicate entry into place + if (discardedDuplicates > 0) + { + dataToSort[dataIndex] = dataToSort[dataIndex + discardedDuplicates]; + } + + // Add the current item to the heap and bubble it up into the correct position + int childIndex = dataIndex; + while (childIndex > 0) + { + int parentIndex = ((childIndex > (heapCapacity - 1) ? heapCapacity : childIndex) - 1) >> 1; + + // Min-heap: if the child item is larger than its parent, break + // Max-heap: if the child item is smaller than its parent, break + if (comparer.Compare(dataToSort[childIndex], dataToSort[parentIndex]) == comparator) + { + break; + } + + var temp = dataToSort[parentIndex]; + dataToSort[parentIndex] = dataToSort[childIndex]; + dataToSort[childIndex] = temp; + + childIndex = parentIndex; + } + + heapCount++; + + // If the heap size is too large, remove the root and rearrange the heap + if (heapCount > heapCapacity) + { + // Move the last item to the root and reset the heap count (this effectively removes the last item) + dataToSort[0] = dataToSort[dataIndex]; + heapCount = heapCapacity; + + // Bubble the root item down into the correct position + int parentIndex = 0; + int parentItemCount = heapCapacity >> 1; + while (parentIndex < parentItemCount) + { + // Min-heap: use the smaller of the two children in the comparison + // Max-heap: use the larger of the two children in the comparison + int leftChildIndex = (parentIndex << 1) + 1; + int rightChildIndex = leftChildIndex + 1; + childIndex = rightChildIndex == heapCapacity || comparer.Compare(dataToSort[leftChildIndex], dataToSort[rightChildIndex]) != comparator + ? leftChildIndex + : rightChildIndex; + + // Min-heap: if the smallest child is larger than or equal to its parent, break + // Max-heap: if the largest child is smaller than or equal to its parent, break + int childComparisonResult = comparer.Compare(dataToSort[childIndex], dataToSort[parentIndex]); + if (childComparisonResult == 0 || childComparisonResult == comparator) + { + break; + } + + var temp = dataToSort[childIndex]; + dataToSort[childIndex] = dataToSort[parentIndex]; + dataToSort[parentIndex] = temp; + + parentIndex = childIndex; + } + } + } + + dataToSort.Sort(0, heapCount, comparer); + + return heapCount; + } + + /// + /// + protected override void EndProcessing() + { + OrderByProperty orderByProperty = new( + this, InputObjects, Property, !Descending, ConvertedCulture, CaseSensitive); + + var dataToProcess = orderByProperty.OrderMatrix; + var comparer = orderByProperty.Comparer; + if (comparer == null || dataToProcess == null || dataToProcess.Count == 0) + { + return; + } + + // Track the number of items that will be output from the data once it is sorted + int sortedItemCount = dataToProcess.Count; + + // If -Stable, -Top & -Bottom were not used, invoke an in-place full sort + if (!Stable && Top == 0 && Bottom == 0) + { + sortedItemCount = FullSort(dataToProcess, comparer); + } + // Otherwise, use an indexed min-/max-heap to perform an in-place heap sort (heap + // sorts are inheritantly stable, meaning they will preserve the respective order + // of duplicate objects as they are sorted on the heap) + else + { + sortedItemCount = Heapify(dataToProcess, comparer); + } + + // Write out the portion of the processed data that was sorted + for (int index = 0; index < sortedItemCount; index++) + { + WriteObject(dataToProcess[index].inputObject); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..839a0b7c051e921d827e95ab9763e534dbe6ed09 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Threading; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Suspend shell, script, or runspace activity for the specified period of time. + /// + [Cmdlet(VerbsLifecycle.Start, "Sleep", DefaultParameterSetName = "Seconds", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097041")] + public sealed class StartSleepCommand : PSCmdlet, IDisposable + { + private bool _disposed = false; + + #region IDisposable + /// + /// Dispose method of IDisposable interface. + /// + public void Dispose() + { + if (!_disposed) + { + if (_waitHandle != null) + { + _waitHandle.Dispose(); + _waitHandle = null; + } + + _disposed = true; + } + } + + #endregion + + #region parameters + + /// + /// Allows sleep time to be specified in seconds. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Seconds", ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateRange(0.0, (double)(int.MaxValue / 1000))] + public double Seconds { get; set; } + + /// + /// Allows sleep time to be specified in milliseconds. + /// + [Parameter(Mandatory = true, ParameterSetName = "Milliseconds", ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, int.MaxValue)] + [Alias("ms")] + public int Milliseconds { get; set; } + + /// + /// Allows sleep time to be specified as a TimeSpan. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "FromTimeSpan", ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateRange(ValidateRangeKind.NonNegative)] + [Alias("ts")] + public TimeSpan Duration { get; set; } + + #endregion + + #region methods + + // Wait handle which is used by thread to sleep. + private ManualResetEvent _waitHandle; + + // object used for synchronizes pipeline thread and stop thread + // access to waitHandle + private readonly object _syncObject = new(); + + // this is set to true by stopProcessing + private bool _stopping = false; + + /// + /// This method causes calling thread to sleep for specified milliseconds. + /// + private void Sleep(int milliSecondsToSleep) + { + lock (_syncObject) + { + if (!_stopping) + { + _waitHandle = new ManualResetEvent(false); + } + } + + _waitHandle?.WaitOne(milliSecondsToSleep, true); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + int sleepTime = 0; + + switch (ParameterSetName) + { + case "Seconds": + sleepTime = (int)(Seconds * 1000); + break; + + case "Milliseconds": + sleepTime = Milliseconds; + break; + + case "FromTimeSpan": + if (Duration.TotalMilliseconds > int.MaxValue) + { + PSArgumentException argumentException = PSTraceSource.NewArgumentException( + nameof(Duration), + StartSleepStrings.MaximumDurationExceeded, + TimeSpan.FromMilliseconds(int.MaxValue), + Duration); + + ThrowTerminatingError( + new ErrorRecord( + argumentException, + "MaximumDurationExceeded", + ErrorCategory.InvalidArgument, + targetObject: null)); + } + + sleepTime = (int)Math.Floor(Duration.TotalMilliseconds); + break; + + default: + Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); + break; + } + + Sleep(sleepTime); + } + + /// + /// StopProcessing override. + /// + protected override void StopProcessing() + { + lock (_syncObject) + { + _stopping = true; + _waitHandle?.Set(); + } + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..4a0f48312995c8a78969b6785da7cc9950ceeb91 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Text; + +using Microsoft.PowerShell.Commands.Internal.Format; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Class for Tee-object implementation. + /// + [Cmdlet("Tee", "Object", DefaultParameterSetName = "File", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097034")] + public sealed class TeeObjectCommand : PSCmdlet, IDisposable + { + /// + /// Object to process. + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject + { + get { return _inputObject; } + + set { _inputObject = value; } + } + + private PSObject _inputObject; + + /// + /// FilePath parameter. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "File")] + [Alias("Path")] + public string FilePath + { + get { return _fileName; } + + set { _fileName = value; } + } + + private string _fileName; + + /// + /// Literal FilePath parameter. + /// + [Parameter(Mandatory = true, ParameterSetName = "LiteralFile")] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _fileName; + } + + set + { + _fileName = value; + } + } + + /// + /// Append switch. + /// + [Parameter(ParameterSetName = "File")] + public SwitchParameter Append + { + get { return _append; } + + set { _append = value; } + } + + private bool _append; + + /// + /// Gets or sets the Encoding. + /// + [Parameter(ParameterSetName = "File")] + [Parameter(ParameterSetName = "LiteralFile")] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding { get; set; } = Encoding.Default; + + /// + /// Variable parameter. + /// + [Parameter(Mandatory = true, ParameterSetName = "Variable")] + public string Variable + { + get { return _variable; } + + set { _variable = value; } + } + + private string _variable; + + /// + /// + protected override void BeginProcessing() + { + _commandWrapper = new CommandWrapper(); + if (string.Equals(ParameterSetName, "File", StringComparison.OrdinalIgnoreCase)) + { + _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); + _commandWrapper.AddNamedParameter("filepath", _fileName); + _commandWrapper.AddNamedParameter("append", _append); + _commandWrapper.AddNamedParameter("encoding", Encoding); + } + else if (string.Equals(ParameterSetName, "LiteralFile", StringComparison.OrdinalIgnoreCase)) + { + _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); + _commandWrapper.AddNamedParameter("LiteralPath", _fileName); + _commandWrapper.AddNamedParameter("append", _append); + _commandWrapper.AddNamedParameter("encoding", Encoding); + } + else + { + // variable parameter set + _commandWrapper.Initialize(Context, "set-variable", typeof(SetVariableCommand)); + _commandWrapper.AddNamedParameter("name", _variable); + // Can't use set-var's passthru because it writes the var object to the pipeline, we want just + // the values to be written + } + } + + /// + /// + protected override void ProcessRecord() + { + _commandWrapper.Process(_inputObject); + WriteObject(_inputObject); + } + + /// + /// + protected override void EndProcessing() + { + _commandWrapper.ShutDown(); + } + + /// + /// Release all resources. + /// + public void Dispose() + { + if (!_alreadyDisposed) + { + _alreadyDisposed = true; + if (_commandWrapper != null) + { + _commandWrapper.Dispose(); + _commandWrapper = null; + } + } + } + + #region private + private CommandWrapper _commandWrapper; + private bool _alreadyDisposed; + #endregion private + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..909cbff3c8f254ccce97e96252a3bbad91042aea --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Net.Http; +using System.Security; +using System.Text.Json; +using System.Text.Json.Nodes; +using Json.Schema; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements Test-Json command. + /// + [Cmdlet(VerbsDiagnostic.Test, "Json", DefaultParameterSetName = JsonStringParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096609")] + [OutputType(typeof(bool))] + public class TestJsonCommand : PSCmdlet + { + #region Parameter Set Names + + private const string JsonStringParameterSet = "JsonString"; + private const string JsonStringWithSchemaStringParameterSet = "JsonStringWithSchemaString"; + private const string JsonStringWithSchemaFileParameterSet = "JsonStringWithSchemaFile"; + private const string JsonPathParameterSet = "JsonPath"; + private const string JsonPathWithSchemaStringParameterSet = "JsonPathWithSchemaString"; + private const string JsonPathWithSchemaFileParameterSet = "JsonPathWithSchemaFile"; + private const string JsonLiteralPathParameterSet = "JsonLiteralPath"; + private const string JsonLiteralPathWithSchemaStringParameterSet = "JsonLiteralPathWithSchemaString"; + private const string JsonLiteralPathWithSchemaFileParameterSet = "JsonLiteralPathWithSchemaFile"; + + #endregion + + #region Json Document Option Constants + + private const string IgnoreCommentsOption = "IgnoreComments"; + private const string AllowTrailingCommasOption = "AllowTrailingCommas"; + + #endregion + + #region Parameters + + /// + /// Gets or sets JSON string to be validated. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = JsonStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = JsonStringWithSchemaStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = JsonStringWithSchemaFileParameterSet)] + public string Json { get; set; } + + /// + /// Gets or sets JSON file path to be validated. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonPathParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonPathWithSchemaStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonPathWithSchemaFileParameterSet)] + public string Path { get; set; } + + /// + /// Gets or sets JSON literal file path to be validated. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonLiteralPathParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonLiteralPathWithSchemaStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonLiteralPathWithSchemaFileParameterSet)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _isLiteralPath ? Path : null; + } + + set + { + _isLiteralPath = true; + Path = value; + } + } + + /// + /// Gets or sets schema to validate the JSON against. + /// This is optional parameter. + /// If the parameter is absent the cmdlet only attempts to parse the JSON string. + /// If the parameter present the cmdlet attempts to parse the JSON string and + /// then validates the JSON against the schema. Before testing the JSON string, + /// the cmdlet parses the schema doing implicitly check the schema too. + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonStringWithSchemaStringParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonPathWithSchemaStringParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonLiteralPathWithSchemaStringParameterSet)] + [ValidateNotNullOrEmpty] + public string Schema { get; set; } + + /// + /// Gets or sets path to the file containing schema to validate the JSON string against. + /// This is optional parameter. + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonStringWithSchemaFileParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonPathWithSchemaFileParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonLiteralPathWithSchemaFileParameterSet)] + [ValidateNotNullOrEmpty] + public string SchemaFile { get; set; } + + /// + /// Gets or sets JSON document options. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [ValidateSet(IgnoreCommentsOption, AllowTrailingCommasOption)] + public string[] Options { get; set; } = Array.Empty(); + + #endregion + + #region Private Members + + private bool _isLiteralPath = false; + private JsonSchema _jschema; + private JsonDocumentOptions _documentOptions; + + #endregion + + /// + /// Prepare a JSON schema. + /// + protected override void BeginProcessing() + { + // By default, a JSON Schema implementation isn't supposed to automatically fetch content. + // Instead JsonSchema.Net has been set up with a registry so that users can pre-register + // any schemas they may need to resolve. + // However, pre-registering schemas doesn't make sense in the context of a Powershell command, + // and automatically fetching referenced URIs is likely the preferred behavior. To do that, + // this property must be set with a method to retrieve and deserialize the content. + // For more information, see https://json-everything.net/json-schema#automatic-resolution + SchemaRegistry.Global.Fetch = static uri => + { + try + { + string text; + switch (uri.Scheme) + { + case "http": + case "https": + { + using var client = new HttpClient(); + text = client.GetStringAsync(uri).Result; + break; + } + case "file": + var filename = Uri.UnescapeDataString(uri.AbsolutePath); + text = File.ReadAllText(filename); + break; + default: + throw new FormatException(string.Format(TestJsonCmdletStrings.InvalidUriScheme, uri.Scheme)); + } + + return JsonSerializer.Deserialize(text); + } + catch (Exception e) + { + throw new JsonSchemaReferenceResolutionException(e); + } + }; + + string resolvedpath = string.Empty; + + try + { + if (Schema != null) + { + try + { + _jschema = JsonSchema.FromText(Schema); + } + catch (JsonException e) + { + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, Schema)); + } + } + else if (SchemaFile != null) + { + try + { + resolvedpath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(SchemaFile); + _jschema = JsonSchema.FromFile(resolvedpath); + } + catch (JsonException e) + { + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, SchemaFile)); + } + } + } + catch (Exception e) when ( + // Handle exceptions related to file access to provide more specific error message + // https://learn.microsoft.com/dotnet/standard/io/handling-io-errors + e is IOException || + e is UnauthorizedAccessException || + e is NotSupportedException || + e is SecurityException + ) + { + Exception exception = new( + string.Format( + CultureInfo.CurrentUICulture, + TestJsonCmdletStrings.JsonSchemaFileOpenFailure, + resolvedpath), + e); + ThrowTerminatingError(new ErrorRecord(exception, "JsonSchemaFileOpenFailure", ErrorCategory.OpenError, resolvedpath)); + } + catch (Exception e) + { + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); + ThrowTerminatingError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, resolvedpath)); + } + + _documentOptions = new JsonDocumentOptions + { + CommentHandling = Options.Contains(IgnoreCommentsOption, StringComparer.OrdinalIgnoreCase) + ? JsonCommentHandling.Skip + : JsonCommentHandling.Disallow, + AllowTrailingCommas = Options.Contains(AllowTrailingCommasOption, StringComparer.OrdinalIgnoreCase) + }; + } + + /// + /// Validate a JSON. + /// + protected override void ProcessRecord() + { + bool result = true; + + string jsonToParse = string.Empty; + + if (Json != null) + { + jsonToParse = Json; + } + else if (Path != null) + { + string resolvedPath = PathUtils.ResolveFilePath(Path, this, _isLiteralPath); + + if (!File.Exists(resolvedPath)) + { + ItemNotFoundException exception = new( + Path, + "PathNotFound", + SessionStateStrings.PathNotFound); + + ThrowTerminatingError(exception.ErrorRecord); + } + + jsonToParse = File.ReadAllText(resolvedPath); + } + + try + { + + var parsedJson = JsonNode.Parse(jsonToParse, nodeOptions: null, _documentOptions); + + if (_jschema != null) + { + EvaluationResults evaluationResults = _jschema.Evaluate(parsedJson, new EvaluationOptions { OutputFormat = OutputFormat.Hierarchical }); + result = evaluationResults.IsValid; + if (!result) + { + ReportValidationErrors(evaluationResults); + } + } + } + catch (JsonSchemaReferenceResolutionException jsonExc) + { + result = false; + + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, jsonExc); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, _jschema)); + } + catch (Exception exc) + { + result = false; + + Exception exception = new(TestJsonCmdletStrings.InvalidJson, exc); + WriteError(new ErrorRecord(exception, "InvalidJson", ErrorCategory.InvalidData, Json)); + } + + WriteObject(result); + } + + /// + /// Recursively reports validation errors from hierarchical evaluation results. + /// Skips nodes (and their children) where IsValid is true to avoid false positives + /// from constructs like OneOf or AnyOf. + /// + /// The evaluation result to process. + private void ReportValidationErrors(EvaluationResults evaluationResult) + { + // Skip this node and all children if validation passed + if (evaluationResult.IsValid) + { + return; + } + + // Report errors at this level + HandleValidationErrors(evaluationResult); + + // Recursively process child results + if (evaluationResult.HasDetails) + { + foreach (var nestedResult in evaluationResult.Details) + { + ReportValidationErrors(nestedResult); + } + } + } + + private void HandleValidationErrors(EvaluationResults evaluationResult) + { + if (!evaluationResult.HasErrors) + { + return; + } + + foreach (var error in evaluationResult.Errors!) + { + Exception exception = new(string.Format(TestJsonCmdletStrings.InvalidJsonAgainstSchemaDetailed, error.Value, evaluationResult.InstanceLocation)); + ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchemaDetailed", ErrorCategory.InvalidData, null); + WriteError(errorRecord); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..24ed81995d1295799b31bc26a4896b10f9ae855e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; + +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implements a cmdlet that applies a script block + /// to each element of the pipeline. + /// + [Cmdlet(VerbsDiagnostic.Measure, "Command", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097029", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(TimeSpan))] + public sealed class MeasureCommandCommand : PSCmdlet + { + #region parameters + + /// + /// This parameter specifies the current pipeline object. + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// The script block to apply. + /// + [Parameter(Position = 0, Mandatory = true)] + public ScriptBlock Expression { get; set; } + + #endregion + + #region private members + + private readonly System.Diagnostics.Stopwatch _stopWatch = new(); + + #endregion + + #region methods + + /// + /// Output the timer. + /// + protected override void EndProcessing() + { + WriteObject(_stopWatch.Elapsed); + } + + /// + /// Execute the script block passing in the current pipeline object as it's only parameter. + /// + protected override void ProcessRecord() + { + // Only accumulate the time used by this scriptblock... + // As results are discarded, write directly to a null pipe instead of accumulating. + _stopWatch.Start(); + Expression.InvokeWithPipe( + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: InputObject, // $_ + input: Array.Empty(), // $input + scriptThis: AutomationNull.Value, + outputPipe: new Pipe { NullPipe = true }, + invocationInfo: null); + + _stopWatch.Stop(); + } + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs new file mode 100644 index 0000000000000000000000000000000000000000..6633a66f96f4278e70e314d85530b89505c7d87e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -0,0 +1,230 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +#if UNIX +using System.Globalization; +using System.Management.Automation; +using System.Runtime.InteropServices; +#else +using System.Management.Automation; +using System.Management.Automation.Internal; +#endif + +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// Removes the Zone.Identifier stream from a file. + [Cmdlet(VerbsSecurity.Unblock, "File", DefaultParameterSetName = "ByPath", SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097033")] + public sealed class UnblockFileCommand : PSCmdlet + { +#if UNIX + private const string MacBlockAttribute = "com.apple.quarantine"; + private const int RemovexattrFollowSymLink = 0; +#endif + + /// + /// The path of the file to unblock. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Path + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + /// + /// The literal path of the file to unblock. + /// + [Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = true)] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return _paths; + } + + set + { + _paths = value; + } + } + + private string[] _paths; + + /// + /// Generate the type(s) + /// + protected override void ProcessRecord() + { + List pathsToProcess = new(); + ProviderInfo provider = null; + + if (string.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase)) + { + foreach (string path in _paths) + { + string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); + + if (IsValidFileForUnblocking(newPath)) + { + pathsToProcess.Add(newPath); + } + } + } + else + { + // Resolve paths + foreach (string path in _paths) + { + try + { + Collection newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); + + foreach (string currentFilepath in newPaths) + { + if (IsValidFileForUnblocking(currentFilepath)) + { + pathsToProcess.Add(currentFilepath); + } + } + } + catch (ItemNotFoundException e) + { + if (!WildcardPattern.ContainsWildcardCharacters(path)) + { + ErrorRecord errorRecord = new(e, + "FileNotFound", + ErrorCategory.ObjectNotFound, + path); + WriteError(errorRecord); + } + } + } + } +#if !UNIX + + // Unblock files + foreach (string path in pathsToProcess) + { + if (ShouldProcess(path)) + { + try + { + AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier"); + } + catch (Exception e) + { + WriteError(new ErrorRecord(exception: e, errorId: "RemoveItemUnableToAccessFile", ErrorCategory.ResourceUnavailable, targetObject: path)); + } + } + } +#else + if (Platform.IsLinux) + { + string errorMessage = UnblockFileStrings.LinuxNotSupported; + Exception e = new PlatformNotSupportedException(errorMessage); + ThrowTerminatingError(new ErrorRecord(exception: e, errorId: "LinuxNotSupported", ErrorCategory.NotImplemented, targetObject: null)); + return; + } + + foreach (string path in pathsToProcess) + { + if (IsBlocked(path)) + { + UInt32 result = RemoveXattr(path, MacBlockAttribute, RemovexattrFollowSymLink); + if (result != 0) + { + string errorMessage = string.Format(CultureInfo.CurrentUICulture, UnblockFileStrings.UnblockError, path); + Exception e = new InvalidOperationException(errorMessage); + WriteError(new ErrorRecord(exception: e, errorId: "UnblockError", ErrorCategory.InvalidResult, targetObject: path)); + } + } + } + +#endif + } + + /// + /// IsValidFileForUnblocking is a helper method used to validate if + /// the supplied file path has to be considered for unblocking. + /// + /// File or directory path. + /// True is the supplied path is a + /// valid file path or else false is returned. + /// If the supplied path is a directory path then false is returned. + private bool IsValidFileForUnblocking(string resolvedpath) + { + bool isValidUnblockableFile = false; + + // Bug 501423 : silently ignore folders given that folders cannot have + // alternate data streams attached to them (i.e. they're already unblocked). + if (!System.IO.Directory.Exists(resolvedpath)) + { + if (!System.IO.File.Exists(resolvedpath)) + { + ErrorRecord errorRecord = new( + new System.IO.FileNotFoundException(resolvedpath), + "FileNotFound", + ErrorCategory.ObjectNotFound, + resolvedpath); + WriteError(errorRecord); + } + else + { + isValidUnblockableFile = true; + } + } + + return isValidUnblockableFile; + } + +#if UNIX + private static bool IsBlocked(string path) + { + const uint valueSize = 1024; + IntPtr value = Marshal.AllocHGlobal((int)valueSize); + try + { + var resultSize = GetXattr(path, MacBlockAttribute, value, valueSize, 0, RemovexattrFollowSymLink); + return resultSize != -1; + } + finally + { + Marshal.FreeHGlobal(value); + } + } + + // Ansi means UTF8 on Unix + // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/RemoveXattr.2.html + [DllImport("libc", SetLastError = true, EntryPoint = "removexattr", CharSet = CharSet.Ansi)] + private static extern UInt32 RemoveXattr(string path, string name, int options); + + [DllImport("libc", EntryPoint = "getxattr", CharSet = CharSet.Ansi)] + private static extern long GetXattr( + [MarshalAs(UnmanagedType.LPStr)] string path, + [MarshalAs(UnmanagedType.LPStr)] string name, + IntPtr value, + ulong size, + uint position, + int options); +#endif + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..cf65a1f73b3153811649c1542716eb4fed6ad62e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Unregisters from an event on an object. + /// + [Cmdlet(VerbsLifecycle.Unregister, "Event", SupportsShouldProcess = true, DefaultParameterSetName = "BySource", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097037")] + public class UnregisterEventCommand : PSCmdlet + { + #region parameters + + /// + /// An identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "BySource")] + public string SourceIdentifier + { + get + { + return _sourceIdentifier; + } + + set + { + _sourceIdentifier = value; + + if (value != null) + { + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + } + } + } + + private string _sourceIdentifier = null; + + /// + /// An identifier for this event subscription. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "ById")] + public int SubscriptionId { get; set; } = -1; + + /// + /// Flag that determines if we should include subscriptions used to support other subscriptions. + /// + [Parameter] + public SwitchParameter Force { get; set; } + + #endregion parameters + + private WildcardPattern _matchPattern; + private bool _foundMatch = false; + + /// + /// Unsubscribe from the event. + /// + protected override void ProcessRecord() + { + // Go through all the received events and write them to the output + // pipeline + foreach (PSEventSubscriber subscriber in Events.Subscribers) + { + // If the event identifier matches, remove the subscription + if ( + ((_sourceIdentifier != null) && _matchPattern.IsMatch(subscriber.SourceIdentifier)) || + ((SubscriptionId >= 0) && (subscriber.SubscriptionId == SubscriptionId)) + ) + { + // If this is a support event but they aren't explicitly + // looking for them, continue. + if (subscriber.SupportEvent && (!Force)) + { + continue; + } + + _foundMatch = true; + + if (ShouldProcess( + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + EventingStrings.EventSubscription, + subscriber.SourceIdentifier), + EventingStrings.Unsubscribe)) + { + Events.UnsubscribeEvent(subscriber); + } + } + } + + // Generate an error if we couldn't find the subscription identifier, + // and no globbing was done. + if ((_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && + (!_foundMatch)) + { + ErrorRecord errorRecord = new( + new ArgumentException( + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + EventingStrings.EventSubscriptionNotFound, _sourceIdentifier)), + "INVALID_SOURCE_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + + WriteError(errorRecord); + } + else if ((SubscriptionId >= 0) && + (!_foundMatch)) + { + ErrorRecord errorRecord = new( + new ArgumentException( + string.Format( + System.Globalization.CultureInfo.CurrentCulture, + EventingStrings.EventSubscriptionNotFound, SubscriptionId)), + "INVALID_SUBSCRIPTION_IDENTIFIER", + ErrorCategory.InvalidArgument, + null); + + WriteError(errorRecord); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs new file mode 100644 index 0000000000000000000000000000000000000000..4a3198d291155dffd0b3a72c84906467e691609f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This is the base class for update-typedata and update-formatdata. + /// + public class UpdateData : PSCmdlet + { + /// + /// File parameter set name. + /// + protected const string FileParameterSet = "FileSet"; + + /// + /// Files to append to the existing set. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, + ParameterSetName = FileParameterSet)] + [Alias("PSPath", "Path")] + [ValidateNotNull] + public string[] AppendPath { get; set; } = Array.Empty(); + + /// + /// Files to prepend to the existing set. + /// + [Parameter(ParameterSetName = FileParameterSet)] + [ValidateNotNull] + public string[] PrependPath { get; set; } = Array.Empty(); + + private static void ReportWrongExtension(string file, string errorId, PSCmdlet cmdlet) + { + ErrorRecord errorRecord = new( + PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongExtension, file, "ps1xml"), + errorId, + ErrorCategory.InvalidArgument, + null); + cmdlet.WriteError(errorRecord); + } + + private static void ReportWrongProviderType(string providerId, string errorId, PSCmdlet cmdlet) + { + ErrorRecord errorRecord = new( + PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongProviderError, providerId), + errorId, + ErrorCategory.InvalidArgument, + null); + cmdlet.WriteError(errorRecord); + } + + /// + /// + /// + /// + /// + /// + internal static Collection Glob(string[] files, string errorId, PSCmdlet cmdlet) + { + Collection retValue = new(); + foreach (string file in files) + { + Collection providerPaths; + ProviderInfo provider = null; + try + { + providerPaths = cmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath(file, out provider); + } + catch (SessionStateException e) + { + cmdlet.WriteError(new ErrorRecord(e, errorId, ErrorCategory.InvalidOperation, file)); + continue; + } + + if (!provider.NameEquals(cmdlet.Context.ProviderNames.FileSystem)) + { + ReportWrongProviderType(provider.FullName, errorId, cmdlet); + continue; + } + + foreach (string providerPath in providerPaths) + { + if (!providerPath.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase)) + { + ReportWrongExtension(providerPath, "WrongExtension", cmdlet); + continue; + } + + retValue.Add(providerPath); + } + } + + return retValue; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs new file mode 100644 index 0000000000000000000000000000000000000000..99507d0461ba470bd6fa322039a294e032030fe6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This cmdlet updates the property of incoming objects and passes them to the + /// pipeline. This cmdlet also returns a .NET object with properties that + /// defines the update action on a list. + /// This cmdlet is most helpful when the cmdlet author wants the user to do + /// update action on object list that are not directly exposed through + /// cmdlet parameter. One wants to update a property value which is a list + /// (multi-valued parameter for a cmdlet), without exposing the list. + /// + [Cmdlet(VerbsData.Update, "List", DefaultParameterSetName = "AddRemoveSet", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109383", RemotingCapability = RemotingCapability.None)] + public class UpdateListCommand : PSCmdlet + { + /// + /// The following is the definition of the input parameter "Add". + /// Objects to add to the list. + /// + [Parameter(ParameterSetName = "AddRemoveSet")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + public object[] Add { get; set; } + + /// + /// The following is the definition of the input parameter "Remove". + /// Objects to be removed from the list. + /// + [Parameter(ParameterSetName = "AddRemoveSet")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + public object[] Remove { get; set; } + + /// + /// The following is the definition of the input parameter "Replace". + /// Objects in this list replace the objects in the target list. + /// + [Parameter(Mandatory = true, ParameterSetName = "ReplaceSet")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + public object[] Replace { get; set; } + + /// + /// The following is the definition of the input parameter "InputObject". + /// List of InputObjects where the updates needs to applied to the specific property. + /// + // [Parameter(ValueFromPipeline = true, ParameterSetName = "AddRemoveSet")] + // [Parameter(ValueFromPipeline = true, ParameterSetName = "ReplaceSet")] + [Parameter(ValueFromPipeline = true)] + [ValidateNotNullOrEmpty] + public PSObject InputObject { get; set; } + + /// + /// The following is the definition of the input parameter "Property". + /// Defines which property of the input object should be updated with Add and Remove actions. + /// + // [Parameter(Position = 0, ParameterSetName = "AddRemoveSet")] + // [Parameter(Position = 0, ParameterSetName = "ReplaceSet")] + [Parameter(Position = 0)] + [ValidateNotNullOrEmpty] + public string Property { get; set; } + + private PSListModifier _listModifier; + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + if (Property != null) + { + if (InputObject == null) + { + WriteError(NewError("MissingInputObjectParameter", "MissingInputObjectParameter", null)); + } + else + { + _listModifier ??= CreatePSListModifier(); + + PSMemberInfo memberInfo = InputObject.Members[Property]; + if (memberInfo != null) + { + try + { + _listModifier.ApplyTo(memberInfo.Value); + WriteObject(InputObject); + } + catch (PSInvalidOperationException e) + { + WriteError(new ErrorRecord(e, "ApplyFailed", ErrorCategory.InvalidOperation, null)); + } + } + else + { + WriteError(NewError("MemberDoesntExist", "MemberDoesntExist", InputObject, Property)); + } + } + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (Property == null) + { + if (InputObject != null) + { + ThrowTerminatingError(NewError("MissingPropertyParameter", "MissingPropertyParameter", null)); + } + else + { + WriteObject(CreateHashtable()); + } + } + } + + private Hashtable CreateHashtable() + { + Hashtable hash = new(2); + if (Add != null) + { + hash.Add("Add", Add); + } + + if (Remove != null) + { + hash.Add("Remove", Remove); + } + + if (Replace != null) + { + hash.Add("Replace", Replace); + } + + return hash; + } + + private PSListModifier CreatePSListModifier() + { + PSListModifier listModifier = new(); + if (Add != null) + { + foreach (object obj in Add) + { + listModifier.Add.Add(obj); + } + } + + if (Remove != null) + { + foreach (object obj in Remove) + { + listModifier.Remove.Add(obj); + } + } + + if (Replace != null) + { + foreach (object obj in Replace) + { + listModifier.Replace.Add(obj); + } + } + + return listModifier; + } + + private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) + { + ErrorDetails details = new(this.GetType().Assembly, "UpdateListStrings", resourceId, args); + ErrorRecord errorRecord = new( + new InvalidOperationException(details.Message), + errorId, + ErrorCategory.InvalidOperation, + targetObject); + return errorRecord; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs new file mode 100644 index 0000000000000000000000000000000000000000..b73d85700404076d89bd89e26566f8c81e4c76ed --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -0,0 +1,1391 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Reflection; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements update-typeData command. + /// + [Cmdlet(VerbsData.Update, "TypeData", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, + DefaultParameterSetName = FileParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097131")] + public class UpdateTypeDataCommand : UpdateData + { + #region dynamic type set + + // Dynamic type set name and type data set name + private const string DynamicTypeSet = "DynamicTypeSet"; + private const string TypeDataSet = "TypeDataSet"; + + private static readonly object s_notSpecified = new(); + + private static bool HasBeenSpecified(object obj) + { + return !System.Object.ReferenceEquals(obj, s_notSpecified); + } + + private PSMemberTypes _memberType; + private bool _isMemberTypeSet = false; + /// + /// The member type of to be added. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + [ValidateSet(System.Management.Automation.Runspaces.TypeData.NoteProperty, + System.Management.Automation.Runspaces.TypeData.AliasProperty, + System.Management.Automation.Runspaces.TypeData.ScriptProperty, + System.Management.Automation.Runspaces.TypeData.CodeProperty, + System.Management.Automation.Runspaces.TypeData.ScriptMethod, + System.Management.Automation.Runspaces.TypeData.CodeMethod, IgnoreCase = true)] + public PSMemberTypes MemberType + { + get + { + return _memberType; + } + + set + { + _memberType = value; + _isMemberTypeSet = true; + } + } + + private string _memberName; + /// + /// The name of the new member. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string MemberName + { + get { return _memberName; } + + set { _memberName = value; } + } + + private object _value1 = s_notSpecified; + /// + /// First value of the new member. The meaning of this value + /// changes according to the member type. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + public object Value + { + get { return _value1; } + + set { _value1 = value; } + } + + private object _value2; + /// + /// Second value of the new member. The meaning of this value + /// changes according to the member type. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNull] + public object SecondValue + { + get { return _value2; } + + set { _value2 = value; } + } + + private Type _typeConverter; + /// + /// The type converter to be added. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNull] + public Type TypeConverter + { + get { return _typeConverter; } + + set { _typeConverter = value; } + } + + private Type _typeAdapter; + /// + /// The type adapter to be added. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNull] + public Type TypeAdapter + { + get { return _typeAdapter; } + + set { _typeAdapter = value; } + } + + /// + /// SerializationMethod. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string SerializationMethod + { + get { return _serializationMethod; } + + set { _serializationMethod = value; } + } + + /// + /// TargetTypeForDeserialization. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNull] + public Type TargetTypeForDeserialization + { + get { return _targetTypeForDeserialization; } + + set { _targetTypeForDeserialization = value; } + } + + /// + /// SerializationDepth. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNull] + [ValidateRange(0, int.MaxValue)] + public int SerializationDepth + { + get { return _serializationDepth; } + + set { _serializationDepth = value; } + } + + /// + /// DefaultDisplayProperty. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string DefaultDisplayProperty + { + get { return _defaultDisplayProperty; } + + set { _defaultDisplayProperty = value; } + } + + /// + /// InheritPropertySerializationSet. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNull] + public bool? InheritPropertySerializationSet + { + get { return _inheritPropertySerializationSet; } + + set { _inheritPropertySerializationSet = value; } + } + + /// + /// StringSerializationSource. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string StringSerializationSource + { + get { return _stringSerializationSource; } + + set { _stringSerializationSource = value; } + } + + /// + /// DefaultDisplayPropertySet. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string[] DefaultDisplayPropertySet + { + get { return _defaultDisplayPropertySet; } + + set { _defaultDisplayPropertySet = value; } + } + + /// + /// DefaultKeyPropertySet. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string[] DefaultKeyPropertySet + { + get { return _defaultKeyPropertySet; } + + set { _defaultKeyPropertySet = value; } + } + + /// + /// PropertySerializationSet. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + [Parameter(ParameterSetName = DynamicTypeSet)] + [ValidateNotNullOrEmpty] + public string[] PropertySerializationSet + { + get { return _propertySerializationSet; } + + set { _propertySerializationSet = value; } + } + + // These members are represented as NoteProperty in types.ps1xml + private string _serializationMethod; + private Type _targetTypeForDeserialization; + private int _serializationDepth = int.MinValue; + private string _defaultDisplayProperty; + private bool? _inheritPropertySerializationSet; + + // These members are represented as AliasProperty in types.ps1xml + private string _stringSerializationSource; + + // These members are represented as PropertySet in types.ps1xml + private string[] _defaultDisplayPropertySet; + private string[] _defaultKeyPropertySet; + private string[] _propertySerializationSet; + + private string _typeName; + /// + /// The type name we want to update on. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = DynamicTypeSet)] + [ArgumentToTypeNameTransformation] + [ValidateNotNullOrEmpty] + public string TypeName + { + get { return _typeName; } + + set { _typeName = value; } + } + + private bool _force = false; + /// + /// True if we should overwrite a possibly existing member. + /// + [Parameter(ParameterSetName = DynamicTypeSet)] + [Parameter(ParameterSetName = TypeDataSet)] + public SwitchParameter Force + { + get { return _force; } + + set { _force = value; } + } + + #endregion dynamic type set + + #region strong type data set + + private TypeData[] _typeData; + /// + /// The TypeData instances. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = TypeDataSet)] + public TypeData[] TypeData + { + get { return _typeData; } + + set { _typeData = value; } + } + + #endregion strong type data set + + /// + /// This method verify if the Type Table is shared and cannot be updated. + /// + protected override void BeginProcessing() + { + if (Context.TypeTable.isShared) + { + var ex = new InvalidOperationException(TypesXmlStrings.SharedTypeTableCannotBeUpdated); + this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedTypeTable", ErrorCategory.InvalidOperation, null)); + } + } + + /// + /// This method implements the ProcessRecord method for update-typeData command. + /// + protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case FileParameterSet: + ProcessTypeFiles(); + break; + case DynamicTypeSet: + ProcessDynamicType(); + break; + case TypeDataSet: + ProcessStrongTypeData(); + break; + } + } + + /// + /// This method implements the EndProcessing method for update-typeData command. + /// + protected override void EndProcessing() + { + this.Context.TypeTable.ClearConsolidatedMembers(); + } + + #region strong typeData + + private void ProcessStrongTypeData() + { + string action = UpdateDataStrings.UpdateTypeDataAction; + string target = UpdateDataStrings.UpdateTypeDataTarget; + + foreach (TypeData item in _typeData) + { + // If type contains no members at all, report the error and skip it + if (!EnsureTypeDataIsNotEmpty(item)) + { + continue; + } + + TypeData type = item.Copy(); + + // Set property IsOverride to be true if -Force parameter is specified + if (_force) + { + type.IsOverride = true; + } + + string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, type.TypeName); + if (ShouldProcess(formattedTarget, action)) + { + try + { + var errors = new ConcurrentBag(); + this.Context.TypeTable.Update(type, errors, false); + // Write out errors... + if (!errors.IsEmpty) + { + foreach (string s in errors) + { + RuntimeException rte = new(s); + this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); + } + } + else + { + // Update successfully, we add the TypeData into cache + if (Context.InitialSessionState != null) + { + Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); + } + else + { + Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); + } + } + } + catch (RuntimeException e) + { + this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); + } + } + } + } + + #endregion strong typeData + + #region dynamic type processing + + /// + /// Process the dynamic type update. + /// + private void ProcessDynamicType() + { + if (string.IsNullOrWhiteSpace(_typeName)) + { + ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); + } + + TypeData type = new(_typeName) { IsOverride = _force }; + + GetMembers(type.Members); + + if (_typeConverter != null) + { + type.TypeConverter = _typeConverter; + } + + if (_typeAdapter != null) + { + type.TypeAdapter = _typeAdapter; + } + + if (_serializationMethod != null) + { + type.SerializationMethod = _serializationMethod; + } + + if (_targetTypeForDeserialization != null) + { + type.TargetTypeForDeserialization = _targetTypeForDeserialization; + } + + if (_serializationDepth != int.MinValue) + { + type.SerializationDepth = (uint)_serializationDepth; + } + + if (_defaultDisplayProperty != null) + { + type.DefaultDisplayProperty = _defaultDisplayProperty; + } + + if (_inheritPropertySerializationSet != null) + { + type.InheritPropertySerializationSet = _inheritPropertySerializationSet.Value; + } + + if (_stringSerializationSource != null) + { + type.StringSerializationSource = _stringSerializationSource; + } + + if (_defaultDisplayPropertySet != null) + { + PropertySetData defaultDisplayPropertySet = new(_defaultDisplayPropertySet); + type.DefaultDisplayPropertySet = defaultDisplayPropertySet; + } + + if (_defaultKeyPropertySet != null) + { + PropertySetData defaultKeyPropertySet = new(_defaultKeyPropertySet); + type.DefaultKeyPropertySet = defaultKeyPropertySet; + } + + if (_propertySerializationSet != null) + { + PropertySetData propertySerializationSet = new(_propertySerializationSet); + type.PropertySerializationSet = propertySerializationSet; + } + + // If the type contains no members at all, report the error and return + if (!EnsureTypeDataIsNotEmpty(type)) + { + return; + } + + // Load the resource strings + string action = UpdateDataStrings.UpdateTypeDataAction; + string target = UpdateDataStrings.UpdateTypeDataTarget; + + string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, _typeName); + + if (ShouldProcess(formattedTarget, action)) + { + try + { + var errors = new ConcurrentBag(); + this.Context.TypeTable.Update(type, errors, false); + // Write out errors... + if (!errors.IsEmpty) + { + foreach (string s in errors) + { + RuntimeException rte = new(s); + this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); + } + } + else + { + // Update successfully, we add the TypeData into cache + if (Context.InitialSessionState != null) + { + Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); + } + else + { + Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); + } + } + } + catch (RuntimeException e) + { + this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); + } + } + } + + /// + /// Get the members for the TypeData. + /// + /// + private void GetMembers(Dictionary members) + { + if (!_isMemberTypeSet) + { + // If the MemberType is not specified, the MemberName, Value, and SecondValue parameters + // should not be specified either + if (_memberName != null || HasBeenSpecified(_value1) || _value2 != null) + { + ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); + } + + return; + } + + switch (MemberType) + { + case PSMemberTypes.NoteProperty: + NotePropertyData note = GetNoteProperty(); + members.Add(note.Name, note); + break; + case PSMemberTypes.AliasProperty: + AliasPropertyData alias = GetAliasProperty(); + members.Add(alias.Name, alias); + break; + case PSMemberTypes.ScriptProperty: + ScriptPropertyData scriptProperty = GetScriptProperty(); + members.Add(scriptProperty.Name, scriptProperty); + break; + case PSMemberTypes.CodeProperty: + CodePropertyData codeProperty = GetCodeProperty(); + members.Add(codeProperty.Name, codeProperty); + break; + case PSMemberTypes.ScriptMethod: + ScriptMethodData scriptMethod = GetScriptMethod(); + members.Add(scriptMethod.Name, scriptMethod); + break; + case PSMemberTypes.CodeMethod: + CodeMethodData codeMethod = GetCodeMethod(); + members.Add(codeMethod.Name, codeMethod); + break; + default: + ThrowTerminatingError(NewError("CannotUpdateMemberType", UpdateDataStrings.CannotUpdateMemberType, null, _memberType.ToString())); + break; + } + } + + private static T GetParameterType(object sourceValue) + { + return (T)LanguagePrimitives.ConvertTo(sourceValue, typeof(T), CultureInfo.InvariantCulture); + } + + private void EnsureMemberNameHasBeenSpecified() + { + if (string.IsNullOrEmpty(_memberName)) + { + ThrowTerminatingError(NewError("MemberNameShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "MemberName", _memberType)); + } + } + + private void EnsureValue1HasBeenSpecified() + { + if (!HasBeenSpecified(_value1)) + { + ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "Value", _memberType)); + } + } + + private void EnsureValue1NotNullOrEmpty() + { + if (_value1 is string) + { + if (string.IsNullOrEmpty((string)_value1)) + { + ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); + } + + return; + } + + if (_value1 == null) + { + ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); + } + } + + private void EnsureValue2HasNotBeenSpecified() + { + if (_value2 != null) + { + ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", _memberType)); + } + } + + private void EnsureValue1AndValue2AreNotBothNull() + { + if (_value1 == null && _value2 == null) + { + ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, _memberType)); + } + } + + /// + /// Check if the TypeData instance contains no members. + /// + /// + /// False if empty, true if not. + private bool EnsureTypeDataIsNotEmpty(TypeData typeData) + { + if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 + && typeData.TypeConverter == null && typeData.TypeAdapter == null + && typeData.DefaultDisplayPropertySet == null + && typeData.DefaultKeyPropertySet == null + && typeData.PropertySerializationSet == null) + { + this.WriteError(NewError("TypeDataEmpty", UpdateDataStrings.TypeDataEmpty, null, typeData.TypeName)); + return false; + } + + return true; + } + + private NotePropertyData GetNoteProperty() + { + EnsureMemberNameHasBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue2HasNotBeenSpecified(); + return new NotePropertyData(_memberName, _value1); + } + + private AliasPropertyData GetAliasProperty() + { + EnsureMemberNameHasBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue1NotNullOrEmpty(); + + AliasPropertyData alias; + string referencedName = GetParameterType(_value1); + if (_value2 != null) + { + Type type = GetParameterType(_value2); + alias = new AliasPropertyData(_memberName, referencedName, type); + return alias; + } + + alias = new AliasPropertyData(_memberName, referencedName); + return alias; + } + + private ScriptPropertyData GetScriptProperty() + { + EnsureMemberNameHasBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue1AndValue2AreNotBothNull(); + + ScriptBlock value1ScriptBlock = null; + if (_value1 != null) + { + value1ScriptBlock = GetParameterType(_value1); + } + + ScriptBlock value2ScriptBlock = null; + if (_value2 != null) + { + value2ScriptBlock = GetParameterType(_value2); + } + + ScriptPropertyData scriptProperty = new(_memberName, value1ScriptBlock, value2ScriptBlock); + return scriptProperty; + } + + private CodePropertyData GetCodeProperty() + { + EnsureMemberNameHasBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue1AndValue2AreNotBothNull(); + + MethodInfo value1CodeReference = null; + if (_value1 != null) + { + value1CodeReference = GetParameterType(_value1); + } + + MethodInfo value2CodeReference = null; + if (_value2 != null) + { + value2CodeReference = GetParameterType(_value2); + } + + CodePropertyData codeProperty = new(_memberName, value1CodeReference, value2CodeReference); + return codeProperty; + } + + private ScriptMethodData GetScriptMethod() + { + EnsureMemberNameHasBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue2HasNotBeenSpecified(); + + ScriptBlock method = GetParameterType(_value1); + ScriptMethodData scriptMethod = new(_memberName, method); + return scriptMethod; + } + + private CodeMethodData GetCodeMethod() + { + EnsureMemberNameHasBeenSpecified(); + EnsureValue1HasBeenSpecified(); + EnsureValue2HasNotBeenSpecified(); + + MethodInfo codeReference = GetParameterType(_value1); + CodeMethodData codeMethod = new(_memberName, codeReference); + return codeMethod; + } + + /// + /// Generate error record. + /// + /// + /// + /// + /// + /// + private static ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) + { + string message = string.Format(CultureInfo.CurrentCulture, template, args); + ErrorRecord errorRecord = new( + new InvalidOperationException(message), + errorId, + ErrorCategory.InvalidOperation, + targetObject); + return errorRecord; + } + + #endregion dynamic type processing + + #region type files processing + + private void ProcessTypeFiles() + { + Collection prependPathTotal = Glob(this.PrependPath, "TypesPrependPathException", this); + Collection appendPathTotal = Glob(this.AppendPath, "TypesAppendPathException", this); + + // There are file path input but they did not pass the validation in the method Glob + if ((PrependPath.Length > 0 || AppendPath.Length > 0) && + prependPathTotal.Count == 0 && appendPathTotal.Count == 0) + { return; } + + string action = UpdateDataStrings.UpdateTypeDataAction; + // Load the resource once and format it whenever a new target + // filename is available + string target = UpdateDataStrings.UpdateTarget; + + if (Context.InitialSessionState != null) + { + // This hashSet is to detect if there are duplicate type files + var fullFileNameHash = new HashSet(StringComparer.CurrentCultureIgnoreCase); + var newTypes = new Collection(); + + for (int i = prependPathTotal.Count - 1; i >= 0; i--) + { + string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, prependPathTotal[i]); + string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(prependPathTotal[i], Context) ?? prependPathTotal[i]; + + if (ShouldProcess(formattedTarget, action)) + { + if (fullFileNameHash.Add(resolvedPath)) + { + newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); + } + } + } + + // Copy everything from context's TypeTable to newTypes + foreach (var entry in Context.InitialSessionState.Types) + { + if (entry.FileName != null) + { + string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; + if (fullFileNameHash.Add(resolvedPath)) + { + newTypes.Add(entry); + } + } + else + { + newTypes.Add(entry); + } + } + + foreach (string appendPathTotalItem in appendPathTotal) + { + string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, appendPathTotalItem); + string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(appendPathTotalItem, Context) ?? appendPathTotalItem; + + if (ShouldProcess(formattedTarget, action)) + { + if (fullFileNameHash.Add(resolvedPath)) + { + newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); + } + } + } + + Context.InitialSessionState.Types.Clear(); + Context.TypeTable.Clear(); + var errors = new ConcurrentBag(); + + foreach (SessionStateTypeEntry sste in newTypes) + { + try + { + if (sste.TypeTable != null) + { + var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateTypeWithTypeTable); + this.WriteError(new ErrorRecord(ex, "CannotUpdateTypeWithTypeTable", ErrorCategory.InvalidOperation, null)); + continue; + } + else if (sste.FileName != null) + { + Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out _); + } + else + { + Context.TypeTable.Update(sste.TypeData, errors, sste.IsRemove); + } + } + catch (RuntimeException ex) + { + this.WriteError(new ErrorRecord(ex, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); + } + + Context.InitialSessionState.Types.Add(sste); + + // Write out any errors... + if (!errors.IsEmpty) + { + foreach (string s in errors) + { + RuntimeException rte = new(s); + this.WriteError(new ErrorRecord(rte, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); + } + + errors = new ConcurrentBag(); + } + } + } + else + { + Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); + } + } + + #endregion type files processing + } + + /// + /// This class implements update-typeData command. + /// + [Cmdlet(VerbsData.Update, "FormatData", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, + DefaultParameterSetName = FileParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097135")] + public class UpdateFormatDataCommand : UpdateData + { + /// + /// This method verify if the Format database manager is shared and cannot be updated. + /// + protected override void BeginProcessing() + { + if (Context.FormatDBManager.isShared) + { + var ex = new InvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated); + this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedFormatTable", ErrorCategory.InvalidOperation, null)); + } + } + + /// + /// This method implements the ProcessRecord method for update-FormatData command. + /// + protected override void ProcessRecord() + { + Collection prependPathTotal = Glob(this.PrependPath, "FormatPrependPathException", this); + Collection appendPathTotal = Glob(this.AppendPath, "FormatAppendPathException", this); + + // There are file path input but they did not pass the validation in the method Glob + if ((PrependPath.Length > 0 || AppendPath.Length > 0) && + prependPathTotal.Count == 0 && appendPathTotal.Count == 0) + { return; } + + string action = UpdateDataStrings.UpdateFormatDataAction; + + // Load the resource once and format it whenever a new target + // filename is available + string target = UpdateDataStrings.UpdateTarget; + + if (Context.InitialSessionState != null) + { + if (Context.InitialSessionState.DisableFormatUpdates) + { + throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); + } + + // This hashSet is to detect if there are duplicate format files + var fullFileNameHash = new HashSet(StringComparer.CurrentCultureIgnoreCase); + var newFormats = new Collection(); + + for (int i = prependPathTotal.Count - 1; i >= 0; i--) + { + string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, prependPathTotal[i]); + + if (ShouldProcess(formattedTarget, action)) + { + if (!fullFileNameHash.Contains(prependPathTotal[i])) + { + fullFileNameHash.Add(prependPathTotal[i]); + newFormats.Add(new SessionStateFormatEntry(prependPathTotal[i])); + } + } + } + + // Always add InitialSessionState.Formats to the new list + foreach (SessionStateFormatEntry entry in Context.InitialSessionState.Formats) + { + if (entry.FileName != null) + { + if (!fullFileNameHash.Contains(entry.FileName)) + { + fullFileNameHash.Add(entry.FileName); + newFormats.Add(entry); + } + } + else + { + newFormats.Add(entry); + } + } + + foreach (string appendPathTotalItem in appendPathTotal) + { + string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, appendPathTotalItem); + + if (ShouldProcess(formattedTarget, action)) + { + if (fullFileNameHash.Add(appendPathTotalItem)) + { + newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); + } + } + } + + var originalFormats = Context.InitialSessionState.Formats; + try + { + // Always rebuild the format information + Context.InitialSessionState.Formats.Clear(); + var entries = new Collection(); + + // Now update the formats... + foreach (SessionStateFormatEntry ssfe in newFormats) + { + string name = ssfe.FileName; + PSSnapInInfo snapin = ssfe.PSSnapIn; + if (snapin != null && !string.IsNullOrEmpty(snapin.Name)) + { + name = snapin.Name; + } + + if (ssfe.Formattable != null) + { + var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable); + this.WriteError(new ErrorRecord(ex, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); + continue; + } + else if (ssfe.FormatData != null) + { + entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); + } + else + { + entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FileName)); + } + + Context.InitialSessionState.Formats.Add(ssfe); + } + + if (entries.Count > 0) + { + Context.FormatDBManager.UpdateDataBase(entries, this.Context.AuthorizationManager, this.Context.EngineHostInterface, false); + FormatAndTypeDataHelper.ThrowExceptionOnError("ErrorsUpdatingFormats", + null, + entries, + FormatAndTypeDataHelper.Category.Formats); + } + } + catch (RuntimeException e) + { + // revert Formats if there is a failure + Context.InitialSessionState.Formats.Clear(); + Context.InitialSessionState.Formats.Add(originalFormats); + this.WriteError(new ErrorRecord(e, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); + } + } + else + { + Dbg.Assert(false, "InitialSessionState must be non-null for Update-FormatData to work"); + } + } + } + + /// + /// Remove-TypeData cmdlet. + /// + [Cmdlet(VerbsCommon.Remove, "TypeData", SupportsShouldProcess = true, DefaultParameterSetName = RemoveTypeDataSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096622")] + public class RemoveTypeDataCommand : PSCmdlet + { + private const string RemoveTypeSet = "RemoveTypeSet"; + private const string RemoveFileSet = "RemoveFileSet"; + private const string RemoveTypeDataSet = "RemoveTypeDataSet"; + + private string _typeName; + + /// + /// The target type to remove. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveTypeSet)] + [ArgumentToTypeNameTransformation] + [ValidateNotNullOrEmpty] + public string TypeName + { + get { return _typeName; } + + set { _typeName = value; } + } + + private string[] _typeFiles; + + /// + /// The type xml file to remove from the cache. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] + [Parameter(Mandatory = true, ParameterSetName = RemoveFileSet)] + [ValidateNotNullOrEmpty] + public string[] Path + { + get { return _typeFiles; } + + set { _typeFiles = value; } + } + + private TypeData _typeData; + + /// + /// The TypeData to remove. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = RemoveTypeDataSet)] + public TypeData TypeData + { + get { return _typeData; } + + set { _typeData = value; } + } + + private static void ConstructFileToIndexMap(string fileName, int index, Dictionary> fileNameToIndexMap) + { + List indexList; + if (fileNameToIndexMap.TryGetValue(fileName, out indexList)) + { + indexList.Add(index); + } + else + { + fileNameToIndexMap[fileName] = new List { index }; + } + } + + /// + /// This method implements the ProcessRecord method for Remove-TypeData command. + /// + protected override void ProcessRecord() + { + if (ParameterSetName == RemoveFileSet) + { + // Load the resource strings + string removeFileAction = UpdateDataStrings.RemoveTypeFileAction; + string removeFileTarget = UpdateDataStrings.UpdateTarget; + + Collection typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); + if (typeFileTotal.Count == 0) + { + return; + } + + // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might + // exist in the cache because the user can add arbitrary files to the cache by $host.Runspace.InitialSessionState.Types.Add() + Dictionary> fileToIndexMap = new(StringComparer.OrdinalIgnoreCase); + List indicesToRemove = new(); + + if (Context.InitialSessionState != null) + { + for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) + { + string fileName = Context.InitialSessionState.Types[index].FileName; + if (fileName == null) + { + continue; + } + + // Resolving the file path because the path to the types file in module manifest is now specified as + // ..\..\types.ps1xml which expands to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Core\..\..\types.ps1xml + fileName = ModuleCmdletBase.ResolveRootedFilePath(fileName, Context) ?? fileName; + ConstructFileToIndexMap(fileName, index, fileToIndexMap); + } + } + + foreach (string typeFile in typeFileTotal) + { + string removeFileFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeFileTarget, typeFile); + if (ShouldProcess(removeFileFormattedTarget, removeFileAction)) + { + List indexList; + if (fileToIndexMap.TryGetValue(typeFile, out indexList)) + { + indicesToRemove.AddRange(indexList); + } + else + { + this.WriteError(NewError("TypeFileNotExistsInCurrentSession", UpdateDataStrings.TypeFileNotExistsInCurrentSession, null, typeFile)); + } + } + } + + if (indicesToRemove.Count > 0) + { + indicesToRemove.Sort(); + for (int i = indicesToRemove.Count - 1; i >= 0; i--) + { + Context.InitialSessionState?.Types.RemoveItem(indicesToRemove[i]); + } + + try + { + if (Context.InitialSessionState != null) + { + bool oldRefreshTypeFormatSetting = Context.InitialSessionState.RefreshTypeAndFormatSetting; + try + { + Context.InitialSessionState.RefreshTypeAndFormatSetting = true; + Context.InitialSessionState.UpdateTypes(Context, false); + } + finally + { + Context.InitialSessionState.RefreshTypeAndFormatSetting = oldRefreshTypeFormatSetting; + } + } + } + catch (RuntimeException ex) + { + this.WriteError(new ErrorRecord(ex, "TypesFileRemoveException", ErrorCategory.InvalidOperation, null)); + } + } + + return; + } + + // Load the resource strings + string removeTypeAction = UpdateDataStrings.RemoveTypeDataAction; + string removeTypeTarget = UpdateDataStrings.RemoveTypeDataTarget; + string typeNameToRemove = null; + + if (ParameterSetName == RemoveTypeDataSet) + { + typeNameToRemove = _typeData.TypeName; + } + else + { + if (string.IsNullOrWhiteSpace(_typeName)) + { + ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); + } + + typeNameToRemove = _typeName; + } + + Dbg.Assert(!string.IsNullOrEmpty(typeNameToRemove), "TypeNameToRemove should be not null and not empty at this point"); + TypeData type = new(typeNameToRemove); + string removeTypeFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeTypeTarget, typeNameToRemove); + + if (ShouldProcess(removeTypeFormattedTarget, removeTypeAction)) + { + try + { + var errors = new ConcurrentBag(); + Context.TypeTable.Update(type, errors, true); + // Write out errors... + if (!errors.IsEmpty) + { + foreach (string s in errors) + { + RuntimeException rte = new(s); + this.WriteError(new ErrorRecord(rte, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); + } + } + else + { + // Type is removed successfully, add it into the cache + if (Context.InitialSessionState != null) + { + Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, true)); + } + else + { + Dbg.Assert(false, "InitialSessionState must be non-null for Remove-Typedata to work"); + } + } + } + catch (RuntimeException e) + { + this.WriteError(new ErrorRecord(e, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); + } + } + } + + /// + /// This method implements the EndProcessing method for Remove-TypeData command. + /// + protected override void EndProcessing() + { + this.Context.TypeTable.ClearConsolidatedMembers(); + } + + private static ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) + { + string message = string.Format(CultureInfo.CurrentCulture, template, args); + ErrorRecord errorRecord = new( + new InvalidOperationException(message), + errorId, + ErrorCategory.InvalidOperation, + targetObject); + return errorRecord; + } + } + + /// + /// Get-TypeData cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "TypeData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097018")] + [OutputType(typeof(System.Management.Automation.PSObject))] + public class GetTypeDataCommand : PSCmdlet + { + private WildcardPattern[] _filter; + + /// + /// Get Formatting information only for the specified typename. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [ValidateNotNullOrEmpty] + [Parameter(Position = 0, ValueFromPipeline = true)] + public string[] TypeName { get; set; } + + private void ValidateTypeName() + { + if (TypeName == null) + { + _filter = new WildcardPattern[] { WildcardPattern.Get("*", WildcardOptions.None) }; + return; + } + + var typeNames = new List(); + var exception = new InvalidOperationException(UpdateDataStrings.TargetTypeNameEmpty); + foreach (string typeName in TypeName) + { + if (string.IsNullOrWhiteSpace(typeName)) + { + WriteError( + new ErrorRecord( + exception, + "TargetTypeNameEmpty", + ErrorCategory.InvalidOperation, + typeName)); + continue; + } + + Type type; + string typeNameInUse = typeName; + // Respect the type shortcut + if (LanguagePrimitives.TryConvertTo(typeNameInUse, out type)) + { + typeNameInUse = type.FullName; + } + + typeNames.Add(typeNameInUse); + } + + _filter = new WildcardPattern[typeNames.Count]; + for (int i = 0; i < _filter.Length; i++) + { + _filter[i] = WildcardPattern.Get(typeNames[i], + WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); + } + } + + /// + /// Takes out the content from the database and writes it out. + /// + protected override void ProcessRecord() + { + ValidateTypeName(); + + Dictionary alltypes = Context.TypeTable.GetAllTypeData(); + + foreach (string type in alltypes.Keys) + { + foreach (WildcardPattern pattern in _filter) + { + if (pattern.IsMatch(type)) + { + WriteObject(alltypes[type]); + break; + } + } + } + } + } + + /// + /// To make it easier to specify a TypeName, we add an ArgumentTransformationAttribute here. + /// * string: return the string + /// * Type: return the Type.ToString() + /// * instance: return instance.GetType().ToString() . + /// + internal sealed class ArgumentToTypeNameTransformationAttribute : ArgumentTransformationAttribute + { + public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) + { + string typeName; + object target = PSObject.Base(inputData); + if (target is Type) + { + typeName = ((Type)target).FullName; + } + else if (target is string) + { + // Respect the type shortcut + Type type; + typeName = (string)target; + if (LanguagePrimitives.TryConvertTo(typeName, out type)) + { + typeName = type.FullName; + } + } + else if (target is TypeData) + { + typeName = ((TypeData)target).TypeName; + } + else + { + typeName = target.GetType().FullName; + } + + return typeName; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs new file mode 100644 index 0000000000000000000000000000000000000000..1e3cc038750411be3e90ef13274f946ff420ac70 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -0,0 +1,376 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Text; + +[module: SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Scope = "type", Target = "~T:Microsoft.PowerShell.Commands.ByteCollection")] + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Don't use! The API is obsolete!. + /// + [Obsolete("This class is included in this SDK for completeness only. The members of this class cannot be used directly, nor should this class be used to derive other classes.", true)] + public enum TextEncodingType + { + /// + /// No encoding. + /// + Unknown, + + /// + /// Unicode encoding. + /// + String, + + /// + /// Unicode encoding. + /// + Unicode, + + /// + /// Byte encoding. + /// + Byte, + + /// + /// Big Endian Unicode encoding. + /// + BigEndianUnicode, + + /// + /// Big Endian UTF32 encoding. + /// + BigEndianUTF32, + + /// + /// UTF8 encoding. + /// + Utf8, + + /// + /// UTF7 encoding. + /// + Utf7, + + /// + /// ASCII encoding. + /// + Ascii, + } + + /// + /// Utility class to contain resources for the Microsoft.PowerShell.Utility module. + /// + [Obsolete("This class is obsolete", true)] + public static class UtilityResources + { + /// + /// + public static string PathDoesNotExist { get { return UtilityCommonStrings.PathDoesNotExist; } } + + /// + /// + public static string FileReadError { get { return UtilityCommonStrings.FileReadError; } } + + /// + /// The resource string used to indicate 'PATH:' in the formatting header. + /// + public static string FormatHexPathPrefix { get { return UtilityCommonStrings.FormatHexPathPrefix; } } + + /// + /// The file '{0}' could not be parsed as a PowerShell Data File. + /// + public static string CouldNotParseAsPowerShellDataFile { get { return UtilityCommonStrings.CouldNotParseAsPowerShellDataFile; } } + } + + /// + /// ByteCollection is used as a wrapper class for the collection of bytes. + /// + public class ByteCollection + { + /// + /// Initializes a new instance of the class. + /// + /// The Offset address to be used while displaying the bytes in the collection. + /// Underlying bytes stored in the collection. + /// Indicates the path of the file whose contents are wrapped in the ByteCollection. + [Obsolete("The constructor is deprecated.", true)] + public ByteCollection(uint offset, byte[] value, string path) + : this((ulong)offset, value, path) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The Offset address to be used while displaying the bytes in the collection. + /// Underlying bytes stored in the collection. + /// Indicates the path of the file whose contents are wrapped in the ByteCollection. + public ByteCollection(ulong offset, byte[] value, string path) + { + if (value == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + Offset64 = offset; + Bytes = value; + Path = path; + Label = path; + } + + /// + /// Initializes a new instance of the class. + /// + /// The Offset address to be used while displaying the bytes in the collection. + /// Underlying bytes stored in the collection. + [Obsolete("The constructor is deprecated.", true)] + public ByteCollection(uint offset, byte[] value) + : this((ulong)offset, value) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The Offset address to be used while displaying the bytes in the collection. + /// Underlying bytes stored in the collection. + public ByteCollection(ulong offset, byte[] value) + { + if (value == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + Offset64 = offset; + Bytes = value; + } + + /// + /// Initializes a new instance of the class. + /// + /// The Offset address to be used while displaying the bytes in the collection. + /// + /// The label for the byte group. This may be a file path or a formatted identifying string for the group. + /// + /// Underlying bytes stored in the collection. + public ByteCollection(ulong offset, string label, byte[] value) + : this(offset, value) + { + Label = label; + } + + /// + /// Initializes a new instance of the class. + /// + /// Underlying bytes stored in the collection. + public ByteCollection(byte[] value) + { + if (value == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(value)); + } + + Bytes = value; + } + + /// + /// Gets the Offset address to be used while displaying the bytes in the collection. + /// + [Obsolete("The property is deprecated, please use Offset64 instead.", true)] + public uint Offset + { + get + { + return (uint)Offset64; + } + + private set + { + Offset64 = value; + } + } + + /// + /// Gets the Offset address to be used while displaying the bytes in the collection. + /// + public ulong Offset64 { get; private set; } + + /// + /// Gets underlying bytes stored in the collection. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public byte[] Bytes { get; } + + /// + /// Gets the path of the file whose contents are wrapped in the ByteCollection. + /// + public string Path { get; } + + /// + /// Gets the hexadecimal representation of the value. + /// + public string HexOffset => string.Create(CultureInfo.CurrentCulture, $"{Offset64:X16}"); + + /// + /// Gets the type of the input objects used to create the . + /// + public string Label { get; } + + private const int BytesPerLine = 16; + + private string _hexBytes = string.Empty; + + /// + /// Gets a space-delimited string of the in this + /// in hexadecimal format. + /// + public string HexBytes + { + get + { + if (_hexBytes == string.Empty) + { + StringBuilder line = new(BytesPerLine * 3); + + foreach (var currentByte in Bytes) + { + line.AppendFormat(CultureInfo.CurrentCulture, "{0:X2} ", currentByte); + } + + _hexBytes = line.ToString().Trim(); + } + + return _hexBytes; + } + } + + private string _ascii = string.Empty; + + /// + /// Gets the ASCII string representation of the in this . + /// + /// + public string Ascii + { + get + { + if (_ascii == string.Empty) + { + StringBuilder ascii = new(BytesPerLine); + + foreach (var currentByte in Bytes) + { + var currentChar = (char)currentByte; + if (currentChar == 0x0) + { + ascii.Append(' '); + } + else if (char.IsControl(currentChar)) + { + ascii.Append((char)0xFFFD); + } + else + { + ascii.Append(currentChar); + } + } + + _ascii = ascii.ToString(); + } + + return _ascii; + } + } + + /// + /// Displays the hexadecimal format of the bytes stored in the collection. + /// + /// + public override string ToString() + { + const int BytesPerLine = 16; + const string LineFormat = "{0:X16} "; + + // '16 + 3' comes from format "{0:X16} ". + // '16' comes from '[Uint64]::MaxValue.ToString("X").Length'. + StringBuilder nextLine = new(16 + 3 + (BytesPerLine * 3)); + StringBuilder asciiEnd = new(BytesPerLine); + + // '+1' comes from 'result.Append(nextLine.ToString() + " " + asciiEnd.ToString());' below. + StringBuilder result = new(nextLine.Capacity + asciiEnd.Capacity + 1); + + if (Bytes.Length > 0) + { + long charCounter = 0; + + var currentOffset = Offset64; + + nextLine.AppendFormat(CultureInfo.InvariantCulture, LineFormat, currentOffset); + + foreach (byte currentByte in Bytes) + { + // Display each byte, in 2-digit hexadecimal, and add that to the left-hand side. + nextLine.AppendFormat("{0:X2} ", currentByte); + + // If the character is printable, add its ascii representation to + // the right-hand side. Otherwise, add a dot to the right hand side. + var currentChar = (char)currentByte; + if (currentChar == 0x0) + { + asciiEnd.Append(' '); + } + else if (char.IsControl(currentChar)) + { + asciiEnd.Append((char)0xFFFD); + } + else + { + asciiEnd.Append(currentChar); + } + + charCounter++; + + // If we've hit the end of a line, combine the right half with the + // left half, and start a new line. + if ((charCounter % BytesPerLine) == 0) + { + result.Append(nextLine).Append(' ').Append(asciiEnd); + nextLine.Clear(); + asciiEnd.Clear(); + currentOffset += BytesPerLine; + nextLine.AppendFormat(CultureInfo.InvariantCulture, LineFormat, currentOffset); + + // Adding a newline to support long inputs strings flowing through InputObject parameterset. + if ((charCounter <= Bytes.Length) && string.IsNullOrEmpty(Path)) + { + result.AppendLine(); + } + } + } + + // At the end of the file, we might not have had the chance to output + // the end of the line yet. Only do this if we didn't exit on the 16-byte + // boundary, though. + if ((charCounter % 16) != 0) + { + while ((charCounter % 16) != 0) + { + nextLine.Append(' ', 3); + asciiEnd.Append(' '); + charCounter++; + } + + result.Append(nextLine).Append(' ').Append(asciiEnd); + } + } + + return result.ToString(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs new file mode 100644 index 0000000000000000000000000000000000000000..a41b284f5682578aca6067182f08b1d2f3ef8249 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -0,0 +1,1413 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Base class for all variable commands. + /// Because -Scope is defined in VariableCommandBase, all derived commands must implement -Scope. + /// + public abstract class VariableCommandBase : PSCmdlet + { + #region Parameters + + /// + /// Selects active scope to work with; used for all variable commands. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + #endregion parameters + + /// + /// The Include parameter for all the variable commands. + /// + protected string[] IncludeFilters + { + get + { + return _include; + } + + set + { + value ??= Array.Empty(); + + _include = value; + } + } + + private string[] _include = Array.Empty(); + + /// + /// The Exclude parameter for all the variable commands. + /// + protected string[] ExcludeFilters + { + get + { + return _exclude; + } + + set + { + value ??= Array.Empty(); + + _exclude = value; + } + } + + private string[] _exclude = Array.Empty(); + + #region helpers + + /// + /// Gets the matching variable for the specified name, using the + /// Include, Exclude, and Scope parameters defined in the base class. + /// + /// + /// The name or pattern of the variables to retrieve. + /// + /// + /// The scope to do the lookup in. If null or empty the normal scoping rules apply. + /// + /// + /// True is returned if a variable exists of the given name but was filtered + /// out via globbing, include, or exclude. + /// + /// + /// If true, don't report errors when trying to access private variables. + /// + /// + /// A collection of the variables matching the name, include, and exclude + /// pattern in the specified scope. + /// + internal List GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet) + { + wasFiltered = false; + + List result = new(); + + if (string.IsNullOrEmpty(name)) + { + name = "*"; + } + + bool nameContainsWildcard = WildcardPattern.ContainsWildcardCharacters(name); + + // Now create the filters + + WildcardPattern nameFilter = + WildcardPattern.Get( + name, + WildcardOptions.IgnoreCase); + + Collection includeFilters = + SessionStateUtilities.CreateWildcardsFromStrings( + _include, + WildcardOptions.IgnoreCase); + + Collection excludeFilters = + SessionStateUtilities.CreateWildcardsFromStrings( + _exclude, + WildcardOptions.IgnoreCase); + + if (!nameContainsWildcard) + { + // Filter the name here against the include and exclude so that + // we can report if the name was filtered vs. there being no + // variable existing of that name. + + bool isIncludeMatch = + SessionStateUtilities.MatchesAnyWildcardPattern( + name, + includeFilters, + true); + + bool isExcludeMatch = + SessionStateUtilities.MatchesAnyWildcardPattern( + name, + excludeFilters, + false); + + if (!isIncludeMatch || isExcludeMatch) + { + wasFiltered = true; + return result; + } + } + + // First get the appropriate view of the variables. If no scope + // is specified, flatten all scopes to produce a currently active + // view. + + IDictionary variableTable = null; + if (string.IsNullOrEmpty(lookupScope)) + { + variableTable = SessionState.Internal.GetVariableTable(); + } + else + { + variableTable = SessionState.Internal.GetVariableTableAtScope(lookupScope); + } + + CommandOrigin origin = MyInvocation.CommandOrigin; + foreach (KeyValuePair entry in variableTable) + { + bool isNameMatch = nameFilter.IsMatch(entry.Key); + bool isIncludeMatch = + SessionStateUtilities.MatchesAnyWildcardPattern( + entry.Key, + includeFilters, + true); + + bool isExcludeMatch = + SessionStateUtilities.MatchesAnyWildcardPattern( + entry.Key, + excludeFilters, + false); + + if (isNameMatch) + { + if (isIncludeMatch && !isExcludeMatch) + { + // See if the variable is visible + if (!SessionState.IsVisible(origin, entry.Value)) + { + // In quiet mode, don't report private variable accesses unless they are specific matches... + if (quiet || nameContainsWildcard) + { + wasFiltered = true; + continue; + } + else + { + // Generate an error for elements that aren't visible... + try + { + SessionState.ThrowIfNotVisible(origin, entry.Value); + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + // Only report the error once... + wasFiltered = true; + continue; + } + } + } + + result.Add(entry.Value); + } + else + { + wasFiltered = true; + } + } + else + { + if (nameContainsWildcard) + { + wasFiltered = true; + } + } + } + + return result; + } + #endregion helpers + + } + + /// + /// Implements get-variable command. + /// + [Cmdlet(VerbsCommon.Get, "Variable", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096711")] + [OutputType(typeof(PSVariable))] + public class GetVariableCommand : VariableCommandBase + { + #region parameters + + /// + /// Name of the PSVariable. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty()] + public string[] Name + { + get + { + return _name; + } + + set + { + value ??= new string[] { "*" }; + + _name = value; + } + } + + private string[] _name = new string[] { "*" }; + + /// + /// Output only the value(s) of the requested variable(s). + /// + [Parameter] + public SwitchParameter ValueOnly + { + get + { + return _valueOnly; + } + + set + { + _valueOnly = value; + } + } + + private bool _valueOnly; + + /// + /// The Include parameter for all the variable commands. + /// + [Parameter] + public string[] Include + { + get + { + return IncludeFilters; + } + + set + { + IncludeFilters = value; + } + } + + /// + /// The Exclude parameter for all the variable commands. + /// + [Parameter] + public string[] Exclude + { + get + { + return ExcludeFilters; + } + + set + { + ExcludeFilters = value; + } + } + + #endregion parameters + + /// + /// Implements ProcessRecord() method for get-variable's command. + /// + protected override void ProcessRecord() + { + foreach (string varName in _name) + { + bool wasFiltered = false; + List matchingVariables = + GetMatchingVariables(varName, Scope, out wasFiltered, /*quiet*/ false); + + matchingVariables.Sort( + static (PSVariable left, PSVariable right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)); + + bool matchFound = false; + foreach (PSVariable matchingVariable in matchingVariables) + { + matchFound = true; + if (_valueOnly) + { + WriteObject(matchingVariable.Value); + } + else + { + WriteObject(matchingVariable); + } + } + + if (!matchFound && !wasFiltered) + { + ItemNotFoundException itemNotFound = + new( + varName, + "VariableNotFound", + SessionStateStrings.VariableNotFound); + + WriteError( + new ErrorRecord( + itemNotFound.ErrorRecord, + itemNotFound)); + } + } + } + } + + /// + /// Class implementing new-variable command. + /// + [Cmdlet(VerbsCommon.New, "Variable", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097121")] + [OutputType(typeof(PSVariable))] + public sealed class NewVariableCommand : VariableCommandBase + { + #region parameters + + /// + /// Name of the PSVariable. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] + public string Name { get; set; } + + /// + /// Value of the PSVariable. + /// + [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public object Value { get; set; } + + /// + /// Description of the variable. + /// + [Parameter] + public string Description { get; set; } + + /// + /// The options for the variable to specify if the variable should + /// be ReadOnly, Constant, and/or Private. + /// + [Parameter] + public ScopedItemOptions Option { get; set; } = ScopedItemOptions.None; + + /// + /// Specifies the visibility of the new variable... + /// + [Parameter] + public SessionStateEntryVisibility Visibility + { + get + { + return (SessionStateEntryVisibility)_visibility; + } + + set + { + _visibility = value; + } + } + + private SessionStateEntryVisibility? _visibility; + + /// + /// Force the operation to make the best attempt at setting the variable. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// The variable object should be passed down the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThru; + } + + set + { + _passThru = value; + } + } + + private bool _passThru; + + #endregion parameters + + /// + /// Add objects received on the pipeline to an ArrayList of values, to + /// take the place of the Value parameter if none was specified on the + /// command line. + /// + protected override void ProcessRecord() + { + // If Force is not specified, see if the variable already exists + // in the specified scope. If the scope isn't specified, then + // check to see if it exists in the current scope. + + if (!Force) + { + PSVariable varFound = null; + if (string.IsNullOrEmpty(Scope)) + { + varFound = + SessionState.PSVariable.GetAtScope(Name, "local"); + } + else + { + varFound = + SessionState.PSVariable.GetAtScope(Name, Scope); + } + + if (varFound != null) + { + SessionStateException sessionStateException = + new( + Name, + SessionStateCategory.Variable, + "VariableAlreadyExists", + SessionStateStrings.VariableAlreadyExists, + ErrorCategory.ResourceExists); + + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + return; + } + } + + // Since the variable doesn't exist or -Force was specified, + // Call should process to validate the set with the user. + + string action = VariableCommandStrings.NewVariableAction; + + string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, Name, Value); + + if (ShouldProcess(target, action)) + { + PSVariable newVariable = new(Name, Value, Option); + + if (_visibility != null) + { + newVariable.Visibility = (SessionStateEntryVisibility)_visibility; + } + + if (Description != null) + { + newVariable.Description = Description; + } + + try + { + if (string.IsNullOrEmpty(Scope)) + { + SessionState.Internal.NewVariable(newVariable, Force); + } + else + { + SessionState.Internal.NewVariableAtScope(newVariable, Scope, Force); + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + return; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + return; + } + + if (_passThru) + { + WriteObject(newVariable); + } + } + } + } + + /// + /// This class implements set-variable command. + /// + [Cmdlet(VerbsCommon.Set, "Variable", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096624")] + [OutputType(typeof(PSVariable))] + public sealed class SetVariableCommand : VariableCommandBase + { + #region parameters + + /// + /// Name of the PSVariable(s) to set. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] + public string[] Name { get; set; } + + /// + /// Value of the PSVariable. + /// + [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public object Value { get; set; } = AutomationNull.Value; + + /// + /// The Include parameter for all the variable commands. + /// + [Parameter] + public string[] Include + { + get + { + return IncludeFilters; + } + + set + { + IncludeFilters = value; + } + } + + /// + /// The Exclude parameter for all the variable commands. + /// + [Parameter] + public string[] Exclude + { + get + { + return ExcludeFilters; + } + + set + { + ExcludeFilters = value; + } + } + + /// + /// Description of the variable. + /// + [Parameter] + public string Description { get; set; } + + /// + /// The options for the variable to specify if the variable should + /// be ReadOnly, Constant, and/or Private. + /// + [Parameter] + public ScopedItemOptions Option + { + get + { + return (ScopedItemOptions)_options; + } + + set + { + _options = value; + } + } + + private ScopedItemOptions? _options; + + /// + /// Force the operation to make the best attempt at setting the variable. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// Sets the visibility of the variable... + /// + [Parameter] + public SessionStateEntryVisibility Visibility + { + get + { + return (SessionStateEntryVisibility)_visibility; + } + + set + { + _visibility = value; + } + } + + private SessionStateEntryVisibility? _visibility; + + /// + /// The variable object should be passed down the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThru; + } + + set + { + _passThru = value; + } + } + + private bool _passThru; + + /// + /// Gets whether we will append to the variable if it exists. + /// + [Parameter] + public SwitchParameter Append { get; set; } + + private bool _nameIsFormalParameter; + private bool _valueIsFormalParameter; + #endregion parameters + + /// + /// Checks to see if the name and value parameters were bound as formal parameters. + /// + protected override void BeginProcessing() + { + if (Name != null && Name.Length > 0) + { + _nameIsFormalParameter = true; + } + + if (Value != AutomationNull.Value) + { + _valueIsFormalParameter = true; + } + + if (Append) + { + // create the list here and add to it if it has a value + // but if they have more than one name, produce an error + if (Name.Length != 1) + { + ErrorRecord appendVariableError = new ErrorRecord(new InvalidOperationException(), "SetVariableAppend", ErrorCategory.InvalidOperation, Name); + appendVariableError.ErrorDetails = new ErrorDetails("SetVariableAppend"); + appendVariableError.ErrorDetails.RecommendedAction = VariableCommandStrings.UseSingleVariable; + ThrowTerminatingError(appendVariableError); + } + + _valueList = new List(); + var currentValue = Context.SessionState.PSVariable.Get(Name[0]); + if (currentValue is not null) + { + if (currentValue.Value is IList ilist) + { + _valueList.AddRange(ilist); + } + else + { + _valueList.Add(currentValue.Value); + } + } + } + } + + /// + /// If name and value are both specified as a formal parameters, then + /// just ignore the incoming objects in ProcessRecord. + /// If name is a formal parameter but the value is coming from the pipeline, + /// then accumulate the values in the valueList and set the variable during + /// EndProcessing(). + /// If name is not a formal parameter, then set + /// the variable each time ProcessRecord is called. + /// + protected override void ProcessRecord() + { + if (_nameIsFormalParameter && _valueIsFormalParameter) + { + if (Append) + { + if (Value != AutomationNull.Value) + { + _valueList ??= new List(); + + _valueList.Add(Value); + } + } + + return; + } + + if (_nameIsFormalParameter && !_valueIsFormalParameter) + { + if (Value != AutomationNull.Value) + { + _valueList ??= new List(); + + _valueList.Add(Value); + } + } + else + { + SetVariable(Name, Value); + } + } + + private List _valueList; + + /// + /// Sets the variable if the name was specified as a formal parameter + /// but the value came from the pipeline. + /// + protected override void EndProcessing() + { + if (_nameIsFormalParameter) + { + if (_valueIsFormalParameter) + { + if (Append) + { + SetVariable(Name, _valueList); + } + else + { + SetVariable(Name, Value); + } + } + else + { + if (_valueList != null) + { + if (_valueList.Count == 1) + { + SetVariable(Name, _valueList[0]); + } + else if (_valueList.Count == 0) + { + SetVariable(Name, AutomationNull.Value); + } + else + { + SetVariable(Name, _valueList.ToArray()); + } + } + else + { + SetVariable(Name, AutomationNull.Value); + } + } + } + } + + /// + /// Sets the variables of the given names to the specified value. + /// + /// + /// The name(s) of the variables to set. + /// + /// + /// The value to set the variable to. + /// + private void SetVariable(string[] varNames, object varValue) + { + CommandOrigin origin = MyInvocation.CommandOrigin; + + foreach (string varName in varNames) + { + // First look for existing variables to set. + + List matchingVariables = new(); + + bool wasFiltered = false; + + if (!string.IsNullOrEmpty(Scope)) + { + // We really only need to find matches if the scope was specified. + // If the scope wasn't specified then we need to create the + // variable in the local scope. + + matchingVariables = + GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); + } + else + { + // Since the scope wasn't specified, it doesn't matter if there + // is a variable in another scope, it only matters if there is a + // variable in the local scope. + + matchingVariables = + GetMatchingVariables( + varName, + System.Management.Automation.StringLiterals.Local, + out wasFiltered, + false); + } + + // We only want to create the variable if we are not filtering + // the name. + + if (matchingVariables.Count == 0 && + !wasFiltered) + { + try + { + ScopedItemOptions newOptions = ScopedItemOptions.None; + + if (!string.IsNullOrEmpty(Scope) && + string.Equals("private", Scope, StringComparison.OrdinalIgnoreCase)) + { + newOptions = ScopedItemOptions.Private; + } + + if (_options != null) + { + newOptions |= (ScopedItemOptions)_options; + } + + object newVarValue = varValue; + if (newVarValue == AutomationNull.Value) + { + newVarValue = null; + } + + PSVariable varToSet = + new( + varName, + newVarValue, + newOptions); + + Description ??= string.Empty; + + varToSet.Description = Description; + + // If visibility was specified, set it on the variable + if (_visibility != null) + { + varToSet.Visibility = Visibility; + } + + string action = VariableCommandStrings.SetVariableAction; + + string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, varName, newVarValue); + + if (ShouldProcess(target, action)) + { + object result = null; + + if (string.IsNullOrEmpty(Scope)) + { + result = + SessionState.Internal.SetVariable(varToSet, Force, origin); + } + else + { + result = + SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin); + } + + if (_passThru && result != null) + { + WriteObject(result); + } + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + continue; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + continue; + } + } + else + { + foreach (PSVariable matchingVariable in matchingVariables) + { + string action = VariableCommandStrings.SetVariableAction; + + string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, matchingVariable.Name, varValue); + + if (ShouldProcess(target, action)) + { + object result = null; + + try + { + // Since the variable existed in the specified scope, or + // in the local scope if no scope was specified, use + // the reference returned to set the variable properties. + + // If we want to force setting over a readonly variable + // we have to temporarily mark the variable writable. + + bool wasReadOnly = false; + if (Force && + (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0) + { + matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true); + wasReadOnly = true; + } + + // Now change the value, options, or description + // and set the variable + + if (varValue != AutomationNull.Value) + { + matchingVariable.Value = varValue; + + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + { + // In 'ConstrainedLanguage' we want to monitor untrusted values assigned to 'Global:' variables + // and 'Script:' variables, because they may be set from 'ConstrainedLanguage' environment and + // referenced within trusted script block, and thus result in security issues. + // Here we are setting the value of an existing variable and don't know what scope this variable + // is from, so we mark the value as untrusted, regardless of the scope. + ExecutionContext.MarkObjectAsUntrusted(matchingVariable.Value); + } + } + + if (Description != null) + { + matchingVariable.Description = Description; + } + + if (_options != null) + { + matchingVariable.Options = (ScopedItemOptions)_options; + } + else + { + if (wasReadOnly) + { + matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true); + } + } + + // If visibility was specified, set it on the variable + if (_visibility != null) + { + matchingVariable.Visibility = Visibility; + } + + result = matchingVariable; + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + continue; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + continue; + } + + if (_passThru && result != null) + { + WriteObject(result); + } + } + } + } + } + } + } + + /// + /// The Remove-Variable cmdlet implementation. + /// + [Cmdlet(VerbsCommon.Remove, "Variable", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097123")] + public sealed class RemoveVariableCommand : VariableCommandBase + { + #region parameters + + /// + /// Name of the PSVariable(s) to set. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] + public string[] Name { get; set; } + + /// + /// The Include parameter for all the variable commands. + /// + [Parameter] + public string[] Include + { + get + { + return IncludeFilters; + } + + set + { + IncludeFilters = value; + } + } + + /// + /// The Exclude parameter for all the variable commands. + /// + [Parameter] + public string[] Exclude + { + get + { + return ExcludeFilters; + } + + set + { + ExcludeFilters = value; + } + } + + /// + /// If true, the variable is removed even if it is ReadOnly. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + #endregion parameters + + /// + /// Removes the matching variables from the specified scope. + /// + protected override void ProcessRecord() + { + // Removal of variables only happens in the local scope if the + // scope wasn't explicitly specified by the user. + + Scope ??= "local"; + + foreach (string varName in Name) + { + // First look for existing variables to set. + bool wasFiltered = false; + + List matchingVariables = + GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); + + if (matchingVariables.Count == 0 && !wasFiltered) + { + // Since the variable wasn't found and no glob + // characters were specified, write an error. + + ItemNotFoundException itemNotFound = + new( + varName, + "VariableNotFound", + SessionStateStrings.VariableNotFound); + + WriteError( + new ErrorRecord( + itemNotFound.ErrorRecord, + itemNotFound)); + + continue; + } + + foreach (PSVariable matchingVariable in matchingVariables) + { + // Since the variable doesn't exist or -Force was specified, + // Call should process to validate the set with the user. + + string action = VariableCommandStrings.RemoveVariableAction; + + string target = StringUtil.Format(VariableCommandStrings.RemoveVariableTarget, matchingVariable.Name); + + if (ShouldProcess(target, action)) + { + try + { + if (string.IsNullOrEmpty(Scope)) + { + SessionState.Internal.RemoveVariable(matchingVariable, _force); + } + else + { + SessionState.Internal.RemoveVariableAtScope(matchingVariable, Scope, _force); + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + } + } + } + } + } + } + + /// + /// This class implements set-variable command. + /// + [Cmdlet(VerbsCommon.Clear, "Variable", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096923")] + [OutputType(typeof(PSVariable))] + public sealed class ClearVariableCommand : VariableCommandBase + { + #region parameters + + /// + /// Name of the PSVariable(s) to set. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] + public string[] Name { get; set; } + + /// + /// The Include parameter for all the variable commands. + /// + [Parameter] + public string[] Include + { + get + { + return IncludeFilters; + } + + set + { + IncludeFilters = value; + } + } + + /// + /// The Exclude parameter for all the variable commands. + /// + [Parameter] + public string[] Exclude + { + get + { + return ExcludeFilters; + } + + set + { + ExcludeFilters = value; + } + } + + /// + /// Force the operation to make the best attempt at clearing the variable. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// The variable object should be passed down the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThru; + } + + set + { + _passThru = value; + } + } + + private bool _passThru; + + #endregion parameters + + /// + /// The implementation of the Clear-Variable command. + /// + protected override void ProcessRecord() + { + foreach (string varName in Name) + { + bool wasFiltered = false; + + List matchingVariables = + GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); + + if (matchingVariables.Count == 0 && !wasFiltered) + { + // Since the variable wasn't found and no glob + // characters were specified, write an error. + + ItemNotFoundException itemNotFound = + new( + varName, + "VariableNotFound", + SessionStateStrings.VariableNotFound); + + WriteError( + new ErrorRecord( + itemNotFound.ErrorRecord, + itemNotFound)); + + continue; + } + + foreach (PSVariable matchingVariable in matchingVariables) + { + // Since the variable doesn't exist or -Force was specified, + // Call should process to validate the set with the user. + + string action = VariableCommandStrings.ClearVariableAction; + + string target = StringUtil.Format(VariableCommandStrings.ClearVariableTarget, matchingVariable.Name); + + if (ShouldProcess(target, action)) + { + PSVariable result = matchingVariable; + + try + { + if (_force && + (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0) + { + // Remove the ReadOnly bit to set the value and then reapply + + matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true); + + result = ClearValue(matchingVariable); + + matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true); + } + else + { + result = ClearValue(matchingVariable); + } + } + catch (SessionStateException sessionStateException) + { + WriteError( + new ErrorRecord( + sessionStateException.ErrorRecord, + sessionStateException)); + continue; + } + catch (PSArgumentException argException) + { + WriteError( + new ErrorRecord( + argException.ErrorRecord, + argException)); + continue; + } + + if (_passThru) + { + WriteObject(result); + } + } + } + } + } + + /// + /// Clears the value of the variable using the PSVariable instance if the scope + /// was specified or using standard variable lookup if the scope was not specified. + /// + /// + /// The variable that matched the name parameter(s). + /// + private PSVariable ClearValue(PSVariable matchingVariable) + { + PSVariable result = matchingVariable; + if (Scope != null) + { + matchingVariable.Value = null; + } + else + { + SessionState.PSVariable.Set(matchingVariable.Name, null); + result = SessionState.PSVariable.Get(matchingVariable.Name); + } + + return result; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..3c4336f07d05c8968cfdfb572f3587cc027957fa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Waits for a given event to arrive. + /// + [Cmdlet(VerbsLifecycle.Wait, "Event", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097042")] + [OutputType(typeof(PSEventArgs))] + public class WaitEventCommand : PSCmdlet + { + #region parameters + + /// + /// An identifier for this event subscription. + /// + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] + public string SourceIdentifier + { + get + { + return _sourceIdentifier; + } + + set + { + _sourceIdentifier = value; + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + } + } + + private string _sourceIdentifier = null; + + /// + /// If timeout is specified, the cmdlet will only wait for this number of seconds. + /// Value of -1 means never timeout. + /// + [Parameter] + [Alias("TimeoutSec")] + [ValidateRange(-1, int.MaxValue)] + public int Timeout + { + get + { + return _timeoutInSeconds; + } + + set + { + _timeoutInSeconds = value; + } + } + + private int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. + + #endregion parameters + + private readonly AutoResetEvent _eventArrived = new(false); + private PSEventArgs _receivedEvent = null; + private readonly object _receivedEventLock = new(); + private WildcardPattern _matchPattern; + + /// + /// Wait for the event to arrive. + /// + protected override void ProcessRecord() + { + DateTime startTime = DateTime.UtcNow; + + // Subscribe to notification of events received + Events.ReceivedEvents.PSEventReceived += ReceivedEvents_PSEventReceived; + bool received = false; + + // Scan the queue to see if it's already arrived + ScanEventQueue(); + + // And wait for our event handler (or Control-C processor) to give us control + PSLocalEventManager eventManager = (PSLocalEventManager)Events; + + while (!received) + { + if (_timeoutInSeconds >= 0) + { + if ((DateTime.UtcNow - startTime).TotalSeconds > _timeoutInSeconds) + break; + } + + received = _eventArrived.WaitOne(200); + + eventManager.ProcessPendingActions(); + } + + // Unsubscribe, and write the event information we received + Events.ReceivedEvents.PSEventReceived -= ReceivedEvents_PSEventReceived; + + if (_receivedEvent != null) + { + WriteObject(_receivedEvent); + } + } + + /// + /// Handle Control-C. + /// + protected override void StopProcessing() + { + _eventArrived.Set(); + } + + private void ReceivedEvents_PSEventReceived(object sender, PSEventArgs e) + { + // If they want to wait on just any event + if (_sourceIdentifier == null) + { + NotifyEvent(e); + } + // They are waiting on a specific one + else + { + ScanEventQueue(); + } + } + + // Go through all the received events. If one matches the subscription identifier, + // break. + private void ScanEventQueue() + { + lock (Events.ReceivedEvents.SyncRoot) + { + foreach (PSEventArgs eventArg in Events.ReceivedEvents) + { + // If they specified a subscription identifier and we don't match, continue + if ((_matchPattern == null) || (_matchPattern.IsMatch(eventArg.SourceIdentifier))) + { + NotifyEvent(eventArg); + return; + } + } + } + } + + // Notify that an event has arrived + private void NotifyEvent(PSEventArgs e) + { + if (_receivedEvent == null) + { + lock (_receivedEventLock) + { + if (_receivedEvent == null) + { + _receivedEvent = e; + _eventArrived.Set(); + } + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs new file mode 100644 index 0000000000000000000000000000000000000000..ea650e80e677e740101fff88307bfa68b5c1c163 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Response object for html content without DOM parsing. + /// + public class BasicHtmlWebResponseObject : WebResponseObject + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The response. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// Cancellation token. + public BasicHtmlWebResponseObject(HttpResponseMessage response, TimeSpan perReadTimeout, CancellationToken cancellationToken) : this(response, null, perReadTimeout, cancellationToken) { } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// The response. + /// The content stream associated with the response. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// Cancellation token. + public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream? contentStream, TimeSpan perReadTimeout, CancellationToken cancellationToken) : base(response, contentStream, perReadTimeout, cancellationToken) + { + InitializeContent(cancellationToken); + InitializeRawContent(response); + } + + #endregion Constructors + + #region Properties + + /// + /// Gets the text body content of this response. + /// + /// + /// Content of the response body, decoded using , + /// if the Content-Type response header is a recognized text + /// type. Otherwise . + /// + public new string Content { get; private set; } + + /// + /// Gets the encoding of the text body content of this response. + /// + /// + /// Encoding of the response body from the Content-Type header, + /// or if the encoding could not be determined. + /// + public Encoding? Encoding { get; private set; } + + private WebCmdletElementCollection? _inputFields; + + /// + /// Gets the HTML input field elements parsed from . + /// + public WebCmdletElementCollection InputFields + { + get + { + if (_inputFields == null) + { + List parsedFields = new(); + MatchCollection fieldMatch = HtmlParser.InputFieldRegex.Matches(Content); + foreach (Match match in fieldMatch) + { + parsedFields.Add(CreateHtmlObject(match.Value, "INPUT")); + } + + _inputFields = new WebCmdletElementCollection(parsedFields); + } + + return _inputFields; + } + } + + private WebCmdletElementCollection? _links; + + /// + /// Gets the HTML a link elements parsed from . + /// + public WebCmdletElementCollection Links + { + get + { + if (_links == null) + { + List parsedLinks = new(); + MatchCollection linkMatch = HtmlParser.LinkRegex.Matches(Content); + foreach (Match link in linkMatch) + { + parsedLinks.Add(CreateHtmlObject(link.Value, "A")); + } + + _links = new WebCmdletElementCollection(parsedLinks); + } + + return _links; + } + } + + private WebCmdletElementCollection? _images; + + /// + /// Gets the HTML img elements parsed from . + /// + public WebCmdletElementCollection Images + { + get + { + if (_images == null) + { + List parsedImages = new(); + MatchCollection imageMatch = HtmlParser.ImageRegex.Matches(Content); + foreach (Match image in imageMatch) + { + parsedImages.Add(CreateHtmlObject(image.Value, "IMG")); + } + + _images = new WebCmdletElementCollection(parsedImages); + } + + return _images; + } + } + + #endregion Properties + + #region Methods + + /// + /// Reads the response content from the web response. + /// + /// The cancellation token. + [MemberNotNull(nameof(Content))] + protected void InitializeContent(CancellationToken cancellationToken) + { + string? contentType = ContentHelper.GetContentType(BaseResponse); + if (ContentHelper.IsText(contentType)) + { + // Fill the Content buffer + string? characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); + + Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding, perReadTimeout, cancellationToken); + Encoding = encoding; + } + else + { + Content = string.Empty; + } + } + + private static PSObject CreateHtmlObject(string html, string tagName) + { + PSObject elementObject = new(); + + elementObject.Properties.Add(new PSNoteProperty("outerHTML", html)); + elementObject.Properties.Add(new PSNoteProperty("tagName", tagName)); + + ParseAttributes(html, elementObject); + + return elementObject; + } + + private void InitializeRawContent(HttpResponseMessage baseResponse) + { + StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); + raw.Append(Content); + RawContent = raw.ToString(); + } + + private static void ParseAttributes(string outerHtml, PSObject elementObject) + { + // We might get an empty input for a directive from the HTML file + if (!string.IsNullOrEmpty(outerHtml)) + { + // Extract just the opening tag of the HTML element (omitting the closing tag and any contents, + // including contained HTML elements) + Match match = HtmlParser.TagRegex.Match(outerHtml); + + // Extract all the attribute specifications within the HTML element opening tag + MatchCollection attribMatches = HtmlParser.AttribsRegex.Matches(match.Value); + + foreach (Match attribMatch in attribMatches) + { + // Extract the name and value for this attribute (allowing for variations like single/double/no + // quotes, and no value at all) + Match nvMatches = HtmlParser.AttribNameValueRegex.Match(attribMatch.Value); + Debug.Assert(nvMatches.Groups.Count == 5); + + // Name is always captured by group #1 + string name = nvMatches.Groups[1].Value; + + // The value (if any) is captured by group #2, #3, or #4, depending on quoting or lack thereof + string? value = null; + if (nvMatches.Groups[2].Success) + { + value = nvMatches.Groups[2].Value; + } + else if (nvMatches.Groups[3].Success) + { + value = nvMatches.Groups[3].Value; + } + else if (nvMatches.Groups[4].Success) + { + value = nvMatches.Groups[4].Value; + } + + elementObject.Properties.Add(new PSNoteProperty(name, value)); + } + } + } + + #endregion Methods + + // This class is needed so the static Regexes are initialized only the first time they are used + private static class HtmlParser + { + internal static readonly Regex AttribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex AttribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex ImageRegex = new Regex(@"]*?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex InputFieldRegex = new Regex(@"]*(/?>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex LinkRegex = new Regex(@"]*(/>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex TagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs new file mode 100644 index 0000000000000000000000000000000000000000..9eca5ce187a755bbe3b8a66610ead6d3f13e4440 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using Humanizer; +using Microsoft.Win32; + +namespace Microsoft.PowerShell.Commands +{ + internal static class ContentHelper + { + #region Internal Methods + + // ContentType may not exist in response header. Return null if not. + internal static string? GetContentType(HttpResponseMessage response) => response.Content.Headers.ContentType?.MediaType; + + internal static string? GetContentType(HttpRequestMessage request) => request.Content?.Headers.ContentType?.MediaType; + + internal static Encoding GetDefaultEncoding() => Encoding.UTF8; + + internal static string GetFriendlyContentLength(long? length) => + length.HasValue + ? $"{length.Value.Bytes().Humanize()} ({length.Value:#,0} bytes)" + : "unknown size"; + + internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) + { + StringBuilder raw = new(); + + string protocol = WebResponseHelper.GetProtocol(response); + if (!string.IsNullOrEmpty(protocol)) + { + int statusCode = WebResponseHelper.GetStatusCode(response); + string statusDescription = WebResponseHelper.GetStatusDescription(response); + raw.AppendLine($"{protocol} {statusCode} {statusDescription}"); + } + + HttpHeaders[] headerCollections = + { + response.Headers, + response.Content.Headers + }; + + foreach (var headerCollection in headerCollections) + { + if (headerCollection == null) + { + continue; + } + + foreach (var header in headerCollection) + { + // Headers may have multiple entries with different values + foreach (string headerValue in header.Value) + { + raw.AppendLine($"{header.Key}: {headerValue}"); + } + } + } + + raw.AppendLine(); + return raw; + } + + internal static bool IsJson([NotNullWhen(true)] string? contentType) + { + if (string.IsNullOrEmpty(contentType)) + { + return false; + } + + // The correct type for JSON content, as specified in RFC 4627 + bool isJson = contentType.Equals("application/json", StringComparison.OrdinalIgnoreCase); + + // Add in these other "javascript" related types that + // sometimes get sent down as the mime type for JSON content + isJson |= contentType.Equals("text/json", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/x-javascript", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("text/x-javascript", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/javascript", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("text/javascript", StringComparison.OrdinalIgnoreCase); + + return isJson; + } + + internal static bool IsText([NotNullWhen(true)] string? contentType) + { + if (string.IsNullOrEmpty(contentType)) + { + return false; + } + + // Any text, xml or json types are text + bool isText = contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) + || IsXml(contentType) + || IsJson(contentType); + + // Further content type analysis is available on Windows + if (Platform.IsWindows && !isText) + { + // Media types registered with Windows as having a perceived type of text, are text + using (RegistryKey? contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType)) + { + if (contentTypeKey != null) + { + if (contentTypeKey.GetValue("Extension") is string extension) + { + using (RegistryKey? extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) + { + if (extensionKey != null) + { + string? perceivedType = extensionKey.GetValue("PerceivedType") as string; + isText = perceivedType == "text"; + } + } + } + } + } + } + + return isText; + } + + internal static bool IsXml([NotNullWhen(true)] string? contentType) + { + if (string.IsNullOrEmpty(contentType)) + { + return false; + } + + // RFC 3023: Media types with the suffix "+xml" are XML + bool isXml = contentType.Equals("application/xml", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/xml-external-parsed-entity", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/xml-dtd", StringComparison.OrdinalIgnoreCase) + || contentType.EndsWith("+xml", StringComparison.OrdinalIgnoreCase); + + return isXml; + } + + internal static bool IsTextBasedContentType([NotNullWhen(true)] string? contentType) + => IsText(contentType) || IsJson(contentType) || IsXml(contentType); + + #endregion Internal Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HttpVersionCompletionsAttribute.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HttpVersionCompletionsAttribute.cs new file mode 100644 index 0000000000000000000000000000000000000000..903ff4d8f80bbcfb49ea69fd471e823b2ad55b3f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HttpVersionCompletionsAttribute.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Net; +using System.Reflection; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A completer for HTTP version names. + /// + internal sealed class HttpVersionCompletionsAttribute : ArgumentCompletionsAttribute + { + public static readonly string[] AllowedVersions; + + static HttpVersionCompletionsAttribute() + { + FieldInfo[] fields = typeof(HttpVersion).GetFields(BindingFlags.Static | BindingFlags.Public); + + var versions = new List(fields.Length - 1); + + for (int i = 0; i < fields.Length; i++) + { + // skip field Unknown and not Version type + if (fields[i].Name == nameof(HttpVersion.Unknown) || fields[i].FieldType != typeof(Version)) + { + continue; + } + + var version = (Version?)fields[i].GetValue(null); + + if (version is not null) + { + versions.Add(version.ToString()); + } + } + + AllowedVersions = versions.ToArray(); + } + + /// + public HttpVersionCompletionsAttribute() : base(AllowedVersions) + { + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs new file mode 100644 index 0000000000000000000000000000000000000000..22ffaef288cd8119785a1986964c7bfa0bb1259b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -0,0 +1,456 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Xml; + +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Invoke-RestMethod command + /// This command makes an HTTP or HTTPS request to a web service, + /// and returns the response in an appropriate way. + /// Intended to work against the wide spectrum of "RESTful" web services + /// currently deployed across the web. + /// + [Cmdlet(VerbsLifecycle.Invoke, "RestMethod", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096706", DefaultParameterSetName = "StandardMethod")] + public class InvokeRestMethodCommand : WebRequestPSCmdlet + { + #region Parameters + + /// + /// Enable automatic following of rel links. + /// + [Parameter] + [Alias("FL")] + public SwitchParameter FollowRelLink + { + get => base._followRelLink; + + set => base._followRelLink = value; + } + + /// + /// Gets or sets the maximum number of rel links to follow. + /// + [Parameter] + [Alias("ML")] + [ValidateRange(1, int.MaxValue)] + public int MaximumFollowRelLink + { + get => base._maximumFollowRelLink; + + set => base._maximumFollowRelLink = value; + } + + /// + /// Gets or sets the ResponseHeadersVariable property. + /// + [Parameter] + [Alias("RHV")] + public string? ResponseHeadersVariable { get; set; } + + /// + /// Gets or sets the variable name to use for storing the status code from the response. + /// + [Parameter] + public string? StatusCodeVariable { get; set; } + + #endregion Parameters + + #region Virtual Method Overrides + + /// + /// Process the web response and output corresponding objects. + /// + /// + internal override void ProcessResponse(HttpResponseMessage response) + { + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(_cancelToken); + + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); + Stream responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); + + if (ShouldWriteToPipeline) + { + responseStream = new BufferingStreamReader(responseStream, perReadTimeout, _cancelToken.Token); + + // First see if it is an RSS / ATOM feed, in which case we can + // stream it - unless the user has overridden it with a return type of "XML" + if (TryProcessFeedStream(responseStream)) + { + // Do nothing, content has been processed. + } + else + { + // Try to get the response encoding from the ContentType header. + string? characterSet = WebResponseHelper.GetCharacterSet(response); + string str = StreamHelper.DecodeStream(responseStream, characterSet, out Encoding encoding, perReadTimeout, _cancelToken.Token); + + string friendlyName = "unknown"; + string encodingWebName = "unknown"; + string encodingPage = encoding.CodePage == -1 ? "unknown" : encoding.CodePage.ToString(); + try + { + // NOTE: These are getter methods that may possibly throw a NotSupportedException exception, + // hence the try/catch + encodingWebName = encoding.WebName; + friendlyName = encoding.EncodingName; + } + catch + { + } + + // NOTE: Tests use this debug output to verify the encoding. + WriteDebug($"WebResponse content encoding: {encodingWebName} ({friendlyName}) CodePage: {encodingPage}"); + + // Determine the response type + RestReturnType returnType = CheckReturnType(response); + + bool convertSuccess = false; + object? obj = null; + Exception? ex = null; + + if (returnType == RestReturnType.Json) + { + convertSuccess = TryConvertToJson(str, out obj, ref ex) || TryConvertToXml(str, out obj, ref ex); + } + // Default to try xml first since it's more common + else + { + convertSuccess = TryConvertToXml(str, out obj, ref ex) || TryConvertToJson(str, out obj, ref ex); + } + + if (!convertSuccess) + { + // Fallback to string + obj = str; + } + + WriteObject(obj); + } + + responseStream.Position = 0; + } + + if (ShouldSaveToOutFile) + { + string outFilePath = WebResponseHelper.GetOutFilePath(response, _qualifiedOutFile); + + WriteVerbose($"File Name: {Path.GetFileName(outFilePath)}"); + + StreamHelper.SaveStreamToFile(responseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), perReadTimeout, _cancelToken.Token); + } + + if (!string.IsNullOrEmpty(StatusCodeVariable)) + { + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(StatusCodeVariable, (int)response.StatusCode); + } + + if (!string.IsNullOrEmpty(ResponseHeadersVariable)) + { + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(ResponseHeadersVariable, WebResponseHelper.GetHeadersDictionary(response)); + } + } + + #endregion Virtual Method Overrides + + #region Helper Methods + + private static RestReturnType CheckReturnType(HttpResponseMessage response) + { + ArgumentNullException.ThrowIfNull(response); + + RestReturnType rt = RestReturnType.Detect; + string? contentType = ContentHelper.GetContentType(response); + + if (ContentHelper.IsJson(contentType)) + { + rt = RestReturnType.Json; + } + else if (ContentHelper.IsXml(contentType)) + { + rt = RestReturnType.Xml; + } + + return rt; + } + + private bool TryProcessFeedStream(Stream responseStream) + { + bool isRssOrFeed = false; + + try + { + XmlReaderSettings readerSettings = GetSecureXmlReaderSettings(); + XmlReader reader = XmlReader.Create(responseStream, readerSettings); + + // See if the reader contained an "RSS" or "Feed" in the first 10 elements (RSS and Feed are normally 2 or 3) + int readCount = 0; + while ((readCount < 10) && reader.Read()) + { + if (string.Equals("rss", reader.Name, StringComparison.OrdinalIgnoreCase) || + string.Equals("feed", reader.Name, StringComparison.OrdinalIgnoreCase)) + { + isRssOrFeed = true; + break; + } + + readCount++; + } + + if (isRssOrFeed) + { + XmlDocument workingDocument = new(); + + // Performing a Read() here to avoid rechecking + // "rss" or "feed" items + reader.Read(); + while (!reader.EOF) + { + // If node is Element and it's the 'Item' or 'Entry' node, emit that node. + if ((reader.NodeType == XmlNodeType.Element) && + (string.Equals("Item", reader.Name, StringComparison.OrdinalIgnoreCase) || + string.Equals("Entry", reader.Name, StringComparison.OrdinalIgnoreCase)) + ) + { + // This one will do reader.Read() internally + XmlNode? result = workingDocument.ReadNode(reader); + WriteObject(result); + } + else + { + reader.Read(); + } + } + } + } + catch (XmlException) + { + // Catch XmlException + } + finally + { + responseStream.Seek(0, SeekOrigin.Begin); + } + + return isRssOrFeed; + } + + // Mostly cribbed from Serialization.cs#GetXmlReaderSettingsForCliXml() + private static XmlReaderSettings GetSecureXmlReaderSettings() + { + XmlReaderSettings xrs = new(); + + xrs.CheckCharacters = false; + xrs.CloseInput = false; + + // The XML data needs to be in conformance to the rules for a well-formed XML 1.0 document. + xrs.IgnoreProcessingInstructions = true; + xrs.MaxCharactersFromEntities = 1024; + xrs.DtdProcessing = DtdProcessing.Ignore; + xrs.XmlResolver = null; + + return xrs; + } + + private static bool TryConvertToXml(string xml, [NotNullWhen(true)] out object? doc, ref Exception? exRef) + { + try + { + XmlReaderSettings settings = GetSecureXmlReaderSettings(); + XmlReader xmlReader = XmlReader.Create(new StringReader(xml), settings); + + XmlDocument xmlDoc = new(); + xmlDoc.PreserveWhitespace = true; + xmlDoc.Load(xmlReader); + + doc = xmlDoc; + } + catch (XmlException ex) + { + exRef = ex; + doc = null; + } + + return doc != null; + } + + private static bool TryConvertToJson(string json, [NotNullWhen(true)] out object? obj, ref Exception? exRef) + { + bool converted = false; + try + { + obj = JsonObject.ConvertFromJson(json, out ErrorRecord error); + + if (obj == null) + { + // This ensures that a null returned by ConvertFromJson() is the actual JSON null literal. + // if not, the ArgumentException will be caught. + JToken.Parse(json); + } + + if (error != null) + { + exRef = error.Exception; + obj = null; + } + else + { + converted = true; + } + } + catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException) + { + exRef = ex; + obj = null; + } + catch (JsonException ex) + { + string msg = string.Format(System.Globalization.CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, ex.Message); + exRef = new ArgumentException(msg, ex); + obj = null; + } + + return converted; + } + + #endregion Helper Methods + + /// + /// Enum for rest return type. + /// + public enum RestReturnType + { + /// + /// Return type not defined in response, + /// best effort detect. + /// + Detect, + + /// + /// Json return type. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + Json, + + /// + /// Xml return type. + /// + Xml, + } + + internal sealed class BufferingStreamReader : Stream + { + internal BufferingStreamReader(Stream baseStream, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + _baseStream = baseStream; + _streamBuffer = new MemoryStream(); + _length = long.MaxValue; + _copyBuffer = new byte[4096]; + _perReadTimeout = perReadTimeout; + _cancellationToken = cancellationToken; + } + + private readonly Stream _baseStream; + private readonly MemoryStream _streamBuffer; + private readonly byte[] _copyBuffer; + private readonly TimeSpan _perReadTimeout; + private readonly CancellationToken _cancellationToken; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override void Flush() + { + _streamBuffer.SetLength(0); + } + + public override long Length => _length; + + private long _length; + + public override long Position + { + get => _streamBuffer.Position; + + set => _streamBuffer.Position = value; + } + + public override int Read(byte[] buffer, int offset, int count) + { + long previousPosition = Position; + bool consumedStream = false; + int totalCount = count; + while (!consumedStream && (Position + totalCount) > _streamBuffer.Length) + { + // If we don't have enough data to fill this from memory, cache more. + // We try to read 4096 bytes from base stream every time, so at most we + // may cache 4095 bytes more than what is required by the Read operation. + int bytesRead = _baseStream.ReadAsync(_copyBuffer.AsMemory(), _perReadTimeout, _cancellationToken).GetAwaiter().GetResult(); + + if (_streamBuffer.Position < _streamBuffer.Length) + { + // Win8: 651902 no need to -1 here as Position refers to the place + // where we can start writing from. + _streamBuffer.Position = _streamBuffer.Length; + } + + _streamBuffer.Write(_copyBuffer, 0, bytesRead); + + totalCount -= bytesRead; + if (bytesRead < _copyBuffer.Length) + { + consumedStream = true; + } + } + + // Reset our backing store to its official position, as reading + // for the CopyTo updates the position. + _streamBuffer.Seek(previousPosition, SeekOrigin.Begin); + + // Read from the backing store into the requested buffer. + int read = _streamBuffer.Read(buffer, offset, count); + + if (read < count) + { + SetLength(Position); + } + + return read; + } + + public override long Seek(long offset, SeekOrigin origin) + { + return _streamBuffer.Seek(offset, origin); + } + + public override void SetLength(long value) + { + _length = value; + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs new file mode 100644 index 0000000000000000000000000000000000000000..f1a455974b95f1175d39d7b1d0d358431b2c9fbf --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -0,0 +1,2125 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Security; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The valid values for the -Authentication parameter for Invoke-RestMethod and Invoke-WebRequest. + /// + public enum WebAuthenticationType + { + /// + /// No authentication. Default. + /// + None, + + /// + /// RFC-7617 Basic Authentication. Requires -Credential. + /// + Basic, + + /// + /// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token. + /// + Bearer, + + /// + /// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token. + /// + OAuth, + } + + // WebSslProtocol is used because not all SslProtocols are supported by HttpClientHandler. + // Also SslProtocols.Default is not the "default" for HttpClientHandler as SslProtocols.Ssl3 is not supported. + /// + /// The valid values for the -SslProtocol parameter for Invoke-RestMethod and Invoke-WebRequest. + /// + [Flags] + public enum WebSslProtocol + { + /// + /// No SSL protocol will be set and the system defaults will be used. + /// + Default = SslProtocols.None, + + /// + /// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2. + /// + Tls = SslProtocols.Tls12, + + /// + /// Specifies the TLS 1.1 is obsolete. Using this value now defaults to TLS 1.2. + /// + Tls11 = SslProtocols.Tls12, + + /// + /// Specifies the TLS 1.2 security protocol. The TLS protocol is defined in IETF RFC 5246. + /// + Tls12 = SslProtocols.Tls12, + + /// + /// Specifies the TLS 1.3 security protocol. The TLS protocol is defined in IETF RFC 8446. + /// + Tls13 = SslProtocols.Tls13 + } + + /// + /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. + /// + public abstract class WebRequestPSCmdlet : PSCmdlet, IDisposable + { + #region Fields + + /// + /// Used to prefix the headers in debug and verbose messaging. + /// + internal const string DebugHeaderPrefix = "--- "; + + /// + /// Cancellation token source. + /// + internal CancellationTokenSource _cancelToken = null; + + /// + /// Automatically follow Rel Links. + /// + internal bool _followRelLink = false; + + /// + /// Maximum number of Rel Links to follow. + /// + internal int _maximumFollowRelLink = int.MaxValue; + + /// + /// Maximum number of Redirects to follow. + /// + internal int _maximumRedirection; + + /// + /// Parse Rel Links. + /// + internal bool _parseRelLink = false; + + /// + /// Automatically follow Rel Links. + /// + internal Dictionary _relationLink = null; + + /// + /// The current size of the local file being resumed. + /// + private long _resumeFileSize = 0; + + /// + /// The remote endpoint returned a 206 status code indicating successful resume. + /// + private bool _resumeSuccess = false; + + /// + /// True if the Dispose() method has already been called to cleanup Disposable fields. + /// + private bool _disposed = false; + + #endregion Fields + + #region Virtual Properties + + #region URI + + /// + /// Deprecated. Gets or sets UseBasicParsing. This has no affect on the operation of the Cmdlet. + /// + [Parameter(DontShow = true)] + public virtual SwitchParameter UseBasicParsing { get; set; } = true; + + /// + /// Gets or sets the Uri property. + /// + [Parameter(Position = 0, Mandatory = true)] + [ValidateNotNullOrEmpty] + public virtual Uri Uri { get; set; } + + #endregion URI + + #region HTTP Version + + /// + /// Gets or sets the HTTP Version property. + /// + [Parameter] + [ArgumentToVersionTransformation] + [HttpVersionCompletions] + public virtual Version HttpVersion { get; set; } + + #endregion HTTP Version + + #region Session + /// + /// Gets or sets the Session property. + /// + [Parameter] + public virtual WebRequestSession WebSession { get; set; } + + /// + /// Gets or sets the SessionVariable property. + /// + [Parameter] + [Alias("SV")] + public virtual string SessionVariable { get; set; } + + #endregion Session + + #region Authorization and Credentials + + /// + /// Gets or sets the AllowUnencryptedAuthentication property. + /// + [Parameter] + public virtual SwitchParameter AllowUnencryptedAuthentication { get; set; } + + /// + /// Gets or sets the Authentication property used to determine the Authentication method for the web session. + /// Authentication does not work with UseDefaultCredentials. + /// Authentication over unencrypted sessions requires AllowUnencryptedAuthentication. + /// Basic: Requires Credential. + /// OAuth/Bearer: Requires Token. + /// + [Parameter] + public virtual WebAuthenticationType Authentication { get; set; } = WebAuthenticationType.None; + + /// + /// Gets or sets the Credential property. + /// + [Parameter] + [Credential] + public virtual PSCredential Credential { get; set; } + + /// + /// Gets or sets the UseDefaultCredentials property. + /// + [Parameter] + public virtual SwitchParameter UseDefaultCredentials { get; set; } + + /// + /// Gets or sets the CertificateThumbprint property. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public virtual string CertificateThumbprint { get; set; } + + /// + /// Gets or sets the Certificate property. + /// + [Parameter] + [ValidateNotNull] + public virtual X509Certificate Certificate { get; set; } + + /// + /// Gets or sets the SkipCertificateCheck property. + /// + [Parameter] + public virtual SwitchParameter SkipCertificateCheck { get; set; } + + /// + /// Gets or sets the TLS/SSL protocol used by the Web Cmdlet. + /// + [Parameter] + public virtual WebSslProtocol SslProtocol { get; set; } = WebSslProtocol.Default; + + /// + /// Gets or sets the Token property. Token is required by Authentication OAuth and Bearer. + /// + [Parameter] + public virtual SecureString Token { get; set; } + + #endregion Authorization and Credentials + + #region Headers + + /// + /// Gets or sets the UserAgent property. + /// + [Parameter] + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the DisableKeepAlive property. + /// + [Parameter] + public virtual SwitchParameter DisableKeepAlive { get; set; } + + /// + /// Gets or sets the ConnectionTimeoutSeconds property. + /// + /// + /// This property applies to sending the request and receiving the response headers only. + /// + [Alias("TimeoutSec")] + [Parameter] + [ValidateRange(0, int.MaxValue)] + public virtual int ConnectionTimeoutSeconds { get; set; } + + /// + /// Gets or sets the OperationTimeoutSeconds property. + /// + /// + /// This property applies to each read operation when receiving the response body. + /// + [Parameter] + [ValidateRange(0, int.MaxValue)] + public virtual int OperationTimeoutSeconds { get; set; } + + /// + /// Gets or sets the Headers property. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Parameter] + public virtual IDictionary Headers { get; set; } + + /// + /// Gets or sets the SkipHeaderValidation property. + /// + /// + /// This property adds headers to the request's header collection without validation. + /// + [Parameter] + public virtual SwitchParameter SkipHeaderValidation { get; set; } + + #endregion Headers + + #region Redirect + + /// + /// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS. + /// + [Parameter] + public virtual SwitchParameter AllowInsecureRedirect { get; set; } + + /// + /// Gets or sets the RedirectMax property. + /// + [Parameter] + [ValidateRange(0, int.MaxValue)] + public virtual int MaximumRedirection { get; set; } = -1; + + /// + /// Gets or sets the MaximumRetryCount property, which determines the number of retries of a failed web request. + /// + [Parameter] + [ValidateRange(0, int.MaxValue)] + public virtual int MaximumRetryCount { get; set; } + + /// + /// Gets or sets the PreserveAuthorizationOnRedirect property. + /// + /// + /// This property overrides compatibility with web requests on Windows. + /// On FullCLR (WebRequest), authorization headers are stripped during redirect. + /// CoreCLR (HTTPClient) does not have this behavior so web requests that work on + /// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility, + /// we'll detect requests with an Authorization header and automatically strip + /// the header when the first redirect occurs. This switch turns off this logic for + /// edge cases where the authorization header needs to be preserved across redirects. + /// + [Parameter] + public virtual SwitchParameter PreserveAuthorizationOnRedirect { get; set; } + + /// + /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. + /// + [Parameter] + [ValidateRange(1, int.MaxValue)] + public virtual int RetryIntervalSec { get; set; } = 5; + + #endregion Redirect + + #region Method + + /// + /// Gets or sets the Method property. + /// + [Parameter(ParameterSetName = "StandardMethod")] + [Parameter(ParameterSetName = "StandardMethodNoProxy")] + public virtual WebRequestMethod Method { get; set; } = WebRequestMethod.Default; + + /// + /// Gets or sets the CustomMethod property. + /// + [Parameter(Mandatory = true, ParameterSetName = "CustomMethod")] + [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] + [Alias("CM")] + [ValidateNotNullOrEmpty] + public virtual string CustomMethod { get => _customMethod; set => _customMethod = value.ToUpperInvariant(); } + + private string _customMethod; + + /// + /// Gets or sets the PreserveHttpMethodOnRedirect property. + /// + [Parameter] + public virtual SwitchParameter PreserveHttpMethodOnRedirect { get; set; } + + /// + /// Gets or sets the UnixSocket property. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public virtual UnixDomainSocketEndPoint UnixSocket { get; set; } + + #endregion Method + + #region NoProxy + + /// + /// Gets or sets the NoProxy property. + /// + [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] + [Parameter(Mandatory = true, ParameterSetName = "StandardMethodNoProxy")] + public virtual SwitchParameter NoProxy { get; set; } + + #endregion NoProxy + + #region Proxy + + /// + /// Gets or sets the Proxy property. + /// + [Parameter(ParameterSetName = "StandardMethod")] + [Parameter(ParameterSetName = "CustomMethod")] + public virtual Uri Proxy { get; set; } + + /// + /// Gets or sets the ProxyCredential property. + /// + [Parameter(ParameterSetName = "StandardMethod")] + [Parameter(ParameterSetName = "CustomMethod")] + [Credential] + public virtual PSCredential ProxyCredential { get; set; } + + /// + /// Gets or sets the ProxyUseDefaultCredentials property. + /// + [Parameter(ParameterSetName = "StandardMethod")] + [Parameter(ParameterSetName = "CustomMethod")] + public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; } + + #endregion Proxy + + #region Input + + /// + /// Gets or sets the Body property. + /// + [Parameter(ValueFromPipeline = true)] + public virtual object Body { get; set; } + + /// + /// Dictionary for use with RFC-7578 multipart/form-data submissions. + /// Keys are form fields and their respective values are form values. + /// A value may be a collection of form values or single form value. + /// + [Parameter] + public virtual IDictionary Form { get; set; } + + /// + /// Gets or sets the ContentType property. + /// + [Parameter] + public virtual string ContentType { get; set; } + + /// + /// Gets or sets the TransferEncoding property. + /// + [Parameter] + [ValidateSet("chunked", "compress", "deflate", "gzip", "identity", IgnoreCase = true)] + public virtual string TransferEncoding { get; set; } + + /// + /// Gets or sets the InFile property. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public virtual string InFile { get; set; } + + /// + /// Keep the original file path after the resolved provider path is assigned to InFile. + /// + private string _originalFilePath; + + #endregion Input + + #region Output + + /// + /// Gets or sets the OutFile property. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public virtual string OutFile { get; set; } + + /// + /// Gets or sets the PassThrough property. + /// + [Parameter] + public virtual SwitchParameter PassThru { get; set; } + + /// + /// Resumes downloading a partial or incomplete file. OutFile is required. + /// + [Parameter] + public virtual SwitchParameter Resume { get; set; } + + /// + /// Gets or sets whether to skip checking HTTP status for error codes. + /// + [Parameter] + public virtual SwitchParameter SkipHttpErrorCheck { get; set; } + + #endregion Output + + #endregion Virtual Properties + + #region Helper Properties + + internal string QualifiedOutFile => QualifyFilePath(OutFile); + + internal string _qualifiedOutFile; + + internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; + + /// + /// Determines whether writing to a file should Resume and append rather than overwrite. + /// + internal bool ShouldResume => Resume.IsPresent && _resumeSuccess; + + internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile); + + internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru; + + #endregion Helper Properties + + #region Abstract Methods + + /// + /// Read the supplied WebResponse object and push the resulting output into the pipeline. + /// + /// Instance of a WebResponse object to be processed. + internal abstract void ProcessResponse(HttpResponseMessage response); + + #endregion Abstract Methods + + #region Overrides + + /// + /// The main execution method for cmdlets derived from WebRequestPSCmdlet. + /// + protected override void ProcessRecord() + { + try + { + // Set cmdlet context for write progress + ValidateParameters(); + PrepareSession(); + + // If the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, + // it needs to be stripped on the first redirect. + bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent + && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + + bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect || PreserveHttpMethodOnRedirect; + + HttpClient client = GetHttpClient(handleRedirect); + + int followedRelLink = 0; + Uri uri = Uri; + do + { + if (followedRelLink > 0) + { + string linkVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.FollowingRelLinkVerboseMsg, + uri.AbsoluteUri); + + WriteVerbose(linkVerboseMsg); + } + + using (HttpRequestMessage request = GetRequest(uri)) + { + FillRequestStream(request); + try + { + _maximumRedirection = WebSession.MaximumRedirection; + + using HttpResponseMessage response = GetResponse(client, request, handleRedirect); + + bool _isSuccess = response.IsSuccessStatusCode; + + // Check if the Resume range was not satisfiable because the file already completed downloading. + // This happens when the local file is the same size as the remote file. + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length == _resumeFileSize) + { + _isSuccess = true; + WriteVerbose(string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.OutFileWritingSkipped, + OutFile)); + + // Disable writing to the OutFile. + OutFile = null; + } + + // Detect insecure redirection. + if (!AllowInsecureRedirect) + { + // We will skip detection if either of the URIs is relative, because the 'Scheme' property is not supported on a relative URI. + // If we have to skip the check, an error may be thrown later if it's actually an insecure https-to-http redirect. + bool originIsHttps = response.RequestMessage.RequestUri.IsAbsoluteUri && response.RequestMessage.RequestUri.Scheme == "https"; + bool destinationIsHttp = response.Headers.Location is not null && response.Headers.Location.IsAbsoluteUri && response.Headers.Location.Scheme == "http"; + + if (originIsHttps && destinationIsHttp) + { + ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); + ThrowTerminatingError(er); + } + } + + if (ShouldCheckHttpStatus && !_isSuccess) + { + string message = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.ResponseStatusCodeFailure, + (int)response.StatusCode, + response.ReasonPhrase); + + HttpResponseException httpEx = new(message, response); + ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + string detailMsg = string.Empty; + try + { + string contentType = ContentHelper.GetContentType(response); + long? contentLength = response.Content.Headers.ContentLength; + + // We can't use ReadAsStringAsync because it doesn't have per read timeouts + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); + string characterSet = WebResponseHelper.GetCharacterSet(response); + var responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); + int initialCapacity = (int)Math.Min(contentLength ?? StreamHelper.DefaultReadBuffer, StreamHelper.DefaultReadBuffer); + var bufferedStream = new WebResponseContentMemoryStream(responseStream, initialCapacity, this, contentLength, perReadTimeout, _cancelToken.Token); + string error = StreamHelper.DecodeStream(bufferedStream, characterSet, out Encoding encoding, perReadTimeout, _cancelToken.Token); + detailMsg = FormatErrorMessage(error, contentType); + } + catch (Exception ex) + { + // Catch all + er.ErrorDetails = new ErrorDetails(ex.ToString()); + } + + if (!string.IsNullOrEmpty(detailMsg)) + { + er.ErrorDetails = new ErrorDetails(detailMsg); + } + + ThrowTerminatingError(er); + } + + if (_parseRelLink || _followRelLink) + { + ParseLinkHeader(response); + } + + ProcessResponse(response); + UpdateSession(response); + + // If we hit our maximum redirection count, generate an error. + // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are + // impossible to detect programmatically when we hit this limit. By handling this ourselves + // (and still writing out the result), users can debug actual HTTP redirect problems. + if (_maximumRedirection == 0 && IsRedirectCode(response.StatusCode)) + { + ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); + WriteError(er); + } + } + catch (TimeoutException ex) + { + ErrorRecord er = new(ex, "OperationTimeoutReached", ErrorCategory.OperationTimeout, null); + ThrowTerminatingError(er); + } + catch (HttpRequestException ex) + { + ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + if (ex.InnerException is not null) + { + er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); + } + + ThrowTerminatingError(er); + } + finally + { + _cancelToken?.Dispose(); + _cancelToken = null; + } + + if (_followRelLink) + { + if (!_relationLink.ContainsKey("next")) + { + return; + } + + uri = new Uri(_relationLink["next"]); + followedRelLink++; + } + } + } + while (_followRelLink && (followedRelLink < _maximumFollowRelLink)); + } + catch (CryptographicException ex) + { + ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); + ThrowTerminatingError(er); + } + catch (NotSupportedException ex) + { + ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); + ThrowTerminatingError(er); + } + } + + /// + /// To implement ^C. + /// + protected override void StopProcessing() => _cancelToken?.Cancel(); + + /// + /// Disposes the associated WebSession if it is not being used as part of a persistent session. + /// + /// True when called from Dispose() and false when called from finalizer. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing && !IsPersistentSession()) + { + WebSession?.Dispose(); + WebSession = null; + } + + _disposed = true; + } + } + + /// + /// Disposes the associated WebSession if it is not being used as part of a persistent session. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + #endregion Overrides + + #region Virtual Methods + + internal virtual void ValidateParameters() + { + // Sessions + if (WebSession is not null && SessionVariable is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); + ThrowTerminatingError(error); + } + + // Authentication + if (UseDefaultCredentials && Authentication != WebAuthenticationType.None) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); + ThrowTerminatingError(error); + } + + if (Authentication != WebAuthenticationType.None && Token is not null && Credential is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); + ThrowTerminatingError(error); + } + + if (Authentication == WebAuthenticationType.Basic && Credential is null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); + ThrowTerminatingError(error); + } + + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token is null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); + ThrowTerminatingError(error); + } + + if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https") + { + ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ThrowTerminatingError(error); + } + + // Credentials + if (UseDefaultCredentials && Credential is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); + ThrowTerminatingError(error); + } + + // Proxy server + if (ProxyUseDefaultCredentials && ProxyCredential is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); + ThrowTerminatingError(error); + } + else if (Proxy is null && (ProxyCredential is not null || ProxyUseDefaultCredentials)) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); + ThrowTerminatingError(error); + } + + // Request body content + if (Body is not null && InFile is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); + ThrowTerminatingError(error); + } + + if (Body is not null && Form is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); + ThrowTerminatingError(error); + } + + if (InFile is not null && Form is not null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); + ThrowTerminatingError(error); + } + + // Validate InFile path + if (InFile is not null) + { + ErrorRecord errorRecord = null; + + try + { + Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider); + + if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + { + errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile); + } + else + { + if (providerPaths.Count > 1) + { + errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); + } + else if (providerPaths.Count == 0) + { + errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); + } + else + { + if (Directory.Exists(providerPaths[0])) + { + errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile); + } + + _originalFilePath = InFile; + InFile = providerPaths[0]; + } + } + } + catch (ItemNotFoundException pathNotFound) + { + errorRecord = new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound); + } + catch (ProviderNotFoundException providerNotFound) + { + errorRecord = new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound); + } + catch (System.Management.Automation.DriveNotFoundException driveNotFound) + { + errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); + } + + if (errorRecord is not null) + { + ThrowTerminatingError(errorRecord); + } + } + + // Output ?? + if (PassThru.IsPresent && OutFile is null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); + ThrowTerminatingError(error); + } + + // Resume requires OutFile. + if (Resume.IsPresent && OutFile is null) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume)); + ThrowTerminatingError(error); + } + + _qualifiedOutFile = ShouldSaveToOutFile ? QualifiedOutFile : null; + + // OutFile must not be a directory to use Resume. + if (Resume.IsPresent && Directory.Exists(_qualifiedOutFile)) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.ResumeNotFilePath, "WebCmdletResumeNotFilePathException", _qualifiedOutFile); + ThrowTerminatingError(error); + } + } + + internal virtual void PrepareSession() + { + // Make sure we have a valid WebRequestSession object to work with + WebSession ??= new WebRequestSession(); + + if (SessionVariable is not null) + { + // Save the session back to the PS environment if requested + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(SessionVariable, WebSession); + } + + // Handle credentials + if (Credential is not null && Authentication == WebAuthenticationType.None) + { + // Get the relevant NetworkCredential + NetworkCredential netCred = Credential.GetNetworkCredential(); + WebSession.Credentials = netCred; + + // Supplying a credential overrides the UseDefaultCredentials setting + WebSession.UseDefaultCredentials = false; + } + else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None) + { + ProcessAuthentication(); + } + else if (UseDefaultCredentials) + { + WebSession.UseDefaultCredentials = true; + } + + if (CertificateThumbprint is not null) + { + using X509Store store = new(StoreName.My, StoreLocation.CurrentUser); + store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); + X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; + X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); + if (tbCollection.Count == 0) + { + throw new CryptographicException(WebCmdletStrings.ThumbprintNotFound); + } + + foreach (X509Certificate2 tbCert in tbCollection) + { + X509Certificate certificate = (X509Certificate)tbCert; + WebSession.AddCertificate(certificate); + } + } + + if (Certificate is not null) + { + WebSession.AddCertificate(Certificate); + } + + // Handle the user agent + if (UserAgent is not null) + { + // Store the UserAgent string + WebSession.UserAgent = UserAgent; + } + + // Proxy and NoProxy parameters are mutually exclusive. + // If NoProxy is provided, WebSession will turn off the proxy + // and if Proxy is provided NoProxy will be turned off. + if (NoProxy.IsPresent) + { + WebSession.NoProxy = true; + } + else + { + if (Proxy is not null) + { + WebProxy webProxy = new(Proxy); + webProxy.BypassProxyOnLocal = false; + if (ProxyCredential is not null) + { + webProxy.Credentials = ProxyCredential.GetNetworkCredential(); + } + else + { + webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials; + } + + // We don't want to update the WebSession unless the proxies are different + // as that will require us to create a new HttpClientHandler and lose connection + // persistence. + if (!webProxy.Equals(WebSession.Proxy)) + { + WebSession.Proxy = webProxy; + } + } + } + + if (MyInvocation.BoundParameters.ContainsKey(nameof(SslProtocol))) + { + WebSession.SslProtocol = SslProtocol; + } + + if (MaximumRedirection > -1) + { + WebSession.MaximumRedirection = MaximumRedirection; + } + + WebSession.UnixSocket = UnixSocket; + + WebSession.SkipCertificateCheck = SkipCertificateCheck.IsPresent; + + // Store the other supplied headers + if (Headers is not null) + { + foreach (string key in Headers.Keys) + { + object value = Headers[key]; + + // null is not valid value for header. + // We silently ignore header if value is null. + if (value is not null) + { + // Add the header value (or overwrite it if already present). + WebSession.Headers[key] = value.ToString(); + } + } + } + + if (MaximumRetryCount > 0) + { + WebSession.MaximumRetryCount = MaximumRetryCount; + + // Only set retry interval if retry count is set. + WebSession.RetryIntervalInSeconds = RetryIntervalSec; + } + + WebSession.ConnectionTimeout = ConvertTimeoutSecondsToTimeSpan(ConnectionTimeoutSeconds); + } + + internal virtual HttpClient GetHttpClient(bool handleRedirect) + { + HttpClient client = WebSession.GetHttpClient(handleRedirect, out bool clientWasReset); + + if (clientWasReset) + { + WriteVerbose(WebCmdletStrings.WebSessionConnectionRecreated); + } + + return client; + } + + internal virtual HttpRequestMessage GetRequest(Uri uri) + { + Uri requestUri = PrepareUri(uri); + HttpMethod httpMethod = string.IsNullOrEmpty(CustomMethod) ? GetHttpMethod(Method) : new HttpMethod(CustomMethod); + + // Create the base WebRequest object + HttpRequestMessage request = new(httpMethod, requestUri); + + if (HttpVersion is not null) + { + request.Version = HttpVersion; + } + + // Pull in session data + if (WebSession.Headers.Count > 0) + { + WebSession.ContentHeaders.Clear(); + foreach (var entry in WebSession.Headers) + { + if (HttpKnownHeaderNames.ContentHeaders.Contains(entry.Key)) + { + WebSession.ContentHeaders.Add(entry.Key, entry.Value); + } + else + { + if (SkipHeaderValidation) + { + request.Headers.TryAddWithoutValidation(entry.Key, entry.Value); + } + else + { + request.Headers.Add(entry.Key, entry.Value); + } + } + } + } + + // Set 'Transfer-Encoding: chunked' if 'Transfer-Encoding' is specified + if (WebSession.Headers.ContainsKey(HttpKnownHeaderNames.TransferEncoding)) + { + request.Headers.TransferEncodingChunked = true; + } + + // Set 'User-Agent' if WebSession.Headers doesn't already contain it + if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out string userAgent)) + { + WebSession.UserAgent = userAgent; + } + else + { + if (SkipHeaderValidation) + { + request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.UserAgent, WebSession.UserAgent); + } + else + { + request.Headers.Add(HttpKnownHeaderNames.UserAgent, WebSession.UserAgent); + } + } + + // Set 'Keep-Alive' to false. This means set the Connection to 'Close'. + if (DisableKeepAlive) + { + request.Headers.Add(HttpKnownHeaderNames.Connection, "Close"); + } + + // Set 'Transfer-Encoding' + if (TransferEncoding is not null) + { + request.Headers.TransferEncodingChunked = true; + TransferCodingHeaderValue headerValue = new(TransferEncoding); + if (!request.Headers.TransferEncoding.Contains(headerValue)) + { + request.Headers.TransferEncoding.Add(headerValue); + } + } + + // If the file to resume downloading exists, create the Range request header using the file size. + // If not, create a Range to request the entire file. + if (Resume.IsPresent) + { + FileInfo fileInfo = new(QualifiedOutFile); + + if (fileInfo.Exists) + { + request.Headers.Range = new RangeHeaderValue(fileInfo.Length, null); + _resumeFileSize = fileInfo.Length; + } + else + { + request.Headers.Range = new RangeHeaderValue(0, null); + } + } + + return request; + } + + internal virtual void FillRequestStream(HttpRequestMessage request) + { + ArgumentNullException.ThrowIfNull(request); + + // Set the request content type + if (ContentType is not null) + { + WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; + } + else if (request.Method == HttpMethod.Post) + { + // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST + WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType); + if (string.IsNullOrEmpty(contentType)) + { + WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded"; + } + } + + if (Form is not null) + { + MultipartFormDataContent formData = new(); + foreach (DictionaryEntry formEntry in Form) + { + // AddMultipartContent will handle PSObject unwrapping, Object type determination and enumerateing top level IEnumerables. + AddMultipartContent(fieldName: formEntry.Key, fieldValue: formEntry.Value, formData: formData, enumerate: true); + } + + SetRequestContent(request, formData); + } + else if (Body is not null) + { + // Coerce body into a usable form + // Make sure we're using the base object of the body, not the PSObject wrapper + object content = Body is PSObject psBody ? psBody.BaseObject : Body; + + switch (content) + { + case FormObject form: + SetRequestContent(request, form.Fields); + break; + case IDictionary dictionary when request.Method != HttpMethod.Get: + SetRequestContent(request, dictionary); + break; + case XmlNode xmlNode: + SetRequestContent(request, xmlNode); + break; + case Stream stream: + SetRequestContent(request, stream); + break; + case byte[] bytes: + SetRequestContent(request, bytes); + break; + case MultipartFormDataContent multipartFormDataContent: + SetRequestContent(request, multipartFormDataContent); + break; + default: + SetRequestContent(request, (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); + break; + } + } + else if (InFile is not null) + { + // Copy InFile data + try + { + // Open the input file + SetRequestContent(request, new FileStream(InFile, FileMode.Open, FileAccess.Read, FileShare.Read)); + } + catch (UnauthorizedAccessException) + { + string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, _originalFilePath); + + throw new UnauthorizedAccessException(msg); + } + } + + // For other methods like Put where empty content has meaning, we need to fill in the content + if (request.Content is null) + { + // If this is a Get request and there is no content, then don't fill in the content as empty content gets rejected by some web services per RFC7230 + if (request.Method == HttpMethod.Get && ContentType is null) + { + return; + } + + request.Content = new StringContent(string.Empty); + request.Content.Headers.Clear(); + } + + foreach (KeyValuePair entry in WebSession.ContentHeaders) + { + if (!string.IsNullOrWhiteSpace(entry.Value)) + { + if (SkipHeaderValidation) + { + request.Content.Headers.TryAddWithoutValidation(entry.Key, entry.Value); + } + else + { + try + { + request.Content.Headers.Add(entry.Key, entry.Value); + } + catch (FormatException ex) + { + ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ThrowTerminatingError(er); + } + } + } + } + } + + internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool handleRedirect) + { + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(request); + + // Add 1 to account for the first request. + int totalRequests = WebSession.MaximumRetryCount + 1; + HttpRequestMessage currentRequest = request; + HttpResponseMessage response = null; + + do + { + // Track the current URI being used by various requests and re-requests. + Uri currentUri = currentRequest.RequestUri; + + _cancelToken = new CancellationTokenSource(); + try + { + if (IsWriteVerboseEnabled()) + { + WriteWebRequestVerboseInfo(currentRequest); + } + + if (IsWriteDebugEnabled()) + { + WriteWebRequestDebugInfo(currentRequest); + } + + // codeql[cs/ssrf] - This is expected Poweshell behavior where user inputted Uri is supported for the context of this method. The user assumes trust for the Uri and invocation is done on the user's machine, not a web application. If there is concern for remoting, they should use restricted remoting. + response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); + + if (IsWriteVerboseEnabled()) + { + WriteWebResponseVerboseInfo(response); + } + + if (IsWriteDebugEnabled()) + { + WriteWebResponseDebugInfo(response); + } + } + catch (TaskCanceledException ex) + { + if (ex.InnerException is TimeoutException) + { + // HTTP Request timed out + ErrorRecord er = new(ex, "ConnectionTimeoutReached", ErrorCategory.OperationTimeout, null); + ThrowTerminatingError(er); + } + else + { + throw; + } + + } + if (handleRedirect + && _maximumRedirection is not 0 + && IsRedirectCode(response.StatusCode) + && response.Headers.Location is not null) + { + _cancelToken.Cancel(); + _cancelToken = null; + + // If explicit count was provided, reduce it for this redirection. + if (_maximumRedirection > 0) + { + _maximumRedirection--; + } + + // For selected redirects, GET must be used with the redirected Location. + if (RequestRequiresForceGet(response.StatusCode, currentRequest.Method) && !PreserveHttpMethodOnRedirect) + { + Method = WebRequestMethod.Get; + CustomMethod = string.Empty; + } + + currentUri = new Uri(request.RequestUri, response.Headers.Location); + + // Continue to handle redirection + using HttpRequestMessage redirectRequest = GetRequest(currentUri); + response.Dispose(); + response = GetResponse(client, redirectRequest, handleRedirect); + } + + // Request again without the Range header because the server indicated the range was not satisfiable. + // This happens when the local file is larger than the remote file. + // If the size of the remote file is the same as the local file, there is nothing to resume. + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && (response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length != _resumeFileSize)) + { + _cancelToken.Cancel(); + + WriteVerbose(WebCmdletStrings.WebMethodResumeFailedVerboseMsg); + + // Disable the Resume switch so the subsequent calls to GetResponse() and FillRequestStream() + // are treated as a standard -OutFile request. This also disables appending local file. + Resume = new SwitchParameter(false); + + using (HttpRequestMessage requestWithoutRange = GetRequest(currentUri)) + { + FillRequestStream(requestWithoutRange); + + response.Dispose(); + response = GetResponse(client, requestWithoutRange, handleRedirect); + } + } + + _resumeSuccess = response.StatusCode == HttpStatusCode.PartialContent; + + // When MaximumRetryCount is not specified, the totalRequests is 1. + if (totalRequests > 1 && ShouldRetry(response.StatusCode)) + { + int retryIntervalInSeconds = WebSession.RetryIntervalInSeconds; + + // If the status code is 429 get the retry interval from the Headers. + // Ignore broken header and its value. + if (response.StatusCode is HttpStatusCode.TooManyRequests && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) + { + try + { + IEnumerator enumerator = retryAfter.GetEnumerator(); + if (enumerator.MoveNext()) + { + retryIntervalInSeconds = Convert.ToInt32(enumerator.Current); + } + } + catch + { + // Ignore broken header. + } + } + + string retryMessage = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.RetryVerboseMsg, + retryIntervalInSeconds, + response.StatusCode); + + WriteVerbose(retryMessage); + + _cancelToken = new CancellationTokenSource(); + Task.Delay(retryIntervalInSeconds * 1000, _cancelToken.Token).GetAwaiter().GetResult(); + _cancelToken.Cancel(); + _cancelToken = null; + + currentRequest.Dispose(); + currentRequest = GetRequest(currentUri); + FillRequestStream(currentRequest); + } + + totalRequests--; + } + while (totalRequests > 0 && !response.IsSuccessStatusCode); + + return response; + } + + internal virtual void UpdateSession(HttpResponseMessage response) + { + ArgumentNullException.ThrowIfNull(response); + } + #endregion Virtual Methods + + #region Helper Methods +#nullable enable + internal static TimeSpan ConvertTimeoutSecondsToTimeSpan(int timeout) => timeout > 0 ? TimeSpan.FromSeconds(timeout) : Timeout.InfiniteTimeSpan; + + private void WriteWebRequestVerboseInfo(HttpRequestMessage request) + { + try + { + // Typical Basic Example: 'WebRequest: v1.1 POST https://httpstat.us/200 with query length 6' + StringBuilder verboseBuilder = new(128); + + // "Redact" the query string from verbose output, the details will be visible in Debug output + string uriWithoutQuery = request.RequestUri?.GetLeftPart(UriPartial.Path) ?? string.Empty; + verboseBuilder.Append($"WebRequest: v{request.Version} {request.Method} {uriWithoutQuery}"); + if (request.RequestUri?.Query is not null && request.RequestUri.Query.Length > 1) + { + verboseBuilder.Append($" with query length {request.RequestUri.Query.Length - 1}"); + } + + string? requestContentType = ContentHelper.GetContentType(request); + if (requestContentType is not null) + { + verboseBuilder.Append($" with {requestContentType} payload"); + } + + long? requestContentLength = request.Content?.Headers?.ContentLength; + if (requestContentLength is not null) + { + verboseBuilder.Append($" with body size {ContentHelper.GetFriendlyContentLength(requestContentLength)}"); + } + if (OutFile is not null) + { + verboseBuilder.Append($" output to {QualifyFilePath(OutFile)}"); + } + + WriteVerbose(verboseBuilder.ToString().Trim()); + } + catch (Exception ex) + { + // Just in case there are any edge cases we missed, we don't break workflows with an exception + WriteVerbose($"Failed to Write WebRequest Verbose Info: {ex} {ex.StackTrace}"); + } + } + + private void WriteWebRequestDebugInfo(HttpRequestMessage request) + { + try + { + // Typical basic example: + // WebRequest Detail + // ---QUERY + // test = 5 + // --- HEADERS + // User - Agent: Mozilla / 5.0, (Linux;Ubuntu 24.04.2 LTS;en - US), PowerShell / 7.6.0 + StringBuilder debugBuilder = new("WebRequest Detail" + Environment.NewLine, 512); + + if (!string.IsNullOrEmpty(request.RequestUri?.Query)) + { + debugBuilder.Append(DebugHeaderPrefix).AppendLine("QUERY"); + string[] queryParams = request.RequestUri.Query.TrimStart('?').Split('&'); + debugBuilder + .AppendJoin(Environment.NewLine, queryParams) + .AppendLine() + .AppendLine(); + } + + debugBuilder.Append(DebugHeaderPrefix).AppendLine("HEADERS"); + + foreach (var headerSet in new HttpHeaders?[] { request.Headers, request.Content?.Headers }) + { + if (headerSet is null) + { + continue; + } + + debugBuilder.AppendLine(headerSet.ToString()); + } + + if (request.Content is not null) + { + debugBuilder + .Append(DebugHeaderPrefix).AppendLine("BODY") + .AppendLine(request.Content switch + { + StringContent stringContent => stringContent + .ReadAsStringAsync(_cancelToken.Token) + .GetAwaiter().GetResult(), + MultipartFormDataContent multipartContent => "=> Multipart Form Content" + + Environment.NewLine + + multipartContent.ReadAsStringAsync(_cancelToken.Token) + .GetAwaiter().GetResult(), + ByteArrayContent byteContent => InFile is not null + ? "[Binary content: " + + ContentHelper.GetFriendlyContentLength(byteContent.Headers.ContentLength) + + "]" + : byteContent.ReadAsStringAsync(_cancelToken.Token).GetAwaiter().GetResult(), + StreamContent streamContent => + "[Stream content: " + ContentHelper.GetFriendlyContentLength(streamContent.Headers.ContentLength) + "]", + _ => "[Unknown content type]", + }) + .AppendLine(); + } + + WriteDebug(debugBuilder.ToString().Trim()); + } + catch (Exception ex) + { + // Just in case there are any edge cases we missed, we don't break workflows with an exception + WriteVerbose($"Failed to Write WebRequest Debug Info: {ex} {ex.StackTrace}"); + } + } + + private void WriteWebResponseVerboseInfo(HttpResponseMessage response) + { + try + { + // Typical basic example: WebResponse: 200 OK with text/plain payload body size 6 B (6 bytes) + StringBuilder verboseBuilder = new(128); + verboseBuilder.Append($"WebResponse: {(int)response.StatusCode} {response.ReasonPhrase ?? response.StatusCode.ToString()}"); + + string? responseContentType = ContentHelper.GetContentType(response); + if (responseContentType is not null) + { + verboseBuilder.Append($" with {responseContentType} payload"); + } + + long? responseContentLength = response.Content?.Headers?.ContentLength; + if (responseContentLength is not null) + { + verboseBuilder.Append($" with body size {ContentHelper.GetFriendlyContentLength(responseContentLength)}"); + } + + WriteVerbose(verboseBuilder.ToString().Trim()); + } + catch (Exception ex) + { + // Just in case there are any edge cases we missed, we don't break workflows with an exception + WriteVerbose($"Failed to Write WebResponse Verbose Info: {ex} {ex.StackTrace}"); + } + } + + private void WriteWebResponseDebugInfo(HttpResponseMessage response) + { + try + { + // Typical basic example + // WebResponse Detail + // --- HEADERS + // Date: Fri, 09 May 2025 18:06:44 GMT + // Server: Kestrel + // Set-Cookie: ARRAffinity=ee0b467f95b53d8dcfe48aeeb4173f93cf819be6e4721f434341647f4695039d;Path=/;HttpOnly;Secure;Domain=httpstat.us, ARRAffinitySameSite=ee0b467f95b53d8dcfe48aeeb4173f93cf819be6e4721f434341647f4695039d;Path=/;HttpOnly;SameSite=None;Secure;Domain=httpstat.us + // Strict-Transport-Security: max-age=2592000 + // Request-Context: appId=cid-v1:3548b0f5-7f75-492f-82bb-b6eb0e864e53 + // Content-Length: 6 + // Content-Type: text/plain + // --- BODY + // 200 OK + StringBuilder debugBuilder = new("WebResponse Detail" + Environment.NewLine, 512); + + debugBuilder.Append(DebugHeaderPrefix).AppendLine("HEADERS"); + + foreach (var headerSet in new HttpHeaders?[] { response.Headers, response.Content?.Headers }) + { + if (headerSet is null) + { + continue; + } + + debugBuilder.AppendLine(headerSet.ToString()); + } + + if (response.Content is not null) + { + debugBuilder.Append(DebugHeaderPrefix).AppendLine("BODY"); + + if (ContentHelper.IsTextBasedContentType(ContentHelper.GetContentType(response))) + { + debugBuilder.AppendLine( + response.Content.ReadAsStringAsync(_cancelToken.Token) + .GetAwaiter().GetResult()); + } + else + { + string friendlyContentLength = ContentHelper.GetFriendlyContentLength( + response.Content?.Headers?.ContentLength); + debugBuilder.AppendLine($"[Binary content: {friendlyContentLength}]"); + } + } + + WriteDebug(debugBuilder.ToString().Trim()); + } + catch (Exception ex) + { + // Just in case there are any edge cases we missed, we don't break workflows with an exception + WriteVerbose($"Failed to Write WebResponse Debug Info: {ex} {ex.StackTrace}"); + } + } + + private Uri PrepareUri(Uri uri) + { + uri = CheckProtocol(uri); + + // Before creating the web request, + // preprocess Body if content is a dictionary and method is GET (set as query) + LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary); + if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET")) + { + UriBuilder uriBuilder = new(uri); + if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) + { + uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary)); + } + else + { + uriBuilder.Query = FormatDictionary(bodyAsDictionary); + } + + uri = uriBuilder.Uri; + + // Set body to null to prevent later FillRequestStream + Body = null; + } + + return uri; + } + + private static Uri CheckProtocol(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + return uri.IsAbsoluteUri ? uri : new Uri("http://" + uri.OriginalString); + } +#nullable restore + + private string QualifyFilePath(string path) => PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); + + private static string FormatDictionary(IDictionary content) + { + ArgumentNullException.ThrowIfNull(content); + + StringBuilder bodyBuilder = new(); + foreach (string key in content.Keys) + { + if (bodyBuilder.Length > 0) + { + bodyBuilder.Append('&'); + } + + object value = content[key]; + + // URLEncode the key and value + string encodedKey = WebUtility.UrlEncode(key); + string encodedValue = value is null ? string.Empty : WebUtility.UrlEncode(value.ToString()); + + bodyBuilder.Append($"{encodedKey}={encodedValue}"); + } + + return bodyBuilder.ToString(); + } + + private ErrorRecord GetValidationError(string msg, string errorId) + { + ValidationMetadataException ex = new(msg); + return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); + } + + private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) + { + msg = string.Format(CultureInfo.InvariantCulture, msg, args); + ValidationMetadataException ex = new(msg); + return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); + } + + private string GetBasicAuthorizationHeader() + { + string password = new NetworkCredential(string.Empty, Credential.Password).Password; + string unencoded = string.Create(CultureInfo.InvariantCulture, $"{Credential.UserName}:{password}"); + byte[] bytes = Encoding.UTF8.GetBytes(unencoded); + return string.Create(CultureInfo.InvariantCulture, $"Basic {Convert.ToBase64String(bytes)}"); + } + + private string GetBearerAuthorizationHeader() + { + return string.Create(CultureInfo.InvariantCulture, $"Bearer {new NetworkCredential(string.Empty, Token).Password}"); + } + + private void ProcessAuthentication() + { + if (Authentication == WebAuthenticationType.Basic) + { + WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader(); + } + else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth) + { + WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader(); + } + else + { + Diagnostics.Assert(false, string.Create(CultureInfo.InvariantCulture, $"Unrecognized Authentication value: {Authentication}")); + } + } + + private bool IsPersistentSession() => MyInvocation.BoundParameters.ContainsKey(nameof(WebSession)) || MyInvocation.BoundParameters.ContainsKey(nameof(SessionVariable)); + + /// + /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// + /// The WebRequest who's content is to be set. + /// A byte array containing the content data. + /// + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// it should be called one time maximum on a given request. + /// + internal void SetRequestContent(HttpRequestMessage request, byte[] content) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); + + request.Content = new ByteArrayContent(content); + } + + /// + /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// + /// The WebRequest who's content is to be set. + /// A String object containing the content data. + /// + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// it should be called one time maximum on a given request. + /// + internal void SetRequestContent(HttpRequestMessage request, string content) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); + + Encoding encoding = null; + + if (WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType) && contentType is not null) + { + // If Content-Type contains the encoding format (as CharSet), use this encoding format + // to encode the Body of the WebRequest sent to the server. Default Encoding format + // would be used if Charset is not supplied in the Content-Type property. + try + { + MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(contentType); + if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet)) + { + encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet); + } + } + catch (Exception ex) when (ex is FormatException || ex is ArgumentException) + { + if (!SkipHeaderValidation) + { + ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, contentType); + ThrowTerminatingError(er); + } + } + } + + byte[] bytes = StreamHelper.EncodeToBytes(content, encoding); + request.Content = new ByteArrayContent(bytes); + } + + internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(xmlNode); + + byte[] bytes = null; + XmlDocument doc = xmlNode as XmlDocument; + if (doc?.FirstChild is XmlDeclaration decl && !string.IsNullOrEmpty(decl.Encoding)) + { + Encoding encoding = Encoding.GetEncoding(decl.Encoding); + bytes = StreamHelper.EncodeToBytes(doc.OuterXml, encoding); + } + else + { + bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null); + } + + request.Content = new ByteArrayContent(bytes); + } + + /// + /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// + /// The WebRequest who's content is to be set. + /// A Stream object containing the content data. + /// + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// it should be called one time maximum on a given request. + /// + internal void SetRequestContent(HttpRequestMessage request, Stream contentStream) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(contentStream); + + request.Content = new StreamContent(contentStream); + } + + /// + /// Sets the ContentLength property of the request and writes the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// + /// The WebRequest who's content is to be set. + /// A MultipartFormDataContent object containing multipart/form-data content. + /// + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// it should be called one time maximum on a given request. + /// + internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(multipartContent); + + // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first + WebSession.ContentHeaders.Clear(); + + request.Content = multipartContent; + } + + internal void SetRequestContent(HttpRequestMessage request, IDictionary content) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); + + string body = FormatDictionary(content); + SetRequestContent(request, body); + } + + internal void ParseLinkHeader(HttpResponseMessage response) + { + Uri requestUri = response.RequestMessage.RequestUri; + if (_relationLink is null) + { + // Must ignore the case of relation links. See RFC 8288 (https://tools.ietf.org/html/rfc8288) + _relationLink = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + else + { + _relationLink.Clear(); + } + + // We only support the URL in angle brackets and `rel`, other attributes are ignored + // user can still parse it themselves via the Headers property + const string Pattern = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")"; + if (response.Headers.TryGetValues("Link", out IEnumerable links)) + { + foreach (string linkHeader in links) + { + MatchCollection matchCollection = Regex.Matches(linkHeader, Pattern); + foreach (Match match in matchCollection) + { + if (match.Success) + { + string url = match.Groups["url"].Value; + string rel = match.Groups["rel"].Value; + if (url != string.Empty && rel != string.Empty && !_relationLink.ContainsKey(rel)) + { + Uri absoluteUri = new(requestUri, url); + _relationLink.Add(rel, absoluteUri.AbsoluteUri); + } + } + } + } + } + } + + /// + /// Adds content to a . Object type detection is used to determine if the value is string, File, or Collection. + /// + /// The Field Name to use. + /// The Field Value to use. + /// The to update. + /// If true, collection types in will be enumerated. If false, collections will be treated as single value. + private static void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) + { + ArgumentNullException.ThrowIfNull(formData); + + // It is possible that the dictionary keys or values are PSObject wrapped depending on how the dictionary is defined and assigned. + // Before processing the field name and value we need to ensure we are working with the base objects and not the PSObject wrappers. + + // Unwrap fieldName PSObjects + if (fieldName is PSObject namePSObject) + { + fieldName = namePSObject.BaseObject; + } + + // Unwrap fieldValue PSObjects + if (fieldValue is PSObject valuePSObject) + { + fieldValue = valuePSObject.BaseObject; + } + + // Treat a single FileInfo as a FileContent + if (fieldValue is FileInfo file) + { + formData.Add(GetMultipartFileContent(fieldName: fieldName, file: file)); + return; + } + + // Treat Strings and other single values as a StringContent. + // If enumeration is false, also treat IEnumerables as StringContents. + // String implements IEnumerable so the explicit check is required. + if (!enumerate || fieldValue is string || fieldValue is not IEnumerable) + { + formData.Add(GetMultipartStringContent(fieldName: fieldName, fieldValue: fieldValue)); + return; + } + + // Treat the value as a collection and enumerate it if enumeration is true + if (enumerate && fieldValue is IEnumerable items) + { + foreach (object item in items) + { + // Recurse, but do not enumerate the next level. IEnumerables will be treated as single values. + AddMultipartContent(fieldName: fieldName, fieldValue: item, formData: formData, enumerate: false); + } + } + } + + /// + /// Gets a from the supplied field name and field value. Uses to convert the objects to strings. + /// + /// The Field Name to use for the + /// The Field Value to use for the + private static StringContent GetMultipartStringContent(object fieldName, object fieldValue) + { + ContentDispositionHeaderValue contentDisposition = new("form-data"); + contentDisposition.Name = LanguagePrimitives.ConvertTo(fieldName); + + // codeql[cs/information-exposure-through-exception] - PowerShell is an on-premise product, meaning local users would already have access to the binaries and stack traces. Therefore, the information would not be exposed in the same way it would be for an ASP .NET service. + StringContent result = new(LanguagePrimitives.ConvertTo(fieldValue)); + result.Headers.ContentDisposition = contentDisposition; + + return result; + } + + /// + /// Gets a from the supplied field name and . Uses to convert the fieldname to a string. + /// + /// The Field Name to use for the + /// The to use for the + private static StreamContent GetMultipartStreamContent(object fieldName, Stream stream) + { + ContentDispositionHeaderValue contentDisposition = new("form-data"); + contentDisposition.Name = LanguagePrimitives.ConvertTo(fieldName); + + StreamContent result = new(stream); + result.Headers.ContentDisposition = contentDisposition; + result.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + + return result; + } + + /// + /// Gets a from the supplied field name and file. Calls to create the and then sets the file name. + /// + /// The Field Name to use for the + /// The file to use for the + private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file) + { + StreamContent result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)); + + result.Headers.ContentDisposition.FileName = file.Name; + result.Headers.ContentDisposition.FileNameStar = file.Name; + + return result; + } + + private static string FormatErrorMessage(string error, string contentType) + { + string formattedError = null; + + try + { + if (ContentHelper.IsXml(contentType)) + { + XmlDocument doc = new(); + doc.LoadXml(error); + + XmlWriterSettings settings = new XmlWriterSettings + { + Indent = true, + NewLineOnAttributes = true, + OmitXmlDeclaration = true + }; + + if (doc.FirstChild is XmlDeclaration decl) + { + settings.Encoding = Encoding.GetEncoding(decl.Encoding); + } + + StringBuilder stringBuilder = new(); + using XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings); + doc.Save(xmlWriter); + string xmlString = stringBuilder.ToString(); + + formattedError = Environment.NewLine + xmlString; + } + else if (ContentHelper.IsJson(contentType)) + { + JsonNode jsonNode = JsonNode.Parse(error); + JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true }; + string jsonString = jsonNode.ToJsonString(options); + + formattedError = Environment.NewLine + jsonString; + } + } + catch + { + // Ignore errors + } + + if (string.IsNullOrEmpty(formattedError)) + { + // Remove HTML tags making it easier to read + formattedError = Regex.Replace(error, "<[^>]*>", string.Empty); + } + + return formattedError; + } + + // Returns true if the status code is one of the supported redirection codes. + private static bool IsRedirectCode(HttpStatusCode statusCode) => statusCode switch + { + HttpStatusCode.Found + or HttpStatusCode.Moved + or HttpStatusCode.MultipleChoices + or HttpStatusCode.PermanentRedirect + or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect => true, + _ => false + }; + + // Returns true if the status code is a redirection code and the action requires switching to GET on redirection. + // See https://learn.microsoft.com/en-us/dotnet/api/system.net.httpstatuscode + private static bool RequestRequiresForceGet(HttpStatusCode statusCode, HttpMethod requestMethod) => statusCode switch + { + HttpStatusCode.Found + or HttpStatusCode.Moved + or HttpStatusCode.MultipleChoices => requestMethod == HttpMethod.Post, + HttpStatusCode.SeeOther => requestMethod != HttpMethod.Get && requestMethod != HttpMethod.Head, + _ => false + }; + + // Returns true if the status code shows a server or client error and MaximumRetryCount > 0 + private static bool ShouldRetry(HttpStatusCode statusCode) => (int)statusCode switch + { + 304 or (>= 400 and <= 599) => true, + _ => false + }; + + private static HttpMethod GetHttpMethod(WebRequestMethod method) => method switch + { + WebRequestMethod.Default or WebRequestMethod.Get => HttpMethod.Get, + WebRequestMethod.Delete => HttpMethod.Delete, + WebRequestMethod.Head => HttpMethod.Head, + WebRequestMethod.Patch => HttpMethod.Patch, + WebRequestMethod.Post => HttpMethod.Post, + WebRequestMethod.Put => HttpMethod.Put, + WebRequestMethod.Options => HttpMethod.Options, + WebRequestMethod.Trace => HttpMethod.Trace, + _ => new HttpMethod(method.ToString().ToUpperInvariant()) + }; + + #endregion Helper Methods + } + + /// + /// Exception class for webcmdlets to enable returning HTTP error response. + /// + public sealed class HttpResponseException : HttpRequestException + { + /// + /// Initializes a new instance of the class. + /// + /// Message for the exception. + /// Response from the HTTP server. + public HttpResponseException(string message, HttpResponseMessage response) : base(message, inner: null, response.StatusCode) + { + Response = response; + } + + /// + /// HTTP error response. + /// + public HttpResponseMessage Response { get; } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs new file mode 100644 index 0000000000000000000000000000000000000000..ace84f480f964848b14ce16b4d98d4cff687324b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net.Http; +using System.Text; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// WebResponseObject. + /// + public class WebResponseObject + { + #region Properties + + /// + /// Gets or sets the BaseResponse property. + /// + public HttpResponseMessage BaseResponse { get; set; } + + /// + /// Gets or protected sets the response body content. + /// + public byte[]? Content { get; protected set; } + + /// + /// Gets the Headers property. + /// + public Dictionary> Headers => _headers ??= WebResponseHelper.GetHeadersDictionary(BaseResponse); + + private Dictionary>? _headers; + + /// + /// Gets or protected sets the full response content. + /// + /// + /// Full response content, including the HTTP status line, headers, and body. + /// + public string? RawContent { get; protected set; } + + /// + /// Gets the length (in bytes) of . + /// + public long RawContentLength => RawContentStream is null ? -1 : RawContentStream.Length; + + /// + /// Gets or protected sets the response body content as a . + /// + public MemoryStream RawContentStream { get; protected set; } + + /// + /// Gets the RelationLink property. + /// + public Dictionary? RelationLink { get; internal set; } + + /// + /// Gets the response status code. + /// + public int StatusCode => WebResponseHelper.GetStatusCode(BaseResponse); + + /// + /// Gets the response status description. + /// + public string StatusDescription => WebResponseHelper.GetStatusDescription(BaseResponse); + + /// + /// Gets or sets the output file path. + /// + public string? OutFile { get; internal set; } + + #endregion Properties + + #region Protected Fields + + /// + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// + protected TimeSpan perReadTimeout; + + #endregion Protected Fields + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The Http response. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// The cancellation token. + public WebResponseObject(HttpResponseMessage response, TimeSpan perReadTimeout, CancellationToken cancellationToken) : this(response, null, perReadTimeout, cancellationToken) { } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// Http response. + /// The http content stream. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// The cancellation token. + public WebResponseObject(HttpResponseMessage response, Stream? contentStream, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + this.perReadTimeout = perReadTimeout; + SetResponse(response, contentStream, cancellationToken); + InitializeContent(); + InitializeRawContent(response); + } + + #endregion Constructors + + #region Methods + + /// + /// Reads the response content from the web response. + /// + private void InitializeContent() + { + Content = RawContentStream.ToArray(); + } + + private void InitializeRawContent(HttpResponseMessage baseResponse) + { + StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); + + // Use ASCII encoding for the RawContent visual view of the content. + if (Content?.Length > 0) + { + raw.Append(ToString()); + } + + RawContent = raw.ToString(); + } + + private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) + || char.IsPunctuation(c) + || char.IsSeparator(c) + || char.IsSymbol(c) + || char.IsWhiteSpace(c); + + [MemberNotNull(nameof(RawContentStream))] + [MemberNotNull(nameof(BaseResponse))] + private void SetResponse(HttpResponseMessage response, Stream? contentStream, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(response); + + BaseResponse = response; + + if (contentStream is MemoryStream ms) + { + RawContentStream = ms; + } + else + { + Stream st = contentStream ?? StreamHelper.GetResponseStream(response, cancellationToken); + + long contentLength = response.Content.Headers.ContentLength.GetValueOrDefault(); + if (contentLength <= 0) + { + contentLength = StreamHelper.DefaultReadBuffer; + } + + int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); + RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault(), perReadTimeout, cancellationToken); + } + + // Set the position of the content stream to the beginning + RawContentStream.Position = 0; + } + + /// + /// Returns the string representation of this web response. + /// + /// The string representation of this web response. + public sealed override string ToString() + { + if (Content is null) + { + return string.Empty; + } + + char[] stringContent = Encoding.ASCII.GetChars(Content); + for (int counter = 0; counter < stringContent.Length; counter++) + { + if (!IsPrintable(stringContent[counter])) + { + stringContent[counter] = '.'; + } + } + + return new string(stringContent); + } + + #endregion Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..82e1277e00cd83a2cd288cc2ec0210c9d08c52b9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The ConvertFrom-Json command. + /// This command converts a Json string representation to a JsonObject. + /// + [Cmdlet(VerbsData.ConvertFrom, "Json", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096606", RemotingCapability = RemotingCapability.None)] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public class ConvertFromJsonCommand : Cmdlet + { + #region parameters + + /// + /// Gets or sets the InputString property. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + [AllowEmptyString] + public string InputObject { get; set; } + + /// + /// InputObjectBuffer buffers all InputObject contents available in the pipeline. + /// + private readonly List _inputObjectBuffer = new(); + + /// + /// Returned data structure is a Hashtable instead a CustomPSObject. + /// + [Parameter] + public SwitchParameter AsHashtable { get; set; } + + /// + /// Gets or sets the maximum depth the JSON input is allowed to have. By default, it is 1024. + /// + [Parameter] + [ValidateRange(ValidateRangeKind.Positive)] + public int Depth { get; set; } = 1024; + + /// + /// Gets or sets the switch to prevent ConvertFrom-Json from unravelling collections during deserialization, instead passing them as a single + /// object through the pipeline. + /// + [Parameter] + public SwitchParameter NoEnumerate { get; set; } + + /// + /// Gets or sets the switch to control how DateTime values are to be parsed as a dotnet object. + /// + [Parameter] + public JsonDateKind DateKind { get; set; } = JsonDateKind.Default; + + #endregion parameters + + #region overrides + + /// + /// Buffers InputObjet contents available in the pipeline. + /// + protected override void ProcessRecord() + { + _inputObjectBuffer.Add(InputObject); + } + + /// + /// The main execution method for the ConvertFrom-Json command. + /// + protected override void EndProcessing() + { + // When Input is provided through pipeline, the input can be represented in the following two ways: + // 1. Each input in the collection is a complete Json content. There can be multiple inputs of this format. + // 2. The complete input is a collection which represents a single Json content. This is typically the majority of the case. + if (_inputObjectBuffer.Count > 0) + { + if (_inputObjectBuffer.Count == 1) + { + ConvertFromJsonHelper(_inputObjectBuffer[0]); + } + else + { + bool successfullyConverted = false; + try + { + // Try to deserialize the first element. + successfullyConverted = ConvertFromJsonHelper(_inputObjectBuffer[0]); + } + catch (ArgumentException) + { + // The first input string does not represent a complete Json Syntax. + // Hence consider the entire input as a single Json content. + } + + if (successfullyConverted) + { + for (int index = 1; index < _inputObjectBuffer.Count; index++) + { + ConvertFromJsonHelper(_inputObjectBuffer[index]); + } + } + else + { + // Process the entire input as a single Json content. + ConvertFromJsonHelper(string.Join(System.Environment.NewLine, _inputObjectBuffer.ToArray())); + } + } + } + } + + /// + /// ConvertFromJsonHelper is a helper method to convert to Json input to .Net Type. + /// + /// Input string. + /// True if successfully converted, else returns false. + private bool ConvertFromJsonHelper(string input) + { + ErrorRecord error = null; + object result = JsonObject.ConvertFromJson(input, AsHashtable.IsPresent, Depth, DateKind, out error); + + if (error != null) + { + ThrowTerminatingError(error); + } + + WriteObject(result, !NoEnumerate.IsPresent); + return (result != null); + } + + #endregion overrides + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..173d999b06d74d3654c881674cbb891d8514a9da --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Threading; + +using Newtonsoft.Json; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The ConvertTo-Json command. + /// This command converts an object to a Json string representation. + /// + [Cmdlet(VerbsData.ConvertTo, "Json", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096925", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(string))] + public class ConvertToJsonCommand : PSCmdlet, IDisposable + { + /// + /// Gets or sets the InputObject property. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [AllowNull] + public object InputObject { get; set; } + + private int _depth = 2; + + private readonly CancellationTokenSource _cancellationSource = new(); + + /// + /// Gets or sets the Depth property. + /// + [Parameter] + [ValidateRange(0, 100)] + public int Depth + { + get { return _depth; } + set { _depth = value; } + } + + /// + /// Gets or sets the Compress property. + /// If the Compress property is set to be true, the Json string will + /// be output in the compressed way. Otherwise, the Json string will + /// be output with indentations. + /// + [Parameter] + public SwitchParameter Compress { get; set; } + + /// + /// Gets or sets the EnumsAsStrings property. + /// If the EnumsAsStrings property is set to true, enum values will + /// be converted to their string equivalent. Otherwise, enum values + /// will be converted to their numeric equivalent. + /// + [Parameter] + public SwitchParameter EnumsAsStrings { get; set; } + + /// + /// Gets or sets the AsArray property. + /// If the AsArray property is set to be true, the result JSON string will + /// be returned with surrounding '[', ']' chars. Otherwise, + /// the array symbols will occur only if there is more than one input object. + /// + [Parameter] + public SwitchParameter AsArray { get; set; } + + /// + /// Specifies how strings are escaped when writing JSON text. + /// If the EscapeHandling property is set to EscapeHtml, the result JSON string will + /// be returned with HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped. + /// + [Parameter] + public StringEscapeHandling EscapeHandling { get; set; } = StringEscapeHandling.Default; + + /// + /// IDisposable implementation, dispose of any disposable resources created by the cmdlet. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Implementation of IDisposable for both manual Dispose() and finalizer-called disposal of resources. + /// + /// + /// Specified as true when Dispose() was called, false if this is called from the finalizer. + /// + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + _cancellationSource.Dispose(); + } + } + + private readonly List _inputObjects = new(); + + /// + /// Caching the input objects for the command. + /// + protected override void ProcessRecord() + { + _inputObjects.Add(InputObject); + } + + /// + /// Do the conversion to json and write output. + /// + protected override void EndProcessing() + { + if (_inputObjects.Count > 0) + { + object objectToProcess = (_inputObjects.Count > 1 || AsArray) ? (_inputObjects.ToArray() as object) : _inputObjects[0]; + + var context = new JsonObject.ConvertToJsonContext( + Depth, + EnumsAsStrings.IsPresent, + Compress.IsPresent, + EscapeHandling, + targetCmdlet: this, + _cancellationSource.Token); + + // null is returned only if the pipeline is stopping (e.g. ctrl+c is signaled). + // in that case, we shouldn't write the null to the output pipe. + string output = JsonObject.ConvertToJson(objectToProcess, in context); + if (output != null) + { + WriteObject(output); + } + } + } + + /// + /// Process the Ctrl+C signal. + /// + protected override void StopProcessing() + { + _cancellationSource.Cancel(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs new file mode 100644 index 0000000000000000000000000000000000000000..6571696e5bfda12d687196e7e5e708514be867eb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; + +namespace Microsoft.PowerShell.Commands +{ + internal static class HttpKnownHeaderNames + { + #region Known_HTTP_Header_Names + + // Known HTTP Header Names. + // List comes from https://github.com/dotnet/runtime/blob/51a8dd5323721b363e61069575511f783e7ea6d3/src/libraries/Common/src/System/Net/HttpKnownHeaderNames.cs + public const string Accept = "Accept"; + public const string AcceptCharset = "Accept-Charset"; + public const string AcceptEncoding = "Accept-Encoding"; + public const string AcceptLanguage = "Accept-Language"; + public const string AcceptPatch = "Accept-Patch"; + public const string AcceptRanges = "Accept-Ranges"; + public const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials"; + public const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; + public const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; + public const string AccessControlAllowOrigin = "Access-Control-Allow-Origin"; + public const string AccessControlExposeHeaders = "Access-Control-Expose-Headers"; + public const string AccessControlMaxAge = "Access-Control-Max-Age"; + public const string Age = "Age"; + public const string Allow = "Allow"; + public const string AltSvc = "Alt-Svc"; + public const string Authorization = "Authorization"; + public const string CacheControl = "Cache-Control"; + public const string Connection = "Connection"; + public const string ContentDisposition = "Content-Disposition"; + public const string ContentEncoding = "Content-Encoding"; + public const string ContentLanguage = "Content-Language"; + public const string ContentLength = "Content-Length"; + public const string ContentLocation = "Content-Location"; + public const string ContentMD5 = "Content-MD5"; + public const string ContentRange = "Content-Range"; + public const string ContentSecurityPolicy = "Content-Security-Policy"; + public const string ContentType = "Content-Type"; + public const string Cookie = "Cookie"; + public const string Cookie2 = "Cookie2"; + public const string Date = "Date"; + public const string ETag = "ETag"; + public const string Expect = "Expect"; + public const string Expires = "Expires"; + public const string From = "From"; + public const string Host = "Host"; + public const string IfMatch = "If-Match"; + public const string IfModifiedSince = "If-Modified-Since"; + public const string IfNoneMatch = "If-None-Match"; + public const string IfRange = "If-Range"; + public const string IfUnmodifiedSince = "If-Unmodified-Since"; + public const string KeepAlive = "Keep-Alive"; + public const string LastModified = "Last-Modified"; + public const string Link = "Link"; + public const string Location = "Location"; + public const string MaxForwards = "Max-Forwards"; + public const string Origin = "Origin"; + public const string P3P = "P3P"; + public const string Pragma = "Pragma"; + public const string ProxyAuthenticate = "Proxy-Authenticate"; + public const string ProxyAuthorization = "Proxy-Authorization"; + public const string ProxyConnection = "Proxy-Connection"; + public const string PublicKeyPins = "Public-Key-Pins"; + public const string Range = "Range"; + public const string Referer = "Referer"; // NB: The spelling-mistake "Referer" for "Referrer" must be matched. + public const string RetryAfter = "Retry-After"; + public const string SecWebSocketAccept = "Sec-WebSocket-Accept"; + public const string SecWebSocketExtensions = "Sec-WebSocket-Extensions"; + public const string SecWebSocketKey = "Sec-WebSocket-Key"; + public const string SecWebSocketProtocol = "Sec-WebSocket-Protocol"; + public const string SecWebSocketVersion = "Sec-WebSocket-Version"; + public const string Server = "Server"; + public const string SetCookie = "Set-Cookie"; + public const string SetCookie2 = "Set-Cookie2"; + public const string StrictTransportSecurity = "Strict-Transport-Security"; + public const string TE = "TE"; + public const string TSV = "TSV"; + public const string Trailer = "Trailer"; + public const string TransferEncoding = "Transfer-Encoding"; + public const string Upgrade = "Upgrade"; + public const string UpgradeInsecureRequests = "Upgrade-Insecure-Requests"; + public const string UserAgent = "User-Agent"; + public const string Vary = "Vary"; + public const string Via = "Via"; + public const string WWWAuthenticate = "WWW-Authenticate"; + public const string Warning = "Warning"; + public const string XAspNetVersion = "X-AspNet-Version"; + public const string XContentDuration = "X-Content-Duration"; + public const string XContentTypeOptions = "X-Content-Type-Options"; + public const string XFrameOptions = "X-Frame-Options"; + public const string XMSEdgeRef = "X-MSEdge-Ref"; + public const string XPoweredBy = "X-Powered-By"; + public const string XRequestID = "X-Request-ID"; + public const string XUACompatible = "X-UA-Compatible"; + + #endregion Known_HTTP_Header_Names + + private static readonly HashSet s_contentHeaderSet; + + static HttpKnownHeaderNames() + { + // Thread-safe initialization. + s_contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); + + s_contentHeaderSet.Add(HttpKnownHeaderNames.Allow); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentDisposition); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentEncoding); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLanguage); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLength); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLocation); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentMD5); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentRange); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentType); + s_contentHeaderSet.Add(HttpKnownHeaderNames.Expires); + s_contentHeaderSet.Add(HttpKnownHeaderNames.LastModified); + } + + internal static HashSet ContentHeaders => s_contentHeaderSet; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs new file mode 100644 index 0000000000000000000000000000000000000000..0bcafcf29645b07ae95d9a2e4fcacfbdf24f4e2b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.IO; +using System.Management.Automation; +using System.Net.Http; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Invoke-WebRequest command. + /// This command makes an HTTP or HTTPS request to a web server and returns the results. + /// + [Cmdlet(VerbsLifecycle.Invoke, "WebRequest", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097126", DefaultParameterSetName = "StandardMethod")] + [OutputType(typeof(BasicHtmlWebResponseObject))] + public class InvokeWebRequestCommand : WebRequestPSCmdlet + { + #region Virtual Method Overrides + + /// + /// Initializes a new instance of the class. + /// + public InvokeWebRequestCommand() : base() + { + _parseRelLink = true; + } + + /// + /// Process the web response and output corresponding objects. + /// + /// + internal override void ProcessResponse(HttpResponseMessage response) + { + ArgumentNullException.ThrowIfNull(response); + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); + Stream responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); + string outFilePath = WebResponseHelper.GetOutFilePath(response, _qualifiedOutFile); + + if (ShouldWriteToPipeline) + { + // Creating a MemoryStream wrapper to response stream here to support IsStopping. + responseStream = new WebResponseContentMemoryStream( + responseStream, + StreamHelper.ChunkSize, + this, + response.Content.Headers.ContentLength.GetValueOrDefault(), + perReadTimeout, + _cancelToken.Token); + WebResponseObject ro = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream, perReadTimeout, _cancelToken.Token) : new WebResponseObject(response, responseStream, perReadTimeout, _cancelToken.Token); + ro.RelationLink = _relationLink; + ro.OutFile = outFilePath; + WriteObject(ro); + + // Use the rawcontent stream from WebResponseObject for further + // processing of the stream. This is need because WebResponse's + // stream can be used only once. + responseStream = ro.RawContentStream; + responseStream.Seek(0, SeekOrigin.Begin); + } + + if (ShouldSaveToOutFile) + { + WriteVerbose($"File Name: {Path.GetFileName(outFilePath)}"); + + // ContentLength is always the partial length, while ContentRange is the full length + // Without Request.Range set, ContentRange is null and partial length (ContentLength) equals to full length + StreamHelper.SaveStreamToFile(responseStream, outFilePath, this, response.Content.Headers.ContentRange?.Length.GetValueOrDefault() ?? response.Content.Headers.ContentLength.GetValueOrDefault(), perReadTimeout, _cancelToken.Token); + } + } + + #endregion Virtual Method Overrides + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..c8fed859771d3f7098d68daebf1a3b238d312da3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Net; + +namespace Microsoft.PowerShell.Commands +{ + internal sealed class WebProxy : IWebProxy, IEquatable + { + private ICredentials? _credentials; + private readonly Uri _proxyAddress; + + internal WebProxy(Uri address) + { + ArgumentNullException.ThrowIfNull(address); + + _proxyAddress = address; + } + + public override bool Equals(object? obj) => Equals(obj as WebProxy); + + public override int GetHashCode() => HashCode.Combine(_proxyAddress, _credentials, BypassProxyOnLocal); + + public bool Equals(WebProxy? other) + { + if (other is null) + { + return false; + } + + // _proxyAddress cannot be null as it is set in the constructor + return other._credentials == _credentials + && _proxyAddress.Equals(other._proxyAddress) + && BypassProxyOnLocal == other.BypassProxyOnLocal; + } + + public ICredentials? Credentials + { + get => _credentials; + + set => _credentials = value; + } + + internal bool BypassProxyOnLocal { get; set; } + + internal bool UseDefaultCredentials + { + get => _credentials == CredentialCache.DefaultCredentials; + + set => _credentials = value ? CredentialCache.DefaultCredentials : null; + } + + public Uri GetProxy(Uri destination) + { + ArgumentNullException.ThrowIfNull(destination); + + return destination.IsLoopback ? destination : _proxyAddress; + } + + public bool IsBypassed(Uri host) => host.IsLoopback; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs new file mode 100644 index 0000000000000000000000000000000000000000..377a7e56265747323a0d9fa102555f9796b4cd3e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Net.Http; + +namespace Microsoft.PowerShell.Commands +{ + internal static class WebResponseHelper + { + internal static string? GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType?.CharSet; + + internal static Dictionary> GetHeadersDictionary(HttpResponseMessage response) + { + var headers = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (var entry in response.Headers) + { + headers[entry.Key] = entry.Value; + } + // In CoreFX, HttpResponseMessage separates content related headers, such as Content-Type to + // HttpResponseMessage.Content.Headers. The remaining headers are in HttpResponseMessage.Headers. + // The keys in both should be unique with no duplicates between them. + // Added for backwards compatibility with PowerShell 5.1 and earlier. + if (response.Content is not null) + { + foreach (var entry in response.Content.Headers) + { + headers[entry.Key] = entry.Value; + } + } + + return headers; + } + + internal static string GetOutFilePath(HttpResponseMessage response, string qualifiedOutFile) + { + // Get file name from last segment of Uri + string? lastUriSegment = System.Net.WebUtility.UrlDecode(response.RequestMessage?.RequestUri?.Segments[^1]); + + return Directory.Exists(qualifiedOutFile) ? Path.Join(qualifiedOutFile, lastUriSegment) : qualifiedOutFile; + } + + internal static string GetProtocol(HttpResponseMessage response) => string.Create(CultureInfo.InvariantCulture, $"HTTP/{response.Version}"); + + internal static int GetStatusCode(HttpResponseMessage response) => (int)response.StatusCode; + + internal static string GetStatusDescription(HttpResponseMessage response) => response.StatusCode.ToString(); + + internal static bool IsText(HttpResponseMessage response) + { + // ContentType may not exist in response header. + string? contentType = ContentHelper.GetContentType(response); + return ContentHelper.IsText(contentType); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs new file mode 100644 index 0000000000000000000000000000000000000000..5ac4adfbb648dab39e24568b2473be340f44450f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Collections.Generic; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// FormObject used in HtmlWebResponseObject. + /// + public class FormObject + { + /// + /// Gets the Id property. + /// + public string Id { get; } + + /// + /// Gets the Method property. + /// + public string Method { get; } + + /// + /// Gets the Action property. + /// + public string Action { get; } + + /// + /// Gets the Fields property. + /// + public Dictionary Fields { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public FormObject(string id, string method, string action) + { + Id = id; + Method = method; + Action = action; + Fields = new Dictionary(); + } + + internal void AddField(string key, string value) + { + if (key is not null && !Fields.TryGetValue(key, out string? _)) + { + Fields[key] = value; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs new file mode 100644 index 0000000000000000000000000000000000000000..5f9235581855d23495a9c65598b9f045bc454e14 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.ObjectModel; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// FormObjectCollection used in HtmlWebResponseObject. + /// + public class FormObjectCollection : Collection + { + /// + /// Gets the FormObject from the key. + /// + /// + /// + public FormObject? this[string key] + { + get + { + FormObject? form = null; + foreach (FormObject f in this) + { + if (string.Equals(key, f.Id, StringComparison.OrdinalIgnoreCase)) + { + form = f; + break; + } + } + + return form; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonDateKind.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonDateKind.cs new file mode 100644 index 0000000000000000000000000000000000000000..2fed27128a6dc65ba32dfac583aa2a4d7c1a9615 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonDateKind.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Enums for ConvertFrom-Json -DateKind parameter. + /// + public enum JsonDateKind + { + /// + /// DateTime values are returned as a DateTime with the Kind representing the time zone in the raw string. + /// + Default, + + /// + /// DateTime values are returned as the Local kind representation of the value. + /// + Local, + + /// + /// DateTime values are returned as the UTC kind representation of the value. + /// + Utc, + + /// + /// DateTime values are returned as a DateTimeOffset value preserving the timezone information. + /// + Offset, + + /// + /// DateTime values are returned as raw strings. + /// + String, + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs new file mode 100644 index 0000000000000000000000000000000000000000..6506f2bd2ce8a10b925da194c7ff7d035ce02535 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -0,0 +1,850 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Language; +using System.Numerics; +using System.Reflection; +using System.Threading; + +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// JsonObject class. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] + public static class JsonObject + { + #region HelperTypes + + /// + /// Context for convert-to-json operation. + /// + public readonly struct ConvertToJsonContext + { + /// + /// Gets the maximum depth for walking the object graph. + /// + public readonly int MaxDepth; + + /// + /// Gets the cancellation token. + /// + public readonly CancellationToken CancellationToken; + + /// + /// Gets the StringEscapeHandling setting. + /// + public readonly StringEscapeHandling StringEscapeHandling; + + /// + /// Gets the EnumsAsStrings setting. + /// + public readonly bool EnumsAsStrings; + + /// + /// Gets the CompressOutput setting. + /// + public readonly bool CompressOutput; + + /// + /// Gets the target cmdlet that is doing the convert-to-json operation. + /// + public readonly PSCmdlet Cmdlet; + + /// + /// Initializes a new instance of the struct. + /// + /// The maximum depth to visit the object. + /// Indicates whether to use enum names for the JSON conversion. + /// Indicates whether to get the compressed output. + public ConvertToJsonContext(int maxDepth, bool enumsAsStrings, bool compressOutput) + : this(maxDepth, enumsAsStrings, compressOutput, StringEscapeHandling.Default, targetCmdlet: null, CancellationToken.None) + { + } + + /// + /// Initializes a new instance of the struct. + /// + /// The maximum depth to visit the object. + /// Indicates whether to use enum names for the JSON conversion. + /// Indicates whether to get the compressed output. + /// Specifies how strings are escaped when writing JSON text. + /// Specifies the cmdlet that is calling this method. + /// Specifies the cancellation token for cancelling the operation. + public ConvertToJsonContext( + int maxDepth, + bool enumsAsStrings, + bool compressOutput, + StringEscapeHandling stringEscapeHandling, + PSCmdlet targetCmdlet, + CancellationToken cancellationToken) + { + this.MaxDepth = maxDepth; + this.CancellationToken = cancellationToken; + this.StringEscapeHandling = stringEscapeHandling; + this.EnumsAsStrings = enumsAsStrings; + this.CompressOutput = compressOutput; + this.Cmdlet = targetCmdlet; + } + } + + private sealed class DuplicateMemberHashSet : HashSet + { + public DuplicateMemberHashSet(int capacity) + : base(capacity, StringComparer.OrdinalIgnoreCase) + { + } + } + + #endregion HelperTypes + + #region ConvertFromJson + + /// + /// Convert a Json string back to an object of type PSObject. + /// + /// The json text to convert. + /// An error record if the conversion failed. + /// A PSObject. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] + public static object ConvertFromJson(string input, out ErrorRecord error) + { + return ConvertFromJson(input, returnHashtable: false, out error); + } + + /// + /// Convert a Json string back to an object of type or + /// depending on parameter . + /// + /// The json text to convert. + /// True if the result should be returned as a + /// instead of a + /// An error record if the conversion failed. + /// A or a + /// if the parameter is true. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] + public static object ConvertFromJson(string input, bool returnHashtable, out ErrorRecord error) + { + return ConvertFromJson(input, returnHashtable, maxDepth: 1024, out error); + } + + /// + /// Convert a JSON string back to an object of type or + /// depending on parameter . + /// + /// The JSON text to convert. + /// True if the result should be returned as a + /// instead of a . + /// The max depth allowed when deserializing the json input. Set to null for no maximum. + /// An error record if the conversion failed. + /// A or a + /// if the parameter is true. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] + public static object ConvertFromJson(string input, bool returnHashtable, int? maxDepth, out ErrorRecord error) + => ConvertFromJson(input, returnHashtable, maxDepth, jsonDateKind: JsonDateKind.Default, out error); + + /// + /// Convert a JSON string back to an object of type or + /// depending on parameter . + /// + /// The JSON text to convert. + /// True if the result should be returned as a + /// instead of a . + /// The max depth allowed when deserializing the json input. Set to null for no maximum. + /// Controls how DateTime values are to be converted. + /// An error record if the conversion failed. + /// A or a + /// if the parameter is true. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] + internal static object ConvertFromJson(string input, bool returnHashtable, int? maxDepth, JsonDateKind jsonDateKind, out ErrorRecord error) + { + ArgumentNullException.ThrowIfNull(input); + + DateParseHandling dateParseHandling; + DateTimeZoneHandling dateTimeZoneHandling; + switch (jsonDateKind) + { + case JsonDateKind.Default: + dateParseHandling = DateParseHandling.DateTime; + dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; + break; + + case JsonDateKind.Local: + dateParseHandling = DateParseHandling.DateTime; + dateTimeZoneHandling = DateTimeZoneHandling.Local; + break; + + case JsonDateKind.Utc: + dateParseHandling = DateParseHandling.DateTime; + dateTimeZoneHandling = DateTimeZoneHandling.Utc; + break; + + case JsonDateKind.Offset: + dateParseHandling = DateParseHandling.DateTimeOffset; + dateTimeZoneHandling = DateTimeZoneHandling.Unspecified; + break; + + case JsonDateKind.String: + dateParseHandling = DateParseHandling.None; + dateTimeZoneHandling = DateTimeZoneHandling.Unspecified; + break; + + default: + throw new ArgumentException($"Unknown JsonDateKind value requested '{jsonDateKind}'"); + } + + error = null; + try + { + var obj = JsonConvert.DeserializeObject( + input, + new JsonSerializerSettings + { + DateParseHandling = dateParseHandling, + DateTimeZoneHandling = dateTimeZoneHandling, + + // This TypeNameHandling setting is required to be secure. + TypeNameHandling = TypeNameHandling.None, + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, + MaxDepth = maxDepth + }); + + switch (obj) + { + case JObject dictionary: + // JObject is a IDictionary + return returnHashtable + ? PopulateHashTableFromJDictionary(dictionary, out error) + : PopulateFromJDictionary(dictionary, new DuplicateMemberHashSet(dictionary.Count), out error); + case JArray list: + return returnHashtable + ? PopulateHashTableFromJArray(list, out error) + : PopulateFromJArray(list, out error); + default: + return obj; + } + } + catch (JsonException je) + { + var msg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, je.Message); + + // the same as JavaScriptSerializer does + throw new ArgumentException(msg, je); + } + } + + // This function is a clone of PopulateFromDictionary using JObject as an input. + private static PSObject PopulateFromJDictionary(JObject entries, DuplicateMemberHashSet memberHashTracker, out ErrorRecord error) + { + error = null; + var result = new PSObject(entries.Count); + foreach (var entry in entries) + { + if (string.IsNullOrEmpty(entry.Key)) + { + var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.EmptyKeyInJsonString); + error = new ErrorRecord( + new InvalidOperationException(errorMsg), + "EmptyKeyInJsonString", + ErrorCategory.InvalidOperation, + null); + return null; + } + + // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject + // does not throw when encountering duplicates and just uses the last entry. + if (memberHashTracker.TryGetValue(entry.Key, out var maybePropertyName) + && string.Equals(entry.Key, maybePropertyName, StringComparison.Ordinal)) + { + var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.DuplicateKeysInJsonString, entry.Key); + error = new ErrorRecord( + new InvalidOperationException(errorMsg), + "DuplicateKeysInJsonString", + ErrorCategory.InvalidOperation, + null); + return null; + } + + // Compare case insensitive to tell the user to use the -AsHashTable option instead. + // This is because PSObject cannot have keys with different casing. + if (memberHashTracker.TryGetValue(entry.Key, out var propertyName)) + { + var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.KeysWithDifferentCasingInJsonString, propertyName, entry.Key); + error = new ErrorRecord( + new InvalidOperationException(errorMsg), + "KeysWithDifferentCasingInJsonString", + ErrorCategory.InvalidOperation, + null); + return null; + } + + switch (entry.Value) + { + case JArray list: + { + // Array + var listResult = PopulateFromJArray(list, out error); + if (error != null) + { + return null; + } + + result.Properties.Add(new PSNoteProperty(entry.Key, listResult)); + break; + } + case JObject dic: + { + // Dictionary + var dicResult = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error); + if (error != null) + { + return null; + } + + result.Properties.Add(new PSNoteProperty(entry.Key, dicResult)); + break; + } + case JValue value: + { + result.Properties.Add(new PSNoteProperty(entry.Key, value.Value)); + break; + } + } + + memberHashTracker.Add(entry.Key); + } + + return result; + } + + // This function is a clone of PopulateFromList using JArray as input. + private static ICollection PopulateFromJArray(JArray list, out ErrorRecord error) + { + error = null; + var result = new object[list.Count]; + var i = 0; + + foreach (var element in list) + { + switch (element) + { + case JArray subList: + // Array + result[i++] = PopulateFromJArray(subList, out error); + if (error != null) + { + return null; + } + + break; + + case JObject dic: + // Dictionary + result[i++] = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error); + if (error != null) + { + return null; + } + + break; + + case JValue value: + if (value.Type != JTokenType.Comment) + { + result[i++] = value.Value; + } + + break; + } + } + + // In the common case of not having any comments, return the original array, otherwise create a sliced copy. + return i == list.Count ? result : result[..i]; + } + + // This function is a clone of PopulateFromDictionary using JObject as an input. + private static Hashtable PopulateHashTableFromJDictionary(JObject entries, out ErrorRecord error) + { + error = null; + OrderedHashtable result = new(entries.Count); + foreach (var entry in entries) + { + // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject + // does not throw when encountering duplicates and just uses the last entry. + if (result.ContainsKey(entry.Key)) + { + string errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.DuplicateKeysInJsonString, entry.Key); + error = new ErrorRecord( + new InvalidOperationException(errorMsg), + "DuplicateKeysInJsonString", + ErrorCategory.InvalidOperation, + null); + return null; + } + + switch (entry.Value) + { + case JArray list: + { + // Array + var listResult = PopulateHashTableFromJArray(list, out error); + if (error != null) + { + return null; + } + + result.Add(entry.Key, listResult); + break; + } + case JObject dic: + { + // Dictionary + var dicResult = PopulateHashTableFromJDictionary(dic, out error); + if (error != null) + { + return null; + } + + result.Add(entry.Key, dicResult); + break; + } + case JValue value: + { + result.Add(entry.Key, value.Value); + break; + } + } + } + + return result; + } + + // This function is a clone of PopulateFromList using JArray as input. + private static ICollection PopulateHashTableFromJArray(JArray list, out ErrorRecord error) + { + error = null; + var result = new object[list.Count]; + var i = 0; + + foreach (var element in list) + { + switch (element) + { + case JArray subList: + // Array + result[i++] = PopulateHashTableFromJArray(subList, out error); + if (error != null) + { + return null; + } + + break; + + case JObject dic: + // Dictionary + result[i++] = PopulateHashTableFromJDictionary(dic, out error); + if (error != null) + { + return null; + } + + break; + + case JValue value: + if (value.Type != JTokenType.Comment) + { + result[i++] = value.Value; + } + + break; + } + } + + // In the common case of not having any comments, return the original array, otherwise create a sliced copy. + return i == list.Count ? result : result[..i]; + } + + #endregion ConvertFromJson + + #region ConvertToJson + + /// + /// Convert an object to JSON string. + /// + public static string ConvertToJson(object objectToProcess, in ConvertToJsonContext context) + { + try + { + // Pre-process the object so that it serializes the same, except that properties whose + // values cannot be evaluated are treated as having the value null. + _maxDepthWarningWritten = false; + object preprocessedObject = ProcessValue(objectToProcess, currentDepth: 0, in context); + var jsonSettings = new JsonSerializerSettings + { + // This TypeNameHandling setting is required to be secure. + TypeNameHandling = TypeNameHandling.None, + MaxDepth = 1024, + StringEscapeHandling = context.StringEscapeHandling + }; + + if (context.EnumsAsStrings) + { + jsonSettings.Converters.Add(new StringEnumConverter()); + } + + if (!context.CompressOutput) + { + jsonSettings.Formatting = Formatting.Indented; + } + + return JsonConvert.SerializeObject(preprocessedObject, jsonSettings); + } + catch (OperationCanceledException) + { + return null; + } + } + + private static bool _maxDepthWarningWritten; + + /// + /// Return an alternate representation of the specified object that serializes the same JSON, except + /// that properties that cannot be evaluated are treated as having the value null. + /// Primitive types are returned verbatim. Aggregate types are processed recursively. + /// + /// The object to be processed. + /// The current depth into the object graph. + /// The context to use for the convert-to-json operation. + /// An object suitable for serializing to JSON. + private static object ProcessValue(object obj, int currentDepth, in ConvertToJsonContext context) + { + context.CancellationToken.ThrowIfCancellationRequested(); + + if (LanguagePrimitives.IsNull(obj)) + { + return null; + } + + PSObject pso = obj as PSObject; + + if (pso != null) + { + obj = pso.BaseObject; + } + + object rv = obj; + bool isPurePSObj = false; + bool isCustomObj = false; + + if (obj == NullString.Value + || obj == DBNull.Value) + { + rv = null; + } + else if (obj is string + || obj is char + || obj is bool + || obj is DateTime + || obj is DateTimeOffset + || obj is Guid + || obj is Uri + || obj is double + || obj is float + || obj is decimal + || obj is BigInteger) + { + rv = obj; + } + else if (obj is Newtonsoft.Json.Linq.JObject jObject) + { + rv = jObject.ToObject>(); + } + else + { + Type t = obj.GetType(); + + if (t.IsPrimitive || (t.IsEnum && ExperimentalFeature.IsEnabled(ExperimentalFeature.PSSerializeJSONLongEnumAsNumber))) + { + rv = obj; + } + else if (t.IsEnum) + { + // Win8:378368 Enums based on System.Int64 or System.UInt64 are not JSON-serializable + // because JavaScript does not support the necessary precision. + Type enumUnderlyingType = Enum.GetUnderlyingType(obj.GetType()); + if (enumUnderlyingType.Equals(typeof(long)) || enumUnderlyingType.Equals(typeof(ulong))) + { + rv = obj.ToString(); + } + else + { + rv = obj; + } + } + else + { + if (currentDepth > context.MaxDepth) + { + if (!_maxDepthWarningWritten && context.Cmdlet != null) + { + _maxDepthWarningWritten = true; + string maxDepthMessage = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.JsonMaxDepthReached, + context.MaxDepth); + context.Cmdlet.WriteWarning(maxDepthMessage); + } + + if (pso != null && pso.ImmediateBaseObjectIsEmpty) + { + // The obj is a pure PSObject, we convert the original PSObject to a string, + // instead of its base object in this case + rv = LanguagePrimitives.ConvertTo(pso, typeof(string), + CultureInfo.InvariantCulture); + isPurePSObj = true; + } + else + { + rv = LanguagePrimitives.ConvertTo(obj, typeof(string), + CultureInfo.InvariantCulture); + } + } + else + { + if (obj is IDictionary dict) + { + rv = ProcessDictionary(dict, currentDepth, in context); + } + else + { + if (obj is IEnumerable enumerable) + { + rv = ProcessEnumerable(enumerable, currentDepth, in context); + } + else + { + rv = ProcessCustomObject(obj, currentDepth, in context); + isCustomObj = true; + } + } + } + } + } + + rv = AddPsProperties(pso, rv, currentDepth, isPurePSObj, isCustomObj, in context); + + return rv; + } + + /// + /// Add to a base object any properties that might have been added to an object (via PSObject) through the Add-Member cmdlet. + /// + /// The containing PSObject, or null if the base object was not contained in a PSObject. + /// The base object that might have been decorated with additional properties. + /// The current depth into the object graph. + /// The processed object is a pure PSObject. + /// The processed object is a custom object. + /// The context for the operation. + /// + /// The original base object if no additional properties had been added, + /// otherwise a dictionary containing the value of the original base object in the "value" key + /// as well as the names and values of an additional properties. + /// + private static object AddPsProperties(object psObj, object obj, int depth, bool isPurePSObj, bool isCustomObj, in ConvertToJsonContext context) + { + if (psObj is not PSObject pso) + { + return obj; + } + + // when isPurePSObj is true, the obj is guaranteed to be a string converted by LanguagePrimitives + if (isPurePSObj) + { + return obj; + } + + bool wasDictionary = true; + + if (obj is not IDictionary dict) + { + wasDictionary = false; + dict = new Dictionary(); + dict.Add("value", obj); + } + + AppendPsProperties(pso, dict, depth, isCustomObj, in context); + + if (!wasDictionary && dict.Count == 1) + { + return obj; + } + + return dict; + } + + /// + /// Append to a dictionary any properties that might have been added to an object (via PSObject) through the Add-Member cmdlet. + /// If the passed in object is a custom object (not a simple object, not a dictionary, not a list, get processed in ProcessCustomObject method), + /// we also take Adapted properties into account. Otherwise, we only consider the Extended properties. + /// When the object is a pure PSObject, it also gets processed in "ProcessCustomObject" before reaching this method, so we will + /// iterate both extended and adapted properties for it. Since it's a pure PSObject, there will be no adapted properties. + /// + /// The containing PSObject, or null if the base object was not contained in a PSObject. + /// The dictionary to which any additional properties will be appended. + /// The current depth into the object graph. + /// The processed object is a custom object. + /// The context for the operation. + private static void AppendPsProperties(PSObject psObj, IDictionary receiver, int depth, bool isCustomObject, in ConvertToJsonContext context) + { + // if the psObj is a DateTime or String type, we don't serialize any extended or adapted properties + if (psObj.BaseObject is string || psObj.BaseObject is DateTime) + { + return; + } + + // serialize only Extended and Adapted properties.. + PSMemberInfoCollection srcPropertiesToSearch = + new PSMemberInfoIntegratingCollection(psObj, + isCustomObject ? PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted) : + PSObject.GetPropertyCollection(PSMemberViewTypes.Extended)); + + foreach (PSPropertyInfo prop in srcPropertiesToSearch) + { + object value = null; + try + { + value = prop.Value; + } + catch (Exception) + { + } + + if (!receiver.Contains(prop.Name)) + { + receiver[prop.Name] = ProcessValue(value, depth + 1, in context); + } + } + } + + /// + /// Return an alternate representation of the specified dictionary that serializes the same JSON, except + /// that any contained properties that cannot be evaluated are treated as having the value null. + /// + private static object ProcessDictionary(IDictionary dict, int depth, in ConvertToJsonContext context) + { + Dictionary result = new(dict.Count); + + foreach (DictionaryEntry entry in dict) + { + string name = entry.Key as string; + if (name == null) + { + // use the error string that matches the message from JavaScriptSerializer + string errorMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.NonStringKeyInDictionary, + dict.GetType().FullName); + + var exception = new InvalidOperationException(errorMsg); + if (context.Cmdlet != null) + { + var errorRecord = new ErrorRecord(exception, "NonStringKeyInDictionary", ErrorCategory.InvalidOperation, dict); + context.Cmdlet.ThrowTerminatingError(errorRecord); + } + else + { + throw exception; + } + } + + result.Add(name, ProcessValue(entry.Value, depth + 1, in context)); + } + + return result; + } + + /// + /// Return an alternate representation of the specified collection that serializes the same JSON, except + /// that any contained properties that cannot be evaluated are treated as having the value null. + /// + private static object ProcessEnumerable(IEnumerable enumerable, int depth, in ConvertToJsonContext context) + { + List result = new(); + + foreach (object o in enumerable) + { + result.Add(ProcessValue(o, depth + 1, in context)); + } + + return result; + } + + /// + /// Return an alternate representation of the specified aggregate object that serializes the same JSON, except + /// that any contained properties that cannot be evaluated are treated as having the value null. + /// + /// The result is a dictionary in which all public fields and public gettable properties of the original object + /// are represented. If any exception occurs while retrieving the value of a field or property, that entity + /// is included in the output dictionary with a value of null. + /// + private static object ProcessCustomObject(object o, int depth, in ConvertToJsonContext context) + { + Dictionary result = new(); + Type t = o.GetType(); + + foreach (FieldInfo info in t.GetFields(BindingFlags.Public | BindingFlags.Instance)) + { + if (!info.IsDefined(typeof(T), true)) + { + object value; + try + { + value = info.GetValue(o); + } + catch (Exception) + { + value = null; + } + + result.Add(info.Name, ProcessValue(value, depth + 1, in context)); + } + } + + foreach (PropertyInfo info2 in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (!info2.IsDefined(typeof(T), true)) + { + MethodInfo getMethod = info2.GetGetMethod(); + if ((getMethod != null) && (getMethod.GetParameters().Length == 0)) + { + object value; + try + { + value = getMethod.Invoke(o, Array.Empty()); + } + catch (Exception) + { + value = null; + } + + result.Add(info2.Name, ProcessValue(value, depth + 1, in context)); + } + } + } + + return result; + } + + #endregion ConvertToJson + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs new file mode 100644 index 0000000000000000000000000000000000000000..1a19d6b0457aed41acb3e78c2e7aa37bb1e0067f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Globalization; +using System.Management.Automation; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Construct the Useragent string. + /// + public static class PSUserAgent + { + private static string? s_windowsUserAgent; + + // Format the user-agent string from the various component parts + internal static string UserAgent => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) {App}"); + + /// + /// Useragent string for InternetExplorer (9.0). + /// + public static string InternetExplorer => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} (compatible; MSIE 9.0; {PlatformName}; {OS}; {Culture})"); + + /// + /// Useragent string for Firefox (4.0). + /// + public static string FireFox => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) Gecko/20100401 Firefox/4.0"); + + /// + /// Useragent string for Chrome (7.0). + /// + public static string Chrome => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6"); + + /// + /// Useragent string for Opera (9.0). + /// + public static string Opera => string.Create(CultureInfo.InvariantCulture, $"Opera/9.70 ({PlatformName}; {OS}; {Culture}) Presto/2.2.1"); + + /// + /// Useragent string for Safari (5.0). + /// + public static string Safari => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"); + + internal static string Compatibility => "Mozilla/5.0"; + + internal static string App => string.Create(CultureInfo.InvariantCulture, $"PowerShell/{PSVersionInfo.PSVersion}"); + + internal static string PlatformName + { + get + { + if (Platform.IsWindows) + { + // Only generate the windows user agent once + if (s_windowsUserAgent is null) + { + // Find the version in the windows operating system description + Regex pattern = new(@"\d+(\.\d+)+"); + string versionText = pattern.Match(OS).Value; + Version windowsPlatformversion = new(versionText); + s_windowsUserAgent = $"Windows NT {windowsPlatformversion.Major}.{windowsPlatformversion.Minor}"; + } + + return s_windowsUserAgent; + } + else if (Platform.IsMacOS) + { + return "Macintosh"; + } + else if (Platform.IsLinux) + { + return "Linux"; + } + else + { + // Unknown/unsupported platform + Diagnostics.Assert(false, "Unable to determine Operating System Platform"); + return string.Empty; + } + } + } + + internal static string OS => RuntimeInformation.OSDescription.Trim(); + + internal static string Culture => CultureInfo.CurrentCulture.Name; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..d24961834b6af560326f0ec393e3ef3b63e261bf --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -0,0 +1,557 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Buffers; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Microsoft.PowerShell.Commands.WebResponse has a public property RawContentStream + /// which is of type MemoryStream. We shipped like that in PowerShell 3. Creating + /// this class as a wrapper to MemoryStream to lazily initialize. Otherwise, the + /// content will unnecessarily be read even if there are no consumers for it. + /// + internal sealed class WebResponseContentMemoryStream : MemoryStream + { + #region Data + + private readonly long? _contentLength; + private readonly Stream _originalStreamToProxy; + private readonly Cmdlet? _ownerCmdlet; + private readonly CancellationToken _cancellationToken; + private readonly TimeSpan _perReadTimeout; + private bool _isInitialized = false; + + #endregion Data + + #region Constructors + /// + /// Initializes a new instance of the class. + /// + /// Response stream. + /// Presize the memory stream. + /// Owner cmdlet if any. + /// Expected download size in Bytes. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// Cancellation token. + internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet? cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) : base(initialCapacity) + { + this._contentLength = contentLength; + _originalStreamToProxy = stream; + _ownerCmdlet = cmdlet; + _cancellationToken = cancellationToken; + _perReadTimeout = perReadTimeout; + } + #endregion Constructors + + /// + /// + public override bool CanRead => true; + + /// + /// + public override bool CanSeek => true; + + /// + /// + public override bool CanWrite => true; + + /// + /// + public override long Length + { + get + { + Initialize(); + return base.Length; + } + } + + /// + /// + /// + /// + /// + /// + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) + { + Initialize(cancellationToken); + return base.CopyToAsync(destination, bufferSize, cancellationToken); + } + + /// + /// + /// + /// + /// + /// + public override int Read(byte[] buffer, int offset, int count) + { + Initialize(); + return base.Read(buffer, offset, count); + } + + /// + /// + /// + /// + /// + /// + /// + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + Initialize(cancellationToken); + return base.ReadAsync(buffer, offset, count, cancellationToken); + } + + /// + /// + /// + public override int ReadByte() + { + Initialize(); + return base.ReadByte(); + } + + /// + /// + /// + public override void SetLength(long value) + { + Initialize(); + base.SetLength(value); + } + + /// + /// + /// + public override byte[] ToArray() + { + Initialize(); + return base.ToArray(); + } + + /// + /// + /// + /// + /// + public override void Write(byte[] buffer, int offset, int count) + { + Initialize(); + base.Write(buffer, offset, count); + } + + /// + /// + /// + /// + /// + /// + /// + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + Initialize(cancellationToken); + return base.WriteAsync(buffer, offset, count, cancellationToken); + } + + /// + /// + /// + public override void WriteByte(byte value) + { + Initialize(); + base.WriteByte(value); + } + + /// + /// + /// + public override void WriteTo(Stream stream) + { + Initialize(); + base.WriteTo(stream); + } + + /// + /// + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + } + + private void Initialize(CancellationToken cancellationToken = default) + { + if (_isInitialized) + { + return; + } + + if (cancellationToken == default) + { + cancellationToken = _cancellationToken; + } + + _isInitialized = true; + try + { + long totalRead = 0; + byte[] buffer = new byte[StreamHelper.ChunkSize]; + ProgressRecord record = new(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); + string totalDownloadSize = _contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)_contentLength); + for (int read = 1; read > 0; totalRead += read) + { + if (_ownerCmdlet is not null) + { + record.StatusDescription = StringUtil.Format( + WebCmdletStrings.ReadResponseProgressStatus, + Utils.DisplayHumanReadableFileSize(totalRead), + totalDownloadSize); + + if (_contentLength > 0) + { + record.PercentComplete = Math.Min((int)(totalRead * 100 / (long)_contentLength), 100); + } + + _ownerCmdlet.WriteProgress(record); + + if (_ownerCmdlet.IsStopping) + { + break; + } + } + + read = _originalStreamToProxy.ReadAsync(buffer.AsMemory(), _perReadTimeout, cancellationToken).GetAwaiter().GetResult(); + + if (read > 0) + { + base.Write(buffer, 0, read); + } + } + + if (_ownerCmdlet is not null) + { + record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalRead); + record.RecordType = ProgressRecordType.Completed; + _ownerCmdlet.WriteProgress(record); + } + + // Make sure the length is set appropriately + base.SetLength(totalRead); + Seek(0, SeekOrigin.Begin); + } + catch (Exception) + { + Dispose(); + throw; + } + } + } + + internal static class StreamTimeoutExtensions + { + internal static async Task ReadAsync(this Stream stream, Memory buffer, TimeSpan readTimeout, CancellationToken cancellationToken) + { + if (readTimeout == Timeout.InfiniteTimeSpan) + { + return await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + try + { + cts.CancelAfter(readTimeout); + return await stream.ReadAsync(buffer, cts.Token).ConfigureAwait(false); + } + catch (TaskCanceledException ex) + { + if (cts.IsCancellationRequested) + { + throw new TimeoutException($"The request was canceled due to the configured OperationTimeout of {readTimeout.TotalSeconds} seconds elapsing", ex); + } + else + { + throw; + } + } + } + + internal static async Task CopyToAsync(this Stream source, Stream destination, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + if (perReadTimeout == Timeout.InfiniteTimeSpan) + { + // No timeout - use fast path + await source.CopyToAsync(destination, cancellationToken).ConfigureAwait(false); + return; + } + + byte[] buffer = ArrayPool.Shared.Rent(StreamHelper.ChunkSize); + CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + try + { + while (true) + { + if (!cts.TryReset()) + { + cts.Dispose(); + cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + } + + cts.CancelAfter(perReadTimeout); + int bytesRead = await source.ReadAsync(buffer, cts.Token).ConfigureAwait(false); + if (bytesRead == 0) + { + break; + } + + await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + } + catch (TaskCanceledException ex) + { + if (cts.IsCancellationRequested) + { + throw new TimeoutException($"The request was canceled due to the configured OperationTimeout of {perReadTimeout.TotalSeconds} seconds elapsing", ex); + } + else + { + throw; + } + } + finally + { + cts.Dispose(); + ArrayPool.Shared.Return(buffer); + } + } + } + + internal static class StreamHelper + { + #region Constants + + internal const int DefaultReadBuffer = 100000; + + internal const int ChunkSize = 10000; + + // Just picked a random number + internal const int ActivityId = 174593042; + + #endregion Constants + + #region Static Methods + + internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(cmdlet); + + Task copyTask = input.CopyToAsync(output, perReadTimeout, cancellationToken); + + bool wroteProgress = false; + ProgressRecord record = new( + ActivityId, + WebCmdletStrings.WriteRequestProgressActivity, + WebCmdletStrings.WriteRequestProgressStatus); + string totalDownloadSize = contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)contentLength); + + try + { + while (!copyTask.Wait(1000, cancellationToken)) + { + record.StatusDescription = StringUtil.Format( + WebCmdletStrings.WriteRequestProgressStatus, + Utils.DisplayHumanReadableFileSize(output.Position), + totalDownloadSize); + + if (contentLength > 0) + { + record.PercentComplete = Math.Min((int)(output.Position * 100 / (long)contentLength), 100); + } + + cmdlet.WriteProgress(record); + wroteProgress = true; + } + } + catch (OperationCanceledException) + { + } + finally + { + if (wroteProgress) + { + // Write out the completion progress record only if we did render the progress. + record.StatusDescription = StringUtil.Format( + copyTask.IsCompleted + ? WebCmdletStrings.WriteRequestComplete + : WebCmdletStrings.WriteRequestCancelled, + output.Position); + record.RecordType = ProgressRecordType.Completed; + cmdlet.WriteProgress(record); + } + } + } + + /// + /// Saves content from stream into filePath. + /// Caller need to ensure position is properly set. + /// + /// Input stream. + /// Output file name. + /// Current cmdlet (Invoke-WebRequest or Invoke-RestMethod). + /// Expected download size in Bytes. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// CancellationToken to track the cmdlet cancellation. + internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + // If the web cmdlet should resume, append the file instead of overwriting. + FileMode fileMode = cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume ? FileMode.Append : FileMode.Create; + using FileStream output = new(filePath, fileMode, FileAccess.Write, FileShare.Read); + WriteToStream(stream, output, cmdlet, contentLength, perReadTimeout, cancellationToken); + } + + private static string StreamToString(Stream stream, Encoding encoding, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + StringBuilder result = new(capacity: ChunkSize); + Decoder decoder = encoding.GetDecoder(); + + int useBufferSize = 64; + if (useBufferSize < encoding.GetMaxCharCount(10)) + { + useBufferSize = encoding.GetMaxCharCount(10); + } + + char[] chars = ArrayPool.Shared.Rent(useBufferSize); + byte[] bytes = ArrayPool.Shared.Rent(useBufferSize * 4); + try + { + int bytesRead = 0; + do + { + // Read at most the number of bytes that will fit in the input buffer. The + // return value is the actual number of bytes read, or zero if no bytes remain. + bytesRead = stream.ReadAsync(bytes.AsMemory(), perReadTimeout, cancellationToken).GetAwaiter().GetResult(); + + bool completed = false; + int byteIndex = 0; + + while (!completed) + { + // If this is the last input data, flush the decoder's internal buffer and state. + bool flush = bytesRead is 0; + decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, useBufferSize, flush, out int bytesUsed, out int charsUsed, out completed); + + // The conversion produced the number of characters indicated by charsUsed. Write that number + // of characters to our result buffer + result.Append(chars, 0, charsUsed); + + // Increment byteIndex to the next block of bytes in the input buffer, if any, to convert. + byteIndex += bytesUsed; + + // The behavior of decoder.Convert changed start .NET 3.1-preview2. + // The change was made in https://github.com/dotnet/coreclr/pull/27229 + // The recommendation from .NET team is to not check for 'completed' if 'flush' is false. + // Break out of the loop if all bytes have been read. + if (!flush && bytesRead == byteIndex) + { + break; + } + } + } + while (bytesRead != 0); + + return result.ToString(); + } + finally + { + ArrayPool.Shared.Return(chars); + ArrayPool.Shared.Return(bytes); + } + } + + internal static string DecodeStream(Stream stream, string? characterSet, out Encoding encoding, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + bool isDefaultEncoding = !TryGetEncoding(characterSet, out encoding); + + string content = StreamToString(stream, encoding, perReadTimeout, cancellationToken); + if (isDefaultEncoding) + { + // We only look within the first 1k characters as the meta element and + // the xml declaration are at the start of the document + string substring = content.Substring(0, Math.Min(content.Length, 1024)); + + // Check for a charset attribute on the meta element to override the default + Match match = s_metaRegex.Match(substring); + + // Check for a encoding attribute on the xml declaration to override the default + if (!match.Success) + { + match = s_xmlRegex.Match(substring); + } + + if (match.Success) + { + characterSet = match.Groups["charset"].Value; + + if (TryGetEncoding(characterSet, out Encoding localEncoding)) + { + stream.Seek(0, SeekOrigin.Begin); + content = StreamToString(stream, localEncoding, perReadTimeout, cancellationToken); + encoding = localEncoding; + } + } + } + + return content; + } + + internal static bool TryGetEncoding(string? characterSet, out Encoding encoding) + { + bool result = false; + try + { + encoding = Encoding.GetEncoding(characterSet!); + result = true; + } + catch (ArgumentException) + { + // Use the default encoding if one wasn't provided + encoding = ContentHelper.GetDefaultEncoding(); + } + + return result; + } + + private static readonly Regex s_metaRegex = new( + @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", + RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking + ); + + private static readonly Regex s_xmlRegex = new( + @"<\?xml\s.*[^.><]*encoding\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", + RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking + ); + + internal static byte[] EncodeToBytes(string str, Encoding encoding) + { + // Just use the default encoding if one wasn't provided + encoding ??= ContentHelper.GetDefaultEncoding(); + + return encoding.GetBytes(str); + } + + internal static Stream GetResponseStream(HttpResponseMessage response, CancellationToken cancellationToken) => response.Content.ReadAsStreamAsync(cancellationToken).GetAwaiter().GetResult(); + + #endregion Static Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs new file mode 100644 index 0000000000000000000000000000000000000000..99326898d9f474a397b9b03442dd88af07a79f87 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// WebCmdletElementCollection for elements in html web responses. + /// + public class WebCmdletElementCollection : ReadOnlyCollection + { + internal WebCmdletElementCollection(IList list) : base(list) + { + } + + /// + /// Finds the element with name or id. + /// + /// + /// Found element as PSObject. + public PSObject? Find(string nameOrId) => FindById(nameOrId) ?? FindByName(nameOrId); + + /// + /// Finds the element by id. + /// + /// + /// Found element as PSObject. + public PSObject? FindById(string id) => Find(id, findById: true); + + /// + /// Finds the element by name. + /// + /// + /// Found element as PSObject. + public PSObject? FindByName(string name) => Find(name, findById: false); + + private PSObject? Find(string nameOrId, bool findById) + { + foreach (PSObject candidate in this) + { + var namePropInfo = candidate.Properties[(findById ? "id" : "name")]; + if (namePropInfo != null && (string)namePropInfo.Value == nameOrId) + { + return candidate; + } + } + + return null; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs new file mode 100644 index 0000000000000000000000000000000000000000..9b90115a1d5c6f412441ea950737d43fc6b1d34d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Enums for web request method. + /// + public enum WebRequestMethod + { + /// + /// Default method. + /// + Default, + + /// + /// GET method. + /// + Get, + + /// + /// HEAD method. + /// + Head, + + /// + /// POST method. + /// + Post, + + /// + /// PUT method. + /// + Put, + + /// + /// DELETE method. + /// + Delete, + + /// + /// TRACE method. + /// + Trace, + + /// + /// OPTIONS method. + /// + Options, + + /// + /// MERGE method. + /// + Merge, + + /// + /// PATCH method. + /// + Patch, + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs new file mode 100644 index 0000000000000000000000000000000000000000..efee6f3240eb818ef85c7a7be7495f17eff6ca6d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -0,0 +1,315 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// WebRequestSession for holding session infos. + /// + public class WebRequestSession : IDisposable + { + #region Fields + + private HttpClient? _client; + private CookieContainer _cookies; + private bool _useDefaultCredentials; + private ICredentials? _credentials; + private X509CertificateCollection? _certificates; + private IWebProxy? _proxy; + private int _maximumRedirection; + private WebSslProtocol _sslProtocol; + private bool _allowAutoRedirect; + private bool _skipCertificateCheck; + private bool _noProxy; + private bool _disposed; + private TimeSpan _connectionTimeout; + private UnixDomainSocketEndPoint? _unixSocket; + + /// + /// Contains true if an existing HttpClient had to be disposed and recreated since the WebSession was last used. + /// + private bool _disposedClient; + + #endregion Fields + + /// + /// Gets or sets the Header property. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Dictionary Headers { get; set; } + + /// + /// Gets or sets the content Headers when using HttpClient. + /// + internal Dictionary ContentHeaders { get; set; } + + /// + /// Gets or sets the Cookies property. + /// + public CookieContainer Cookies { get => _cookies; set => SetClassVar(ref _cookies, value); } + + #region Credentials + + /// + /// Gets or sets the UseDefaultCredentials property. + /// + public bool UseDefaultCredentials { get => _useDefaultCredentials; set => SetStructVar(ref _useDefaultCredentials, value); } + + /// + /// Gets or sets the Credentials property. + /// + public ICredentials? Credentials { get => _credentials; set => SetClassVar(ref _credentials, value); } + + /// + /// Gets or sets the Certificates property. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public X509CertificateCollection? Certificates { get => _certificates; set => SetClassVar(ref _certificates, value); } + + #endregion Credentials + + /// + /// Gets or sets the UserAgent property. + /// + public string UserAgent { get; set; } + + /// + /// Gets or sets the Proxy property. + /// + public IWebProxy? Proxy + { + get => _proxy; + set + { + SetClassVar(ref _proxy, value); + if (_proxy is not null) + { + NoProxy = false; + } + } + } + + /// + /// Gets or sets the MaximumRedirection property. + /// + public int MaximumRedirection { get => _maximumRedirection; set => SetStructVar(ref _maximumRedirection, value); } + + /// + /// Gets or sets the count of retries for request failures. + /// + public int MaximumRetryCount { get; set; } + + /// + /// Gets or sets the interval in seconds between retries. + /// + public int RetryIntervalInSeconds { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public WebRequestSession() + { + // Build the headers collection + Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + ContentHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); + + // Build the cookie jar + _cookies = new CookieContainer(); + + // Initialize the credential and certificate caches + _useDefaultCredentials = false; + _credentials = null; + _certificates = null; + + // Setup the default UserAgent + UserAgent = PSUserAgent.UserAgent; + + _proxy = null; + _maximumRedirection = -1; + _allowAutoRedirect = true; + } + + internal WebSslProtocol SslProtocol { set => SetStructVar(ref _sslProtocol, value); } + + internal bool SkipCertificateCheck { set => SetStructVar(ref _skipCertificateCheck, value); } + + internal TimeSpan ConnectionTimeout { set => SetStructVar(ref _connectionTimeout, value); } + + internal UnixDomainSocketEndPoint UnixSocket { set => SetClassVar(ref _unixSocket, value); } + + internal bool NoProxy + { + set + { + SetStructVar(ref _noProxy, value); + if (_noProxy) + { + Proxy = null; + } + } + } + + /// + /// Add a X509Certificate to the Certificates collection. + /// + /// The certificate to be added. + internal void AddCertificate(X509Certificate certificate) + { + Certificates ??= new X509CertificateCollection(); + if (!Certificates.Contains(certificate)) + { + ResetClient(); + Certificates.Add(certificate); + } + } + + /// + /// Gets an existing or creates a new HttpClient for this WebRequest session if none currently exists (either because it was never + /// created, or because changes to the WebSession properties required the existing HttpClient to be disposed). + /// + /// True if the caller does not want the HttpClient to ever handle redirections automatically. + /// Contains true if an existing HttpClient had to be disposed and recreated since the WebSession was last used. + /// The HttpClient cached in the WebSession, based on all current settings. + internal HttpClient GetHttpClient(bool suppressHttpClientRedirects, out bool clientWasReset) + { + // Do not auto redirect if the caller does not want it, or maximum redirections is 0 + SetStructVar(ref _allowAutoRedirect, !(suppressHttpClientRedirects || MaximumRedirection == 0)); + + clientWasReset = _disposedClient; + + if (_client is null) + { + _client = CreateHttpClient(); + _disposedClient = false; + } + + return _client; + } + + private HttpClient CreateHttpClient() + { + SocketsHttpHandler handler = new(); + + if (_unixSocket is not null) + { + handler.ConnectCallback = async (context, token) => + { + Socket socket = new(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); + await socket.ConnectAsync(_unixSocket).ConfigureAwait(false); + + return new NetworkStream(socket, ownsSocket: false); + }; + } + + handler.CookieContainer = Cookies; + handler.AutomaticDecompression = DecompressionMethods.All; + + if (Credentials is not null) + { + handler.Credentials = Credentials; + } + else if (UseDefaultCredentials) + { + handler.Credentials = CredentialCache.DefaultCredentials; + } + + if (_noProxy) + { + handler.UseProxy = false; + } + else if (Proxy is not null) + { + handler.Proxy = Proxy; + } + + if (Certificates is not null) + { + handler.SslOptions.ClientCertificates = new X509CertificateCollection(Certificates); + } + + if (_skipCertificateCheck) + { + handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; }; + } + + handler.AllowAutoRedirect = _allowAutoRedirect; + if (_allowAutoRedirect && MaximumRedirection > 0) + { + handler.MaxAutomaticRedirections = MaximumRedirection; + } + + handler.SslOptions.EnabledSslProtocols = (SslProtocols)_sslProtocol; + + // Check timeout setting (in seconds) + return new HttpClient(handler) + { + Timeout = _connectionTimeout + }; + } + + private void SetClassVar(ref T oldValue, T newValue) where T : class? + { + if (oldValue != newValue) + { + ResetClient(); + oldValue = newValue; + } + } + + private void SetStructVar(ref T oldValue, T newValue) where T : struct + { + if (!oldValue.Equals(newValue)) + { + ResetClient(); + oldValue = newValue; + } + } + + private void ResetClient() + { + if (_client is not null) + { + _disposedClient = true; + _client.Dispose(); + _client = null; + } + } + + /// + /// Dispose the WebRequestSession. + /// + /// True when called from Dispose() and false when called from finalizer. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _client?.Dispose(); + } + + _disposed = true; + } + } + + /// + /// Dispose the WebRequestSession. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs new file mode 100644 index 0000000000000000000000000000000000000000..2d7fc9d233df4e58ea5572c90acca3b640e4806e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + #region WriteOutputCommand + /// + /// This class implements Write-Output command. + /// + [Cmdlet(VerbsCommunications.Write, "Output", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097117", RemotingCapability = RemotingCapability.None)] + public sealed class WriteOutputCommand : PSCmdlet + { + /// + /// Holds the list of objects to be written. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromRemainingArguments = true)] + [AllowNull] + [AllowEmptyCollection] + public PSObject InputObject { get; set; } + + /// + /// Prevents Write-Output from unravelling collections passed to the InputObject parameter. + /// + [Parameter] + public SwitchParameter NoEnumerate { get; set; } + + /// + /// This method implements the ProcessRecord method for Write-output command. + /// + protected override void ProcessRecord() + { + if (InputObject == null) + { + WriteObject(InputObject); + return; + } + + WriteObject(InputObject, !NoEnumerate.IsPresent); + } + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs new file mode 100644 index 0000000000000000000000000000000000000000..d20d7d8712b03b28bd832eb34e5a11fbbd5b9220 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -0,0 +1,463 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Runtime.Serialization; + +namespace Microsoft.PowerShell.Commands +{ + #region WriteDebugCommand + /// + /// This class implements Write-Debug command. + /// + [Cmdlet(VerbsCommunications.Write, "Debug", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097132", RemotingCapability = RemotingCapability.None)] + public sealed class WriteDebugCommand : PSCmdlet + { + /// + /// Message to be sent and processed if debug mode is on. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [AllowEmptyString] + [Alias("Msg")] + public string Message { get; set; } + + /// + /// This method implements the ProcessRecord method for Write-Debug command. + /// + protected override void ProcessRecord() + { + // + // The write-debug command must use the script's InvocationInfo rather than its own, + // so we create the DebugRecord here and fill it up with the appropriate InvocationInfo; + // then, we call the command runtime directly and pass this record to WriteDebug(). + // + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) + { + DebugRecord record = new(Message); + + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) + { + record.SetInvocationInfo(invocationInfo); + } + + mshCommandRuntime.WriteDebug(record); + } + else + { + WriteDebug(Message); + } + } + } + #endregion WriteDebugCommand + + #region WriteVerboseCommand + /// + /// This class implements Write-Verbose command. + /// + [Cmdlet(VerbsCommunications.Write, "Verbose", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097043", RemotingCapability = RemotingCapability.None)] + public sealed class WriteVerboseCommand : PSCmdlet + { + /// + /// Message to be sent if verbose messages are being shown. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [AllowEmptyString] + [Alias("Msg")] + public string Message { get; set; } + + /// + /// This method implements the ProcessRecord method for Write-verbose command. + /// + protected override void ProcessRecord() + { + // + // The write-verbose command must use the script's InvocationInfo rather than its own, + // so we create the VerboseRecord here and fill it up with the appropriate InvocationInfo; + // then, we call the command runtime directly and pass this record to WriteVerbose(). + // + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) + { + VerboseRecord record = new(Message); + + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) + { + record.SetInvocationInfo(invocationInfo); + } + + mshCommandRuntime.WriteVerbose(record); + } + else + { + WriteVerbose(Message); + } + } + } + #endregion WriteVerboseCommand + + #region WriteWarningCommand + /// + /// This class implements Write-Warning command. + /// + [Cmdlet(VerbsCommunications.Write, "Warning", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097044", RemotingCapability = RemotingCapability.None)] + public sealed class WriteWarningCommand : PSCmdlet + { + /// + /// Message to be sent if warning messages are being shown. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [AllowEmptyString] + [Alias("Msg")] + public string Message { get; set; } + + /// + /// This method implements the ProcessRecord method for Write-Warning command. + /// + protected override void ProcessRecord() + { + // + // The write-warning command must use the script's InvocationInfo rather than its own, + // so we create the WarningRecord here and fill it up with the appropriate InvocationInfo; + // then, we call the command runtime directly and pass this record to WriteWarning(). + // + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) + { + WarningRecord record = new(Message); + + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) + { + record.SetInvocationInfo(invocationInfo); + } + + mshCommandRuntime.WriteWarning(record); + } + else + { + WriteWarning(Message); + } + } + } + #endregion WriteWarningCommand + + #region WriteInformationCommand + /// + /// This class implements Write-Information command. + /// + [Cmdlet(VerbsCommunications.Write, "Information", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097040", RemotingCapability = RemotingCapability.None)] + public sealed class WriteInformationCommand : PSCmdlet + { + /// + /// Object to be sent to the Information stream. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [Alias("Msg", "Message")] + [AllowNull] + public object MessageData { get; set; } + + /// + /// Any tags to be associated with this information. + /// + [Parameter(Position = 1)] + public string[] Tags { get; set; } + + /// + /// This method implements the processing of the Write-Information command. + /// + protected override void BeginProcessing() + { + if (Tags != null) + { + foreach (string tag in Tags) + { + if (tag.StartsWith("PS", StringComparison.OrdinalIgnoreCase)) + { + ErrorRecord er = new( + new InvalidOperationException(StringUtil.Format(UtilityCommonStrings.PSPrefixReservedInInformationTag, tag)), + "PSPrefixReservedInInformationTag", ErrorCategory.InvalidArgument, tag); + ThrowTerminatingError(er); + } + } + } + } + + /// + /// This method implements the ProcessRecord method for Write-Information command. + /// + protected override void ProcessRecord() + { + WriteInformation(MessageData, Tags); + } + } + + #endregion WriteInformationCommand + + #region WriteOrThrowErrorCommand + + /// + /// This class implements the Write-Error command. + /// + public class WriteOrThrowErrorCommand : PSCmdlet + { + /// + /// ErrorRecord.Exception -- if not specified, ErrorRecord.Exception is System.Exception. + /// + [Parameter(Position = 0, ParameterSetName = "WithException", Mandatory = true)] + public Exception Exception { get; set; } + + /// + /// If Exception is specified, this is ErrorRecord.ErrorDetails.Message; + /// otherwise, the Exception is System.Exception, and this is Exception.Message. + /// + [Parameter(Position = 0, ParameterSetName = "NoException", Mandatory = true, ValueFromPipeline = true)] + [Parameter(ParameterSetName = "WithException")] + [AllowNull] + [AllowEmptyString] + [Alias("Msg")] + public string Message { get; set; } + + /// + /// If Exception is specified, this is ErrorRecord.ErrorDetails.Message; + /// otherwise, the Exception is System.Exception, and this is Exception.Message. + /// + [Parameter(Position = 0, ParameterSetName = "ErrorRecord", Mandatory = true)] + public ErrorRecord ErrorRecord { get; set; } + + /// + /// ErrorRecord.CategoryInfo.Category. + /// + [Parameter(ParameterSetName = "NoException")] + [Parameter(ParameterSetName = "WithException")] + public ErrorCategory Category { get; set; } = ErrorCategory.NotSpecified; + + /// + /// ErrorRecord.ErrorId. + /// + [Parameter(ParameterSetName = "NoException")] + [Parameter(ParameterSetName = "WithException")] + public string ErrorId { get; set; } = string.Empty; + + /// + /// ErrorRecord.TargetObject. + /// + [Parameter(ParameterSetName = "NoException")] + [Parameter(ParameterSetName = "WithException")] + public object TargetObject { get; set; } + + /// + /// ErrorRecord.ErrorDetails.RecommendedAction. + /// + [Parameter] + public string RecommendedAction { get; set; } = string.Empty; + + /* 2005/01/25 removing throw-error + /// + /// If true, this is throw-error. Otherwise, this is write-error. + /// + internal bool _terminating = false; + */ + + /// + /// ErrorRecord.CategoryInfo.Activity. + /// + [Parameter] + [Alias("Activity")] + public string CategoryActivity { get; set; } = string.Empty; + + /// + /// ErrorRecord.CategoryInfo.Reason. + /// + [Parameter] + [Alias("Reason")] + public string CategoryReason { get; set; } = string.Empty; + + /// + /// ErrorRecord.CategoryInfo.TargetName. + /// + [Parameter] + [Alias("TargetName")] + public string CategoryTargetName { get; set; } = string.Empty; + + /// + /// ErrorRecord.CategoryInfo.TargetType. + /// + [Parameter] + [Alias("TargetType")] + public string CategoryTargetType { get; set; } = string.Empty; + + /// + /// Write an error to the output pipe, or throw a terminating error. + /// + protected override void ProcessRecord() + { + ErrorRecord errorRecord = this.ErrorRecord; + if (errorRecord != null) + { + // copy constructor + errorRecord = new ErrorRecord(errorRecord, null); + } + else + { + Exception e = this.Exception; + string msg = Message; + e ??= new WriteErrorException(msg); + + string errid = ErrorId; + if (string.IsNullOrEmpty(errid)) + { + errid = e.GetType().FullName; + } + + errorRecord = new ErrorRecord( + e, + errid, + Category, + TargetObject + ); + + if (this.Exception != null && !string.IsNullOrEmpty(msg)) + { + errorRecord.ErrorDetails = new ErrorDetails(msg); + } + } + + string recact = RecommendedAction; + if (!string.IsNullOrEmpty(recact)) + { + errorRecord.ErrorDetails ??= new ErrorDetails(errorRecord.ToString()); + + errorRecord.ErrorDetails.RecommendedAction = recact; + } + + if (!string.IsNullOrEmpty(CategoryActivity)) + errorRecord.CategoryInfo.Activity = CategoryActivity; + if (!string.IsNullOrEmpty(CategoryReason)) + errorRecord.CategoryInfo.Reason = CategoryReason; + if (!string.IsNullOrEmpty(CategoryTargetName)) + errorRecord.CategoryInfo.TargetName = CategoryTargetName; + if (!string.IsNullOrEmpty(CategoryTargetType)) + errorRecord.CategoryInfo.TargetType = CategoryTargetType; + + /* 2005/01/25 removing throw-error + if (_terminating) + { + ThrowTerminatingError(errorRecord); + } + else + { + */ + + // 2005/07/14-913791 "write-error output is confusing and misleading" + // set InvocationInfo to the script not the command + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo myInvocation) + { + errorRecord.SetInvocationInfo(myInvocation); + errorRecord.PreserveInvocationInfoOnce = true; + if (!string.IsNullOrEmpty(CategoryActivity)) + errorRecord.CategoryInfo.Activity = CategoryActivity; + else + errorRecord.CategoryInfo.Activity = "Write-Error"; + } + + WriteError(errorRecord); + /* + } + */ + } + } + + /// + /// This class implements Write-Error command. + /// + [Cmdlet(VerbsCommunications.Write, "Error", DefaultParameterSetName = "NoException", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097039", RemotingCapability = RemotingCapability.None)] + public sealed class WriteErrorCommand : WriteOrThrowErrorCommand + { + /// + /// Initializes a new instance of the class. + /// + public WriteErrorCommand() + { + } + } + + /* 2005/01/25 removing throw-error + /// + /// This class implements Write-Error command. + /// + [Cmdlet("Throw", "Error", DefaultParameterSetName = "NoException")] + public sealed class ThrowErrorCommand : WriteOrThrowErrorCommand + { + /// + /// Constructor. + /// + public ThrowErrorCommand() + { + using (tracer.TraceConstructor(this)) + { + _terminating = true; + } + } + } + */ + + #endregion WriteOrThrowErrorCommand + + #region WriteErrorException + /// + /// The write-error cmdlet uses WriteErrorException + /// when the user only specifies a string and not + /// an Exception or ErrorRecord. + /// + public class WriteErrorException : SystemException + { + #region ctor + /// + /// Initializes a new instance of the class. + /// + /// Constructed object. + public WriteErrorException() + : base(StringUtil.Format(WriteErrorStrings.WriteErrorException)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// Constructed object. + public WriteErrorException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Constructed object. + public WriteErrorException(string message, + Exception innerException) + : base(message, innerException) + { + } + #endregion ctor + + #region Serialization + /// + /// Initializes a new instance of the class for serialization. + /// + /// Serialization information. + /// Streaming context. + /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected WriteErrorException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + #endregion Serialization + } + #endregion WriteErrorException +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..31670935fcf16f793047eb6b47e59fd61336abb0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The base class for the SetAliasCommand and NewAliasCommand. + /// + public class WriteAliasCommandBase : PSCmdlet + { + #region Parameters + + /// + /// The Name parameter for the command. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string Name { get; set; } + + /// + /// The Value parameter for the command. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] + public string Value { get; set; } + + /// + /// The description for the alias. + /// + [Parameter] + public string Description { get; set; } = string.Empty; + + /// + /// The Option parameter allows the alias to be set to + /// ReadOnly (for existing aliases) and/or Constant (only + /// for new aliases). + /// + [Parameter] + public ScopedItemOptions Option { get; set; } = ScopedItemOptions.None; + + /// + /// If set to true, the alias that is set is passed to the pipeline. + /// + [Parameter] + public SwitchParameter PassThru + { + get + { + return _passThru; + } + + set + { + _passThru = value; + } + } + + private bool _passThru; + + /// + /// The scope parameter for the command determines which scope the alias is set in. + /// + [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] + public string Scope { get; set; } + + /// + /// If set to true and an existing alias of the same name exists + /// and is ReadOnly, the alias will be overwritten. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + #endregion Parameters + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..48d84636ce272cefaee9831da4b124a9ed06ca15 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Management.Automation; +using System.Text; +using System.Xml; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// WriteHost cmdlet. + /// + [Cmdlet(VerbsCommunications.Write, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097137", RemotingCapability = RemotingCapability.None)] + public sealed class WriteHostCommand : ConsoleColorCmdlet + { + /// + /// Object to be output. + /// + [Parameter(Position = 0, ValueFromRemainingArguments = true, ValueFromPipeline = true)] + [Alias("Msg", "Message")] + public object Object { get; set; } + + /// + /// False to add a newline to the end of the output string, true if not. + /// + [Parameter] + public SwitchParameter NoNewline + { + get + { + return _notAppendNewline; + } + + set + { + _notAppendNewline = value; + } + } + + /// + /// Gets and sets the separator to print between objects. + /// + /// + [Parameter] + public object Separator { get; set; } = " "; + + // + // Cmdlet Overrides + // + private string ProcessObject(object o) + { + if (o != null) + { + if (o is string s) + { + // strings are IEnumerable, so we special case them + if (s.Length > 0) + { + return s; + } + } + else if (o is XmlNode xmlNode) + { + return xmlNode.Name; + } + else if (o is IEnumerable enumerable) + { + // unroll enumerables, including arrays. + + bool printSeparator = false; + StringBuilder result = new(); + + foreach (object element in enumerable) + { + if (printSeparator && Separator != null) + { + result.Append(Separator.ToString()); + } + + result.Append(ProcessObject(element)); + printSeparator = true; + } + + return result.ToString(); + } + else + { + s = o.ToString(); + + if (s.Length > 0) + { + return s; + } + } + } + + return null; + } + + /// + /// Outputs the object to the host console, with optional newline. + /// + protected override void ProcessRecord() + { + string result = ProcessObject(Object) ?? string.Empty; + + HostInformationMessage informationMessage = new(); + informationMessage.Message = result; + informationMessage.NoNewLine = NoNewline.IsPresent; + + try + { + informationMessage.ForegroundColor = ForegroundColor; + informationMessage.BackgroundColor = BackgroundColor; + } + catch (System.Management.Automation.Host.HostException) + { + // Expected if the host is not interactive, or doesn't have Foreground / Background + // colours. + } + + this.WriteInformation(informationMessage, new string[] { "PSHOST" }); + } + + private bool _notAppendNewline = false; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..0751954c54ed1fed7981a1ca4d72ecaf8bb0d85e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implements the write-progress cmdlet. + /// + [Cmdlet(VerbsCommunications.Write, "Progress", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097036", RemotingCapability = RemotingCapability.None)] + public sealed class WriteProgressCommand : PSCmdlet + { + /// + /// Describes the activity for which progress is being reported. + /// + [Parameter( + Position = 0, + HelpMessageBaseName = HelpMessageBaseName, + HelpMessageResourceId = "ActivityParameterHelpMessage")] + public string Activity { get; set; } + + /// + /// Describes the current state of the activity. + /// + [Parameter( + Position = 1, + HelpMessageBaseName = HelpMessageBaseName, + HelpMessageResourceId = "StatusParameterHelpMessage")] + [ValidateNotNullOrEmpty] + public string Status { get; set; } = WriteProgressResourceStrings.Processing; + + /// + /// Uniquely identifies this activity for purposes of chaining subordinate activities. + /// + [Parameter(Position = 2)] + [ValidateRange(0, int.MaxValue)] + public int Id { get; set; } + + /// + /// Percentage completion of the activity, or -1 if n/a. + /// + [Parameter] + [ValidateRange(-1, 100)] + public int PercentComplete { get; set; } = -1; + + /// + /// Seconds remaining to complete the operation, or -1 if n/a. + /// + [Parameter] + public int SecondsRemaining { get; set; } = -1; + + /// + /// Description of current operation in activity, empty if n/a. + /// + [Parameter] + public string CurrentOperation { get; set; } + + /// + /// Identifies the parent Id of this activity, or -1 if none. + /// + [Parameter] + [ValidateRange(-1, int.MaxValue)] + public int ParentId { get; set; } = -1; + + /// + /// Identifies whether the activity has completed (and the display for it should be removed), + /// or if it is proceeding (and the display for it should be shown). + /// + [Parameter] + public SwitchParameter Completed + { + get + { + return _completed; + } + + set + { + _completed = value; + } + } + + /// + /// Identifies the source of the record. + /// + [Parameter] + public int SourceId { get; set; } + + /// + /// Writes a ProgressRecord created from the parameters. + /// + protected override + void + ProcessRecord() + { + ProgressRecord pr; + if (string.IsNullOrEmpty(Activity)) + { + if (!Completed) + { + ThrowTerminatingError(new ErrorRecord( + new ArgumentException("Missing value for mandatory parameter.", nameof(Activity)), + "MissingActivity", + ErrorCategory.InvalidArgument, + Activity)); + return; + } + else + { + pr = new(Id); + pr.StatusDescription = Status; + } + } + else + { + pr = new(Id, Activity, Status); + } + + pr.ParentActivityId = ParentId; + pr.PercentComplete = PercentComplete; + pr.SecondsRemaining = SecondsRemaining; + pr.CurrentOperation = CurrentOperation; + pr.RecordType = this.Completed ? ProgressRecordType.Completed : ProgressRecordType.Processing; + + WriteProgress(SourceId, pr); + } + + private bool _completed; + + private const string HelpMessageBaseName = "WriteProgressResourceStrings"; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..cc3b1f2b251b23edefa3a3aac23b02c829603812 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -0,0 +1,1307 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security; +using System.Text; +using System.Xml; +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implementation for the Export-Clixml command. + /// + [Cmdlet(VerbsData.Export, "Clixml", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096926")] + public sealed class ExportClixmlCommand : PSCmdlet, IDisposable + { + #region Command Line Parameters + + // If a Passthru parameter is added, the SupportsShouldProcess + // implementation will need to be modified. + + /// + /// Depth of serialization. + /// + [Parameter] + [ValidateRange(1, int.MaxValue)] + public int Depth { get; set; } + + /// + /// Mandatory file name to write to. + /// + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] + public string Path { get; set; } + + /// + /// Mandatory file name to write to. + /// + [Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return Path; + } + + set + { + Path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// Input object to be exported. + /// + [Parameter(ValueFromPipeline = true, Mandatory = true)] + [AllowNull] + public PSObject InputObject { get; set; } + + /// + /// Property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// Property that prevents file overwrite. + /// + [Parameter] + [Alias("NoOverwrite")] + public SwitchParameter NoClobber + { + get + { + return _noclobber; + } + + set + { + _noclobber = value; + } + } + + private bool _noclobber; + + /// + /// Encoding optional flag. + /// + [Parameter] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] + [ValidateNotNullOrEmpty] + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.Default; + + #endregion Command Line Parameters + + #region Overrides + + /// + /// BeginProcessing override. + /// + protected override + void + BeginProcessing() + { + CreateFileStream(); + } + + /// + /// + protected override + void + ProcessRecord() + { + if (_serializer != null) + { + _serializer.Serialize(InputObject); + _xw.Flush(); + } + } + + /// + /// + protected override + void + EndProcessing() + { + if (_serializer != null) + { + _serializer.Done(); + _serializer = null; + } + + CleanUp(); + } + + /// + /// + protected override void StopProcessing() + { + base.StopProcessing(); + _serializer.Stop(); + } + + #endregion Overrides + + #region file + + /// + /// Handle to file stream. + /// + private FileStream _fs; + + /// + /// Stream writer used to write to file. + /// + private XmlWriter _xw; + + /// + /// Serializer used for serialization. + /// + private Serializer _serializer; + + /// + /// FileInfo of file to clear read-only flag when operation is complete. + /// + private FileInfo _readOnlyFileInfo = null; + + private void CreateFileStream() + { + Dbg.Assert(Path != null, "FileName is mandatory parameter"); + + if (!ShouldProcess(Path)) + { + return; + } + + StreamWriter sw; + PathUtils.MasterStreamOpen( + this, + this.Path, + this.Encoding, + false, // default encoding + false, // append + this.Force, + this.NoClobber, + out _fs, + out sw, + out _readOnlyFileInfo, + _isLiteralPath + ); + + // create xml writer + XmlWriterSettings xmlSettings = new(); + xmlSettings.CloseOutput = true; + xmlSettings.Encoding = sw.Encoding; + xmlSettings.Indent = true; + xmlSettings.OmitXmlDeclaration = true; + _xw = XmlWriter.Create(sw, xmlSettings); + if (Depth == 0) + { + _serializer = new Serializer(_xw); + } + else + { + _serializer = new Serializer(_xw, Depth, true); + } + } + + private + void + CleanUp() + { + if (_fs != null) + { + if (_xw != null) + { + _xw.Dispose(); + _xw = null; + } + + _fs.Dispose(); + _fs = null; + } + } + + #endregion file + + #region IDisposable Members + + /// + /// Set to true when object is disposed. + /// + private bool _disposed; + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + if (!_disposed) + { + CleanUp(); + } + + _disposed = true; + } + + #endregion IDisposable Members + } + + /// + /// Implements Import-Clixml command. + /// + [Cmdlet(VerbsData.Import, "Clixml", SupportsPaging = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096618")] + public sealed class ImportClixmlCommand : PSCmdlet, IDisposable + { + #region Command Line Parameters + + /// + /// Mandatory file name to read from. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + public string[] Path { get; set; } + + /// + /// Mandatory file name to read from. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return Path; + } + + set + { + Path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + #endregion Command Line Parameters + + #region IDisposable Members + + private bool _disposed = false; + + /// + /// Release all resources. + /// + public void Dispose() + { + if (!_disposed) + { + if (_helper != null) + { + _helper.Dispose(); + _helper = null; + } + + _disposed = true; + } + } + + #endregion + + private ImportXmlHelper _helper; + + /// + /// ProcessRecord overload. + /// + protected override void ProcessRecord() + { + if (Path != null) + { + foreach (string path in Path) + { + _helper = new ImportXmlHelper(path, this, _isLiteralPath); + _helper.Import(); + } + } + } + + /// + /// + protected override void StopProcessing() + { + base.StopProcessing(); + _helper.Stop(); + } + } + + /// + /// Implementation for the convertto-xml command. + /// + [Cmdlet(VerbsData.ConvertTo, "Xml", SupportsShouldProcess = false, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096603", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(XmlDocument), typeof(string))] + public sealed class ConvertToXmlCommand : PSCmdlet, IDisposable + { + #region Command Line Parameters + + /// + /// Depth of serialization. + /// + [Parameter(HelpMessage = "Specifies how many levels of contained objects should be included in the XML representation")] + [ValidateRange(1, int.MaxValue)] + public int Depth { get; set; } + + /// + /// Input Object which is written to XML format. + /// + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] + [AllowNull] + public PSObject InputObject { get; set; } + + /// + /// Property that sets NoTypeInformation parameter. + /// + [Parameter(HelpMessage = "Specifies not to include the Type information in the XML representation")] + public SwitchParameter NoTypeInformation + { + get + { + return _notypeinformation; + } + + set + { + _notypeinformation = value; + } + } + + private bool _notypeinformation; + + /// + /// Property that sets As parameter. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [ValidateSet("Stream", "String", "Document")] + public string As { get; set; } = "Document"; + + #endregion Command Line Parameters + + #region Overrides + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + if (!As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) + { + CreateMemoryStream(); + } + else + { + WriteObject(string.Create(CultureInfo.InvariantCulture, $"")); + WriteObject(""); + } + } + + /// + /// Override ProcessRecord. + /// + protected override void ProcessRecord() + { + if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) + { + CreateMemoryStream(); + + _serializer?.SerializeAsStream(InputObject); + + if (_serializer != null) + { + _serializer.DoneAsStream(); + _serializer = null; + } + // Loading to the XML Document + _ms.Position = 0; + StreamReader read = new(_ms); + string data = read.ReadToEnd(); + WriteObject(data); + + // Cleanup + CleanUp(); + } + else + { + _serializer?.Serialize(InputObject); + } + } + + /// + /// + protected override void EndProcessing() + { + if (_serializer != null) + { + _serializer.Done(); + _serializer = null; + } + + if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) + { + WriteObject(""); + } + else + { + // Loading to the XML Document + _ms.Position = 0; + if (As.Equals("Document", StringComparison.OrdinalIgnoreCase)) + { + // this is a trusted xml doc - the cmdlet generated the doc into a private memory stream + XmlDocument xmldoc = new(); + xmldoc.Load(_ms); + WriteObject(xmldoc); + } + else if (As.Equals("String", StringComparison.OrdinalIgnoreCase)) + { + StreamReader read = new(_ms); + string data = read.ReadToEnd(); + WriteObject(data); + } + } + + // Cleaning up + CleanUp(); + } + + /// + /// StopProcessing. + /// + protected override void StopProcessing() + { + _serializer.Stop(); + } + + #endregion Overrides + + #region memory + + /// + /// XmlText writer. + /// + private XmlWriter _xw; + + /// + /// Serializer used for serialization. + /// + private CustomSerialization _serializer; + + /// + /// Memory Stream used for serialization. + /// + private MemoryStream _ms; + + private void CreateMemoryStream() + { + // Memory Stream + _ms = new MemoryStream(); + + // We use XmlTextWriter originally: + // _xw = new XmlTextWriter(_ms, null); + // _xw.Formatting = Formatting.Indented; + // This implies the following settings: + // - Encoding is null -> use the default encoding 'UTF-8' when creating the writer from the stream; + // - XmlTextWriter closes the underlying stream / writer when 'Close/Dispose' is called on it; + // - Use the default indentation setting -- two space characters. + // + // We configure the same settings in XmlWriterSettings when refactoring this code to use XmlWriter: + // - The default encoding used by XmlWriterSettings is 'UTF-8', but we call it out explicitly anyway; + // - Set CloseOutput to true; + // - Set Indent to true, and by default, IndentChars is two space characters. + // + // We use XmlWriterSettings.OmitXmlDeclaration instead of XmlWriter.WriteStartDocument because the + // xml writer created by calling XmlWriter.Create(Stream, XmlWriterSettings) will write out the xml + // declaration even without calling WriteStartDocument(). + + var xmlSettings = new XmlWriterSettings(); + xmlSettings.Encoding = Encoding.UTF8; + xmlSettings.CloseOutput = true; + xmlSettings.Indent = true; + + if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) + { + // Omit xml declaration in this case because we will write out the declaration string in BeginProcess. + xmlSettings.OmitXmlDeclaration = true; + } + + _xw = XmlWriter.Create(_ms, xmlSettings); + + if (Depth == 0) + { + _serializer = new CustomSerialization(_xw, NoTypeInformation); + } + else + { + _serializer = new CustomSerialization(_xw, NoTypeInformation, Depth); + } + } + + /// + ///Cleaning up the MemoryStream. + /// + private void CleanUp() + { + if (_ms != null) + { + if (_xw != null) + { + _xw.Dispose(); + _xw = null; + } + + _ms.Dispose(); + _ms = null; + } + } + + #endregion memory + + #region IDisposable Members + + /// + /// Set to true when object is disposed. + /// + private bool _disposed; + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + if (!_disposed) + { + CleanUp(); + } + + _disposed = true; + } + + #endregion IDisposable Members + } + + /// + /// Implements ConvertTo-CliXml command. + /// + [Cmdlet(VerbsData.ConvertTo, "CliXml", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2280866")] + [OutputType(typeof(string))] + public sealed class ConvertToClixmlCommand : PSCmdlet + { + #region Parameters + + /// + /// Gets or sets input objects to be converted to CliXml object. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + public PSObject InputObject { get; set; } + + /// + /// Gets or sets depth of serialization. + /// + [Parameter] + [ValidateRange(1, int.MaxValue)] + public int Depth { get; set; } = 2; + + #endregion Parameters + + #region Private Members + + private readonly List _inputObjectBuffer = new(); + + #endregion Private Members + + #region Overrides + + /// + /// Process record. + /// + protected override void ProcessRecord() + { + _inputObjectBuffer.Add(InputObject); + } + + /// + /// End Processing. + /// + protected override void EndProcessing() + { + WriteObject(PSSerializer.Serialize(_inputObjectBuffer, Depth, enumerate: true)); + } + + #endregion Overrides + } + + /// + /// Implements ConvertFrom-CliXml command. + /// + [Cmdlet(VerbsData.ConvertFrom, "CliXml", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2280770")] + public sealed class ConvertFromClixmlCommand : PSCmdlet + { + #region Parameters + + /// + /// Gets or sets input object which is written in CliXml format. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + public string InputObject { get; set; } + + #endregion Parameters + + #region Overrides + + /// + /// Process record. + /// + protected override void ProcessRecord() + { + WriteObject(PSSerializer.Deserialize(InputObject)); + } + + #endregion Overrides + } + + /// + /// Helper class to import single XML file. + /// + internal sealed class ImportXmlHelper : IDisposable + { + #region constructor + + /// + /// XML file to import. + /// + private readonly string _path; + + /// + /// Reference to cmdlet which is using this helper class. + /// + private readonly PSCmdlet _cmdlet; + private readonly bool _isLiteralPath; + + internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) + { + Dbg.Assert(fileName != null, "filename is mandatory"); + Dbg.Assert(cmdlet != null, "cmdlet is mandatory"); + _path = fileName; + _cmdlet = cmdlet; + _isLiteralPath = isLiteralPath; + } + + #endregion constructor + + #region file + + /// + /// Handle to file stream. + /// + internal FileStream _fs; + + /// + /// XmlReader used to read file. + /// + internal XmlReader _xr; + + private static XmlReader CreateXmlReader(Stream stream) + { + TextReader textReader = new StreamReader(stream); + + // skip #< CLIXML directive + const string cliXmlDirective = "#< CLIXML"; + if (textReader.Peek() == (int)cliXmlDirective[0]) + { + string line = textReader.ReadLine(); + if (!line.Equals(cliXmlDirective, StringComparison.Ordinal)) + { + stream.Seek(0, SeekOrigin.Begin); + } + } + + return XmlReader.Create(textReader, InternalDeserializer.XmlReaderSettingsForCliXml); + } + + internal void CreateFileStream() + { + _fs = PathUtils.OpenFileStream(_path, _cmdlet, _isLiteralPath); + _xr = CreateXmlReader(_fs); + } + + private void CleanUp() + { + if (_fs != null) + { + _fs.Dispose(); + _fs = null; + } + } + + #endregion file + + #region IDisposable Members + + /// + /// Set to true when object is disposed. + /// + private bool _disposed; + + /// + /// Public dispose method. + /// + public void Dispose() + { + if (!_disposed) + { + CleanUp(); + } + + _disposed = true; + GC.SuppressFinalize(this); + } + + #endregion IDisposable Members + + private Deserializer _deserializer; + + internal void Import() + { + CreateFileStream(); + _deserializer = new Deserializer(_xr); + // If total count has been requested, return a dummy object with zero confidence + if (_cmdlet.PagingParameters.IncludeTotalCount) + { + PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0); + _cmdlet.WriteObject(totalCount); + } + + ulong skip = _cmdlet.PagingParameters.Skip; + ulong first = _cmdlet.PagingParameters.First; + + // if paging is not specified then keep the old V2 behavior + if (skip == 0 && first == ulong.MaxValue) + { + while (!_deserializer.Done()) + { + object result = _deserializer.Deserialize(); + _cmdlet.WriteObject(result); + } + } + // else try to flatten the output if possible + else + { + ulong skipped = 0; + ulong count = 0; + while (!_deserializer.Done() && count < first) + { + object result = _deserializer.Deserialize(); + + if (result is PSObject psObject) + { + if (psObject.BaseObject is ICollection c) + { + foreach (object o in c) + { + if (count >= first) + break; + + if (skipped++ >= skip) + { + count++; + _cmdlet.WriteObject(o); + } + } + } + else + { + if (skipped++ >= skip) + { + count++; + _cmdlet.WriteObject(result); + } + } + } + else if (skipped++ >= skip) + { + count++; + _cmdlet.WriteObject(result); + continue; + } + } + } + } + + internal void Stop() => _deserializer?.Stop(); + } + + #region Select-Xml + /// + /// This cmdlet is used to search an xml document based on the XPath Query. + /// + [Cmdlet(VerbsCommon.Select, "Xml", DefaultParameterSetName = "Xml", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097031")] + [OutputType(typeof(SelectXmlInfo))] + public class SelectXmlCommand : PSCmdlet + { + #region parameters + /// + /// Specifies the path which contains the xml files. The default is the current user directory. + /// + [Parameter(Position = 1, Mandatory = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Path")] + [ValidateNotNullOrEmpty] + public string[] Path { get; set; } + + /// + /// Specifies the literal path which contains the xml files. The default is the current user directory. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "LiteralPath")] + [ValidateNotNullOrEmpty] + [Alias("PSPath", "LP")] + public string[] LiteralPath + { + get + { + return Path; + } + + set + { + Path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// The following is the definition of the input parameter "XML". + /// Specifies the xml Node. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, + ParameterSetName = "Xml")] + [ValidateNotNullOrEmpty] + [Alias("Node")] + public System.Xml.XmlNode[] Xml { get; set; } + + /// + /// The following is the definition of the input parameter in string format. + /// Specifies the string format of a fully qualified xml. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, + ParameterSetName = "Content")] + [ValidateNotNullOrEmpty] + public string[] Content { get; set; } + + /// + /// The following is the definition of the input parameter "Xpath". + /// Specifies the String in XPath language syntax. The xml documents will be + /// searched for the nodes/values represented by this parameter. + /// + [Parameter(Mandatory = true, Position = 0)] + [ValidateNotNullOrEmpty] + public string XPath { get; set; } + + /// + /// The following definition used to specify the NameSpace of xml. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public Hashtable Namespace { get; set; } + + #endregion parameters + + #region private + + private void WriteResults(XmlNodeList foundXmlNodes, string filePath) + { + Dbg.Assert(foundXmlNodes != null, "Caller should verify foundNodes != null"); + + foreach (XmlNode foundXmlNode in foundXmlNodes) + { + SelectXmlInfo selectXmlInfo = new(); + selectXmlInfo.Node = foundXmlNode; + selectXmlInfo.Pattern = XPath; + selectXmlInfo.Path = filePath; + + this.WriteObject(selectXmlInfo); + } + } + + private void ProcessXmlNode(XmlNode xmlNode, string filePath) + { + Dbg.Assert(xmlNode != null, "Caller should verify xmlNode != null"); + + XmlNodeList xList; + if (Namespace != null) + { + XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, Namespace); + xList = xmlNode.SelectNodes(XPath, xmlns); + } + else + { + xList = xmlNode.SelectNodes(XPath); + } + + this.WriteResults(xList, filePath); + } + + private void ProcessXmlFile(string filePath) + { + // Cannot use ImportXMLHelper because it will throw terminating error which will + // not be inline with Select-String + // So doing self processing of the file. + try + { + XmlDocument xmlDocument = InternalDeserializer.LoadUnsafeXmlDocument( + new FileInfo(filePath), + true, /* preserve whitespace, comments, etc. */ + null); /* default maxCharactersInDocument */ + + this.ProcessXmlNode(xmlDocument, filePath); + } + catch (NotSupportedException notSupportedException) + { + this.WriteFileReadError(filePath, notSupportedException); + } + catch (IOException ioException) + { + this.WriteFileReadError(filePath, ioException); + } + catch (SecurityException securityException) + { + this.WriteFileReadError(filePath, securityException); + } + catch (UnauthorizedAccessException unauthorizedAccessException) + { + this.WriteFileReadError(filePath, unauthorizedAccessException); + } + catch (XmlException xmlException) + { + this.WriteFileReadError(filePath, xmlException); + } + catch (InvalidOperationException invalidOperationException) + { + this.WriteFileReadError(filePath, invalidOperationException); + } + } + + private void WriteFileReadError(string filePath, Exception exception) + { + string errorMessage = string.Format( + CultureInfo.InvariantCulture, + // filePath is culture invariant, exception message is to be copied verbatim + UtilityCommonStrings.FileReadError, + filePath, + exception.Message); + + ArgumentException argumentException = new(errorMessage, exception); + ErrorRecord errorRecord = new(argumentException, "ProcessingFile", ErrorCategory.InvalidArgument, filePath); + + this.WriteError(errorRecord); + } + + private XmlNamespaceManager AddNameSpaceTable(string parametersetname, XmlDocument xDoc, Hashtable namespacetable) + { + XmlNamespaceManager xmlns; + if (parametersetname.Equals("Xml")) + { + XmlNameTable xmlnt = new NameTable(); + xmlns = new XmlNamespaceManager(xmlnt); + } + else + { + xmlns = new XmlNamespaceManager(xDoc.NameTable); + } + + foreach (DictionaryEntry row in namespacetable) + { + try + { + xmlns.AddNamespace(row.Key.ToString(), row.Value.ToString()); + } + catch (NullReferenceException) + { + string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); + InvalidOperationException e = new(message); + ErrorRecord er = new(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); + WriteError(er); + } + catch (ArgumentNullException) + { + string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); + InvalidOperationException e = new(message); + ErrorRecord er = new(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); + WriteError(er); + } + } + + return xmlns; + } + + #endregion private + + #region override + + /// + /// ProcessRecord method. + /// + 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 fullresolvedPaths = new(); + foreach (string fpath in Path) + { + if (_isLiteralPath) + { + string resolvedPath = GetUnresolvedProviderPathFromPSPath(fpath); + fullresolvedPaths.Add(resolvedPath); + } + else + { + ProviderInfo provider; + Collection 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"); + } + } + #endregion overrides + } + + /// + /// The object returned by Select-Xml representing the result of a match. + /// + public sealed class SelectXmlInfo + { + /// + /// If the object is InputObject, Input Stream is used. + /// + private const string inputStream = "InputStream"; + private const string MatchFormat = "{0}:{1}"; + private const string SimpleFormat = "{0}"; + + /// + /// The XmlNode that matches search. + /// + public XmlNode Node { get; set; } + + /// + /// The FileName from which the match is found. + /// + public string Path + { + get + { + return _path; + } + + set + { + if (string.IsNullOrEmpty(value)) + { + _path = inputStream; + } + else + { + _path = value; + } + } + } + + private string _path; + + /// + /// The pattern used to search. + /// + public string Pattern { get; set; } + + /// + /// Returns the string representation of this object. The format + /// depends on whether a path has been set for this object or not. + /// + /// + public override string ToString() + { + return ToString(null); + } + + /// + /// Return String representation of the object. + /// + /// + /// + private string ToString(string directory) + { + string displayPath = (directory != null) ? RelativePath(directory) : _path; + return FormatLine(GetNodeText(), displayPath); + } + + /// + /// Returns the XmlNode Value or InnerXml. + /// + /// + internal string GetNodeText() + { + string nodeText = string.Empty; + if (Node != null) + { + if (Node.Value != null) + { + nodeText = Node.Value.Trim(); + } + else + { + nodeText = Node.InnerXml.Trim(); + } + } + + return nodeText; + } + + /// + /// Returns the path of the matching file truncated relative to the parameter. + /// + /// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo + /// the routine would return bar\baz.c + /// + /// + /// The directory base the truncation on. + /// The relative path that was produced. + private string RelativePath(string directory) + { + string relPath = _path; + if (!relPath.Equals(inputStream)) + { + if (relPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase)) + { + int offset = directory.Length; + if (offset < relPath.Length) + { + if (directory[offset - 1] == '\\' || directory[offset - 1] == '/') + relPath = relPath.Substring(offset); + else if (relPath[offset] == '\\' || relPath[offset] == '/') + relPath = relPath.Substring(offset + 1); + } + } + } + + return relPath; + } + + /// + /// Formats a line for use in ToString. + /// + /// + /// + /// + private string FormatLine(string text, string displaypath) + { + if (_path.Equals(inputStream)) + { + return StringUtil.Format(SimpleFormat, text); + } + else + { + return StringUtil.Format(MatchFormat, text, displaypath); + } + } + } + #endregion Select-Xml +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..491aaf85361c4712da82bad8f53e7a0270eefa9e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A cmdlet that gets the TraceSource instances that are instantiated in the process. + /// + [Cmdlet(VerbsCommon.Get, "TraceSource", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096707")] + [OutputType(typeof(PSTraceSource))] + public class GetTraceSourceCommand : TraceCommandBase + { + #region Parameters + + /// + /// Gets or sets the category parameter which determines which trace switch to get. + /// + /// + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty()] + public string[] Name + { + get + { + return _names; + } + + set + { + if (value == null || value.Length == 0) + { + value = new string[] { "*" }; + } + + _names = value; + } + } + + private string[] _names = new string[] { "*" }; + + #endregion Parameters + + #region Cmdlet code + + /// + /// Gets the PSTraceSource for the specified category. + /// + protected override void ProcessRecord() + { + var sources = GetMatchingTraceSource(_names, true); + var result = sources.OrderBy(static source => source.Name); + WriteObject(result, true); + } + + #endregion Cmdlet code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs new file mode 100644 index 0000000000000000000000000000000000000000..b7e4ed279aab46eb54afbf24d09fdabf60c7848e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal.Host; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This subclass of TraceListener allows for the trace output + /// coming from a System.Management.Automation.TraceSwitch + /// to be passed to the Msh host's RawUI methods. + /// + /// + /// This trace listener cannot be specified in the app.config file. + /// It must be added through the add-tracelistener cmdlet. + /// + internal sealed class PSHostTraceListener + : System.Diagnostics.TraceListener + { + #region TraceListener constructors and disposer + + /// + /// Initializes a new instance of the class. + /// + internal PSHostTraceListener(PSCmdlet cmdlet) + : base(string.Empty) + { + if (cmdlet == null) + { + throw new PSArgumentNullException(nameof(cmdlet)); + } + + Diagnostics.Assert( + cmdlet.Host.UI is InternalHostUserInterface, + "The internal host must be available to trace"); + + _ui = cmdlet.Host.UI as InternalHostUserInterface; + } + + ~PSHostTraceListener() + { + Dispose(false); + } + + /// + /// Closes the TraceListenerDialog so that it no longer receives trace output. + /// + /// + /// True if the TraceListener is being disposed, false otherwise. + /// + protected override void Dispose(bool disposing) + { + try + { + if (disposing) + { + this.Close(); + } + } + finally + { + base.Dispose(disposing); + } + } + + #endregion TraceListener constructors and disposer + + /// + /// Sends the given output string to the host for processing. + /// + /// + /// The trace output to be written. + /// + public override void Write(string output) + { + try + { + _cachedWrite.Append(output); + } + catch (Exception) + { + // Catch and ignore all exceptions while tracing + // We don't want tracing to bring down the process. + } + } + + private readonly StringBuilder _cachedWrite = new(); + + /// + /// Sends the given output string to the host for processing. + /// + /// + /// The trace output to be written. + /// + public override void WriteLine(string output) + { + try + { + _cachedWrite.Append(output); + _cachedWrite.Insert(0, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff ")); + + _ui.WriteDebugLine(_cachedWrite.ToString()); + _cachedWrite.Remove(0, _cachedWrite.Length); + } + catch (Exception) + { + // Catch and ignore all exceptions while tracing + // We don't want tracing to bring down the process. + } + } + + /// + /// The host interface to write the debug line to. + /// + private readonly InternalHostUserInterface _ui; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..9f8694ebd2047f4d0b949de0329711dd82871cdc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A cmdlet that sets the properties of the TraceSwitch instances that are instantiated in the process. + /// + [Cmdlet(VerbsCommon.Set, "TraceSource", DefaultParameterSetName = "optionsSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097129")] + [OutputType(typeof(PSTraceSource))] + public class SetTraceSourceCommand : TraceListenerCommandBase + { + #region Parameters + + /// + /// The TraceSource parameter determines which TraceSource categories the + /// operation will take place on. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + public string[] Name + { + get { return base.NameInternal; } + + set { base.NameInternal = value; } + } + + /// + /// The flags to be set on the TraceSource. + /// + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "optionsSet")] + public PSTraceSourceOptions Option + { + get + { + return base.OptionsInternal; + } + + set + { + base.OptionsInternal = value; + } + } + + /// + /// The parameter which determines the options for output from the trace listeners. + /// + [Parameter(ParameterSetName = "optionsSet")] + public TraceOptions ListenerOption + { + get + { + return base.ListenerOptionsInternal; + } + + set + { + base.ListenerOptionsInternal = value; + } + } + + /// + /// Adds the file trace listener using the specified file. + /// + /// + [Parameter(ParameterSetName = "optionsSet")] + [Alias("PSPath", "Path")] + public string FilePath + { + get { return base.FileListener; } + + set { base.FileListener = value; } + } + + /// + /// Force parameter to control read-only files. + /// + [Parameter(ParameterSetName = "optionsSet")] + public SwitchParameter Force + { + get { return base.ForceWrite; } + + set { base.ForceWrite = value; } + } + + /// + /// If this parameter is specified the Debugger trace listener will be added. + /// + /// + [Parameter(ParameterSetName = "optionsSet")] + public SwitchParameter Debugger + { + get { return base.DebuggerListener; } + + set { base.DebuggerListener = value; } + } + + /// + /// If this parameter is specified the PSHost trace listener will be added. + /// + /// + [Parameter(ParameterSetName = "optionsSet")] + public SwitchParameter PSHost + { + get { return base.PSHostListener; } + + set { base.PSHostListener = value; } + } + + /// + /// If set, the specified listeners will be removed regardless of their type. + /// + [Parameter(ParameterSetName = "removeAllListenersSet")] + [ValidateNotNullOrEmpty] + public string[] RemoveListener { get; set; } = new string[] { "*" }; + + /// + /// If set, the specified file trace listeners will be removed. + /// + [Parameter(ParameterSetName = "removeFileListenersSet")] + [ValidateNotNullOrEmpty] + public string[] RemoveFileListener { get; set; } = new string[] { "*" }; + + /// + /// Determines if the modified PSTraceSource should be written out. + /// Default is false. + /// + /// + [Parameter(ParameterSetName = "optionsSet")] + public SwitchParameter PassThru + { + get { return _passThru; } + + set { _passThru = value; } + } + + private bool _passThru; + + #endregion Parameters + + #region Cmdlet code + + /// + /// Sets the TraceSource properties. + /// + protected override void ProcessRecord() + { + Collection matchingSources = null; + + switch (ParameterSetName) + { + case "optionsSet": + Collection preconfiguredTraceSources = null; + matchingSources = ConfigureTraceSource(Name, true, out preconfiguredTraceSources); + + if (PassThru) + { + WriteObject(matchingSources, true); + WriteObject(preconfiguredTraceSources, true); + } + + break; + + case "removeAllListenersSet": + matchingSources = GetMatchingTraceSource(Name, true); + RemoveListenersByName(matchingSources, RemoveListener, false); + break; + + case "removeFileListenersSet": + matchingSources = GetMatchingTraceSource(Name, true); + RemoveListenersByName(matchingSources, RemoveFileListener, true); + break; + } + } + + #endregion Cmdlet code + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..9118fd773fd6dddbc059bb91a7c2ca9efadaa7d1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A base class for cmdlets that has helper methods for globbing trace source instances. + /// + public class TraceCommandBase : PSCmdlet + { + /// + /// Gets the matching PSTraceSource instances for the specified patterns. + /// + /// + /// The patterns used to match the PSTraceSource name. + /// + /// + /// If true and the pattern does not contain wildcard patterns and no + /// match is found, then WriteError will be called. + /// + /// + /// A collection of the matching PSTraceSource instances. + /// + internal Collection GetMatchingTraceSource( + string[] patternsToMatch, + bool writeErrorIfMatchNotFound) + { + Collection ignored = null; + return GetMatchingTraceSource(patternsToMatch, writeErrorIfMatchNotFound, out ignored); + } + + /// + /// Gets the matching PSTraceSource instances for the specified patterns. + /// + /// + /// The patterns used to match the PSTraceSource name. + /// + /// + /// If true and the pattern does not contain wildcard patterns and no + /// match is found, then WriteError will be called. + /// + /// + /// The patterns for which a match was not found. + /// + /// + /// A collection of the matching PSTraceSource instances. + /// + internal Collection GetMatchingTraceSource( + string[] patternsToMatch, + bool writeErrorIfMatchNotFound, + out Collection notMatched) + { + notMatched = new Collection(); + + Collection results = new(); + foreach (string patternToMatch in patternsToMatch) + { + bool matchFound = false; + + if (string.IsNullOrEmpty(patternToMatch)) + { + notMatched.Add(patternToMatch); + continue; + } + + WildcardPattern pattern = + WildcardPattern.Get( + patternToMatch, + WildcardOptions.IgnoreCase); + + Dictionary traceCatalog = PSTraceSource.TraceCatalog; + + foreach (PSTraceSource source in traceCatalog.Values) + { + // Try matching by full name + + if (pattern.IsMatch(source.FullName)) + { + matchFound = true; + results.Add(source); + } + // Try matching by the short name. + else if (pattern.IsMatch(source.Name)) + { + matchFound = true; + results.Add(source); + } + } + + if (!matchFound) + { + notMatched.Add(patternToMatch); + + // Only write an error if no match was found, the pattern doesn't + // contain wildcard characters, and caller wants us to. + + if (writeErrorIfMatchNotFound && + !WildcardPattern.ContainsWildcardCharacters(patternToMatch)) + { + ItemNotFoundException itemNotFound = + new( + patternToMatch, + "TraceSourceNotFound", + SessionStateStrings.TraceSourceNotFound); + + ErrorRecord errorRecord = new(itemNotFound.ErrorRecord, itemNotFound); + WriteError(errorRecord); + } + } + } + + return results; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..1eadd4934b36972633caf46807e4035048f4f0bf --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; +using System.Threading; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A cmdlet that traces the specified categories and flags for the duration of the + /// specified expression. + /// + [Cmdlet(VerbsDiagnostic.Trace, "Command", DefaultParameterSetName = "expressionSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097136")] + public class TraceCommandCommand : TraceListenerCommandBase, IDisposable + { + #region Parameters + + /// + /// This parameter specifies the current pipeline object. + /// + [Parameter(ValueFromPipeline = true)] + public PSObject InputObject { get; set; } = AutomationNull.Value; + + /// + /// The TraceSource parameter determines which TraceSource categories the + /// operation will take place on. + /// + [Parameter(Position = 0, Mandatory = true)] + public string[] Name + { + get { return base.NameInternal; } + + set { base.NameInternal = value; } + } + + /// + /// The flags to be set on the TraceSource. + /// + /// + [Parameter(Position = 2)] + public PSTraceSourceOptions Option + { + get + { + return base.OptionsInternal; + } + + set + { + base.OptionsInternal = value; + } + } + + /// + /// The parameter for the expression that should be traced. + /// + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "expressionSet")] + public ScriptBlock Expression { get; set; } + + /// + /// The parameter for the expression that should be traced. + /// + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "commandSet")] + public string Command { get; set; } + + /// + /// When set, this parameter is the arguments to pass to the command specified by + /// the -Command parameter. + /// + [Parameter(ParameterSetName = "commandSet", ValueFromRemainingArguments = true)] + [Alias("Args")] + public object[] ArgumentList { get; set; } + + /// + /// The parameter which determines the options for output from the trace listeners. + /// + [Parameter] + public TraceOptions ListenerOption + { + get + { + return base.ListenerOptionsInternal; + } + + set + { + base.ListenerOptionsInternal = value; + } + } + + /// + /// Adds the file trace listener using the specified file. + /// + /// + [Parameter] + [Alias("PSPath", "Path")] + public string FilePath + { + get { return base.FileListener; } + + set { base.FileListener = value; } + } + + /// + /// Force parameter to control read-only files. + /// + [Parameter] + public SwitchParameter Force + { + get { return base.ForceWrite; } + + set { base.ForceWrite = value; } + } + + /// + /// If this parameter is specified the Debugger trace listener will be added. + /// + /// + [Parameter] + public SwitchParameter Debugger + { + get { return base.DebuggerListener; } + + set { base.DebuggerListener = value; } + } + + /// + /// If this parameter is specified the Msh Host trace listener will be added. + /// + /// + [Parameter] + public SwitchParameter PSHost + { + get { return base.PSHostListener; } + + set { base.PSHostListener = value; } + } + + #endregion Parameters + + #region Cmdlet code + + private Collection _matchingSources; + + /// + /// Gets the PSTraceSource instances that match the names specified. + /// + protected override void BeginProcessing() + { + Collection preconfiguredSources = null; + _matchingSources = ConfigureTraceSource(base.NameInternal, false, out preconfiguredSources); + + TurnOnTracing(_matchingSources, false); + TurnOnTracing(preconfiguredSources, true); + + // Now that tracing has been configured, move all the sources into a + // single collection + + foreach (PSTraceSource preconfiguredSource in preconfiguredSources) + { + _matchingSources.Add(preconfiguredSource); + } + + if (ParameterSetName == "commandSet") + { + // Create the CommandProcessor and add it to a pipeline + + CommandProcessorBase commandProcessor = + this.Context.CommandDiscovery.LookupCommandProcessor(Command, CommandOrigin.Runspace, false); + + // Add the parameters that were specified + + ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, ArgumentList); + + _pipeline = new PipelineProcessor(); + _pipeline.Add(commandProcessor); + + // Hook up the success and error pipelines to this cmdlet's WriteObject and + // WriteError methods + + _pipeline.ExternalErrorOutput = new TracePipelineWriter(this, true, _matchingSources); + _pipeline.ExternalSuccessOutput = new TracePipelineWriter(this, false, _matchingSources); + } + + ResetTracing(_matchingSources); + } + + /// + /// Executes the expression. + /// Note, this was taken from apply-expression. + /// + protected override void ProcessRecord() + { + TurnOnTracing(_matchingSources, false); + + object result = null; + switch (ParameterSetName) + { + case "expressionSet": + result = RunExpression(); + break; + + case "commandSet": + result = StepCommand(); + break; + } + + ResetTracing(_matchingSources); + + if (result == null) + { + return; + } + + if (!LanguagePrimitives.IsNull(result)) + { + WriteObject(result, true); + } + } + + /// + /// Finishes running the command if specified and then sets the + /// tracing options and listeners back to their original values. + /// + protected override void EndProcessing() + { + if (_pipeline != null) + { + TurnOnTracing(_matchingSources, false); + + Array results = _pipeline.SynchronousExecuteEnumerate(AutomationNull.Value); + + ResetTracing(_matchingSources); + + WriteObject(results, true); + } + + this.Dispose(); + } + + /// + /// Ensures that the sub-pipeline we created gets stopped as well. + /// + protected override void StopProcessing() => _pipeline?.Stop(); + + #endregion Cmdlet code + + private object RunExpression() + { + return Expression.DoInvokeReturnAsIs( + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: InputObject, + input: new object[] { InputObject }, + scriptThis: AutomationNull.Value, + args: Array.Empty()); + } + + private object StepCommand() + { + if (InputObject != AutomationNull.Value) + { + _pipeline.Step(InputObject); + } + + return null; + } + + private PipelineProcessor _pipeline; + + #region IDisposable + + /// + /// Resets the TraceSource flags back to their original value and restores + /// the original TraceListeners. + /// + public void Dispose() + { + if (!_disposed) + { + _disposed = true; + + // Reset the flags for the trace switch back to the original value + ResetTracing(_matchingSources); + ClearStoredState(); + _matchingSources = null; + + if (_pipeline != null) + { + _pipeline.Dispose(); + _pipeline = null; + } + + // If there are any file streams, close those as well. + + if (this.FileStreams != null) + { + foreach (FileStream fileStream in this.FileStreams) + { + fileStream.Flush(); + fileStream.Dispose(); + } + } + + GC.SuppressFinalize(this); + } + } + + private bool _disposed; + #endregion IDisposable + } + + /// + /// This class acts a pipe redirector for the sub-pipeline created by the Trace-Command + /// cmdlet. It gets attached to the sub-pipelines success or error pipeline and redirects + /// all objects written to these pipelines to trace-command pipeline. + /// + internal sealed class TracePipelineWriter : PipelineWriter + { + internal TracePipelineWriter( + TraceListenerCommandBase cmdlet, + bool writeError, + Collection matchingSources) + { + ArgumentNullException.ThrowIfNull(cmdlet); + ArgumentNullException.ThrowIfNull(matchingSources); + + _cmdlet = cmdlet; + _writeError = writeError; + _matchingSources = matchingSources; + } + + /// + /// Get the wait handle signaled when buffer space is available in the underlying stream. + /// + public override WaitHandle WaitHandle + { + get { return null; } + } + + /// + /// Check if the stream is open for further writes. + /// + /// true if the underlying stream is open, otherwise; false. + /// + /// Attempting to write to the underlying stream if IsOpen is false throws + /// an . + /// + public override bool IsOpen + { + get + { + return _isOpen; + } + } + + /// + /// Returns the number of objects in the underlying stream. + /// + public override int Count + { + get { return 0; } + } + + /// + /// Get the capacity of the stream. + /// + /// + /// The capacity of the stream. + /// + /// + /// The capacity is the number of objects that stream may contain at one time. Once this + /// limit is reached, attempts to write into the stream block until buffer space + /// becomes available. + /// + public override int MaxCapacity + { + get { return int.MaxValue; } + } + + /// + /// Close the stream. + /// + /// + /// Causes subsequent calls to IsOpen to return false and calls to + /// a write operation to throw an ObjectDisposedException. + /// All calls to Close() after the first call are silently ignored. + /// + /// + /// The stream is already disposed. + /// + public override void Close() + { + if (_isOpen) + { + Flush(); + _isOpen = false; + } + } + + /// + /// Flush the data from the stream. Closed streams may be flushed, + /// but disposed streams may not. + /// + /// + /// The underlying stream is disposed. + /// + public override void Flush() + { + } + + /// + /// Write a single object into the underlying stream. + /// + /// The object to add to the stream. + /// + /// One, if the write was successful, otherwise; + /// zero if the stream was closed before the object could be written, + /// or if the object was AutomationNull.Value. + /// + /// + /// The underlying stream is closed. + /// + public override int Write(object obj) + { + _cmdlet.ResetTracing(_matchingSources); + + if (_writeError) + { + ErrorRecord errorRecord = ConvertToErrorRecord(obj); + + if (errorRecord != null) + { + _cmdlet.WriteError(errorRecord); + } + } + else + { + _cmdlet.WriteObject(obj); + } + + _cmdlet.TurnOnTracing(_matchingSources, false); + return 1; + } + + /// + /// Write objects to the underlying stream. + /// + /// Object or enumeration to read from. + /// + /// If enumerateCollection is true, and + /// is an enumeration according to LanguagePrimitives.GetEnumerable, + /// the objects in the enumeration will be unrolled and + /// written separately. Otherwise, + /// will be written as a single object. + /// + /// The number of objects written. + /// + /// The underlying stream is closed. + /// + /// + /// contains AutomationNull.Value + /// + public override int Write(object obj, bool enumerateCollection) + { + _cmdlet.ResetTracing(_matchingSources); + + int numWritten = 0; + if (_writeError) + { + if (enumerateCollection) + { + foreach (object o in LanguagePrimitives.GetEnumerable(obj)) + { + ErrorRecord errorRecord = ConvertToErrorRecord(o); + if (errorRecord != null) + { + numWritten++; + _cmdlet.WriteError(errorRecord); + } + } + } + else + { + ErrorRecord errorRecord = ConvertToErrorRecord(obj); + if (errorRecord != null) + { + numWritten++; + _cmdlet.WriteError(errorRecord); + } + } + } + else + { + numWritten++; + _cmdlet.WriteObject(obj, enumerateCollection); + } + + _cmdlet.TurnOnTracing(_matchingSources, false); + + return numWritten; + } + + private static ErrorRecord ConvertToErrorRecord(object obj) + { + ErrorRecord result = null; + if (obj is PSObject mshobj) + { + object baseObject = mshobj.BaseObject; + if (baseObject is not PSCustomObject) + { + obj = baseObject; + } + } + + if (obj is ErrorRecord errorRecordResult) + { + result = errorRecordResult; + } + + return result; + } + + private readonly TraceListenerCommandBase _cmdlet; + private readonly bool _writeError; + private bool _isOpen = true; + private readonly Collection _matchingSources = new(); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..f1e4fe2dfa00adb3b796d7d7e64895e34d66d90d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -0,0 +1,609 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// A base class for the trace cmdlets that allow you to specify + /// which trace listeners to add to a TraceSource. + /// + public class TraceListenerCommandBase : TraceCommandBase + { + #region Parameters + + /// + /// The TraceSource parameter determines which TraceSource categories the + /// operation will take place on. + /// + internal string[] NameInternal { get; set; } = Array.Empty(); + + /// + /// The flags to be set on the TraceSource. + /// + /// + internal PSTraceSourceOptions OptionsInternal + { + get + { + return _options; + } + + set + { + _options = value; + optionsSpecified = true; + } + } + + private PSTraceSourceOptions _options = PSTraceSourceOptions.All; + + /// + /// True if the Options parameter has been set, or false otherwise. + /// + internal bool optionsSpecified; + + /// + /// The parameter which determines the options for output from the trace listeners. + /// + internal TraceOptions ListenerOptionsInternal + { + get + { + return _traceOptions; + } + + set + { + traceOptionsSpecified = true; + _traceOptions = value; + } + } + + private TraceOptions _traceOptions = TraceOptions.None; + + /// + /// True if the TraceOptions parameter was specified, or false otherwise. + /// + internal bool traceOptionsSpecified; + + /// + /// Adds the file trace listener using the specified file. + /// + /// + internal string FileListener { get; set; } + + /// + /// Property that sets force parameter. This will clear the + /// read-only attribute on an existing file if present. + /// + /// + /// Note that we do not attempt to reset the read-only attribute. + /// + public bool ForceWrite { get; set; } + + /// + /// If this parameter is specified the Debugger trace listener will be added. + /// + /// + internal bool DebuggerListener { get; set; } + + /// + /// If this parameter is specified the Msh Host trace listener will be added. + /// + /// + internal SwitchParameter PSHostListener + { + get { return _host; } + + set { _host = value; } + } + + private bool _host = false; + + #endregion Parameters + + internal Collection ConfigureTraceSource( + string[] sourceNames, + bool preConfigure, + out Collection preconfiguredSources) + { + preconfiguredSources = new Collection(); + + // Find the matching and unmatched trace sources. + + Collection notMatched = null; + Collection matchingSources = GetMatchingTraceSource(sourceNames, false, out notMatched); + + if (preConfigure) + { + // Set the flags if they were specified + if (optionsSpecified) + { + SetFlags(matchingSources); + } + + AddTraceListenersToSources(matchingSources); + SetTraceListenerOptions(matchingSources); + } + + // Now try to preset options for sources which have not yet been + // constructed. + + foreach (string notMatchedName in notMatched) + { + if (string.IsNullOrEmpty(notMatchedName)) + { + continue; + } + + if (WildcardPattern.ContainsWildcardCharacters(notMatchedName)) + { + continue; + } + + PSTraceSource newTraceSource = + PSTraceSource.GetNewTraceSource( + notMatchedName, + string.Empty, + true); + + preconfiguredSources.Add(newTraceSource); + } + + // Preconfigure any trace sources that were not already present + + if (preconfiguredSources.Count > 0) + { + if (preConfigure) + { + // Set the flags if they were specified + if (optionsSpecified) + { + SetFlags(preconfiguredSources); + } + + AddTraceListenersToSources(preconfiguredSources); + SetTraceListenerOptions(preconfiguredSources); + } + + // Add the sources to the preconfigured table so that they are found + // when the trace source finally gets created by the system. + + foreach (PSTraceSource sourceToPreconfigure in preconfiguredSources) + { + if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(sourceToPreconfigure.Name)) + { + PSTraceSource.PreConfiguredTraceSource.Add(sourceToPreconfigure.Name, sourceToPreconfigure); + } + } + } + + return matchingSources; + } + + #region AddTraceListeners + /// + /// Adds the console, debugger, file, or host listener if requested. + /// + internal void AddTraceListenersToSources(Collection matchingSources) + { + if (DebuggerListener) + { + if (_defaultListener == null) + { + _defaultListener = + new DefaultTraceListener(); + + // Note, this is not meant to be localized. + _defaultListener.Name = "Debug"; + } + + AddListenerToSources(matchingSources, _defaultListener); + } + + if (PSHostListener) + { + if (_hostListener == null) + { + ((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue; + _hostListener = new PSHostTraceListener(this); + + // Note, this is not meant to be localized. + _hostListener.Name = "Host"; + } + + AddListenerToSources(matchingSources, _hostListener); + } + + if (FileListener != null) + { + if (_fileListeners == null) + { + _fileListeners = new Collection(); + FileStreams = new Collection(); + + Exception error = null; + + try + { + Collection resolvedPaths = new(); + try + { + // Resolve the file path + ProviderInfo provider = null; + resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(FileListener, out provider); + + // We can only export aliases to the file system + if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) + { + throw + new PSNotSupportedException( + StringUtil.Format(TraceCommandStrings.TraceFileOnly, + FileListener, + provider.FullName)); + } + } + catch (ItemNotFoundException) + { + // Since the file wasn't found, just make a provider-qualified path out if it + // and use that. + + PSDriveInfo driveInfo = null; + ProviderInfo provider = null; + string path = + this.SessionState.Path.GetUnresolvedProviderPathFromPSPath( + FileListener, + new CmdletProviderContext(this.Context), + out provider, + out driveInfo); + + // We can only export aliases to the file system + if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) + { + throw + new PSNotSupportedException( + StringUtil.Format(TraceCommandStrings.TraceFileOnly, + FileListener, + provider.FullName)); + } + + resolvedPaths.Add(path); + } + + if (resolvedPaths.Count > 1) + { + throw + new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, FileListener)); + } + + string resolvedPath = resolvedPaths[0]; + + Exception fileOpenError = null; + try + { + if (ForceWrite && System.IO.File.Exists(resolvedPath)) + { + // remove readonly attributes on the file + System.IO.FileInfo fInfo = new(resolvedPath); + if (fInfo != null) + { + // Save some disk write time by checking whether file is readonly.. + if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + // Make sure the file is not read only + fInfo.Attributes &= ~(FileAttributes.ReadOnly); + } + } + } + + // Trace commands always append..So there is no need to set overwrite with force.. + FileStream fileStream = new(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + FileStreams.Add(fileStream); + + // Open the file stream + + TextWriterTraceListener fileListener = + new(fileStream, resolvedPath); + + fileListener.Name = FileListener; + + _fileListeners.Add(fileListener); + } + catch (IOException ioException) + { + fileOpenError = ioException; + } + catch (SecurityException securityException) + { + fileOpenError = securityException; + } + catch (UnauthorizedAccessException unauthorized) + { + fileOpenError = unauthorized; + } + + if (fileOpenError != null) + { + ErrorRecord errorRecord = + new( + fileOpenError, + "FileListenerPathResolutionFailed", + ErrorCategory.OpenError, + resolvedPath); + + WriteError(errorRecord); + } + } + catch (ProviderNotFoundException providerNotFound) + { + error = providerNotFound; + } + catch (System.Management.Automation.DriveNotFoundException driveNotFound) + { + error = driveNotFound; + } + catch (NotSupportedException notSupported) + { + error = notSupported; + } + + if (error != null) + { + ErrorRecord errorRecord = + new( + error, + "FileListenerPathResolutionFailed", + ErrorCategory.InvalidArgument, + FileListener); + + WriteError(errorRecord); + } + } + + foreach (TraceListener listener in _fileListeners) + { + AddListenerToSources(matchingSources, listener); + } + } + } + + private DefaultTraceListener _defaultListener; + private PSHostTraceListener _hostListener; + private Collection _fileListeners; + + /// + /// The file streams that were open by this command. + /// + internal Collection FileStreams { get; private set; } + + private static void AddListenerToSources(Collection matchingSources, TraceListener listener) + { + // Now add the listener to all the sources + foreach (PSTraceSource source in matchingSources) + { + source.Listeners.Add(listener); + } + } + + #endregion AddTraceListeners + + #region RemoveTraceListeners + + /// + /// Removes the tracelisteners from the specified trace sources. + /// + internal static void RemoveListenersByName( + Collection matchingSources, + string[] listenerNames, + bool fileListenersOnly) + { + Collection listenerMatcher = + SessionStateUtilities.CreateWildcardsFromStrings( + listenerNames, + WildcardOptions.IgnoreCase); + + // Loop through all the matching sources and remove the matching listeners + + foreach (PSTraceSource source in matchingSources) + { + // Get the indexes of the listeners that need to be removed. + // This is done because we cannot remove the listeners while + // we are enumerating them. + + for (int index = source.Listeners.Count - 1; index >= 0; --index) + { + TraceListener listenerToRemove = source.Listeners[index]; + + if (fileListenersOnly && listenerToRemove is not TextWriterTraceListener) + { + // Since we only want to remove file listeners, skip any that + // aren't file listeners + continue; + } + + // Now match the names + + if (SessionStateUtilities.MatchesAnyWildcardPattern( + listenerToRemove.Name, + listenerMatcher, + true)) + { + listenerToRemove.Flush(); + listenerToRemove.Dispose(); + source.Listeners.RemoveAt(index); + } + } + } + } + + #endregion RemoveTraceListeners + + #region SetTraceListenerOptions + + /// + /// Sets the trace listener options based on the ListenerOptions parameter. + /// + internal void SetTraceListenerOptions(Collection matchingSources) + { + // Set the trace options if they were specified + if (traceOptionsSpecified) + { + foreach (PSTraceSource source in matchingSources) + { + foreach (TraceListener listener in source.Listeners) + { + listener.TraceOutputOptions = this.ListenerOptionsInternal; + } + } + } + } + + #endregion SetTraceListenerOptions + + #region SetFlags + + /// + /// Sets the flags for all the specified TraceSources. + /// + internal void SetFlags(Collection matchingSources) + { + foreach (PSTraceSource structuredSource in matchingSources) + { + structuredSource.Options = this.OptionsInternal; + } + } + #endregion SetFlags + + #region TurnOnTracing + + /// + /// Turns on tracing for the TraceSources, flags, and listeners defined by the parameters. + /// + internal void TurnOnTracing(Collection matchingSources, bool preConfigured) + { + foreach (PSTraceSource source in matchingSources) + { + // Store the current state of the TraceSource + if (!_storedTraceSourceState.ContainsKey(source)) + { + // Copy the listeners into a different collection + + Collection listenerCollection = new(); + foreach (TraceListener listener in source.Listeners) + { + listenerCollection.Add(listener); + } + + if (preConfigured) + { + // If the source is a preconfigured source, then the default options + // and listeners should be stored as the existing state. + + _storedTraceSourceState[source] = + new KeyValuePair>( + PSTraceSourceOptions.None, + new Collection()); + } + else + { + _storedTraceSourceState[source] = + new KeyValuePair>( + source.Options, + listenerCollection); + } + } + + // Now set the new flags + source.Options = this.OptionsInternal; + } + + // Now turn on the listeners + + AddTraceListenersToSources(matchingSources); + SetTraceListenerOptions(matchingSources); + } + + #endregion TurnOnTracing + + #region ResetTracing + + /// + /// Resets tracing to the previous level for the TraceSources defined by the parameters. + /// Note, TurnOnTracing must be called before calling ResetTracing or else all + /// TraceSources will be turned off. + /// + internal void ResetTracing(Collection matchingSources) + { + foreach (PSTraceSource source in matchingSources) + { + // First flush all the existing trace listeners + + foreach (TraceListener listener in source.Listeners) + { + listener.Flush(); + } + + if (_storedTraceSourceState.ContainsKey(source)) + { + // Restore the TraceSource to its original state + + KeyValuePair> storedState = + _storedTraceSourceState[source]; + + source.Listeners.Clear(); + foreach (TraceListener listener in storedState.Value) + { + source.Listeners.Add(listener); + } + + source.Options = storedState.Key; + } + else + { + // Since we don't have any stored state for this TraceSource, + // just turn it off. + + source.Listeners.Clear(); + source.Options = PSTraceSourceOptions.None; + } + } + } + + #endregion ResetTracing + + #region stored state + + /// + /// Clears the store TraceSource state. + /// + protected void ClearStoredState() + { + // First close all listeners + + foreach (KeyValuePair> pair in _storedTraceSourceState.Values) + { + foreach (TraceListener listener in pair.Value) + { + listener.Flush(); + listener.Dispose(); + } + } + + _storedTraceSourceState.Clear(); + } + + private readonly Dictionary>> _storedTraceSourceState = + new(); + + #endregion stored state + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx new file mode 100644 index 0000000000000000000000000000000000000000..cb18968d6ed1ae9d9fb463b4e44045b5b3413458 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + To add a member, only one member type can be specified. The member types specified are: "{0}" + + + Cannot add a member with type "{0}". Specify a different type for the MemberTypes parameter. + + + The SecondValue parameter is not necessary for a member of type "{0}", and should not be specified. Do not specify the SecondValue parameter when you add members of this type. + + + The Value parameter is required for a member of type "{0}". Specify the Value parameter when adding members of this type. + + + Both Value and SecondValue parameters should not be null for a member of type "{0}". Specify a non-null value for one of the two parameters. + + + Cannot add a member with the name "{0}" because a member with that name already exists. To overwrite the member anyway, add the Force parameter to your command. + + + Cannot force the member with name "{0}" and type "{1}" to be added. A member with that name and type already exists, and the existing member is not an instance extension. + + + The member referenced by this alias should not be null or empty. + + + The Value parameter should not be null for a member of type "{0}". Specify a non-null value for the Value parameter when adding members of this type. + + + The SecondValue parameter should not be null for a member of type "{0}". Specify a non-null value for the SecondValue parameter when adding members of this type. + + + The parameter NotePropertyName cannot take values that could be converted to the type {0}. To define the name of a member with those values, use Add-Member, and specify the member type. + + + The name for a NoteProperty member should not be null or an empty string. + + + The TypeName parameter should not be null, empty, or contain only white spaces. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..6b178fb85ebe234e8192cb3a3ca20fceba2329b7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The source code was already compiled and loaded. + + + Cannot add type. The "{0}" extension is not supported. + + + Cannot add type. Input files must all have the same file extension. + + + Cannot add type. The assembly '{0}' could not be found. + + + Cannot add type. The type name '{0}' already exists. + + + Cannot set output assembly. The path {0} did not resolve to a single file. + + + Cannot add type. Compilation errors occurred. + + + Cannot add type. The OutputType parameter requires that the OutputAssembly parameter be specified. + + + Cannot add type. Definition of new types is not supported in this language mode. + + + The specified reference assembly '{0}' is unnecessary and ignored. + + + Both the assembly types 'ConsoleApplication' and 'WindowsApplication' are not currently supported. + + + Add-Type Cmdlet + + + Add-Type cmdlet will not be allowed in ConstrainedLanguage mode. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..f10c2e64236360e7da2aea3c16e618d9a3be321b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx @@ -0,0 +1,171 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Set Alias + + + Name: {0} Value: {1} + + + New Alias + + + Name: {0} Value: {1} + + + Import Alias + + + Name: {0} Value: {1} + + + Cannot open file {0} to export the alias. {1} + + + Alias File + + + Exported by : {0} + + + Date/Time : {0:F} + + + Computer : {0} + + + Cannot import the alias because the specified path '{0}' referred to a '{1}' provider path. Change the value of the Path parameter to a file system path. + + + Cannot import alias because path '{0}' contains wildcard characters that resolve to multiple paths. Aliases can be imported from only one file. Change the value of the Path parameter to a path that resolves to a single file. + + + Cannot open file {0} to import the alias. {1} + + + Cannot import an alias. Line number {1} in the file '{0}' is not a properly-formatted, comma-separated values (CSV) line for aliases. Change the line to contain four values separated by commas. If the value text itself contains a comma, then the value must be contained in quotation marks. + + + Cannot import the alias because line number {1} in the file '{0}' contains an option that is not recognized for aliases. Change the file to contain valid options. + + + This command cannot find a matching alias because an alias with the {0} '{1}' does not exist. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx new file mode 100644 index 0000000000000000000000000000000000000000..285dea7301e69886866154de9d6e7a1e0d40d6ca --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Data line '{0}' is not in 'name=value' format. + + + Data item '{1}' in line '{0}' is already defined. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..ae0b785d645fa1407d7502eac94fcfacd123ac74 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The supplied template was invalid: {0}. For more information on the template syntax, type 'Get-Help ConvertFrom-String' + + + No input was supplied + + + {0} is not a valid Regular Expression delimiter + + + One or more PropertyNames are invalid + + + Template file path resolves to more than one file. Specify a path to a single file + + + ConvertFrom-String appears to be having trouble parsing your data using the template you've provided. We'd love to take a look at what went wrong, if you'd like to share the data and template used to parse it. We've saved these files to {0} and {1} - feel free to attach them in a mail to psdmfb@microsoft.com. We will review all submissions, although we can't guarantee a response. + + + ConvertFrom-String appears to be having trouble parsing your data using the template you've provided. We'd love to take a look at what went wrong, if you'd like to share the data and template used to parse it. We've saved these files to {0} and {1} - feel free to attach them in a mail to psdmfb@microsoft.com. We will review all submissions, although we can't guarantee a response. + + + Error converting string value to specified type at file character position {0} + + + Template file is required for UpdateTemplate parameter + + + Template file was not found + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..f01b88d875410189b4605019f43c0905d9f61b45 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Accepted meta properties are content-type, default-style, application-name, author, description, generator, keywords, x-ua-compatible, and viewport. The meta pair: {0} and {1} may not function correctly. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..d77c7422abe1947a518cbd834e1cf53ab1c9bfe3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The type of the input object '{0}' is invalid. + + + Only FileSystem Provider paths are supported. The file path is not supported: '{0}'. + + + The property {0} of the given object is null or empty. + + + Invalid parameter set name: {0}. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..9e65acdc23c67999f12c3bf0dad54d8125c42313 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Text examples must follow the pattern "input value = output value" + + + PSObject examples should have 'Before' and 'After' properties + + + Convert-String appears to be having trouble parsing your data using the examples you've provided. We'd love to take a look at what went wrong - feel free to send the command you tried in a mail to psdmfb@microsoft.com. We will review all submissions, although we can't guarantee a response. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..dde1be6ab49ac1513e8aef36a63dfddaa03b1dbc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot append CSV content to the following file: {1}. The appended object does not have a property that corresponds to the following column: {0}. To continue with mismatched properties, add the -Force parameter, and then retry the command. + {0} is a placeholder for property name (i.e. ProcessId) + {1} is a placeholder for filename (i.e. c:\users\lukasza\foo.csv) + + {StrContains="Force"} + + Reviewed by TArcher on 2010-06-29. + + + + You must specify either the -UseQuotes or -QuoteFields parameters, but not both. + + + You must specify either the -Path or -LiteralPath parameters, but not both. + + + One or more headers were not specified. Default names starting with "H" have been used in place of any missing headers. + + + FileName is a mandatory parameter. + + + ReconcilePreexistingPropertyNames method should only get called when appending. + + + ReconcilePreexistingPropertyNames method should only get called when preexisting property names have been read successfully. + + + BuildPropertyNames method should be called only once per cmdlet instance. + + + Type hierarchy should not have null values. + + + EOF is reached. + + + You must specify either the -Append or -NoHeader parameters, but not both. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx new file mode 100644 index 0000000000000000000000000000000000000000..043fa4a932098cb50b423e7d4e8ff11806531617 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx @@ -0,0 +1,180 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Line cannot be less than 1. + + + There is no breakpoint with ID '{0}'. + + + File '{0}' does not exist. + + + Cannot set breakpoint on file '{0}'; only *.ps1 and *.psm1 files are valid. + + + Debugging is not supported on remote sessions. + + + Cannot set breakpoint. The language mode for this session is incompatible with the system-wide language mode. + + + Breakpoints cannot be set in the remote session because remote debugging is not supported by the current host. + + + You cannot debug the default host Runspace using this cmdlet. To debug the default Runspace use the normal debugging commands from the host. + + + Cannot debug Runspace. The host has no debugger. Try debugging the Runspace inside the PowerShell console or with Visual Studio Code, both of which have built-in debuggers. + + + Cannot debug Runspace. There is no host or host UI. The debugger requires a host and host UI for debugging. + + + More than one Runspace was found. Only one Runspace can be debugged at a time. + + + To end the debugging session type the 'Detach' command at the debugger prompt, or type 'Ctrl+C' otherwise. + + + Command or script completed. + + + Debugging Runspace: {0} + + + Cannot set debug options on Runspace {0} because it is not in the Opened state. + + + Failed to persist debug options for Process {0}. + + + No debugger was found for Runspace {0}. + + + No Runspace was found. + + + Wait-Debugger called on line {0} in {1}. + + + A breakpoint associated with another runspace cannot be updated because there is no runspace with instance ID '{0}'. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..2eff70b62674784c42847c8df77d35169cbb4119 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Event with source identifier '{0}' does not exist. + + + Event with identifier '{0}' does not exist. + + + Event subscription with source identifier '{0}' does not exist. + + + Event subscription with identifier '{0}' does not exist. + + + Event subscription '{0}' + + + Event '{0}' + + + Action must be specified for non-forwarded events. + + + Unsubscribe + + + Remove + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..824b56ec6bfb84b2f37637ff0ebb95170b0c2e10 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx @@ -0,0 +1,213 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + There are two instances of non-sequence Property '{0}' at {1} and {2} in parent Span {3} + + + Property '{0}' at {1} has no value and is not optional or a containing span + + + No program can be found for the given input + + + Internal error: Property cannot be null + + + Unexpected Span ending bracket found at {0} + + + Missing Span value at {0} while processing {1} + + + Invalid format at {0} while processing {1} + + + Invalid type name '{0}' at {1} while processing {2} + + + Missing Span name at {0} while processing {1} + + + First character of a name must be a letter or underscore at {0} while processing {1} + + + Characters of a name must be letters, digits, or underscores at {0} while processing {1} + + + Cannot embed attribute suffixes (e.g. optional, sequence) in names at {0} while processing {1} + + + Cannot use reserved word '{2}' at {0} while processing {1} + + + Expected value indicator at {0} while processing {1} + + + Unable to convert string value to specified type while processing {0} + + + Unexpected EOF while processing {0} + + + Span starting at line {0} column {1} + + + Internal error: Property '{0}' at {1} has no containing parent + + + Property '{0}' definition at {1} is inconsistent with earlier definition(s) + + + Internal error: no parent region found. + + + Internal error: parent regions cannot be null or empty. + + + line {0} column {1} + + + at {0} + + + '{0}' + + + line {0} column {1} + + + No template text file start for Span {0} + + + Internal error: Property '{0}' not found + + + Internal error: Invalid parser operation + + + Cached program was not found in template file for property: {0} + + + Template text does not match cached programs + + + The template text contains no example to parse + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx new file mode 100644 index 0000000000000000000000000000000000000000..e5bdb6dc12ba812ccc5eb4d2d367496c24c12afc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The data format is not supported by Out-GridView. + + + Microsoft .NET Framework 4.5 was installed while one or more PowerShell sessions were running. To use the {0} cmdlet, close all PowerShell windows, and then open a new PowerShell window. + + + Type + + + Value + + + Index + + + A command named '{0}' was not found. + + + More than one command named '{0}' was found. Start '{1}' with no parameters, and then type '{0}' to filter the results. + + + Cannot write to console input buffer. + + + {0} should be smaller than {1}. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetFormatDataStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetFormatDataStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..de231836cd5fc9c836db55e39f999728b6d7ba7b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetFormatDataStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Processing view defintion '{0}' + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx new file mode 100644 index 0000000000000000000000000000000000000000..a2e19681b64c073c85a96cfed963f02568ad6e08 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + You must specify an object for the Get-Member cmdlet. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..c81839c8409494860661e6903239ae12e1a6e0a4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 'maxValue' must be greater than zero. + + + The Minimum value ({0}) cannot be greater than or equal to the Maximum value ({1}). + + + 'minValue' cannot be greater than maxValue. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..f59439da714cb20c790a67cab49f10dfa5bf5c96 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + "The platform is not supported (System.Diagnostics.Stopwatch.IsHighResolution is false)." + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..c01248ed5d7eaca374fe42c6aa87a35dc77addf1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot process the color because {0} is not a valid color. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..a5f3e822ce3711abef82efa1a89b990177cad9b7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This command cannot be completed due to the following error: '{0}'. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..71e978c89b4ce46dd947a2b7eade8244f7a829ce --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + An element with the same key but a different value already exists. Key: {0} + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..3ee0ae73220813a2207907bdff8cb389f587c944 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx @@ -0,0 +1,216 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Data returned by the remote {0} command is not in the expected format. + + + The {0} cmdlet requires the following commands in the remote session: Get-Command, Get-FormatData, and Select-Object. The following commands are used, but optional: Get-Help, and Measure-Object. Verify that the remote session includes the required commands, and then try again. + + + Running the {0} command in a remote session reported the following error: {1}. + + + Running the {0} command in a remote session returned no results. + + + No session has been associated with this implicit remoting module. + + + Could not resolve remote alias '{0}'. + + + Proxy creation has been skipped for the '{0}' command, because the name did not match the value of the Name parameter. + + + Extended type definition has been skipped for the '{0}' type because its name did not match the value of the FormatTypeName parameter. + + + Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of the command name. + + + Proxy creation has been skipped for the following command: '{0}', because it would shadow an existing local command. Use the AllowClobber parameter if you want to shadow existing local commands. + + + No command proxies have been created, because all of the requested remote commands would shadow existing local commands. Use the AllowClobber parameter if you want to shadow existing local commands. + + + Implicit remoting for {0} + + + Implicit remoting event (session id: {0}; event handler id: {1}) + + + Implicit remoting module + + + generated on {0} + + + by {0} cmdlet + + + Invoked with the following command line: {0} + + + Optional parameter that can be used to specify the session on which this proxy module works + + + Creating a new session for implicit remoting of "{{0}}" command... + + + Session for implicit remoting module at {{0}} + + + Creating implicit remoting module ... + + + Getting command information from remote session ... + + + Getting command information from remote session ... {0} commands received + + + Getting formatting and output information from remote session ... + + + Getting formatting and output information from remote session ... {0} objects received + + + Completed. + + + PowerShell Credential Request + + + Enter your credentials for {0}. + + + Enter the HTTP proxy credentials that are used for the following connection: {0} + + + Commands that are available in the new remote session are different than those available when the implicit remoting module was created. Consider creating the module again by using the Export-PSSession cmdlet. + + + Files cannot be loaded because running scripts is disabled on this system. Provide a valid certificate with which to sign the files. + + + The file {0} could not be signed. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..cf792788c6f56657c02b6ad0582fdbb076d8a924 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The data file '{0}' cannot be found. + + + The FileName parameter was not specified. The FileName parameter is required when Import-LocalizedData is not called from a script file. + + + The following error occurred while PowerShell was opening the data file '{0}': +{1}. + + + The following error occurred while PowerShell was loading the '{0}' script data file: +{1}. + + + The argument for the FileName parameter should not contain a path. + + + Cannot find the PowerShell data file '{0}' in directory '{1}', or in any parent culture directories. + + + Cannot import localized data. The definition of additional supported commands is not allowed in this language mode. + + + The BindingVariable name '{0}' is invalid. + + + Import-LocalizedData Cmdlet + + + Additional supported commands (via SupportedCommand parameter) will not be allowed in ConstrainedLanguage mode. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..2b6b80959d02ac955a6b254dee121b4bf3b49519 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot open the file because the current provider ({0}) cannot open files. + + + The file {0} cannot be read: {1} + + + The option "Context" is not valid when searching results that are piped from Select-String output. + + + The string {0} is not a valid regular expression: {1} + + + You must specify -Culture parameter only with -SimpleMatch parameter. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..e27aa35e747f555b5b6723f323f839b5b8962199 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The property "{0}" cannot be found in the input for any objects. + + + Input object "{0}" is not numeric. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..8c8d59034ccab3fad38a31ee4fbeb8ea9ca1743d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx @@ -0,0 +1,162 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + A constructor was not found. Cannot find an appropriate constructor for type {0}. + + + Cannot find type [{0}]: verify that the assembly containing this type is loaded. + + + Cannot load COM type {0}. + + + The object written to the pipeline is an instance of the type "{0}" from the component's primary interoperability assembly. If this type exposes different members than the IDispatch members, scripts that are written to work with this object might not work if the primary interoperability assembly is not installed. + + + The member "{1}" was not found for the specified {2} object. + + + The value supplied is not valid, or the property is read-only. Change the value, and then try again. + + + Creating instances of attribute and delegated Windows RT types is not supported. + + + Cannot create instances of the ByRef-like type "{0}". ByRef-like types are not supported in PowerShell. + + + Cannot create type. Only core types are supported in this language mode. + + + Cannot create type. Only core types are supported in {0} language mode on a policy locked down machine. + + + New-Object Cmdlet Type Creation + + + The type '{0}' will not be created in ConstrainedLanguage mode. + + + New-Object Cmdlet COM Object Creation + + + The COM object '{0}' will not be created in ConstrainedLanguage mode. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..0b4c01443f30d2c0b38f359d5a539922dea4c653 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Courier New + {StringCategory="Font Name"} + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..02d3aad766dded74c11af496bd0f4a56c25a8122 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot rename multiple results. + + + Property "{0}" cannot be found. + + + Multiple properties cannot be expanded. + + + The property cannot be processed because the property "{0}" already exists. + + + A property is an empty script block and does not provide a name. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..3f53249c1b349f7432ea7bdec058f02c731433fe --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The email cannot be sent because no SMTP server was specified. You must specify an SMTP server by using either the SmtpServer parameter or the $PSEmailServer variable. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..4e05f063ce121bec0dadd08e60af2760a39695f8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + "Sort-Object" - "{0}" cannot be found in "InputObject". + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/StartSleepStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/StartSleepStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..32804b9e21b8be38065dd5ee55bbded39de8ea4c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/StartSleepStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The '-Duration' parameter value must not exceed '{0}', provided value was '{1}'. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..cc607eda4189055ad73a32ce0fb258c0a8083168 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot parse the JSON schema. + + + Cannot parse the JSON. + + + The JSON is not valid with the schema: {0} at '{1}' + + + Can not open JSON schema file: {0} + + + URI scheme '{0}' is not supported. Only HTTP(S) and local file system URIs are allowed. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..c09ba1ea796676b14869abbd9847d1263d49dd23 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Trace output can only be written to the file system. The path '{0}' referred to a '{1}' provider path. + + + Trace output can only be written to a single file. The path '{0}' resolved to more than one file. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..b2af7eba67e44f8e0f004e00956beb6d23f381a1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The cmdlet does not support Linux. + + + There was an error unblocking {0}. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..ba1bdfd6174c7223eeba127c7e44c3643cbe2890 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx @@ -0,0 +1,186 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot open the file because the current provider is "{0}", and this command requires a file. + + + Cannot read the file "{0}" because it does not have the file name extension "{1}". + + + Update TypeData + + + Update FormatData + + + FileName: {0} + + + Cannot update a member with type "{0}". Specify a different type for the MemberType parameter. + + + The {0} parameter is required for the type "{1}". Please specify the {0} parameter. + + + The {0} parameter should not be null or an empty string for a member of type "{1}". Specify a non-null value for the {0} parameter when updating this member type. + + + The {0} parameter is not necessary for a member of type "{1}", and should not be specified. Do not specify the {0} parameter when updating this member type. + + + No member is specified for the update on type "{0}". + + + The target type name should not be null, empty, or contain only white spaces. + + + The Value and SecondValue parameters should not both be null for a member of type "{0}". Specify a non-null value for one of the two parameters. + + + Only one member type can be specified. The member types specified are: "{0}". Update the type with only one member type. + + + The MemberName, Value, and SecondValue parameters cannot be specified without the MemberType parameter. + + + Remove TypeData + + + Name of the type that will be removed: {0} + + + Type to update: {0} + + + Remove type file + + + The file {0} is not imported into the current session. + + + Updating format data is not allowed in this runspace. The 'DisableFormatUpdates' property is set to True when creating the runspace. + + + Cannot update the format data with a FormatTable instance. + + + Cannot update the type data with a TypeTable instance. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..e6b985db27505c8f4c36f04838930c7d5cd505c5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The property '{0}' cannot be found on this object + + + You must specify the Property parameter when the InputObject parameter is specified. + + + You must specify the InputObject parameter when the Property parameter is specified. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..0eedd2d38d256398f8b2cc4eb573eb06b093c0ce --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {2} has one or more exceptions that are not valid. + + + This command cannot be run because the file path '{0}' is not valid. Please provide a valid file path and then run the command. + + + This command cannot be run because '{0}' is empty or blank. Please specify CSSUri and then run the command. + + + Cannot open the file because the current provider ({0}) cannot open files. + + + This command cannot be run because the prefix value in the Namespace parameter is null. Provide a valid value for the prefix, and then run the command again. + + + The objects grouped by this property cannot be expanded because there is a key duplication. Provide a valid value for the property, and then try again. + + + The command is not supported on this operating system. + + + The file '{0}' cannot be read: {1} + + + Cannot convert input of type '{0}' to hexadecimal. To view the hexadecimal formatting of its string representation, pipe it to the Out-String cmdlet before piping it to Format-Hex. + + + The given path '{0}' is not supported. This command only supports the FileSystem Provider paths. + + + Path: + + + The command cannot be run because the AsString parameter requires that you specify the AsHashtable parameter. + + + The command cannot be run because using the AsHashTable parameter with more than one property requires adding the AsString parameter. + + + Cannot find path '{0}' because it does not exist. + + + Cannot use tag '{0}'. The 'PS' prefix is reserved. + + + The file '{0}' could not be parsed as a PowerShell Data File. + + + Cannot construct a security descriptor from the given SDDL due to the following error: {0} + + + Invoke-Expression Cmdlet + + + Invoke-Expression cmdlet script block will be run in ConstrainedLanguage mode. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..3bca38847db1ac2a3971b4b4d75a9f87d441981e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This PowerShell snap-in contains utility cmdlets that are used to view and organize data in different ways. + + + Microsoft Corporation + + + PowerShell utility snap-in + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..d385adda038fa97d991b67f06f091a364b5b8012 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Set variable + + + Name: {0} Value: {1} + + + Use a single variable rather than a collection + + + New variable + + + Name: {0} Value: {1} + + + Remove variable + + + Name: {0} + + + Clear variable + + + Name: {0} + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..cb080d37012e67bf6477c4ad2f5d82afdc8cf3de --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -0,0 +1,252 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Access to the path '{0}' is denied. + + + The cmdlet cannot protect plain text secrets sent over unencrypted connections. To suppress this warning and send plain text secrets over unencrypted networks, reissue the command specifying the AllowUnencryptedAuthentication parameter. + + + The cmdlet cannot run because the following conflicting parameters are specified: Authentication and UseDefaultCredentials. Authentication does not support Default Credentials. Specify either Authentication or UseDefaultCredentials, then retry. + + + The cmdlet cannot run because the following parameter is not specified: Credential. The supplied Authentication type requires a Credential. Specify Credential, then retry. + + + The cmdlet cannot run because the following parameter is not specified: Token. The supplied Authentication type requires a Token. Specify Token, then retry. + + + The cmdlet cannot run because the following conflicting parameters are specified: Credential and Token. Specify either Credential or Token, then retry. + + + The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry. + + + The cmdlet cannot run because the following conflicting parameters are specified: Body and Form. Specify either Body or Form, then retry. + + + The cmdlet cannot run because the following conflicting parameters are specified: InFile and Form. Specify either InFile or Form, then retry. + + + The cmdlet cannot run because the -ContentType parameter is not a valid Content-Type header. Specify a valid Content-Type for -ContentType, then retry. To suppress header validation, supply the -SkipHeaderValidation parameter. + + + The cmdlet cannot run because the following conflicting parameters are specified: Credential and UseDefaultCredentials. Specify either Credential or UseDefaultCredentials, then retry. + + + Path '{0}' resolves to a directory. Specify a path including a file name, and then retry the command. + + + The provided JSON includes a property whose name is an empty string, this is only supported using the -AsHashTable switch. + + + Cannot convert the JSON string because a dictionary that was converted from the string contains the duplicated key '{0}'. + + + The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again. + + + Cannot follow an insecure redirection by default. Reissue the command specifying the -AllowInsecureRedirect switch. + + + Cannot convert the JSON string because it contains keys with different casing. Please use the -AsHashTable switch instead. The key that was attempted to be added to the existing key '{0}' was '{1}'. + + + The maximum redirection count has been exceeded. To increase the number of redirections allowed, supply a higher value to the -MaximumRedirection parameter. + + + Path '{0}' can be resolved to multiple paths. + + + The type '{0}' is not supported for serialization or deserialization of a dictionary. Keys must be strings. + + + Path '{0}' cannot be resolved to a file. + + + Path '{0}' is not a file system path. Please specify the path to a file in the file system. + + + The cmdlet cannot run because the following parameter is missing: OutFile. Provide a valid OutFile parameter value when using the {0} parameter, then retry. + + + The file will not be re-downloaded because the remote file is the same size as the OutFile: {0} + + + The cmdlet cannot run because the following conflicting parameters are specified: ProxyCredential and ProxyUseDefaultCredentials. Specify either ProxyCredential or ProxyUseDefaultCredentials, then retry. + + + The cmdlet cannot run because the following parameter is missing: Proxy. Provide a valid proxy URI for the Proxy parameter when using the ProxyCredential or ProxyUseDefaultCredentials parameters, then retry. + + + Reading web response stream completed. Bytes downloaded: {0} + + + Reading web response stream + + + Downloaded: {0} of {1} + + + The Resume switch can only be used if OutFile targets a file but it resolves to a directory: {0}. + + + The cmdlet cannot run because the following conflicting parameters are specified: Session and SessionVariable. Specify either Session or SessionVariable, then retry. + + + Unable to retrieve certificates because the thumbprint is not valid. Verify the thumbprint and retry. + + + Web request completed. (Number of bytes processed: {0}) + + + Web request cancelled. (Number of bytes processed: {0}) + + + Web request status + + + Downloaded: {0} of {1} + + + Conversion from JSON failed with error: {0} + + + Response status code does not indicate success: {0} ({1}). + + + Following rel link {0} + + + The remote server indicated it could not resume downloading. The local file will be overwritten. + + + Received HTTP/{0} response of content type {1} of unknown size + + + Retrying after interval of {0} seconds. Status code for previous attempt: {1} + + + Resulting JSON is truncated as serialization has exceeded the set depth of {0}. + + + The WebSession properties were changed between requests forcing all HTTP connections in the session to be recreated. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..13d2058e7b23d62918a4cedf16aa39363f6c234f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + "The Write-Error cmdlet reported an error." + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..9603b4deb9925a9f60ac66cc793a74f8f16b4c00 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Text to describe the activity for which progress is being reported. + + + Text to describe the current state of the activity for which progress is being reported. + + + Processing + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs new file mode 100644 index 0000000000000000000000000000000000000000..ebb3325d0b767bf0b44d41847022f56346b46e7c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell +{ + /// + /// PSUtilityPSSnapIn is a class for facilitating registry + /// of necessary information for PowerShell utility PSSnapin. + /// + [RunInstaller(true)] + public sealed class PSUtilityPSSnapIn : PSSnapIn + { + /// + /// Create an instance of this class. + /// + public PSUtilityPSSnapIn() + : base() + { + } + + /// + /// Get name of this PSSnapin. + /// + public override string Name + { + get + { + return RegistryStrings.UtilityMshSnapinName; + } + } + + /// + /// Get the default vendor string for this PSSnapin. + /// + public override string Vendor + { + get + { + return "Microsoft"; + } + } + + /// + /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. + /// + public override string VendorResource + { + get + { + return "UtilityMshSnapInResources,Vendor"; + } + } + + /// + /// Get the default description string for this PSSnapin. + /// + public override string Description + { + get + { + return "This PSSnapIn contains utility cmdlets used to manipulate data."; + } + } + + /// + /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. + /// + public override string DescriptionResource + { + get + { + return "UtilityMshSnapInResources,Description"; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..26b1dbe9a489f68b202c5789fe54cd8e042b7475 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("powershell-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: System.Runtime.InteropServices.ComVisible(false)] diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj new file mode 100644 index 0000000000000000000000000000000000000000..bbc8023b1daf3d086eeaced6f4dde4ecc7e88f49 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj @@ -0,0 +1,29 @@ + + + + PowerShell Host + $(NoWarn);CS1570;CA1416 + Microsoft.PowerShell.ConsoleHost + + + + + + + + $(DefineConstants);CORECLR + + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs new file mode 100644 index 0000000000000000000000000000000000000000..8cc6bd8ab0200b404c453ae66571484903b1afd0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs @@ -0,0 +1,271 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace Microsoft.PowerShell +{ + internal static class ComInterfaces + { + [DllImport("kernel32.dll", SetLastError = false, EntryPoint = "GetStartupInfoW")] + internal static extern void GetStartupInfo(out StartUpInfo lpStartupInfo); + + /// + /// IntPtr is being used for the string fields to make the marshaller faster and + /// simpler. With IntPtr, all fields are blittable, and since we don't use the + /// string fields at all, nothing is lost. + /// + [StructLayout(LayoutKind.Sequential)] + internal readonly struct StartUpInfo + { + public readonly uint cb; + private readonly IntPtr lpReserved; + public readonly IntPtr lpDesktop; + public readonly IntPtr lpTitle; + public readonly uint dwX; + public readonly uint dwY; + public readonly uint dwXSize; + public readonly uint dwYSize; + public readonly uint dwXCountChars; + public readonly uint dwYCountChars; + public readonly uint dwFillAttribute; + public readonly uint dwFlags; + public readonly ushort wShowWindow; + private readonly ushort cbReserved2; + private readonly IntPtr lpReserved2; + public readonly IntPtr hStdInput; + public readonly IntPtr hStdOutput; + public readonly IntPtr hStdError; + } + + [ComImport] + [Guid("00021401-0000-0000-C000-000000000046")] + [ClassInterface(ClassInterfaceType.None)] + internal class CShellLink { } + + [ComImport] + [Guid("000214F9-0000-0000-C000-000000000046")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + internal interface IShellLinkW + { + void GetPath( + [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, + int cchMaxPath, + IntPtr pfd, + uint fFlags); + + void GetIDList(out IntPtr ppidl); + + void SetIDList(IntPtr pidl); + + void GetDescription( + [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, + int cchMaxName); + + void SetDescription( + [MarshalAs(UnmanagedType.LPWStr)] string pszName); + + void GetWorkingDirectory( + [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, + int cchMaxPath + ); + + void SetWorkingDirectory( + [MarshalAs(UnmanagedType.LPWStr)] string pszDir); + + void GetArguments( + [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, + int cchMaxPath); + + void SetArguments( + [MarshalAs(UnmanagedType.LPWStr)] string pszArgs); + + void GetHotKey(out short wHotKey); + + void SetHotKey(short wHotKey); + + void GetShowCmd(out uint iShowCmd); + + void SetShowCmd(uint iShowCmd); + + void GetIconLocation( + [Out(), MarshalAs(UnmanagedType.LPWStr)] out StringBuilder pszIconPath, + int cchIconPath, + out int iIcon); + + void SetIconLocation( + [MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, + int iIcon); + + void SetRelativePath( + [MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, + uint dwReserved); + + void Resolve(IntPtr hwnd, uint fFlags); + + void SetPath( + [MarshalAs(UnmanagedType.LPWStr)] string pszFile); + } + + /// + /// A property store. + /// + [ComImport] + [Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + internal interface IPropertyStore + { + /// + /// Gets the number of properties contained in the property store. + /// + /// + /// + [PreserveSig] + HResult GetCount([Out] out uint propertyCount); + + /// + /// Get a property key located at a specific index. + /// + /// + /// + /// + [PreserveSig] + HResult GetAt([In] uint propertyIndex, out PropertyKey key); + + /// + /// Gets the value of a property from the store. + /// + /// + /// + /// + [PreserveSig] + HResult GetValue([In] in PropertyKey key, [Out] PropVariant pv); + + /// + /// Sets the value of a property in the store. + /// + /// + /// + /// + [PreserveSig] + HResult SetValue([In] in PropertyKey key, [In] PropVariant pv); + + /// + /// Commits the changes. + /// + /// + [PreserveSig] + HResult Commit(); + } + + [ComImport] + [Guid("6332DEBF-87B5-4670-90C0-5E57B408A49E")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + internal interface ICustomDestinationList + { + void SetAppID( + [MarshalAs(UnmanagedType.LPWStr)] string pszAppID); + + [PreserveSig] + HResult BeginList( + out uint cMaxSlots, + ref Guid riid, + [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); + + [PreserveSig] + HResult AppendCategory( + [MarshalAs(UnmanagedType.LPWStr)] string pszCategory, + [MarshalAs(UnmanagedType.Interface)] IObjectArray poa); + + void AppendKnownCategory( + [MarshalAs(UnmanagedType.I4)] KnownDestinationCategory category); + + [PreserveSig] + HResult AddUserTasks( + [MarshalAs(UnmanagedType.Interface)] IObjectArray poa); + + void CommitList(); + + void GetRemovedDestinations( + ref Guid riid, + [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); + + void DeleteList( + [MarshalAs(UnmanagedType.LPWStr)] string pszAppID); + + void AbortList(); + } + + internal enum KnownDestinationCategory + { + Frequent = 1, + Recent + } + + [ComImport] + [Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + internal interface IObjectArray + { + void GetCount(out uint cObjects); + + void GetAt( + uint iIndex, + ref Guid riid, + [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); + } + + [ComImport] + [Guid("5632B1A4-E38A-400A-928A-D4CD63230295")] + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + internal interface IObjectCollection + { + // IObjectArray + void GetCount(out uint cObjects); + + void GetAt( + uint iIndex, + ref Guid riid, + [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); + + // IObjectCollection + void AddObject( + [MarshalAs(UnmanagedType.Interface)] object pvObject); + + void AddFromArray( + [MarshalAs(UnmanagedType.Interface)] IObjectArray poaSource); + + void RemoveObject(uint uiIndex); + + void Clear(); + } + + [ComImport] + [Guid("45e2b4ae-b1c3-11d0-b92f-00a0c90312e1"), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + internal interface IShellLinkDataListW + { + [PreserveSig] + int AddDataBlock(IntPtr pDataBlock); + + [PreserveSig] + int CopyDataBlock(uint dwSig, out IntPtr ppDataBlock); + + [PreserveSig] + int RemoveDataBlock(uint dwSig); + + void GetFlags(out uint pdwFlags); + + void SetFlags(uint dwFlags); + } + + [DllImport("ole32.Dll")] + internal static extern HResult CoCreateInstance(ref Guid clsid, + [MarshalAs(UnmanagedType.IUnknown)] object inner, + uint context, + ref Guid uuid, + [MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs new file mode 100644 index 0000000000000000000000000000000000000000..4789bcef06f8857fdcbe7fe6ae03ddab11fa3e1d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.PowerShell +{ + /// + /// HRESULT Wrapper + /// + internal enum HResult + { + /// + /// S_OK + /// + Ok = 0x0000, + + /// + /// S_FALSE. + /// + False = 0x0001, + + /// + /// E_INVALIDARG. + /// + InvalidArguments = unchecked((int)0x80070057), + + /// + /// E_OUTOFMEMORY. + /// + OutOfMemory = unchecked((int)0x8007000E), + + /// + /// E_NOINTERFACE. + /// + NoInterface = unchecked((int)0x80004002), + + /// + /// E_FAIL. + /// + Fail = unchecked((int)0x80004005), + + /// + /// E_ELEMENTNOTFOUND. + /// + ElementNotFound = unchecked((int)0x80070490), + + /// + /// TYPE_E_ELEMENTNOTFOUND. + /// + TypeElementNotFound = unchecked((int)0x8002802B), + + /// + /// NO_OBJECT. + /// + NoObject = unchecked((int)0x800401E5), + + /// + /// Win32 Error code: ERROR_CANCELLED. + /// + Win32ErrorCanceled = 1223, + + /// + /// ERROR_CANCELLED. + /// + Canceled = unchecked((int)0x800704C7), + + /// + /// The requested resource is in use. + /// + ResourceInUse = unchecked((int)0x800700AA), + + /// + /// The requested resources is read-only. + /// + AccessDenied = unchecked((int)0x80030005) + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs new file mode 100644 index 0000000000000000000000000000000000000000..408c59c482a0bf833f31a6a95f5ba8cbfcbcd9c5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.PowerShell +{ + /// + /// Represents the OLE struct PROPVARIANT. + /// This class is intended for internal use only. + /// + /// + /// Originally sourced from https://blogs.msdn.com/adamroot/pages/interop-with-propvariants-in-net.aspx + /// and modified to add ability to set values + /// + [StructLayout(LayoutKind.Explicit)] + internal sealed class PropVariant : IDisposable + { + // This is actually a VarEnum value, but the VarEnum type requires 4 bytes instead of the expected 2. + [FieldOffset(0)] + private readonly ushort _valueType; + + [FieldOffset(8)] + private readonly IntPtr _ptr; + + /// + /// Set a string value. + /// + internal PropVariant(string value) + { + if (value == null) + { + throw new ArgumentException("PropVariantNullString", nameof(value)); + } + + _valueType = (ushort)VarEnum.VT_LPWSTR; + _ptr = Marshal.StringToCoTaskMemUni(value); + } + + /// + /// Disposes the object, calls the clear function. + /// + public void Dispose() + { + PropVariantNativeMethods.PropVariantClear(this); + + GC.SuppressFinalize(this); + } + + /// + /// Finalizes an instance of the class. + /// + ~PropVariant() + { + Dispose(); + } + + private static class PropVariantNativeMethods + { + [DllImport("Ole32.dll", PreserveSig = false)] + internal static extern void PropVariantClear([In, Out] PropVariant pvar); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs new file mode 100644 index 0000000000000000000000000000000000000000..93346424dc550254cacb9ec2d02eec48414d9862 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.PowerShell +{ + /// + /// Defines a unique key for a Shell Property. + /// + [StructLayout(LayoutKind.Sequential, Pack = 4)] + internal readonly struct PropertyKey : IEquatable + { + #region Public Properties + /// + /// A unique GUID for the property. + /// + public Guid FormatId { get; } + + /// + /// Property identifier (PID) + /// + public int PropertyId { get; } + + #endregion + + #region Public Construction + + /// + /// PropertyKey Constructor. + /// + /// A unique GUID for the property. + /// Property identifier (PID). + internal PropertyKey(Guid formatId, int propertyId) + { + this.FormatId = formatId; + this.PropertyId = propertyId; + } + + #endregion + + #region IEquatable Members + + /// + /// Returns whether this object is equal to another. This is vital for performance of value types. + /// + /// The object to compare against. + /// Equality result. + public bool Equals(PropertyKey other) + { + return other.Equals((object)this); + } + + #endregion + + #region equality and hashing + + /// + /// Returns the hash code of the object. This is vital for performance of value types. + /// + /// + public override int GetHashCode() + { + return FormatId.GetHashCode() ^ PropertyId; + } + + /// + /// Returns whether this object is equal to another. This is vital for performance of value types. + /// + /// The object to compare against. + /// Equality result. + public override bool Equals(object obj) + { + if (obj == null) + return false; + + if (obj is not PropertyKey) + return false; + + PropertyKey other = (PropertyKey)obj; + return other.FormatId.Equals(FormatId) && (other.PropertyId == PropertyId); + } + + /// + /// Implements the == (equality) operator. + /// + /// First property key to compare. + /// Second property key to compare. + /// True if object a equals object b. false otherwise. + public static bool operator ==(PropertyKey propKey1, PropertyKey propKey2) + { + return propKey1.Equals(propKey2); + } + + /// + /// Implements the != (inequality) operator. + /// + /// First property key to compare. + /// Second property key to compare. + /// True if object a does not equal object b. false otherwise. + public static bool operator !=(PropertyKey propKey1, PropertyKey propKey2) + { + return !propKey1.Equals(propKey2); + } + + /// + /// Override ToString() to provide a user friendly string representation. + /// + /// String representing the property key. + public override string ToString() + { + return string.Format(System.Globalization.CultureInfo.InvariantCulture, + "PropertyKeyFormatString", + FormatId.ToString("B"), PropertyId); + } + + #endregion + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs new file mode 100644 index 0000000000000000000000000000000000000000..5606eabd567010db0b89c277945ac8ddce81cf24 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Management.Automation; +using System.Reflection; +using System.Threading; + +using static Microsoft.PowerShell.ComInterfaces; + +namespace Microsoft.PowerShell +{ + internal static class TaskbarJumpList + { + // Creating a JumpList entry takes around 55ms when the PowerShell process is interactive and + // owns the current window (otherwise it does a fast exit anyway). Since there is no 'GET' like API, + // we always have to execute this call because we do not know if it has been created yet. + // The JumpList does persist as long as the filepath of the executable does not change but there + // could be disruptions to it like e.g. the bi-annual Windows update, we decided to + // not over-optimize this and always create the JumpList as a non-blocking background STA thread instead. + internal static void CreateRunAsAdministratorJumpList() + { + // The STA apartment state is not supported on NanoServer and Windows IoT. + // Plus, there is not need to create jump list in those environment anyways. + if (!Platform.IsWindowsDesktop) + { + return; + } + + // Some COM APIs are implicitly STA only, therefore the executing thread must run in STA. + var thread = new Thread(() => + { + try + { + CreateElevatedEntry(ConsoleHostStrings.RunAsAdministrator); + } + catch (Exception) + { + // Due to COM threading complexity there might still be sporadic failures but they can be + // ignored as creating the JumpList is not critical and persists after its first creation. + } + }); + + try + { + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + catch (ThreadStartException) + { + // STA may not be supported on some platforms + } + } + + private static void CreateElevatedEntry(string title) + { + // Check startupInfo first to know if the current shell is interactive and owns a window before proceeding + // This check is fast (less than 1ms) and allows for quick-exit + GetStartupInfo(out StartUpInfo startupInfo); + const uint STARTF_USESHOWWINDOW = 0x00000001; + const ushort SW_HIDE = 0; + if (((startupInfo.dwFlags & STARTF_USESHOWWINDOW) == 1) && (startupInfo.wShowWindow != SW_HIDE)) + { + string cmdPath = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe"); + + // Check for maximum available slots in JumpList and start creating the custom Destination List + var CLSID_DestinationList = new Guid(@"77f10cf0-3db5-4966-b520-b7c54fd35ed6"); + const uint CLSCTX_INPROC_SERVER = 1; + var IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046"); + var hResult = CoCreateInstance(ref CLSID_DestinationList, null, CLSCTX_INPROC_SERVER, ref IID_IUnknown, out object pCustDestListobj); + if (hResult < 0) + { + Debug.Fail($"Creating ICustomDestinationList failed with HResult '{hResult}'."); + return; + } + + var pCustDestList = (ICustomDestinationList)pCustDestListobj; + hResult = pCustDestList.BeginList(out uint uMaxSlots, new Guid(@"92CA9DCD-5622-4BBA-A805-5E9F541BD8C9"), out object pRemovedItems); + if (hResult < 0) + { + Debug.Fail($"BeginList on ICustomDestinationList failed with HResult '{hResult}'."); + return; + } + + if (uMaxSlots >= 1) + { + // Create JumpListLink + var nativeShellLink = (IShellLinkW)new CShellLink(); + var nativePropertyStore = (IPropertyStore)nativeShellLink; + nativeShellLink.SetPath(cmdPath); + nativeShellLink.SetShowCmd(0); + var shellLinkDataList = (IShellLinkDataListW)nativeShellLink; + shellLinkDataList.GetFlags(out uint flags); + flags |= 0x00800000; // SLDF_ALLOW_LINK_TO_LINK + flags |= 0x00002000; // SLDF_RUNAS_USER + shellLinkDataList.SetFlags(flags); + var PKEY_TITLE = new PropertyKey(new Guid("{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"), 2); + hResult = nativePropertyStore.SetValue(in PKEY_TITLE, new PropVariant(title)); + if (hResult < 0) + { + pCustDestList.AbortList(); + Debug.Fail($"SetValue on IPropertyStore with title '{title}' failed with HResult '{hResult}'."); + return; + } + + hResult = nativePropertyStore.Commit(); + if (hResult < 0) + { + pCustDestList.AbortList(); + Debug.Fail($"Commit on IPropertyStore failed with HResult '{hResult}'."); + return; + } + + // Create collection and add JumpListLink + var CLSID_EnumerableObjectCollection = new Guid(@"2d3468c1-36a7-43b6-ac24-d3f02fd9607a"); + const uint CLSCTX_INPROC_HANDLER = 2; + const uint CLSCTX_INPROC = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER; + hResult = CoCreateInstance(ref CLSID_EnumerableObjectCollection, null, CLSCTX_INPROC, ref IID_IUnknown, out object instance); + if (hResult < 0) + { + pCustDestList.AbortList(); + Debug.Fail($"Creating IObjectCollection failed with HResult '{hResult}'."); + return; + } + + var pShortCutCollection = (IObjectCollection)instance; + pShortCutCollection.AddObject((IShellLinkW)nativePropertyStore); + + // Add collection to custom destination list and commit the result + hResult = pCustDestList.AddUserTasks((IObjectArray)pShortCutCollection); + if (hResult < 0) + { + pCustDestList.AbortList(); + Debug.Fail($"AddUserTasks on ICustomDestinationList failed with HResult '{hResult}'."); + return; + } + + pCustDestList.CommitList(); + } + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs new file mode 100644 index 0000000000000000000000000000000000000000..0fb85e740f4c30aa6c6f4dfcdd8c91c1331e0dc8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -0,0 +1,1650 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Configuration; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Management.Automation.Runspaces; +using System.Security; +using System.Text; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// Null class implementation of PSHostUserInterface used when no console is available and when PowerShell + /// is run in servmode where no console is needed. + /// + internal class NullHostUserInterface : PSHostUserInterface + { + /// + /// RawUI. + /// + public override PSHostRawUserInterface? RawUI + => null; + + /// + /// Prompt. + /// + /// + /// + /// + /// + public override Dictionary Prompt(string caption, string message, Collection descriptions) + => throw new PSNotImplementedException(); + + /// + /// PromptForChoice. + /// + /// + /// + /// + /// + /// + public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) + => throw new PSNotImplementedException(); + + /// + /// PromptForCredential. + /// + /// + /// + /// + /// + /// + public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName) + => throw new PSNotImplementedException(); + + /// + /// PromptForCredential. + /// + /// + /// + /// + /// + /// + /// + /// + public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) + => throw new PSNotImplementedException(); + + /// + /// ReadLine. + /// + /// + public override string ReadLine() + => throw new PSNotImplementedException(); + + /// + /// ReadLineAsSecureString. + /// + /// + public override SecureString ReadLineAsSecureString() + => throw new PSNotImplementedException(); + + /// + /// Write. + /// + /// + public override void Write(string value) + { } + + /// + /// Write. + /// + /// + /// + /// + public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) + { } + + /// + /// WriteDebugLine. + /// + /// + public override void WriteDebugLine(string message) + { } + + /// + /// WriteErrorLine. + /// + /// + public override void WriteErrorLine(string value) + => Console.Out.WriteLine(value); + + /// + /// WriteLine. + /// + /// + public override void WriteLine(string value) + { } + + /// + /// WriteProgress. + /// + /// + /// + public override void WriteProgress(long sourceId, ProgressRecord record) + { } + + /// + /// WriteVerboseLine. + /// + /// + public override void WriteVerboseLine(string message) + { } + + /// + /// WriteWarningLine. + /// + /// + public override void WriteWarningLine(string message) + { } + } + + internal class CommandLineParameterParser + { + private const int MaxPipePathLengthLinux = 108; + private const int MaxPipePathLengthMacOS = 104; + + internal static int MaxNameLength() + { + if (Platform.IsWindows) + { + return ushort.MaxValue; + } + + int maxLength = Platform.IsLinux ? MaxPipePathLengthLinux : MaxPipePathLengthMacOS; + return maxLength - Path.GetTempPath().Length; + } + + internal bool? InputRedirectedTestHook; + + private static readonly string[] s_validParameters = { + "sta", + "mta", + "command", + "commandwithargs", + "configurationname", + "custompipename", + "encodedcommand", + "executionpolicy", + "file", + "help", + "inputformat", + "login", + "noexit", + "nologo", + "noninteractive", + "noprofile", + "noprofileloadtime", + "outputformat", + "removeworkingdirectorytrailingcharacter", + "settingsfile", + "version", + "windowstyle", + "workingdirectory" + }; + +#pragma warning disable SA1025 // CodeMustNotContainMultipleWhitespaceInARow + /// + /// These represent the parameters that are used when starting pwsh. + /// We can query in our telemetry to determine how pwsh was invoked. + /// + [Flags] + internal enum ParameterBitmap : long + { + Command = 0x0000000000000001, // -Command | -c + ConfigurationName = 0x0000000000000002, // -ConfigurationName | -config + CustomPipeName = 0x0000000000000004, // -CustomPipeName + EncodedCommand = 0x0000000000000008, // -EncodedCommand | -e | -ec + EncodedArgument = 0x0000000000000010, // -EncodedArgument + ExecutionPolicy = 0x0000000000000020, // -ExecutionPolicy | -ex | -ep + File = 0x0000000000000040, // -File | -f + Help = 0x0000000000000080, // -Help, -?, /? + InputFormat = 0x0000000000000100, // -InputFormat | -inp | -if + Interactive = 0x0000000000000200, // -Interactive | -i + Login = 0x0000000000000400, // -Login | -l + MTA = 0x0000000000000800, // -MTA + NoExit = 0x0000000000001000, // -NoExit | -noe + NoLogo = 0x0000000000002000, // -NoLogo | -nol + NonInteractive = 0x0000000000004000, // -NonInteractive | -noni + NoProfile = 0x0000000000008000, // -NoProfile | -nop + OutputFormat = 0x0000000000010000, // -OutputFormat | -o | -of + SettingsFile = 0x0000000000020000, // -SettingsFile | -settings + SSHServerMode = 0x0000000000040000, // -SSHServerMode | -sshs + SocketServerMode = 0x0000000000080000, // -SocketServerMode | -sockets + ServerMode = 0x0000000000100000, // -ServerMode | -server + NamedPipeServerMode = 0x0000000000200000, // -NamedPipeServerMode | -namedpipes + STA = 0x0000000000400000, // -STA + Version = 0x0000000000800000, // -Version | -v + WindowStyle = 0x0000000001000000, // -WindowStyle | -w + WorkingDirectory = 0x0000000002000000, // -WorkingDirectory | -wd + ConfigurationFile = 0x0000000004000000, // -ConfigurationFile + NoProfileLoadTime = 0x0000000008000000, // -NoProfileLoadTime + CommandWithArgs = 0x0000000010000000, // -CommandWithArgs | -cwa + + // Enum values for specified ExecutionPolicy + EPUnrestricted = 0x0000000100000000, // ExecutionPolicy unrestricted + EPRemoteSigned = 0x0000000200000000, // ExecutionPolicy remote signed + EPAllSigned = 0x0000000400000000, // ExecutionPolicy all signed + EPRestricted = 0x0000000800000000, // ExecutionPolicy restricted + EPDefault = 0x0000001000000000, // ExecutionPolicy default + EPBypass = 0x0000002000000000, // ExecutionPolicy bypass + EPUndefined = 0x0000004000000000, // ExecutionPolicy undefined + EPIncorrect = 0x0000008000000000, // ExecutionPolicy incorrect + + // V2 Socket Server Mode + V2SocketServerMode = 0x0000100000000000, // -V2SocketServerMode | -v2so + } +#pragma warning restore SA1025 // CodeMustNotContainMultipleWhitespaceInARow + + internal ParameterBitmap ParametersUsed = 0; + + internal double ParametersUsedAsDouble + { + get { return (double)ParametersUsed; } + } + + [Conditional("DEBUG")] + private void AssertArgumentsParsed() + { + if (!_dirty) + { + throw new InvalidOperationException("Parse has not been called yet"); + } + } + + internal CommandLineParameterParser() + { + } + + #region Internal properties + + internal bool AbortStartup + { + get + { + AssertArgumentsParsed(); + return _abortStartup; + } + } + + internal string? SettingsFile + { + get + { + AssertArgumentsParsed(); + return _settingsFile; + } + } + + internal string? InitialCommand + { + get + { + AssertArgumentsParsed(); + return _commandLineCommand; + } + } + + internal bool WasInitialCommandEncoded + { + get + { + AssertArgumentsParsed(); + return _wasCommandEncoded; + } + } + +#if !UNIX + internal ProcessWindowStyle? WindowStyle + { + get + { + AssertArgumentsParsed(); + return _windowStyle; + } + } +#endif + + internal bool ShowBanner + { + get + { + AssertArgumentsParsed(); + return _showBanner; + } + } + + internal bool NoExit + { + get + { + AssertArgumentsParsed(); + return _noExit; + } + } + + internal bool SkipProfiles + { + get + { + AssertArgumentsParsed(); + return _skipUserInit; + } + } + + internal uint ExitCode + { + get + { + AssertArgumentsParsed(); + return _exitCode; + } + } + + internal bool ExplicitReadCommandsFromStdin + { + get + { + AssertArgumentsParsed(); + return _explicitReadCommandsFromStdin; + } + } + + internal bool NoPrompt + { + get + { + AssertArgumentsParsed(); + return _noPrompt; + } + } + + internal Collection Args + { + get + { + AssertArgumentsParsed(); + return _collectedArgs; + } + } + + internal string? ConfigurationFile + { + get + { + AssertArgumentsParsed(); + return _configurationFile; + } + } + + internal string? ConfigurationName + { + get + { + AssertArgumentsParsed(); + return _configurationName; + } + + set + { + if (!string.IsNullOrEmpty(value)) + { + _configurationName = value; + } + } + } + + internal bool SocketServerMode + { + get + { + AssertArgumentsParsed(); + return _socketServerMode; + } + } + + internal bool NamedPipeServerMode + { + get + { + AssertArgumentsParsed(); + return _namedPipeServerMode; + } + } + + internal bool SSHServerMode + { + get + { + AssertArgumentsParsed(); + return _sshServerMode; + } + } + + internal bool ServerMode + { + get + { + AssertArgumentsParsed(); + return _serverMode; + } + } + + // Added for using in xUnit tests + internal string? ErrorMessage + { + get + { + AssertArgumentsParsed(); + return _error; + } + } + + // Added for using in xUnit tests + internal bool ShowShortHelp + { + get + { + AssertArgumentsParsed(); + return _showHelp; + } + } + + // Added for using in xUnit tests + internal bool ShowExtendedHelp + { + get + { + AssertArgumentsParsed(); + return _showExtendedHelp; + } + } + + internal bool NoProfileLoadTime + { + get + { + AssertArgumentsParsed(); + return _noProfileLoadTime; + } + } + + internal bool ShowVersion + { + get + { + AssertArgumentsParsed(); + return _showVersion; + } + } + + internal string? CustomPipeName + { + get + { + AssertArgumentsParsed(); + return _customPipeName; + } + } + + internal Serialization.DataFormat OutputFormat + { + get + { + AssertArgumentsParsed(); + return _outFormat; + } + } + + internal bool OutputFormatSpecified + { + get + { + AssertArgumentsParsed(); + return _outputFormatSpecified; + } + } + + internal Serialization.DataFormat InputFormat + { + get + { + AssertArgumentsParsed(); + return _inFormat; + } + } + + internal string? File + { + get + { + AssertArgumentsParsed(); + return _file; + } + } + + internal string? ExecutionPolicy + { + get + { + AssertArgumentsParsed(); + return _executionPolicy; + } + } + + internal bool StaMode + { + get + { + AssertArgumentsParsed(); + if (_staMode.HasValue) + { + return _staMode.Value; + } + else + { + return Platform.IsStaSupported; + } + } + } + + internal bool ThrowOnReadAndPrompt + { + get + { + AssertArgumentsParsed(); + return _noInteractive; + } + } + + internal bool NonInteractive + { + get + { + AssertArgumentsParsed(); + return _noInteractive; + } + } + + internal string? WorkingDirectory + { + get + { + AssertArgumentsParsed(); +#if !UNIX + if (_removeWorkingDirectoryTrailingCharacter && _workingDirectory?.Length > 0) + { + return _workingDirectory.Remove(_workingDirectory.Length - 1); + } +#endif + return _workingDirectory; + } + } + +#if !UNIX + internal bool RemoveWorkingDirectoryTrailingCharacter + { + get + { + AssertArgumentsParsed(); + return _removeWorkingDirectoryTrailingCharacter; + } + } + + internal DateTimeOffset? UTCTimestamp + { + get + { + AssertArgumentsParsed(); + return _utcTimestamp; + } + } + + internal string? Token + { + get + { + AssertArgumentsParsed(); + return _token; + } + } + + internal bool V2SocketServerMode + { + get + { + AssertArgumentsParsed(); + return _v2SocketServerMode; + } + } +#endif + + #endregion Internal properties + + #region static methods + /// + /// Processes the -SettingFile Argument. + /// + /// + /// The command line parameters to be processed. + /// + /// + /// The index in args to the argument following '-SettingFile'. + /// + /// + /// Returns true if the argument was parsed successfully and false if not. + /// + private bool TryParseSettingFileHelper(string[] args, int settingFileArgIndex) + { + if (settingFileArgIndex >= args.Length) + { + SetCommandLineError(CommandLineParameterParserStrings.MissingSettingsFileArgument); + return false; + } + + string configFile; + try + { + configFile = NormalizeFilePath(args[settingFileArgIndex]); + } + catch (Exception ex) + { + string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidSettingsFileArgument, args[settingFileArgIndex], ex.Message); + SetCommandLineError(error); + return false; + } + + if (!System.IO.File.Exists(configFile)) + { + string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.SettingsFileNotExists, configFile); + SetCommandLineError(error); + return false; + } + + _settingsFile = configFile; + + return true; + } + + internal static string GetConfigurationNameFromGroupPolicy() + { + // Current user policy takes precedence. + var consoleSessionSetting = Utils.GetPolicySetting(Utils.CurrentUserThenSystemWideConfig); + + return (consoleSessionSetting?.EnableConsoleSessionConfiguration == true && !string.IsNullOrEmpty(consoleSessionSetting?.ConsoleSessionConfigurationName)) ? + consoleSessionSetting.ConsoleSessionConfigurationName : string.Empty; + } + + /// + /// Gets the word in a switch from the current argument or parses a file. + /// For example -foo, /foo, or --foo would return 'foo'. + /// + /// + /// The command line parameters to be processed. + /// + /// + /// The index in args to the argument to process. + /// + /// + /// Used during parsing files. + /// + /// + /// Returns a Tuple: + /// The first value is a String called 'switchKey' with the word in a switch from the current argument or null. + /// The second value is a bool called 'shouldBreak', indicating if the parsing look should break. + /// + private (string switchKey, bool shouldBreak) GetSwitchKey(string[] args, ref int argIndex, ref bool noexitSeen) + { + string switchKey = args[argIndex].Trim(); + if (string.IsNullOrEmpty(switchKey)) + { + return (switchKey: string.Empty, shouldBreak: false); + } + + char firstChar = switchKey[0]; + if (!CharExtensions.IsDash(firstChar) && firstChar != '/') + { + // then it's a file + --argIndex; + ParseFile(args, ref argIndex, noexitSeen); + + return (switchKey: string.Empty, shouldBreak: true); + } + + // 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) && CharExtensions.IsDash(firstChar) && switchKey[0] == firstChar) + { + switchKey = switchKey.Substring(1); + } + + return (switchKey: switchKey, shouldBreak: false); + } + + internal static string NormalizeFilePath(string path) + { + // Normalize slashes + path = path.Replace( + StringLiterals.AlternatePathSeparator, + StringLiterals.DefaultPathSeparator); + + return Path.GetFullPath(path); + } + + /// + /// Determine the execution policy based on the supplied string. + /// If the string doesn't match to any known execution policy, set it to incorrect. + /// + /// The value provided on the command line. + /// The execution policy. + private static ParameterBitmap GetExecutionPolicy(string? _executionPolicy) + { + if (_executionPolicy is null) + { + return ParameterBitmap.EPUndefined; + } + + ParameterBitmap executionPolicySetting = ParameterBitmap.EPIncorrect; + + if (string.Equals(_executionPolicy, "default", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPDefault; + } + else if (string.Equals(_executionPolicy, "remotesigned", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPRemoteSigned; + } + else if (string.Equals(_executionPolicy, "bypass", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPBypass; + } + else if (string.Equals(_executionPolicy, "allsigned", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPAllSigned; + } + else if (string.Equals(_executionPolicy, "restricted", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPRestricted; + } + else if (string.Equals(_executionPolicy, "unrestricted", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPUnrestricted; + } + else if (string.Equals(_executionPolicy, "undefined", StringComparison.OrdinalIgnoreCase)) + { + executionPolicySetting = ParameterBitmap.EPUndefined; + } + + return executionPolicySetting; + } + + private static bool MatchSwitch(string switchKey, string match, string smallestUnambiguousMatch) + { + Dbg.Assert(!string.IsNullOrEmpty(match), "need a value"); + Dbg.Assert(match.Trim().ToLowerInvariant() == match, "match should be normalized to lowercase w/ no outside whitespace"); + Dbg.Assert(smallestUnambiguousMatch.Trim().ToLowerInvariant() == smallestUnambiguousMatch, "match should be normalized to lowercase w/ no outside whitespace"); + Dbg.Assert(match.Contains(smallestUnambiguousMatch), "sUM should be a substring of match"); + + return (switchKey.Length >= smallestUnambiguousMatch.Length + && match.StartsWith(switchKey, StringComparison.OrdinalIgnoreCase)); + } + + #endregion + + private void ShowError(PSHostUserInterface hostUI) + { + if (_error != null) + { + hostUI.WriteErrorLine(_error); + } + } + + private void ShowHelp(PSHostUserInterface hostUI, string? helpText) + { + if (helpText is null) + { + return; + } + + if (_showHelp) + { + hostUI.WriteLine(); + hostUI.Write(helpText); + if (_showExtendedHelp) + { + hostUI.Write(ManagedEntranceStrings.ExtendedHelp); + } + + hostUI.WriteLine(); + } + } + + private void DisplayBanner(PSHostUserInterface hostUI, string? bannerText) + { + if (_showBanner && !_showHelp) + { + // If banner text is not supplied do nothing. + if (!string.IsNullOrEmpty(bannerText)) + { + hostUI.WriteLine(bannerText); + } + + if (UpdatesNotification.CanNotifyUpdates) + { + UpdatesNotification.ShowUpdateNotification(hostUI); + } + } + } + + /// + /// Processes all the command line parameters to ConsoleHost. Returns the exit code to be used to terminate the process, or + /// Success to indicate that the program should continue running. + /// + /// + /// The command line parameters to be processed. + /// + internal void Parse(string[] args) + { + if (_dirty) + { + throw new InvalidOperationException("This instance has already been used. Create a new instance."); + } + + for (int i = 0; i < args.Length; i++) + { + ArgumentNullException.ThrowIfNull(args[i], CommandLineParameterParserStrings.NullElementInArgs); + } + + // Indicates that we've called this method on this instance, and that when it's done, the state variables + // will reflect the parse. + _dirty = true; + + ParseHelper(args); + } + + private void ParseHelper(string[] args) + { + if (args.Length == 0) + { + return; + } + + bool noexitSeen = false; + + for (int i = 0; i < args.Length; ++i) + { + (string switchKey, bool shouldBreak) switchKeyResults = GetSwitchKey(args, ref i, 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; + ParametersUsed |= ParameterBitmap.Version; + break; + } + + if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?")) + { + _showHelp = true; + _showExtendedHelp = true; + _abortStartup = true; + ParametersUsed |= ParameterBitmap.Help; + } + else if (MatchSwitch(switchKey, "login", "l")) + { + // On Windows, '-Login' does nothing. + // On *nix, '-Login' is already handled much earlier to improve startup performance, so we do nothing here. + ParametersUsed |= ParameterBitmap.Login; + } + else if (MatchSwitch(switchKey, "noexit", "noe")) + { + _noExit = true; + noexitSeen = true; + ParametersUsed |= ParameterBitmap.NoExit; + } + else if (MatchSwitch(switchKey, "noprofile", "nop")) + { + _skipUserInit = true; + ParametersUsed |= ParameterBitmap.NoProfile; + } + else if (MatchSwitch(switchKey, "nologo", "nol")) + { + _showBanner = false; + ParametersUsed |= ParameterBitmap.NoLogo; + } + else if (MatchSwitch(switchKey, "noninteractive", "noni")) + { + _noInteractive = true; + ParametersUsed |= ParameterBitmap.NonInteractive; + } + else if (MatchSwitch(switchKey, "socketservermode", "so")) + { + _socketServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.SocketServerMode; + } +#if !UNIX + else if (MatchSwitch(switchKey, "v2socketservermode", "v2so")) + { + _v2SocketServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.V2SocketServerMode; + } +#endif + else if (MatchSwitch(switchKey, "servermode", "s")) + { + _serverMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.ServerMode; + } + else if (MatchSwitch(switchKey, "namedpipeservermode", "nam")) + { + _namedPipeServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.NamedPipeServerMode; + } + else if (MatchSwitch(switchKey, "sshservermode", "sshs")) + { + _sshServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.SSHServerMode; + } + else if (MatchSwitch(switchKey, "noprofileloadtime", "noprofileloadtime")) + { + _noProfileLoadTime = true; + ParametersUsed |= ParameterBitmap.NoProfileLoadTime; + } + else if (MatchSwitch(switchKey, "interactive", "i")) + { + _noInteractive = false; + ParametersUsed |= ParameterBitmap.Interactive; + } + else if (MatchSwitch(switchKey, "configurationfile", "configurationfile")) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + CommandLineParameterParserStrings.MissingConfigurationFileArgument); + break; + } + + _configurationFile = args[i]; + ParametersUsed |= ParameterBitmap.ConfigurationFile; + } + else if (MatchSwitch(switchKey, "configurationname", "config")) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + CommandLineParameterParserStrings.MissingConfigurationNameArgument); + break; + } + + _configurationName = args[i]; + ParametersUsed |= ParameterBitmap.ConfigurationName; + } + else if (MatchSwitch(switchKey, "custompipename", "cus")) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + CommandLineParameterParserStrings.MissingCustomPipeNameArgument); + break; + } + +#if UNIX + int maxNameLength = MaxNameLength(); + if (args[i].Length > maxNameLength) + { + SetCommandLineError( + string.Format( + CommandLineParameterParserStrings.CustomPipeNameTooLong, + maxNameLength, + args[i], + args[i].Length)); + break; + } +#endif + + _customPipeName = args[i]; + ParametersUsed |= ParameterBitmap.CustomPipeName; + } + else if (MatchSwitch(switchKey, "commandwithargs", "commandwithargs") || MatchSwitch(switchKey, "cwa", "cwa")) + { + _commandHasArgs = true; + + if (!ParseCommand(args, ref i, noexitSeen, false)) + { + break; + } + + i++; + CollectPSArgs(args, ref i); + ParametersUsed |= ParameterBitmap.CommandWithArgs; + } + else if (MatchSwitch(switchKey, "command", "c")) + { + if (!ParseCommand(args, ref i, noexitSeen, false)) + { + break; + } + + ParametersUsed |= ParameterBitmap.Command; + } + else if (MatchSwitch(switchKey, "windowstyle", "w")) + { +#if UNIX + SetCommandLineError( + CommandLineParameterParserStrings.WindowStyleArgumentNotImplemented); + break; +#else + ++i; + if (i >= args.Length) + { + SetCommandLineError( + CommandLineParameterParserStrings.MissingWindowStyleArgument); + break; + } + + try + { + _windowStyle = LanguagePrimitives.ConvertTo(args[i]); + } + catch (PSInvalidCastException e) + { + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message)); + break; + } + + ParametersUsed |= ParameterBitmap.WindowStyle; +#endif + } + else if (MatchSwitch(switchKey, "file", "f")) + { + if (!ParseFile(args, ref i, noexitSeen)) + { + break; + } + + ParametersUsed |= ParameterBitmap.File; + } +#if DEBUG + else if (MatchSwitch(switchKey, "isswait", "isswait")) + { + // Just toss this option, it was processed earlier in 'ManagedEntrance.Start()'. + } +#endif + else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o")) + { + ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter); + _outputFormatSpecified = true; + ParametersUsed |= ParameterBitmap.OutputFormat; + } + else if (MatchSwitch(switchKey, "inputformat", "inp") || MatchSwitch(switchKey, "if", "if")) + { + ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter); + ParametersUsed |= ParameterBitmap.InputFormat; + } + else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep")) + { + ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter); + ParametersUsed |= ParameterBitmap.ExecutionPolicy; + var executionPolicy = GetExecutionPolicy(_executionPolicy); + if (executionPolicy == ParameterBitmap.EPIncorrect) + { + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidExecutionPolicyArgument, _executionPolicy), + showHelp: true); + break; + } + + ParametersUsed |= executionPolicy; + } + else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e")) + { + _wasCommandEncoded = true; + if (!ParseCommand(args, ref i, noexitSeen, true)) + { + break; + } + + ParametersUsed |= ParameterBitmap.EncodedCommand; + } + else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea")) + { + if (!CollectArgs(args, ref i)) + { + break; + } + + ParametersUsed |= ParameterBitmap.EncodedArgument; + } + else if (MatchSwitch(switchKey, "settingsfile", "settings")) + { + // Parse setting file arg and write error + if (!TryParseSettingFileHelper(args, ++i)) + { + break; + } + + ParametersUsed |= ParameterBitmap.SettingsFile; + } + else if (MatchSwitch(switchKey, "sta", "sta")) + { + if (!Platform.IsWindowsDesktop || !Platform.IsStaSupported) + { + SetCommandLineError( + CommandLineParameterParserStrings.STANotImplemented); + break; + } + + if (_staMode.HasValue) + { + // -sta and -mta are mutually exclusive. + SetCommandLineError( + CommandLineParameterParserStrings.MtaStaMutuallyExclusive); + break; + } + + _staMode = true; + ParametersUsed |= ParameterBitmap.STA; + } + else if (MatchSwitch(switchKey, "mta", "mta")) + { + if (!Platform.IsWindowsDesktop) + { + SetCommandLineError( + CommandLineParameterParserStrings.MTANotImplemented); + break; + } + + if (_staMode.HasValue) + { + // -sta and -mta are mutually exclusive. + SetCommandLineError( + CommandLineParameterParserStrings.MtaStaMutuallyExclusive); + break; + } + + _staMode = false; + ParametersUsed |= ParameterBitmap.MTA; + } + else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd")) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + CommandLineParameterParserStrings.MissingWorkingDirectoryArgument); + break; + } + + _workingDirectory = args[i]; + ParametersUsed |= ParameterBitmap.WorkingDirectory; + } +#if !UNIX + else if (MatchSwitch(switchKey, "removeworkingdirectorytrailingcharacter", "removeworkingdirectorytrailingcharacter")) + { + _removeWorkingDirectoryTrailingCharacter = true; + } + else if (MatchSwitch(switchKey, "token", "to")) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.MissingMandatoryArgument, "-Token")); + break; + } + + _token = args[i]; + + // Not adding anything to ParametersUsed, because it is required with V2 socket server mode + // So, we can assume it based on that bit + } + else if (MatchSwitch(switchKey, "utctimestamp", "utc")) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.MissingMandatoryArgument, "-UTCTimestamp")); + break; + } + + // Parse as iso8601UtcString + _utcTimestamp = DateTimeOffset.ParseExact(args[i], "yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + + // Not adding anything to ParametersUsed, because it is required with V2 socket server mode + // So, we can assume it based on that bit + } +#endif + else + { + // The first parameter we fail to recognize marks the beginning of the file string. + --i; + if (!ParseFile(args, ref i, noexitSeen)) + { + break; + } + + // default to filename being the next argument. + ParametersUsed |= ParameterBitmap.File; + } + } + + Dbg.Assert( + ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) + || (_exitCode == ConsoleHost.ExitCodeSuccess), + "if exit code is failure, then abortstartup should be true"); + } + + internal void ShowErrorHelpBanner(PSHostUserInterface hostUI, string? bannerText, string? helpText) + { + ShowError(hostUI); + ShowHelp(hostUI, helpText); + DisplayBanner(hostUI, bannerText); + } + + private void SetCommandLineError(string msg, bool showHelp = false, bool showBanner = false) + { + if (_error != null) + { + throw new ArgumentException(nameof(SetCommandLineError), nameof(_error)); + } + + _error = msg; + _showHelp = showHelp; + _showBanner = showBanner; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + } + + private void ParseFormat(string[] args, ref int i, ref Serialization.DataFormat format, string resourceStr) + { + StringBuilder sb = new StringBuilder(); + foreach (string s in Enum.GetNames()) + { + sb.Append(s); + sb.Append(Environment.NewLine); + } + + ++i; + if (i >= args.Length) + { + SetCommandLineError( + StringUtil.Format( + resourceStr, + sb.ToString()), + showHelp: true); + return; + } + + try + { + format = (Serialization.DataFormat)Enum.Parse(typeof(Serialization.DataFormat), args[i], true); + } + catch (ArgumentException) + { + SetCommandLineError( + StringUtil.Format( + CommandLineParameterParserStrings.BadFormatParameterValue, + args[i], + sb.ToString()), + showHelp: true); + } + } + + private void ParseExecutionPolicy(string[] args, ref int i, ref string? executionPolicy, string resourceStr) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError(resourceStr, showHelp: true); + return; + } + + executionPolicy = args[i]; + } + + // 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... + private bool ParseFile(string[] args, ref int i, bool noexitSeen) + { + ++i; + if (i >= args.Length) + { + SetCommandLineError( + CommandLineParameterParserStrings.MissingFileArgument, + showHelp: true, + showBanner: false); + return false; + } + + // 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. + try + { + _file = NormalizeFilePath(args[i]); + } + catch (Exception e) + { + // Catch all exceptions - we're just going to exit anyway so there's + // no issue of the system being destabilized. + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgument, args[i], e.Message), + showBanner: false); + return false; + } + + if (!System.IO.File.Exists(_file)) + { + if (args[i].StartsWith('-') && args[i].Length > 1) + { + string param = args[i].Substring(1, args[i].Length - 1); + StringBuilder possibleParameters = new StringBuilder(); + foreach (string validParameter in s_validParameters) + { + if (validParameter.Contains(param, StringComparison.OrdinalIgnoreCase)) + { + possibleParameters.Append("\n -"); + possibleParameters.Append(validParameter); + } + } + + if (possibleParameters.Length > 0) + { + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidArgument, args[i]) + + Environment.NewLine + + possibleParameters.ToString(), + showBanner: false); + return false; + } + } + + SetCommandLineError( + string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, args[i]), + showHelp: true); + return false; + } +#if !UNIX + // Only do the .ps1 extension check on Windows since shebang is not supported + if (!_file.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) + { + SetCommandLineError(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, args[i])); + return false; + } +#endif + + i++; + + CollectPSArgs(args, ref i); + } + + return true; + } + + private void CollectPSArgs(string[] args, ref int i) + { + // Try parse '$true', 'true', '$false' and 'false' values. + static object ConvertToBoolIfPossible(string arg) + { + // Before parsing we skip '$' if present. + return arg.Length > 0 && bool.TryParse(arg.AsSpan(arg[0] == '$' ? 1 : 0), out bool boolValue) + ? (object)boolValue + : (object)arg; + } + + string? pendingParameter = null; + + 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) && CharExtensions.IsDash(arg[0]) && arg.Length > 1) + { + int offset = arg.IndexOf(':'); + if (offset >= 0) + { + if (offset == arg.Length - 1) + { + pendingParameter = arg.TrimEnd(':'); + } + else + { + string argValue = arg.Substring(offset + 1); + string argName = arg.Substring(0, offset); + _collectedArgs.Add(new CommandParameter(argName, ConvertToBoolIfPossible(argValue))); + } + } + else + { + _collectedArgs.Add(new CommandParameter(arg)); + } + } + else + { + _collectedArgs.Add(new CommandParameter(null, arg)); + } + + ++i; + } + } + + private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEncoded) + { + if (_commandLineCommand != null) + { + // we've already set the command, so squawk + SetCommandLineError(CommandLineParameterParserStrings.CommandAlreadySpecified, showHelp: true); + return false; + } + + ++i; + if (i >= args.Length) + { + SetCommandLineError(CommandLineParameterParserStrings.MissingCommandParameter, showHelp: true); + return false; + } + + if (isEncoded) + { + try + { + _commandLineCommand = StringToBase64Converter.Base64ToString(args[i]); + } + // decoding failed + catch + { + SetCommandLineError(CommandLineParameterParserStrings.BadCommandValue, showHelp: true); + return false; + } + } + else if (args[i] == "-") + { + // the arg to -command is -, which is secret code for "read the commands from stdin with no prompts" + + _explicitReadCommandsFromStdin = true; + _noPrompt = true; + + ++i; + if (i != args.Length) + { + // there are more parameters to -command than -, which is an error. + + SetCommandLineError(CommandLineParameterParserStrings.TooManyParametersToCommand, showHelp: true); + return false; + } + + if (InputRedirectedTestHook.HasValue ? !InputRedirectedTestHook.Value : !Console.IsInputRedirected) + { + SetCommandLineError(CommandLineParameterParserStrings.StdinNotRedirected, showHelp: true); + return false; + } + } + else + { + if (_commandHasArgs) + { + _commandLineCommand = args[i]; + } + else + { + _commandLineCommand = string.Join(' ', args, i, args.Length - i); + i = args.Length; + } + } + + if (!noexitSeen && !_explicitReadCommandsFromStdin) + { + // don't reset this if they've already specified -noexit + _noExit = false; + } + + _showBanner = false; + + return true; + } + + private bool CollectArgs(string[] args, ref int i) + { + if (_collectedArgs.Count != 0) + { + SetCommandLineError(CommandLineParameterParserStrings.ArgsAlreadySpecified, showHelp: true); + return false; + } + + ++i; + if (i >= args.Length) + { + SetCommandLineError(CommandLineParameterParserStrings.MissingArgsValue, showHelp: true); + return false; + } + + try + { + object[] a = StringToBase64Converter.Base64ToArgsConverter(args[i]); + if (a != null) + { + foreach (object obj in a) + { + _collectedArgs.Add(new CommandParameter(null, obj)); + } + } + } + catch + { + // decoding failed + SetCommandLineError(CommandLineParameterParserStrings.BadArgsValue, showHelp: true); + return false; + } + + return true; + } + + private bool _socketServerMode; +#if !UNIX + private bool _v2SocketServerMode; +#endif + private bool _serverMode; + private bool _namedPipeServerMode; + private bool _sshServerMode; + private bool _noProfileLoadTime; + private bool _showVersion; + private string? _configurationFile; + private string? _configurationName; + private string? _error; + private bool _showHelp; + private bool _showExtendedHelp; + private bool _showBanner = true; + private bool _noInteractive; + private bool _abortStartup; + private bool _skipUserInit; + private string? _customPipeName; + private bool? _staMode = null; + private bool _noExit = true; + private bool _explicitReadCommandsFromStdin; + private bool _noPrompt; + private string? _commandLineCommand; + private bool _wasCommandEncoded; + private bool _commandHasArgs; + private uint _exitCode = ConsoleHost.ExitCodeSuccess; + private bool _dirty; + private Serialization.DataFormat _outFormat = Serialization.DataFormat.Text; + private bool _outputFormatSpecified = false; + private Serialization.DataFormat _inFormat = Serialization.DataFormat.Text; + private readonly Collection _collectedArgs = new Collection(); + private string? _file; + private string? _executionPolicy; + private string? _settingsFile; + private string? _workingDirectory; +#if !UNIX + private string? _token; + private DateTimeOffset? _utcTimestamp; +#endif + +#if !UNIX + private ProcessWindowStyle? _windowStyle; + private bool _removeWorkingDirectoryTrailingCharacter = false; +#endif + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs new file mode 100644 index 0000000000000000000000000000000000000000..7bda4bc5688757904a7736b3b5379db12f6780dc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -0,0 +1,3189 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +// Implementation notes: In the functions that take ConsoleHandle parameters, we only assert that the handle is valid and not +// closed, as opposed to doing a check and throwing an exception. This is because the win32 APIs that those functions wrap will +// fail on invalid/closed handles, and the check for API failure will throw the exception. +// +// On the use of DangerousGetHandle: If the handle has been invalidated, then the API we pass it to will return an error. These +// handles should not be exposed to recycling attacks (because they are not exposed at all), but if they were, the worse they +// could do is diddle with the console buffer. + +using System; +using System.Buffers; +using System.Text; +using System.Runtime.InteropServices; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.ComponentModel; +using System.Collections.Generic; +using System.Globalization; +using System.Diagnostics; +using Microsoft.Win32.SafeHandles; + +using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle; + +using WORD = System.UInt16; +using ULONG = System.UInt32; +using DWORD = System.UInt32; +using NakedWin32Handle = System.IntPtr; +using HWND = System.IntPtr; +using HDC = System.IntPtr; + +#endif + +using System.Diagnostics.CodeAnalysis; +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// Class ConsoleControl is used to wrap the various win32 console APIs 1:1 (i.e. at a low level, without attempting to be a + /// "true" object-oriented library. + /// + internal static class ConsoleControl + { +#if !UNIX + #region structs + + internal enum InputRecordEventTypes : ushort + { + // from wincon.h. These look like bit flags, but of course they could not really be used that way, since it would + // not make sense to have more than one of the INPUT_RECORD union members "in effect" at any one time. + + KEY_EVENT = 0x0001, + MOUSE_EVENT = 0x0002, + WINDOW_BUFFER_SIZE_EVENT = 0x0004, + MENU_EVENT = 0x0008, + FOCUS_EVENT = 0x0010 + } + + [StructLayout(LayoutKind.Sequential)] + internal struct INPUT_RECORD + { + internal WORD EventType; + internal KEY_EVENT_RECORD KeyEvent; + } + + [Flags] + internal enum ControlKeyStates : uint + { + // From wincon.h. + RIGHT_ALT_PRESSED = 0x0001, // the right alt key is pressed. + LEFT_ALT_PRESSED = 0x0002, // the left alt key is pressed. + RIGHT_CTRL_PRESSED = 0x0004, // the right ctrl key is pressed. + LEFT_CTRL_PRESSED = 0x0008, // the left ctrl key is pressed. + SHIFT_PRESSED = 0x0010, // the shift key is pressed. + NUMLOCK_ON = 0x0020, // the numlock light is on. + SCROLLLOCK_ON = 0x0040, // the scrolllock light is on. + CAPSLOCK_ON = 0x0080, // the capslock light is on. + ENHANCED_KEY = 0x0100 // the key is enhanced. + } + + // LayoutKind must be Explicit + [StructLayout(LayoutKind.Sequential)] + internal struct KEY_EVENT_RECORD + { + internal bool KeyDown; + + internal WORD RepeatCount; + + internal WORD VirtualKeyCode; + + internal WORD VirtualScanCode; + + internal char UnicodeChar; + + internal DWORD ControlKeyState; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct COORD + { + internal short X; + + internal short Y; + + public override string ToString() + { + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); + } + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CONSOLE_READCONSOLE_CONTROL + { + // from public/internal/windows/inc/winconp.h + internal ULONG nLength; + + internal ULONG nInitialChars; + + internal ULONG dwCtrlWakeupMask; + + internal /* out */ ULONG dwControlKeyState; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct CONSOLE_FONT_INFO_EX + { + internal int cbSize; + internal int nFont; + internal short FontWidth; + internal short FontHeight; + internal int FontFamily; + internal int FontWeight; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + internal string FontFace; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CHAR_INFO + { + internal ushort UnicodeChar; + + internal WORD Attributes; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SMALL_RECT + { + internal short Left; + + internal short Top; + + internal short Right; + + internal short Bottom; + + public override string ToString() + { + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}"); + } + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CONSOLE_SCREEN_BUFFER_INFO + { + internal COORD BufferSize; + + internal COORD CursorPosition; + + internal WORD Attributes; + + internal SMALL_RECT WindowRect; + + internal COORD MaxWindowSize; + + // NTRAID#Windows Out Of Band Releases-938428-2006/07/17-jwh + // Bring the total size of the struct to 24 bytes. + internal DWORD Padding; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CONSOLE_CURSOR_INFO + { + internal DWORD Size; + + internal bool Visible; + + public override string ToString() + { + return string.Create(CultureInfo.InvariantCulture, $"Size: {Size}, Visible: {Visible}"); + } + } + + [StructLayout(LayoutKind.Sequential)] + internal struct FONTSIGNATURE + { + // From public\sdk\inc\wingdi.h + + // fsUsb*: A 128-bit Unicode subset bitfield (USB) identifying up to 126 Unicode subranges + internal DWORD fsUsb0; + internal DWORD fsUsb1; + internal DWORD fsUsb2; + internal DWORD fsUsb3; + // fsCsb*: A 64-bit, code-page bitfield (CPB) that identifies a specific character set or code page. + internal DWORD fsCsb0; + internal DWORD fsCsb1; + } + + #region SentInput Data Structures + + [StructLayout(LayoutKind.Sequential)] + internal struct INPUT + { + internal DWORD Type; + internal MouseKeyboardHardwareInput Data; + } + + [StructLayout(LayoutKind.Explicit)] + internal struct MouseKeyboardHardwareInput + { + [FieldOffset(0)] + internal MouseInput Mouse; + + [FieldOffset(0)] + internal KeyboardInput Keyboard; + + [FieldOffset(0)] + internal HardwareInput Hardware; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct MouseInput + { + /// + /// The absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. + /// Absolute data is specified as the x coordinate of the mouse; relative data is specified as the number of pixels moved. + /// + internal int X; + + /// + /// The absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. + /// Absolute data is specified as the y coordinate of the mouse; relative data is specified as the number of pixels moved. + /// + internal int Y; + + /// + /// If dwFlags contains MOUSEEVENTF_WHEEL, then mouseData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user; + /// a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120. + /// + internal DWORD MouseData; + + /// + /// A set of bit flags that specify various aspects of mouse motion and button clicks. + /// See (https://msdn.microsoft.com/library/ms646273(VS.85).aspx) + /// + internal DWORD Flags; + + /// + /// The time stamp for the event, in milliseconds. If this parameter is 0, the system will provide its own time stamp. + /// + internal DWORD Time; + + /// + /// An additional value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information. + /// + internal IntPtr ExtraInfo; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct KeyboardInput + { + /// + /// A virtual-key code. The code must be a value in the range 1 to 254. + /// If the dwFlags member specifies KEYEVENTF_UNICODE, wVk must be 0. + /// + internal WORD Vk; + + /// + /// A hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE, + /// wScan specifies a Unicode character which is to be sent to the foreground application. + /// + internal WORD Scan; + + /// + /// Specifies various aspects of a keystroke. + /// This member can be certain combinations of the following values. + /// + internal DWORD Flags; + + /// + /// The time stamp for the event, in milliseconds. + /// If this parameter is zero, the system will provide its own time stamp. + /// + internal DWORD Time; + + /// + /// An additional value associated with the keystroke. + /// Use the GetMessageExtraInfo function to obtain this information. + /// + internal IntPtr ExtraInfo; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct HardwareInput + { + /// + /// The message generated by the input hardware. + /// + internal DWORD Msg; + + /// + /// The low-order word of the lParam parameter for uMsg. + /// + internal WORD ParamL; + + /// + /// The high-order word of the lParam parameter for uMsg. + /// + internal WORD ParamH; + } + + internal enum VirtualKeyCode : ushort + { + /// + /// LEFT ARROW key. + /// + Left = 0x25, + + /// + /// ENTER key. + /// + Return = 0x0D, + } + + /// + /// Specify the type of the input. + /// + internal enum InputType : uint + { + /// + /// INPUT_MOUSE = 0x00. + /// + Mouse = 0, + + /// + /// INPUT_KEYBOARD = 0x01. + /// + Keyboard = 1, + + /// + /// INPUT_HARDWARE = 0x02. + /// + Hardware = 2, + } + + internal enum KeyboardFlag : uint + { + /// + /// If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224). + /// + ExtendedKey = 0x0001, + + /// + /// If specified, the key is being released. If not specified, the key is being pressed. + /// + KeyUp = 0x0002, + + /// + /// If specified, wScan identifies the key and wVk is ignored. + /// + Unicode = 0x0004, + + /// + /// If specified, the system synthesizes a VK_PACKET keystroke. The wVk parameter must be zero. + /// This flag can only be combined with the KEYEVENTF_KEYUP flag. + /// + ScanCode = 0x0008 + } + + #endregion SentInput Data Structures + + #endregion structs + + #region Window Visibility + [DllImport(PinvokeDllNames.GetConsoleWindowDllName)] + internal static extern IntPtr GetConsoleWindow(); + + internal const int SW_HIDE = 0; + internal const int SW_SHOWNORMAL = 1; + internal const int SW_NORMAL = 1; + internal const int SW_SHOWMINIMIZED = 2; + internal const int SW_SHOWMAXIMIZED = 3; + internal const int SW_MAXIMIZE = 3; + internal const int SW_SHOWNOACTIVATE = 4; + internal const int SW_SHOW = 5; + internal const int SW_MINIMIZE = 6; + internal const int SW_SHOWMINNOACTIVE = 7; + internal const int SW_SHOWNA = 8; + internal const int SW_RESTORE = 9; + internal const int SW_SHOWDEFAULT = 10; + internal const int SW_FORCEMINIMIZE = 11; + internal const int SW_MAX = 11; + +#if !UNIX + /// + /// Code to control the display properties of the a window... + /// + /// The window to show... + /// The command to do. + /// True if it was successful. + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + internal static void SetConsoleMode(ProcessWindowStyle style) + { + IntPtr hwnd = GetConsoleWindow(); + Dbg.Assert(hwnd != IntPtr.Zero, "Console handle should never be zero"); + switch (style) + { + case ProcessWindowStyle.Hidden: + ShowWindow(hwnd, SW_HIDE); + break; + case ProcessWindowStyle.Maximized: + ShowWindow(hwnd, SW_MAXIMIZE); + break; + case ProcessWindowStyle.Minimized: + ShowWindow(hwnd, SW_MINIMIZE); + break; + case ProcessWindowStyle.Normal: + ShowWindow(hwnd, SW_NORMAL); + break; + } + } +#endif + #endregion + + #region Input break handler (Ctrl-C, Ctrl-Break) + + /// + /// Types of control ConsoleBreakSignals received by break Win32Handler delegates. + /// + internal enum ConsoleBreakSignal : uint + { + // These correspond to the CRTL_XXX_EVENT #defines in public/sdk/inc/wincon.h + + CtrlC = 0, + CtrlBreak = 1, + Close = 2, + Logoff = 5, + + // This only gets received by services + + Shutdown = 6, + + // None is not really a signal -- it's used to indicate that no signal exists. + + None = 0xFF + } + + // NOTE: this delegate will be executed in its own thread + + internal delegate bool BreakHandler(ConsoleBreakSignal ConsoleBreakSignal); + + /// + /// Set the console's break handler. + /// + /// + /// + /// If Win32's SetConsoleCtrlHandler fails + /// + internal static void AddBreakHandler(BreakHandler handlerDelegate) + { + bool result = NativeMethods.SetConsoleCtrlHandler(handlerDelegate, true); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "AddBreakHandler", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.AddBreakHandlerExceptionMessage); + throw e; + } + } + + /// + /// Set the console's break handler to null. + /// + /// + /// If Win32's SetConsoleCtrlHandler fails + /// + internal static void RemoveBreakHandler() + { + bool result = NativeMethods.SetConsoleCtrlHandler(null, false); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "RemoveBreakHandler", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.RemoveBreakHandlerExceptionTemplate); + throw e; + } + } + + #endregion + + #region Win32Handles + + private static readonly Lazy _keyboardInputHandle = new Lazy(() => + { + var handle = NativeMethods.CreateFile( + "CONIN$", + (UInt32)(NativeMethods.AccessQualifiers.GenericRead | NativeMethods.AccessQualifiers.GenericWrite), + (UInt32)NativeMethods.ShareModes.ShareRead, + (IntPtr)0, + (UInt32)NativeMethods.CreationDisposition.OpenExisting, + 0, + (IntPtr)0); + + if (handle == NativeMethods.INVALID_HANDLE_VALUE) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "RetreiveInputConsoleHandle", + ErrorCategory.ResourceUnavailable, + ConsoleControlStrings.GetInputModeExceptionTemplate); + throw e; + } + + return new ConsoleHandle(handle, true); + } + ); + + /// + /// Returns a ConsoleHandle to the console (keyboard device) + /// + internal static ConsoleHandle GetConioDeviceHandle() + { + return _keyboardInputHandle.Value; + } + + private static readonly Lazy _outputHandle = new Lazy(() => + { + // We use CreateFile here instead of GetStdWin32Handle, as GetStdWin32Handle will return redirected handles + var handle = NativeMethods.CreateFile( + "CONOUT$", + (UInt32)(NativeMethods.AccessQualifiers.GenericRead | NativeMethods.AccessQualifiers.GenericWrite), + (UInt32)NativeMethods.ShareModes.ShareWrite, + (IntPtr)0, + (UInt32)NativeMethods.CreationDisposition.OpenExisting, + 0, + (IntPtr)0); + + if (handle == NativeMethods.INVALID_HANDLE_VALUE) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "RetreiveActiveScreenBufferConsoleHandle", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetActiveScreenBufferHandleExceptionTemplate); + throw e; + } + + return new ConsoleHandle(handle, true); + } + ); + + /// + /// Returns a ConsoleHandle to the active screen buffer, even if that output has been redirected. + /// + /// + /// + /// If Win32's CreateFile fails + /// + internal static ConsoleHandle GetActiveScreenBufferHandle() + { + return _outputHandle.Value; + } + + #endregion + + #region Mode + + /// + /// Flags used by ConsoleControl.GetMode and ConsoleControl.SetMode. + /// + [Flags] + internal enum ConsoleModes : uint + { + // These values from wincon.h + // input modes + ProcessedInput = 0x001, + LineInput = 0x002, + EchoInput = 0x004, + WindowInput = 0x008, + MouseInput = 0x010, + Insert = 0x020, + QuickEdit = 0x040, + Extended = 0x080, + AutoPosition = 0x100, + // output modes + ProcessedOutput = 0x001, // yes, I know they are the same values as some flags defined above. + WrapEndOfLine = 0x002, + VirtualTerminal = 0x004, + // Error getting console mode + Unknown = 0xffffffff, + } + + /// + /// Returns a mask of ConsoleModes flags describing the current modality of the console. + /// + /// + /// If Win32's GetConsoleMode fails + /// + internal static ConsoleModes GetMode(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + UInt32 m = 0; + bool result = NativeMethods.GetConsoleMode(consoleHandle.DangerousGetHandle(), out m); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "GetConsoleMode", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetModeExceptionTemplate); + throw e; + } + + return (ConsoleModes)m; + } + + /// + /// Sets the current mode of the console device. + /// + /// + /// Handle to the console device returned by GetInputHandle + /// + /// + /// Mask of mode flags + /// + /// + /// If Win32's SetConsoleMode fails + /// + internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode) + { + Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + bool result = NativeMethods.SetConsoleMode(consoleHandle.DangerousGetHandle(), (DWORD)mode); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "SetConsoleMode", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetModeExceptionTemplate); + throw e; + } + } + + #endregion + + #region Input + + /// + /// Reads input from the console device according to the mode in effect (see GetMode, SetMode) + /// + /// + /// Handle to the console device returned by GetInputHandle + /// + /// Length of initial content of the edit buffer. Zero if no initial content exists. + /// Must be less than editBuffer length. + /// + /// + /// Edit buffer with optional initial content. + /// Caution! Last position in the edit buffer is for a null in native code. + /// + /// + /// Number of characters to read from the device. + /// Must be less than editBuffer length. + /// + /// + /// True to allow the user to terminate input by hitting the tab or shift-tab key, in addition to the enter key + /// + /// + /// Bit mask indicating the state of the control/shift keys at the point input was terminated. + /// + /// + /// + /// + /// If Win32's ReadConsole fails + /// + internal static string ReadConsole( + ConsoleHandle consoleHandle, + int initialContentLength, + Span editBuffer, + int charactersToRead, + bool endOnTab, + out uint keyState) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + Dbg.Assert(initialContentLength < editBuffer.Length, "initialContentLength must be less than editBuffer.Length"); + Dbg.Assert(charactersToRead < editBuffer.Length, "charactersToRead must be less than editBuffer.Length"); + keyState = 0; + + CONSOLE_READCONSOLE_CONTROL control = new CONSOLE_READCONSOLE_CONTROL(); + + control.nLength = (ULONG)Marshal.SizeOf(control); + control.nInitialChars = (ULONG)initialContentLength; + control.dwControlKeyState = 0; + if (endOnTab) + { + const int TAB = 0x9; + + control.dwCtrlWakeupMask = (1 << TAB); + } + + DWORD charsReaded = 0; + + bool result = + NativeMethods.ReadConsole( + consoleHandle.DangerousGetHandle(), + editBuffer, + (DWORD)charactersToRead, + out charsReaded, + ref control); + keyState = control.dwControlKeyState; + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException( + err, + "ReadConsole", + ErrorCategory.ReadError, + ConsoleControlStrings.ReadConsoleExceptionTemplate); + throw e; + } + + if (charsReaded > (uint)charactersToRead) + { + charsReaded = (uint)charactersToRead; + } + + return editBuffer.Slice(0, (int)charsReaded).ToString(); + } + + /// + /// Wraps Win32 ReadConsoleInput. + /// Returns the number of records read in buffer. + /// + /// + /// handle for the console where input is read + /// + /// + /// array where data read are stored + /// + /// + /// actual number of input records read + /// + /// + /// If Win32's ReadConsoleInput fails + /// + internal static int ReadConsoleInput(ConsoleHandle consoleHandle, ref INPUT_RECORD[] buffer) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + DWORD recordsRead = 0; + bool result = + NativeMethods.ReadConsoleInput( + consoleHandle.DangerousGetHandle(), + buffer, + (DWORD)buffer.Length, + out recordsRead); + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "ReadConsoleInput", + ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleInputExceptionTemplate); + throw e; + } + + return (int)recordsRead; + } + + /// + /// Wraps Win32 PeekConsoleInput. + /// + /// + /// handle for the console where input is peeked + /// + /// + /// array where data read are stored + /// + /// + /// actual number of input records peeked + /// + /// + /// If Win32's PeekConsoleInput fails + /// + internal static int PeekConsoleInput + ( + ConsoleHandle consoleHandle, + ref INPUT_RECORD[] buffer + ) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + DWORD recordsRead; + bool result = + NativeMethods.PeekConsoleInput( + consoleHandle.DangerousGetHandle(), + buffer, + (DWORD)buffer.Length, + out recordsRead); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "PeekConsoleInput", + ErrorCategory.ReadError, ConsoleControlStrings.PeekConsoleInputExceptionTemplate); + throw e; + } + + return (int)recordsRead; + } + + /// + /// Wraps Win32 GetNumberOfConsoleInputEvents. + /// + /// + /// handle for the console where the number of console input events is obtained + /// + /// + /// number of console input events + /// + /// + /// If Win32's GetNumberOfConsoleInputEvents fails + /// + internal static int GetNumberOfConsoleInputEvents(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + DWORD numEvents; + bool result = NativeMethods.GetNumberOfConsoleInputEvents(consoleHandle.DangerousGetHandle(), out numEvents); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "GetNumberOfConsoleInputEvents", + ErrorCategory.ReadError, ConsoleControlStrings.GetNumberOfConsoleInputEventsExceptionTemplate); + throw e; + } + + return (int)numEvents; + } + + /// + /// Wraps Win32 FlushConsoleInputBuffer. + /// + /// + /// handle for the console where the input buffer is flushed + /// + /// + /// If Win32's FlushConsoleInputBuffer fails + /// + internal static void FlushConsoleInputBuffer(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + bool result = false; + NakedWin32Handle h = consoleHandle.DangerousGetHandle(); + result = NativeMethods.FlushConsoleInputBuffer(h); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "FlushConsoleInputBuffer", + ErrorCategory.ReadError, ConsoleControlStrings.FlushConsoleInputBufferExceptionTemplate); + throw e; + } + } + + #endregion Input + + #region Buffer + + /// + /// Wraps Win32 GetConsoleScreenBufferInfo + /// Returns Console Screen Buffer Info. + /// + /// + /// Handle for the console where the screen buffer info is obtained + /// + /// + /// info about the screen buffer. See the definition of CONSOLE_SCREEN_BUFFER_INFO + /// + /// + /// If Win32's GetConsoleScreenBufferInfo fails + /// + internal static CONSOLE_SCREEN_BUFFER_INFO GetConsoleScreenBufferInfo(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + bool result = NativeMethods.GetConsoleScreenBufferInfo(consoleHandle.DangerousGetHandle(), out bufferInfo); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "GetConsoleScreenBufferInfo", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleScreenBufferInfoExceptionTemplate); + throw e; + } + + return bufferInfo; + } + + /// + /// Set the output buffer's size. + /// + /// + /// + /// + /// If Win32's SetConsoleScreenBufferSize fails + /// + internal static void SetConsoleScreenBufferSize(ConsoleHandle consoleHandle, Size newSize) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + COORD s; + + s.X = (short)newSize.Width; + s.Y = (short)newSize.Height; + + bool result = NativeMethods.SetConsoleScreenBufferSize(consoleHandle.DangerousGetHandle(), s); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "SetConsoleScreenBufferSize", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleScreenBufferSizeExceptionTemplate); + throw e; + } + } + + internal static bool IsConsoleColor(ConsoleColor c) + { + switch (c) + { + case ConsoleColor.Black: + case ConsoleColor.Blue: + case ConsoleColor.Cyan: + case ConsoleColor.DarkBlue: + case ConsoleColor.DarkCyan: + case ConsoleColor.DarkGray: + case ConsoleColor.DarkGreen: + case ConsoleColor.DarkMagenta: + case ConsoleColor.DarkRed: + case ConsoleColor.DarkYellow: + case ConsoleColor.Gray: + case ConsoleColor.Green: + case ConsoleColor.Magenta: + case ConsoleColor.Red: + case ConsoleColor.White: + case ConsoleColor.Yellow: + return true; + } + + return false; + } + + internal static void WORDToColor(WORD attribute, out ConsoleColor foreground, out ConsoleColor background) + { + // foreground color is the low-byte in the word, background color is the hi-byte. + foreground = (ConsoleColor)(attribute & 0x0f); + background = (ConsoleColor)((attribute & 0xf0) >> 4); + Dbg.Assert(IsConsoleColor(foreground), "unknown color"); + Dbg.Assert(IsConsoleColor(background), "unknown color"); + } + + internal static WORD ColorToWORD(ConsoleColor foreground, ConsoleColor background) + { + WORD result = (WORD)(((int)background << 4) | (int)foreground); + + return result; + } + + /// + /// Wrap32 WriteConsoleOutput. + /// This wrapper is not limited to 64K or 8K CHAR_INFO to which Win32's WriteConsoleOutput + /// is constrained. + /// + /// + /// handle for the console where output is written + /// + /// + /// location on screen buffer where writing starts + /// + /// + /// 2D array of cells. Caller needs to ensure that the array is 2D. + /// + /// + /// If Win32's GetConsoleScreenBufferInfo fails + /// If there is not enough memory to complete calls to Win32's WriteConsoleOutput + /// + /// + /// If is null + /// + /// + /// If it is illegal to write to the output buffer + /// + internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + if (contents == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(contents)); + } + + uint codePage; + if (IsCJKOutputCodePage(out codePage)) + { + // contentsRegion indicates the area in contents (declared below) in which + // the data read from ReadConsoleOutput is stored. + Rectangle contentsRegion = new Rectangle(); + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = + GetConsoleScreenBufferInfo(consoleHandle); + + int bufferWidth = bufferInfo.BufferSize.X; + int bufferHeight = bufferInfo.BufferSize.Y; + Rectangle screenRegion = new Rectangle( + origin.X, origin.Y, + Math.Min(origin.X + contents.GetLength(1) - 1, bufferWidth - 1), + Math.Min(origin.Y + contents.GetLength(0) - 1, bufferHeight - 1)); + + contentsRegion.Left = contents.GetLowerBound(1); + contentsRegion.Top = contents.GetLowerBound(0); + contentsRegion.Right = contentsRegion.Left + + screenRegion.Right - screenRegion.Left; + contentsRegion.Bottom = contentsRegion.Top + + screenRegion.Bottom - screenRegion.Top; + +#if DEBUG + // Check contents in contentsRegion + CheckWriteConsoleOutputContents(contents, contentsRegion); +#endif + + // Identify edges and areas of identical contiguous edges in contentsRegion + List sameEdgeAreas = new List(); + int firstLeftTrailingRow = -1, firstRightLeadingRow = -1; + BuildEdgeTypeInfo(contentsRegion, contents, + sameEdgeAreas, out firstLeftTrailingRow, out firstRightLeadingRow); + +#if DEBUG + CheckWriteEdges(consoleHandle, codePage, origin, contents, contentsRegion, + bufferInfo, firstLeftTrailingRow, firstRightLeadingRow); +#endif + + foreach (BufferCellArrayRowTypeRange area in sameEdgeAreas) + { + Coordinates o = new Coordinates(origin.X, + origin.Y + area.Start - contentsRegion.Top); + Rectangle contRegion = new Rectangle( + contentsRegion.Left, area.Start, contentsRegion.Right, area.End); + if ((area.Type & BufferCellArrayRowType.LeftTrailing) != 0) + { + contRegion.Left++; + o.X++; + if (o.X >= bufferWidth || contRegion.Right < contRegion.Left) + { + return; + } + } + + WriteConsoleOutputCJK(consoleHandle, o, contRegion, contents, area.Type); + } + } + else + { + WriteConsoleOutputPlain(consoleHandle, origin, contents); + } + } + + private static void BuildEdgeTypeInfo( + Rectangle contentsRegion, + BufferCell[,] contents, + List sameEdgeAreas, + out int firstLeftTrailingRow, + out int firstRightLeadingRow) + { + firstLeftTrailingRow = -1; + firstRightLeadingRow = -1; + BufferCellArrayRowType edgeType = + GetEdgeType(contents[contentsRegion.Top, contentsRegion.Left], + contents[contentsRegion.Top, contentsRegion.Right]); + for (int r = contentsRegion.Top; r <= contentsRegion.Bottom;) + { + BufferCellArrayRowTypeRange range; + range.Start = r; + range.Type = edgeType; + if (firstLeftTrailingRow == -1 && ((range.Type & BufferCellArrayRowType.LeftTrailing) != 0)) + { + firstLeftTrailingRow = r; + } + + if (firstRightLeadingRow == -1 && ((range.Type & BufferCellArrayRowType.RightLeading) != 0)) + { + firstRightLeadingRow = r; + } + + while (true) + { + r++; + if (r > contentsRegion.Bottom) + { + range.End = r - 1; + sameEdgeAreas.Add(range); + return; + } + + edgeType = GetEdgeType(contents[r, contentsRegion.Left], contents[r, contentsRegion.Right]); + if (edgeType != range.Type) + { + range.End = r - 1; + sameEdgeAreas.Add(range); + break; + } + } + } + } + + private static BufferCellArrayRowType GetEdgeType(BufferCell left, BufferCell right) + { + BufferCellArrayRowType edgeType = 0; + if (left.BufferCellType == BufferCellType.Trailing) + { + edgeType |= BufferCellArrayRowType.LeftTrailing; + } + + if (right.BufferCellType == BufferCellType.Leading) + { + edgeType |= BufferCellArrayRowType.RightLeading; + } + + return edgeType; + } + + private struct BufferCellArrayRowTypeRange + { + internal int Start; + internal int End; + internal BufferCellArrayRowType Type; + } + + [Flags] + private enum BufferCellArrayRowType : uint + { + LeftTrailing = 0x1, + RightLeading = 0x2 + } + + /// + /// Check the existing screen columns left and right of areas to be written. + /// + /// + /// + /// Must be within the screen buffer. + /// + /// + /// + /// + /// + /// + /// If it is illegal to write at + /// + /// + /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called in CHK builds")] + internal static void CheckWriteEdges( + ConsoleHandle consoleHandle, + uint codePage, Coordinates origin, + BufferCell[,] contents, + Rectangle contentsRegion, + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo, + int firstLeftTrailingRow, + int firstRightLeadingRow) + { + Rectangle existingRegion = new Rectangle(0, 0, 1, contentsRegion.Bottom - contentsRegion.Top); + if (origin.X == 0) + { + if (firstLeftTrailingRow >= 0) + { + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstLeftTrailingRow}, {contentsRegion.Left}]")); + } + } + else + { + // use ReadConsoleOutputCJK because checking the left and right edges of the existing output + // is NOT needed + BufferCell[,] leftExisting = new BufferCell[existingRegion.Bottom + 1, 2]; + ReadConsoleOutputCJK(consoleHandle, codePage, + new Coordinates(origin.X - 1, origin.Y), existingRegion, ref leftExisting); + for (int r = contentsRegion.Top, i = 0; r <= contentsRegion.Bottom; r++, i++) + { + if (leftExisting[r, 0].BufferCellType == BufferCellType.Leading ^ + contents[r, contentsRegion.Left].BufferCellType == BufferCellType.Trailing) + { + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Left}]")); + } + } + } + // Check right edge + if (origin.X + (contentsRegion.Right - contentsRegion.Left) + 1 >= bufferInfo.BufferSize.X) + { + if (firstRightLeadingRow >= 0) + { + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstRightLeadingRow}, {contentsRegion.Right}]")); + } + } + else + { + // use ReadConsoleOutputCJK because checking the left and right edges of the existing output + // is NOT needed + BufferCell[,] rightExisting = new BufferCell[existingRegion.Bottom + 1, 2]; + ReadConsoleOutputCJK(consoleHandle, codePage, + new Coordinates(origin.X + (contentsRegion.Right - contentsRegion.Left), origin.Y), existingRegion, ref rightExisting); + for (int r = contentsRegion.Top, i = 0; r <= contentsRegion.Bottom; r++, i++) + { + if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading ^ + contents[r, contentsRegion.Right].BufferCellType == BufferCellType.Leading) + { + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Right}]")); + } + } + } + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called in CHK builds")] + private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rectangle contentsRegion) + { + for (int r = contentsRegion.Top; r <= contentsRegion.Bottom; r++) + { + for (int c = contentsRegion.Left; c <= contentsRegion.Right; c++) + { + // Changes have been made in the following code such that 2 cell characters + // (Chinese, Japanese or Korean) can be in a single BufferCell structure + // which is complete + if (contents[r, c].BufferCellType == BufferCellType.Trailing && + contents[r, c].Character != 0) + { + // trailing character is not 0 + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]")); + } + + if (contents[r, c].BufferCellType == BufferCellType.Leading) + { + c++; + if (c > contentsRegion.Right) + { + break; + } + + if (contents[r, c].Character != 0 || contents[r, c].BufferCellType != BufferCellType.Trailing) + { + // for a 2 cell character, either there is no trailing BufferCell or + // the trailing BufferCell's character is not 0 + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]")); + } + } + } + } + } + + private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinates origin, Rectangle contentsRegion, BufferCell[,] contents, BufferCellArrayRowType rowType) + { + Dbg.Assert(origin.X >= 0 && origin.Y >= 0, + "origin must be within the output buffer"); + int rows = contentsRegion.Bottom - contentsRegion.Top + 1; + int cols = contentsRegion.Right - contentsRegion.Left + 1; + + CONSOLE_FONT_INFO_EX fontInfo = GetConsoleFontInfo(consoleHandle); + int fontType = fontInfo.FontFamily & NativeMethods.FontTypeMask; + bool trueTypeInUse = (fontType & NativeMethods.TrueTypeFont) == NativeMethods.TrueTypeFont; + + int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes + + COORD bufferCoord; + + bufferCoord.X = 0; + bufferCoord.Y = 0; + + // keeps track of which screen area write + SMALL_RECT writeRegion; + + writeRegion.Top = (short)origin.Y; + + int rowsRemaining = rows; + + while (rowsRemaining > 0) + { + // Iteration of columns is nested inside iteration of rows. + // If the size of contents exceeds the buffer limit, writing is + // done in blocks of size equal to the bufferlimit from left to right + // then top to bottom. + // For each iteration of rows, + // - writeRegion.Left and bufferSize.X are reset + // - rowsRemaining, writeRegion.Top, writeRegion.Bottom, and bufferSize.Y + // are updated + // For each iteration of columns, + // - writeRegion.Left, writeRegion.Right and bufferSize.X are updated + + writeRegion.Left = (short)origin.X; + + COORD bufferSize; + + bufferSize.X = (short)Math.Min(cols, bufferLimit); + bufferSize.Y = (short)Math.Min + ( + rowsRemaining, + bufferLimit / bufferSize.X + ); + writeRegion.Bottom = (short)(writeRegion.Top + bufferSize.Y - 1); + + // atRow is at which row of contents a particular iteration is operating + int atRow = rows - rowsRemaining + contentsRegion.Top; + + // number of columns yet to be written + int colsRemaining = cols; + while (colsRemaining > 0) + { + writeRegion.Right = (short)(writeRegion.Left + bufferSize.X - 1); + + // atCol is at which column of contents a particular iteration is operating + int atCol = cols - colsRemaining + contentsRegion.Left; + // if this is not the last column iteration && + // the leftmost BufferCell is a leading cell, don't write that cell + if (colsRemaining > bufferSize.X && + contents[atRow, atCol + bufferSize.X - 1].BufferCellType == BufferCellType.Leading) + { + bufferSize.X--; + writeRegion.Right--; + } + + CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X]; + + // copy characterBuffer to contents; + int characterBufferIndex = 0; + bool lastCharIsLeading = false; + BufferCell lastLeadingCell = new BufferCell(); + for (int r = atRow; r < bufferSize.Y + atRow; r++) + { + for (int c = atCol; c < bufferSize.X + atCol; c++, characterBufferIndex++) + { + if (contents[r, c].BufferCellType == BufferCellType.Complete) + { + characterBuffer[characterBufferIndex].UnicodeChar = + (ushort)contents[r, c].Character; + characterBuffer[characterBufferIndex].Attributes = + (ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor)); + + lastCharIsLeading = false; + } + else if (contents[r, c].BufferCellType == BufferCellType.Leading) + { + characterBuffer[characterBufferIndex].UnicodeChar = + (ushort)contents[r, c].Character; + characterBuffer[characterBufferIndex].Attributes = + (ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor) + | (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE); + + lastCharIsLeading = true; + lastLeadingCell = contents[r, c]; + } + else if (contents[r, c].BufferCellType == BufferCellType.Trailing) + { + // The FontFamily is a 8-bit integer. The low-order bit (bit 0) specifies the pitch of the font. + // If it is 1, the font is variable pitch (or proportional). If it is 0, the font is fixed pitch + // (or monospace). Bits 1 and 2 specify the font type. If both bits are 0, the font is a raster font; + // if bit 1 is 1 and bit 2 is 0, the font is a vector font; if bit 1 is 0 and bit 2 is set, or if both + // bits are 1, the font is true type. Bit 3 is 1 if the font is a device font; otherwise, it is 0. + // We only care about the bit 1 and 2, which indicate the font type. + // There are only two font type defined for the Console, at + // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\. + // Console\Nls --- national language supports + // Console\RasterFonts --- raster type font + // Console\TrueTypeFont --- true type font + // For CJK characters, if it's TrueType, we need to output the trailing character marked with "Trailing_byte" + // attribute. But if it's RasterFont, we ignore the trailing character, and the "Leading_byte"/"Trailing_byte" + // attributes are not effective at all when reading the character from the console buffer. + if (lastCharIsLeading && trueTypeInUse) + { + // For TrueType Font, we output the trailing byte with "Trailing_byte" attribute + characterBuffer[characterBufferIndex].UnicodeChar = lastLeadingCell.Character; + characterBuffer[characterBufferIndex].Attributes = + (ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor) + | (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE); + } + else + { + // We don't output anything for this cell if Raster font is in use, or if the last cell is not a leading byte + characterBufferIndex--; + } + + lastCharIsLeading = false; + } + } + } + + // Now writeRegion, bufferSize and characterBuffer are updated. + // Call NativeMethods.WriteConsoleOutput + bool result; + if ((rowType & BufferCellArrayRowType.RightLeading) != 0 && + colsRemaining == bufferSize.X) + { + COORD bSize = bufferSize; + bSize.X++; + SMALL_RECT wRegion = writeRegion; + wRegion.Right++; + + result = NativeMethods.WriteConsoleOutput( + consoleHandle.DangerousGetHandle(), + characterBuffer, + bSize, + bufferCoord, + ref wRegion); + } + else + { + result = NativeMethods.WriteConsoleOutput( + consoleHandle.DangerousGetHandle(), + characterBuffer, + bufferSize, + bufferCoord, + ref writeRegion); + } + + if (!result) + { + // When WriteConsoleOutput fails, half bufferLimit + if (bufferLimit < 2) + { + int err = Marshal.GetLastWin32Error(); + HostException e = CreateHostException(err, "WriteConsoleOutput", + ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate); + throw e; + } + + bufferLimit /= 2; + if (cols == colsRemaining) + { + // if cols == colsRemaining, nothing is guaranteed written in this pass and + // the unwritten area is still rectangular + bufferSize.Y = 0; + break; + } + else + { + // some areas have been written. This could only happen when the number of columns + // to write is larger than bufferLimit. In that case, the algorithm writes one row + // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged + // to retry with a smaller bufferSize.X. + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + continue; + } + } + + colsRemaining -= bufferSize.X; + writeRegion.Left += bufferSize.X; + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + } // column iteration + + rowsRemaining -= bufferSize.Y; + writeRegion.Top += bufferSize.Y; + } // row iteration + } + + private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents) + { + int rows = contents.GetLength(0); + int cols = contents.GetLength(1); + + if ((rows <= 0) || cols <= 0) + { + tracer.WriteLine("contents passed in has 0 rows and columns"); + return; + } + + int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes + + COORD bufferCoord; + + bufferCoord.X = 0; + bufferCoord.Y = 0; + + // keeps track of which screen area write + SMALL_RECT writeRegion; + + writeRegion.Top = (short)origin.Y; + + int rowsRemaining = rows; + + while (rowsRemaining > 0) + { + // Iteration of columns is nested inside iteration of rows. + // If the size of contents exceeds the buffer limit, writing is + // done in blocks of size equal to the bufferlimit from left to right + // then top to bottom. + // For each iteration of rows, + // - writeRegion.Left and bufferSize.X are reset + // - rowsRemaining, writeRegion.Top, writeRegion.Bottom, and bufferSize.Y + // are updated + // For each iteration of columns, + // - writeRegion.Left, writeRegion.Right and bufferSize.X are updated + + writeRegion.Left = (short)origin.X; + + COORD bufferSize; + + bufferSize.X = (short)Math.Min(cols, bufferLimit); + bufferSize.Y = (short)Math.Min + ( + rowsRemaining, + bufferLimit / bufferSize.X + ); + writeRegion.Bottom = (short)(writeRegion.Top + bufferSize.Y - 1); + + // atRow is at which row of contents a particular iteration is operating + int atRow = rows - rowsRemaining + contents.GetLowerBound(0); + + // number of columns yet to be written + int colsRemaining = cols; + + while (colsRemaining > 0) + { + writeRegion.Right = (short)(writeRegion.Left + bufferSize.X - 1); + + // atCol is at which column of contents a particular iteration is operating + int atCol = cols - colsRemaining + contents.GetLowerBound(1); + CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X]; + + // copy characterBuffer to contents; + for (int r = atRow, characterBufferIndex = 0; + r < bufferSize.Y + atRow; r++) + { + for (int c = atCol; c < bufferSize.X + atCol; c++, characterBufferIndex++) + { + characterBuffer[characterBufferIndex].UnicodeChar = + (ushort)contents[r, c].Character; + characterBuffer[characterBufferIndex].Attributes = + ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor); + } + } + + // Now writeRegion, bufferSize and characterBuffer are updated. + // Call NativeMethods.WriteConsoleOutput + bool result = + NativeMethods.WriteConsoleOutput( + consoleHandle.DangerousGetHandle(), + characterBuffer, + bufferSize, + bufferCoord, + ref writeRegion); + + if (!result) + { + // When WriteConsoleOutput fails, half bufferLimit + if (bufferLimit < 2) + { + int err = Marshal.GetLastWin32Error(); + HostException e = CreateHostException(err, "WriteConsoleOutput", + ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate); + throw e; + } + + bufferLimit /= 2; + if (cols == colsRemaining) + { + // if cols == colsRemaining, nothing is guaranteed written in this pass and + // the unwritten area is still rectangular + bufferSize.Y = 0; + break; + } + else + { + // some areas have been written. This could only happen when the number of columns + // to write is larger than bufferLimit. In that case, the algorithm writes one row + // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged + // to retry with a smaller bufferSize.X. + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + continue; + } + } + + colsRemaining -= bufferSize.X; + writeRegion.Left += bufferSize.X; + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + } // column iteration + + rowsRemaining -= bufferSize.Y; + writeRegion.Top += bufferSize.Y; + } // row iteration + } + + /// + /// Wrap32 ReadConsoleOutput + /// This wrapper is not limited to 64K or 8K CHAR_INFO to which Win32's ReadConsoleOutput + /// is constrained. + /// + /// + /// handle for the console where output is read + /// + /// + /// location on screen buffer where reading begins + /// + /// + /// indicates the area in where the data read + /// is stored. + /// + /// + /// this is ref because the bounds and size of the array are needed. + /// + /// + /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput + /// + internal static void ReadConsoleOutput + ( + ConsoleHandle consoleHandle, + Coordinates origin, + Rectangle contentsRegion, + ref BufferCell[,] contents + ) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + uint codePage; + if (IsCJKOutputCodePage(out codePage)) + { + ReadConsoleOutputCJK(consoleHandle, codePage, origin, contentsRegion, ref contents); + // check left edge + BufferCell[,] cellArray = null; + Coordinates checkOrigin; + Rectangle cellArrayRegion = new Rectangle(0, 0, 1, contentsRegion.Bottom - contentsRegion.Top); + if (origin.X > 0 && ShouldCheck(contentsRegion.Left, contents, contentsRegion)) + { + cellArray = new BufferCell[cellArrayRegion.Bottom + 1, 2]; + checkOrigin = new Coordinates(origin.X - 1, origin.Y); + ReadConsoleOutputCJK(consoleHandle, codePage, checkOrigin, + cellArrayRegion, ref cellArray); + for (int i = 0; i <= cellArrayRegion.Bottom; i++) + { + if (cellArray[i, 0].BufferCellType == BufferCellType.Leading) + { + contents[contentsRegion.Top + i, 0].Character = (char)0; + contents[contentsRegion.Top + i, 0].BufferCellType = BufferCellType.Trailing; + } + } + } + + // check right edge + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = + GetConsoleScreenBufferInfo(consoleHandle); + if (origin.X + (contentsRegion.Right - contentsRegion.Left) + 1 < bufferInfo.BufferSize.X && + ShouldCheck(contentsRegion.Right, contents, contentsRegion)) + { + cellArray ??= new BufferCell[cellArrayRegion.Bottom + 1, 2]; + + checkOrigin = new Coordinates(origin.X + + (contentsRegion.Right - contentsRegion.Left), origin.Y); + ReadConsoleOutputCJK(consoleHandle, codePage, checkOrigin, + cellArrayRegion, ref cellArray); + for (int i = 0; i <= cellArrayRegion.Bottom; i++) + { + if (cellArray[i, 0].BufferCellType == BufferCellType.Leading) + { + contents[contentsRegion.Top + i, contentsRegion.Right] = cellArray[i, 0]; + } + } + } + } + else + { + ReadConsoleOutputPlain(consoleHandle, origin, contentsRegion, ref contents); + } + } + + #region ReadConsoleOutput CJK + /// + /// If an edge cell read is a blank, it is potentially part of a double width character. Hence, + /// at least one of the left and right edges should be checked. + /// + /// + /// + /// + /// + private static bool ShouldCheck(int edge, BufferCell[,] contents, Rectangle contentsRegion) + { + for (int i = contentsRegion.Top; i <= contentsRegion.Bottom; i++) + { + if (contents[i, edge].Character == ' ') + { + return true; + } + } + + return false; + } + + private static bool ReadConsoleOutputCJKSmall + ( + ConsoleHandle consoleHandle, + uint codePage, + Coordinates origin, + Rectangle contentsRegion, + ref BufferCell[,] contents + ) + { + COORD bufferSize; + bufferSize.X = (short)(contentsRegion.Right - contentsRegion.Left + 1); + bufferSize.Y = (short)(contentsRegion.Bottom - contentsRegion.Top + 1); + COORD bufferCoord; + bufferCoord.X = 0; + bufferCoord.Y = 0; + CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.X * bufferSize.Y]; + SMALL_RECT readRegion; + readRegion.Left = (short)origin.X; + readRegion.Top = (short)origin.Y; + readRegion.Right = (short)(origin.X + bufferSize.X - 1); + readRegion.Bottom = (short)(origin.Y + bufferSize.Y - 1); + + bool result = NativeMethods.ReadConsoleOutput( + consoleHandle.DangerousGetHandle(), + characterBuffer, + bufferSize, + bufferCoord, + ref readRegion); + if (!result) + { + return false; + } + + int characterBufferIndex = 0; + + for (int r = contentsRegion.Top; r <= contentsRegion.Bottom; r++) + { + for (int c = contentsRegion.Left; c <= contentsRegion.Right; c++, characterBufferIndex++) + { + ConsoleColor fgColor, bgColor; + + contents[r, c].Character = (char)characterBuffer[characterBufferIndex].UnicodeChar; + WORDToColor(characterBuffer[characterBufferIndex].Attributes, + out fgColor, + out bgColor); + contents[r, c].ForegroundColor = fgColor; + contents[r, c].BackgroundColor = bgColor; + + // Set the attributes of the buffercells to be the same as that of the + // incoming CHAR_INFO. In case where the CHAR_INFO character is a + // trailing byte set the Character of BufferCell to 0. This is done + // because at a lot of places this check is being done. Having a trailing + // character to be 0 is by design. + + if ((characterBuffer[characterBufferIndex].Attributes & (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE) + == (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE) + { + contents[r, c].BufferCellType = BufferCellType.Leading; + } + else if ((characterBuffer[characterBufferIndex].Attributes & (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE) + == (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE) + { + contents[r, c].Character = (char)0; + contents[r, c].BufferCellType = BufferCellType.Trailing; + } + else + { + int charLength = LengthInBufferCells(contents[r, c].Character); + if (charLength == 2) + { + // When it's RasterFont, the "Leading_byte"/"Trailing_byte" are not effective, we + // need to decide the leading byte by checking the char length. + contents[r, c].BufferCellType = BufferCellType.Leading; + c++; + contents[r, c].Character = (char)0; + contents[r, c].ForegroundColor = fgColor; + contents[r, c].BackgroundColor = bgColor; + contents[r, c].BufferCellType = BufferCellType.Trailing; + } + else + { + contents[r, c].BufferCellType = BufferCellType.Complete; + } + } + } + } + + return true; + } + + /// + /// Can handle reading CJK characters, but the left and right edges are not checked. + /// + /// + /// + /// + /// + /// + /// + /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput + /// + internal static void ReadConsoleOutputCJK + ( + ConsoleHandle consoleHandle, + uint codePage, + Coordinates origin, + Rectangle contentsRegion, + ref BufferCell[,] contents + ) + { + int rows = contentsRegion.Bottom - contentsRegion.Top + 1; + int cols = contentsRegion.Right - contentsRegion.Left + 1; + + if ((rows <= 0) || cols <= 0) + { + tracer.WriteLine("invalid contents region"); + return; + } + + int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes + + COORD bufferCoord; + + bufferCoord.X = 0; + bufferCoord.Y = 0; + + // keeps track of which screen area is read + SMALL_RECT readRegion; + + readRegion.Top = (short)origin.Y; + + int rowsRemaining = rows; + + while (rowsRemaining > 0) + { + // Iteration of columns is nested inside iteration of rows. + // If the size of contents exceeds the buffer limit, reading is + // done in blocks of size equal to the bufferlimit from left to right + // then top to bottom. + // For each iteration of rows, + // - readRegion.Left and bufferSize.X are reset + // - rowsRemaining, readRegion.Top, readRegion.Bottom, and bufferSize.Y + // are updated + // For each iteration of columns, + // - readRegion.Left, readRegion.Right and bufferSize.X are updated + + readRegion.Left = (short)origin.X; + + COORD bufferSize; + bufferSize.X = (short)Math.Min(cols, bufferLimit); + bufferSize.Y = (short)Math.Min + ( + rowsRemaining, + bufferLimit / bufferSize.X + ); + readRegion.Bottom = (short)(readRegion.Top + bufferSize.Y - 1); + + // atContentsRow is at which row of contents a particular iteration is operating + int atContentsRow = rows - rowsRemaining + contentsRegion.Top; + + // number of columns yet to be read + int colsRemaining = cols; + + while (colsRemaining > 0) + { + // atContentsCol is at which column of contents a particular iteration is operating + int atContentsCol = cols - colsRemaining + contentsRegion.Left; + + readRegion.Right = (short)(readRegion.Left + bufferSize.X - 1); + + // Now readRegion and bufferSize are updated. + Rectangle atContents = new Rectangle(atContentsCol, atContentsRow, + atContentsCol + bufferSize.X - 1, atContentsRow + bufferSize.Y - 1); + bool result = + ReadConsoleOutputCJKSmall(consoleHandle, codePage, + new Coordinates(readRegion.Left, readRegion.Top), + atContents, + ref contents); + if (!result) + { + // When WriteConsoleOutput fails, half bufferLimit + if (bufferLimit < 2) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "ReadConsoleOutput", + ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleOutputExceptionTemplate); + throw e; + } + else + { + // if cols == colsRemaining, nothing is guaranteed read in this pass and + // the unread area is still rectangular + bufferLimit /= 2; + if (cols == colsRemaining) + { + bufferSize.Y = 0; + break; + } + else + { + // some areas have been read. This could only happen when the number of columns + // to write is larger than bufferLimit. In that case, the algorithm reads one row + // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged + // to retry with a smaller bufferSize.X. + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + continue; + } + } + } + + colsRemaining -= bufferSize.X; + readRegion.Left += bufferSize.X; + if (colsRemaining > 0 && (bufferSize.Y == 1) && + (contents[atContents.Bottom, atContents.Right].Character == ' ')) + { + colsRemaining++; + readRegion.Left--; + } + + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + } // column iteration + + rowsRemaining -= bufferSize.Y; + readRegion.Top += bufferSize.Y; + } // row iteration + + // The following nested loop set the value of the empty cells in contents: + // character to ' ' + // foreground color to console's foreground color + // background color to console's background color + int rowIndex = contents.GetLowerBound(0); + int rowEnd = contents.GetUpperBound(0); + int colBegin = contents.GetLowerBound(1); + int colEnd = contents.GetUpperBound(1); + CONSOLE_SCREEN_BUFFER_INFO bufferInfo = + GetConsoleScreenBufferInfo(consoleHandle); + ConsoleColor foreground = 0; + ConsoleColor background = 0; + + WORDToColor( + bufferInfo.Attributes, + out foreground, + out background + ); + + while (rowIndex <= rowEnd) + { + int colIndex = colBegin; + while (true) + { + // if contents[rowIndex,colIndex] is in contentsRegion, hence a non-empty cell, + // move colIndex to one past the right end of contentsRegion + if (contentsRegion.Top <= rowIndex && rowIndex <= contentsRegion.Bottom && + contentsRegion.Left <= colIndex && colIndex <= contentsRegion.Right) + { + colIndex = contentsRegion.Right + 1; + } + // colIndex past contents last column + if (colIndex > colEnd) + { + break; + } + + contents[rowIndex, colIndex] = new BufferCell( + ' ', foreground, background, BufferCellType.Complete); + colIndex++; + } + + rowIndex++; + } + } + #endregion ReadConsoleOutput CJK + + private static void ReadConsoleOutputPlain + ( + ConsoleHandle consoleHandle, + Coordinates origin, + Rectangle contentsRegion, + ref BufferCell[,] contents + ) + { + int rows = contentsRegion.Bottom - contentsRegion.Top + 1; + int cols = contentsRegion.Right - contentsRegion.Left + 1; + + if ((rows <= 0) || cols <= 0) + { + tracer.WriteLine("invalid contents region"); + return; + } + + int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes + + COORD bufferCoord; + + bufferCoord.X = 0; + bufferCoord.Y = 0; + + // keeps track of which screen area read + SMALL_RECT readRegion; + + readRegion.Top = (short)origin.Y; + + int rowsRemaining = rows; + + while (rowsRemaining > 0) + { + // Iteration of columns is nested inside iteration of rows. + // If the size of contents exceeds the buffer limit, reading is + // done in blocks of size equal to the bufferlimit from left to right + // then top to bottom. + // For each iteration of rows, + // - readRegion.Left and bufferSize.X are reset + // - rowsRemaining, readRegion.Top, readRegion.Bottom, and bufferSize.Y + // are updated + // For each iteration of columns, + // - readRegion.Left, readRegion.Right and bufferSize.X are updated + + readRegion.Left = (short)origin.X; + + COORD bufferSize; + bufferSize.X = (short)Math.Min(cols, bufferLimit); + bufferSize.Y = (short)Math.Min + ( + rowsRemaining, + bufferLimit / bufferSize.X + ); + readRegion.Bottom = (short)(readRegion.Top + bufferSize.Y - 1); + + // atContentsRow is at which row of contents a particular iteration is operating + int atContentsRow = rows - rowsRemaining + contentsRegion.Top; + + // number of columns yet to be read + int colsRemaining = cols; + + while (colsRemaining > 0) + { + readRegion.Right = (short)(readRegion.Left + bufferSize.X - 1); + + // Now readRegion and bufferSize are updated. + // Call NativeMethods.ReadConsoleOutput + CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X]; + bool result = NativeMethods.ReadConsoleOutput( + consoleHandle.DangerousGetHandle(), + characterBuffer, + bufferSize, + bufferCoord, + ref readRegion); + + if (!result) + { + // When WriteConsoleOutput fails, half bufferLimit + if (bufferLimit < 2) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "ReadConsoleOutput", + ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleOutputExceptionTemplate); + throw e; + } + // if cols == colsRemaining, nothing is guaranteed read in this pass and + // the unread area is still rectangular + bufferLimit /= 2; + if (cols == colsRemaining) + { + bufferSize.Y = 0; + break; + } + else + { + // some areas have been read. This could only happen when the number of columns + // to write is larger than bufferLimit. In that case, the algorithm reads one row + // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged + // to retry with a smaller bufferSize.X. + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + continue; + } + } + + // atContentsCol is at which column of contents a particular iteration is operating + int atContentsCol = cols - colsRemaining + contentsRegion.Left; + + // copy characterBuffer to contents; + int characterBufferIndex = 0; + for (int r = atContentsRow; r < bufferSize.Y + atContentsRow; r++) + { + for (int c = atContentsCol; c < bufferSize.X + atContentsCol; c++, characterBufferIndex++) + { + contents[r, c].Character = (char)characterBuffer[characterBufferIndex].UnicodeChar; + ConsoleColor fgColor, bgColor; + WORDToColor(characterBuffer[characterBufferIndex].Attributes, + out fgColor, + out bgColor); + contents[r, c].ForegroundColor = fgColor; + contents[r, c].BackgroundColor = bgColor; + } + } + + colsRemaining -= bufferSize.X; + readRegion.Left += bufferSize.X; + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); + } // column iteration + + rowsRemaining -= bufferSize.Y; + readRegion.Top += bufferSize.Y; + } // row iteration + + // The following nested loop set the value of the empty cells in contents: + // character to ' ' + // foreground color to console's foreground color + // background color to console's background color + int rowIndex = contents.GetLowerBound(0); + int rowEnd = contents.GetUpperBound(0); + int colBegin = contents.GetLowerBound(1); + int colEnd = contents.GetUpperBound(1); + CONSOLE_SCREEN_BUFFER_INFO bufferInfo = + GetConsoleScreenBufferInfo(consoleHandle); + ConsoleColor foreground = 0; + ConsoleColor background = 0; + + WORDToColor( + bufferInfo.Attributes, + out foreground, + out background + ); + + while (rowIndex <= rowEnd) + { + int colIndex = colBegin; + while (true) + { + // if contents[rowIndex,colIndex] is in contentsRegion, hence a non-empty cell, + // move colIndex to one past the right end of contentsRegion + if (contentsRegion.Top <= rowIndex && rowIndex <= contentsRegion.Bottom && + contentsRegion.Left <= colIndex && colIndex <= contentsRegion.Right) + { + colIndex = contentsRegion.Right + 1; + } + // colIndex past contents last column + if (colIndex > colEnd) + { + break; + } + + contents[rowIndex, colIndex].Character = ' '; + contents[rowIndex, colIndex].ForegroundColor = foreground; + contents[rowIndex, colIndex].BackgroundColor = background; + colIndex++; + } + + rowIndex++; + } + } + + /// + /// Wraps Win32 FillConsoleOutputCharacter. + /// + /// + /// handle for the console where output is filled + /// + /// + /// character to fill the console output + /// + /// + /// number of times to write character + /// + /// + /// location on screen buffer where writing starts + /// + /// + /// If Win32's FillConsoleOutputCharacter fails + /// + internal static void FillConsoleOutputCharacter + ( + ConsoleHandle consoleHandle, + char character, + int numberToWrite, + Coordinates origin + ) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + COORD c; + + c.X = (short)origin.X; + c.Y = (short)origin.Y; + + bool result = + NativeMethods.FillConsoleOutputCharacter( + consoleHandle.DangerousGetHandle(), + character, + (DWORD)numberToWrite, + c, + out _); + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "FillConsoleOutputCharacter", + ErrorCategory.WriteError, ConsoleControlStrings.FillConsoleOutputCharacterExceptionTemplate); + throw e; + } + // we don't assert that the number actually written matches the number we asked for, as the function may clip if + // the number of cells to write extends past the end of the screen buffer. + } + + /// + /// Wraps Win32 FillConsoleOutputAttribute. + /// + /// + /// handle for the console where output is filled + /// + /// + /// attribute to fill the console output + /// + /// + /// number of times to write attribute + /// + /// + /// location on screen buffer where writing starts + /// + /// + /// If Win32's FillConsoleOutputAttribute fails + /// + internal static void FillConsoleOutputAttribute + ( + ConsoleHandle consoleHandle, + WORD attribute, + int numberToWrite, + Coordinates origin + ) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + COORD c; + + c.X = (short)origin.X; + c.Y = (short)origin.Y; + + bool result = + NativeMethods.FillConsoleOutputAttribute( + consoleHandle.DangerousGetHandle(), + attribute, + (DWORD)numberToWrite, + c, + out _); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "FillConsoleOutputAttribute", + ErrorCategory.WriteError, ConsoleControlStrings.FillConsoleOutputAttributeExceptionTemplate); + throw e; + } + } + + /// + /// Wrap Win32 ScrollConsoleScreenBuffer. + /// + /// + /// handle for the console where screen buffer is scrolled + /// + /// + /// area to be scrolled + /// + /// + /// area to be updated after scrolling + /// + /// + /// location to which the top left corner of scrollRectangle move + /// + /// + /// character and attribute to fill the area vacated by the scroll + /// + /// + /// If Win32's ScrollConsoleScreenBuffer fails + /// + internal static void ScrollConsoleScreenBuffer + ( + ConsoleHandle consoleHandle, + SMALL_RECT scrollRectangle, + SMALL_RECT clipRectangle, + COORD destOrigin, CHAR_INFO fill + ) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + bool result = + NativeMethods.ScrollConsoleScreenBuffer( + consoleHandle.DangerousGetHandle(), + ref scrollRectangle, + ref clipRectangle, + destOrigin, + ref fill); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "ScrollConsoleScreenBuffer", + ErrorCategory.WriteError, ConsoleControlStrings.ScrollConsoleScreenBufferExceptionTemplate); + throw e; + } + } + + #endregion Buffer + + #region Window + + /// + /// Wraps Win32 SetConsoleWindowInfo. + /// + /// + /// handle for the console where window info is set + /// + /// + /// If this parameter is TRUE, the coordinates specify the new upper-left and + /// lower-right corners of the window. If it is false, the coordinates are offsets + /// to the current window-corner coordinates + /// + /// + /// specify the size and position of the console screen buffer's window + /// + /// + /// If Win32's SetConsoleWindowInfo fails + /// + internal static void SetConsoleWindowInfo(ConsoleHandle consoleHandle, bool absolute, SMALL_RECT windowInfo) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + bool result = NativeMethods.SetConsoleWindowInfo(consoleHandle.DangerousGetHandle(), absolute, ref windowInfo); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "SetConsoleWindowInfo", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleWindowInfoExceptionTemplate); + throw e; + } + } + + /// + /// Wraps Win32 GetLargestConsoleWindowSize. + /// + /// + /// handle for the console for which the largest window size is obtained + /// + /// + /// the largest window size + /// + /// + /// If Win32's GetLargestConsoleWindowSize fails + /// + internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + COORD result = NativeMethods.GetLargestConsoleWindowSize(consoleHandle.DangerousGetHandle()); + + if ((result.X == 0) && (result.Y == 0)) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "GetLargestConsoleWindowSize", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetLargestConsoleWindowSizeExceptionTemplate); + throw e; + } + + return new Size(result.X, result.Y); + } + + /// + /// Wraps Win32 GetConsoleTitle. 1K is the safe limit experimentally. The 64K limit + /// found in the docs is disregarded because it is essentially meaningless. + /// + /// + /// a string for the title of the window + /// + /// + /// If Win32's GetConsoleTitle fails + /// + internal static string GetConsoleWindowTitle() + { + const int MaxWindowTitleLength = 1024; + const DWORD bufferSize = MaxWindowTitleLength; + DWORD result; + StringBuilder consoleTitle = new StringBuilder((int)bufferSize); + + result = NativeMethods.GetConsoleTitle(consoleTitle, bufferSize); + // If the result is zero, it may mean and error but it may also mean + // that the window title has been set to null. Since we can't tell the + // the difference, we'll just return the empty string every time. + if (result == 0) + { + return string.Empty; + } + + return consoleTitle.ToString(); + } + + private static bool s_dontsetConsoleWindowTitle; + + /// + /// Wraps Win32 SetConsoleTitle. + /// + /// + /// a string for the title of the window + /// + /// + /// If Win32's SetConsoleTitle fails + /// + internal static void SetConsoleWindowTitle(string consoleTitle) + { + if (s_dontsetConsoleWindowTitle) + { + return; + } + + bool result = NativeMethods.SetConsoleTitle(consoleTitle); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + // ERROR_GEN_FAILURE is returned if this api can't be used with the terminal + if (err == 0x1f) + { + tracer.WriteLine("Call to SetConsoleTitle failed: {0}", err); + s_dontsetConsoleWindowTitle = true; + + // We ignore this specific error as the console can still continue to operate + return; + } + + HostException e = CreateHostException(err, "SetConsoleWindowTitle", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleWindowTitleExceptionTemplate); + throw e; + } + } + + #endregion Window + + /// + /// Wrap Win32 WriteConsole. + /// + /// + /// Handle for the console where the string is written. + /// + /// + /// String that is written. + /// + /// + /// New line is written. + /// + /// + /// If the Win32's WriteConsole fails. + /// + internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan output, bool newLine) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + if (output.Length == 0) + { + if (newLine) + { + WriteConsole(consoleHandle, Environment.NewLine); + } + + return; + } + + // Native WriteConsole doesn't support output buffer longer than 64K, so we need to chop the output string if it is too long. + // This records the chopping position in output string. + int cursor = 0; + // This is 64K/4 - 1 to account for possible width of each character. + const int MaxBufferSize = 16383; + const int MaxStackAllocSize = 512; + ReadOnlySpan outBuffer; + + // In case that a new line is required, we try to write out the last chunk and the new-line string together, + // to avoid one extra call to 'WriteConsole' just for a new line string. + while (cursor + MaxBufferSize < output.Length) + { + outBuffer = output.Slice(cursor, MaxBufferSize); + cursor += MaxBufferSize; + WriteConsole(consoleHandle, outBuffer); + } + + outBuffer = output.Slice(cursor); + if (!newLine) + { + WriteConsole(consoleHandle, outBuffer); + return; + } + + char[] rentedArray = null; + string lineEnding = Environment.NewLine; + int size = outBuffer.Length + lineEnding.Length; + + // We expect the 'size' will often be small, and thus optimize that case with 'stackalloc'. + Span buffer = size <= MaxStackAllocSize ? stackalloc char[size] : default; + + try + { + if (buffer.IsEmpty) + { + rentedArray = ArrayPool.Shared.Rent(size); + buffer = rentedArray.AsSpan().Slice(0, size); + } + + outBuffer.CopyTo(buffer); + lineEnding.CopyTo(buffer.Slice(outBuffer.Length)); + WriteConsole(consoleHandle, buffer); + } + finally + { + if (rentedArray is not null) + { + ArrayPool.Shared.Return(rentedArray); + } + } + } + + private static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan buffer) + { + DWORD charsWritten; + bool result = + NativeMethods.WriteConsole( + consoleHandle.DangerousGetHandle(), + buffer, + (DWORD)buffer.Length, + out charsWritten, + IntPtr.Zero); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException( + err, + "WriteConsole", + ErrorCategory.WriteError, + ConsoleControlStrings.WriteConsoleExceptionTemplate); + throw e; + } + } + + /// + /// Wraps Win32 SetConsoleTextAttribute. + /// + /// + /// handle for the console where text attribute is set + /// + /// + /// text attribute to set the console + /// + /// + /// if the Win32's SetConsoleTextAttribute fails + /// + internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD attribute) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + bool result = NativeMethods.SetConsoleTextAttribute(consoleHandle.DangerousGetHandle(), attribute); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "SetConsoleTextAttribute", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleTextAttributeExceptionTemplate); + throw e; + } + } + +#endif + #region Dealing with CJK + + // Return the length of a VT100 control sequence character in str starting + // at the given offset. + // + // This code only handles the following formatting sequences, corresponding to + // the patterns: + // CSI params? 'm' // SGR: Select Graphics Rendition + // CSI params? '#' [{}pq] // XTPUSHSGR ('{'), XTPOPSGR ('}'), or their aliases ('p' and 'q') + // + // Where: + // params: digit+ ((';' | ':') params)? + // CSI: C0_CSI | C1_CSI + // C0_CSI: \x001b '[' // ESC '[' + // C1_CSI: \x009b + // + // There are many other VT100 escape sequences, but these text attribute sequences + // (color-related, underline, etc.) are sufficient for our formatting system. We + // won't handle cursor movements or other attempts at animation. + // + // Note that offset is adjusted past the escape sequence, or at least one + // character forward if there is no escape sequence at the specified position. + internal static int ControlSequenceLength(string str, ref int offset) + { + var start = offset; + + // First, check for the CSI: + if ((str[offset] == (char)0x1b) && (str.Length > (offset + 1)) && (str[offset + 1] == '[')) + { + // C0 CSI + offset += 2; + } + else if (str[offset] == (char)0x9b) + { + // C1 CSI + offset += 1; + } + else + { + // No CSI at the current location, so we are done looking, but we still + // need to advance offset. + offset += 1; + return 0; + } + + if (offset >= str.Length) + { + return 0; + } + + // Next, handle possible numeric arguments: + char c; + do + { + c = str[offset++]; + } + while ((offset < str.Length) && (char.IsDigit(c) || (c == ';') || (c == ':'))); + + // Finally, handle the command characters for the specific sequences we + // handle: + if (c == 'm') + { + // SGR: Select Graphics Rendition + return offset - start; + } + + // Maybe XTPUSHSGR or XTPOPSGR, but we need to read another char. Offset is + // already positioned on the next char (or past the end). + if (offset >= str.Length) + { + return 0; + } + + if (c == '#') + { + // '{' : XTPUSHSGR + // '}' : XTPOPSGR + // 'p' : alias for XTPUSHSGR + // 'q' : alias for XTPOPSGR + c = str[offset++]; + if ((c == '{') || + (c == '}') || + (c == 'p') || + (c == 'q')) + { + return offset - start; + } + } + + return 0; + } + + /// + /// From IsConsoleFullWidth in \windows\core\ntcon\server\dbcs.c. + /// + /// + [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", + MessageId = "Microsoft.PowerShell.ConsoleControl+NativeMethods.ReleaseDC(System.IntPtr,System.IntPtr)")] + internal static int LengthInBufferCells(string str, int offset, bool checkEscapeSequences) + { + Dbg.Assert(offset >= 0, "offset >= 0"); + Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length"); + + var escapeSequenceAdjustment = 0; + if (checkEscapeSequences) + { + int i = 0; + while (i < offset) + { + ControlSequenceLength(str, ref i); + } + + // If offset != i, we're in the middle of a sequence, which the caller should avoid, + // but we'll tolerate. + while (i < str.Length) + { + escapeSequenceAdjustment += ControlSequenceLength(str, ref i); + } + } + + int length = 0; + foreach (char c in str) + { + length += LengthInBufferCells(c); + } + + return length - offset - escapeSequenceAdjustment; + } + + internal static int LengthInBufferCells(char c) + { + // The following is based on http://www.cl.cam.ac.uk/~mgk25/c/wcwidth.c + // which is derived from https://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt + bool isWide = c >= 0x1100 && + (c <= 0x115f || /* Hangul Jamo init. consonants */ + c == 0x2329 || c == 0x232a || + ((uint)(c - 0x2e80) <= (0xa4cf - 0x2e80) && + c != 0x303f) || /* CJK ... Yi */ + ((uint)(c - 0xac00) <= (0xd7a3 - 0xac00)) || /* Hangul Syllables */ + ((uint)(c - 0xf900) <= (0xfaff - 0xf900)) || /* CJK Compatibility Ideographs */ + ((uint)(c - 0xfe10) <= (0xfe19 - 0xfe10)) || /* Vertical forms */ + ((uint)(c - 0xfe30) <= (0xfe6f - 0xfe30)) || /* CJK Compatibility Forms */ + ((uint)(c - 0xff00) <= (0xff60 - 0xff00)) || /* Fullwidth Forms */ + ((uint)(c - 0xffe0) <= (0xffe6 - 0xffe0))); + + // We can ignore these ranges because .Net strings use surrogate pairs + // for this range and we do not handle surrogate pairs. + // (c >= 0x20000 && c <= 0x2fffd) || + // (c >= 0x30000 && c <= 0x3fffd) + return 1 + (isWide ? 1 : 0); + } + +#if !UNIX + + /// + /// Check if the output buffer code page is Japanese, Simplified Chinese, Korean, or Traditional Chinese. + /// + /// + /// + internal static bool IsCJKOutputCodePage(out uint codePage) + { + codePage = NativeMethods.GetConsoleOutputCP(); + return codePage == 932 || // Japanese + codePage == 936 || // Simplified Chinese + codePage == 949 || // Korean + codePage == 950; // Traditional Chinese + } + +#endif + #endregion Dealing with CJK + +#if !UNIX + + #region Cursor + + /// + /// Wraps Win32 GetConsoleCursorInfo. + /// + /// + /// handle for the console where cursor info is obtained + /// + /// + /// cursor info + /// + /// + /// If Win32's GetConsoleCursorInfo fails + /// + internal static CONSOLE_CURSOR_INFO GetConsoleCursorInfo(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + CONSOLE_CURSOR_INFO cursorInfo; + + bool result = NativeMethods.GetConsoleCursorInfo(consoleHandle.DangerousGetHandle(), out cursorInfo); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "GetConsoleCursorInfo", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleCursorInfoExceptionTemplate); + throw e; + } + + return cursorInfo; + } + + internal static CONSOLE_FONT_INFO_EX GetConsoleFontInfo(ConsoleHandle consoleHandle) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + CONSOLE_FONT_INFO_EX fontInfo = new CONSOLE_FONT_INFO_EX(); + fontInfo.cbSize = Marshal.SizeOf(fontInfo); + bool result = NativeMethods.GetCurrentConsoleFontEx(consoleHandle.DangerousGetHandle(), false, ref fontInfo); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "GetConsoleFontInfo", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleFontInfoExceptionTemplate); + throw e; + } + + return fontInfo; + } + + /// + /// Wraps Win32 SetConsoleCursorInfo. + /// + /// + /// handle for the console where cursor info is set + /// + /// + /// cursor info to set the cursor + /// + /// + /// If Win32's SetConsoleCursorInfo fails + /// + internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_CURSOR_INFO cursorInfo) + { + Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); + Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); + + bool result = NativeMethods.SetConsoleCursorInfo(consoleHandle.DangerousGetHandle(), ref cursorInfo); + + if (!result) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "SetConsoleCursorInfo", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleCursorInfoExceptionTemplate); + throw e; + } + } + + #endregion Cursor + + #region helper + + /// + /// Helper function to create the proper HostException. + /// + /// + /// + /// + /// + /// + private static HostException CreateHostException( + int win32Error, string errorId, ErrorCategory category, string resourceStr) + { + Win32Exception innerException = new Win32Exception(win32Error); + string msg = StringUtil.Format(resourceStr, innerException.Message, win32Error); + HostException e = new HostException(msg, innerException, errorId, category); + return e; + } + + #endregion helper + + #region SendInput + + internal static void MimicKeyPress(INPUT[] inputs) + { + Dbg.Assert(inputs != null && inputs.Length > 0, "inputs should not be null or empty"); + var numberOfSuccessfulEvents = NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()); + + if (numberOfSuccessfulEvents == 0) + { + int err = Marshal.GetLastWin32Error(); + + HostException e = CreateHostException(err, "SendKeyPressInput", + ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SendKeyPressInputExceptionTemplate); + throw e; + } + } + + #endregion SendInput + + /// + /// Class to hold the Native Methods used in this file enclosing class. + /// + internal static class NativeMethods + { + internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h + + internal const int FontTypeMask = 0x06; + internal const int TrueTypeFont = 0x04; + + #region CreateFile + + [Flags] + internal enum AccessQualifiers : uint + { + // From winnt.h + GenericRead = 0x80000000, + GenericWrite = 0x40000000 + } + + [Flags] + internal enum ShareModes : uint + { + // From winnt.h + ShareRead = 0x00000001, + ShareWrite = 0x00000002 + } + + internal enum CreationDisposition : uint + { + // From winbase.h + CreateNew = 1, + CreateAlways = 2, + OpenExisting = 3, + OpenAlways = 4, + TruncateExisting = 5 + } + + [DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern NakedWin32Handle CreateFile + ( + string fileName, + DWORD desiredAccess, + DWORD ShareModes, + IntPtr securityAttributes, + DWORD creationDisposition, + DWORD flagsAndAttributes, + NakedWin32Handle templateFileWin32Handle + ); + + #endregion CreateFile + + #region Code Page + + [DllImport(PinvokeDllNames.GetConsoleOutputCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] + internal static extern uint GetConsoleOutputCP(); + + #endregion Code Page + + [DllImport(PinvokeDllNames.GetConsoleWindowDllName, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern HWND GetConsoleWindow(); + + [DllImport(PinvokeDllNames.GetDCDllName, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern HDC GetDC(HWND hwnd); + + [DllImport(PinvokeDllNames.ReleaseDCDllName, SetLastError = false, CharSet = CharSet.Unicode)] + internal static extern int ReleaseDC(HWND hwnd, HDC hdc); + + [DllImport(PinvokeDllNames.FlushConsoleInputBufferDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool FlushConsoleInputBuffer(NakedWin32Handle consoleInput); + + [DllImport(PinvokeDllNames.FillConsoleOutputAttributeDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool FillConsoleOutputAttribute + ( + NakedWin32Handle consoleOutput, + WORD attribute, + DWORD length, + COORD writeCoord, + out DWORD numberOfAttrsWritten + ); + + [DllImport(PinvokeDllNames.FillConsoleOutputCharacterDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool FillConsoleOutputCharacter + ( + NakedWin32Handle consoleOutput, + char character, + DWORD length, + COORD writeCoord, + out DWORD numberOfCharsWritten + ); + + [DllImport(PinvokeDllNames.WriteConsoleDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern unsafe bool WriteConsole + ( + NakedWin32Handle consoleOutput, + char* buffer, + DWORD numberOfCharsToWrite, + out DWORD numberOfCharsWritten, + IntPtr reserved + ); + + internal static unsafe bool WriteConsole + ( + NakedWin32Handle consoleOutput, + ReadOnlySpan buffer, + DWORD numberOfCharsToWrite, + out DWORD numberOfCharsWritten, + IntPtr reserved + ) + { + fixed (char* bufferPtr = &MemoryMarshal.GetReference(buffer)) + { + return WriteConsole(consoleOutput, bufferPtr, numberOfCharsToWrite, out numberOfCharsWritten, reserved); + } + } + + [DllImport(PinvokeDllNames.GetConsoleTitleDllName, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern DWORD GetConsoleTitle(StringBuilder consoleTitle, DWORD size); + + [DllImport(PinvokeDllNames.SetConsoleTitleDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleTitle(string consoleTitle); + + [DllImport(PinvokeDllNames.GetConsoleModeDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetConsoleMode(NakedWin32Handle consoleHandle, out UInt32 mode); + + [DllImport(PinvokeDllNames.GetConsoleScreenBufferInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetConsoleScreenBufferInfo(NakedWin32Handle consoleHandle, out CONSOLE_SCREEN_BUFFER_INFO consoleScreenBufferInfo); + + [DllImport(PinvokeDllNames.GetLargestConsoleWindowSizeDllName, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern COORD GetLargestConsoleWindowSize(NakedWin32Handle consoleOutput); + + [DllImport(PinvokeDllNames.ReadConsoleDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern unsafe bool ReadConsole + ( + NakedWin32Handle consoleInput, + char* lpBuffer, + DWORD numberOfCharsToRead, + out DWORD numberOfCharsRead, + ref CONSOLE_READCONSOLE_CONTROL controlData + ); + + internal static unsafe bool ReadConsole + ( + NakedWin32Handle consoleInput, + Span buffer, + DWORD numberOfCharsToRead, + out DWORD numberOfCharsRead, + ref CONSOLE_READCONSOLE_CONTROL controlData + ) + { + fixed (char* bufferPtr = &MemoryMarshal.GetReference(buffer)) + { + return ReadConsole(consoleInput, bufferPtr, numberOfCharsToRead, out numberOfCharsRead, ref controlData); + } + } + + [DllImport(PinvokeDllNames.PeekConsoleInputDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool PeekConsoleInput + ( + NakedWin32Handle consoleInput, + [Out] INPUT_RECORD[] buffer, + DWORD length, + out DWORD numberOfEventsRead + ); + + [DllImport(PinvokeDllNames.GetNumberOfConsoleInputEventsDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetNumberOfConsoleInputEvents(NakedWin32Handle consoleInput, out DWORD numberOfEvents); + + [DllImport(PinvokeDllNames.SetConsoleCtrlHandlerDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleCtrlHandler(BreakHandler handlerRoutine, bool add); + + [DllImport(PinvokeDllNames.SetConsoleModeDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleMode(NakedWin32Handle consoleHandle, DWORD mode); + + [DllImport(PinvokeDllNames.SetConsoleScreenBufferSizeDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleScreenBufferSize(NakedWin32Handle consoleOutput, COORD size); + + [DllImport(PinvokeDllNames.SetConsoleTextAttributeDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleTextAttribute(NakedWin32Handle consoleOutput, WORD attributes); + + [DllImport(PinvokeDllNames.SetConsoleWindowInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleWindowInfo(NakedWin32Handle consoleHandle, bool absolute, ref SMALL_RECT windowInfo); + + [DllImport(PinvokeDllNames.WriteConsoleOutputDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool WriteConsoleOutput + ( + NakedWin32Handle consoleOutput, + CHAR_INFO[] buffer, + COORD bufferSize, + COORD bufferCoord, + ref SMALL_RECT writeRegion + ); + + [DllImport(PinvokeDllNames.ReadConsoleOutputDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ReadConsoleOutput + ( + NakedWin32Handle consoleOutput, + [Out] CHAR_INFO[] buffer, + COORD bufferSize, + COORD bufferCoord, + ref SMALL_RECT readRegion + ); + + [DllImport(PinvokeDllNames.ScrollConsoleScreenBufferDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ScrollConsoleScreenBuffer + ( + NakedWin32Handle consoleOutput, + ref SMALL_RECT scrollRectangle, + ref SMALL_RECT clipRectangle, + COORD destinationOrigin, + ref CHAR_INFO fill + ); + + [DllImport(PinvokeDllNames.SendInputDllName, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern UInt32 SendInput(UInt32 inputNumbers, INPUT[] inputs, int sizeOfInput); + + // There is no GetCurrentConsoleFontEx on Core + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetCurrentConsoleFontEx(NakedWin32Handle consoleOutput, bool bMaximumWindow, ref CONSOLE_FONT_INFO_EX consoleFontInfo); + + [DllImport(PinvokeDllNames.GetConsoleCursorInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetConsoleCursorInfo(NakedWin32Handle consoleOutput, out CONSOLE_CURSOR_INFO consoleCursorInfo); + + [DllImport(PinvokeDllNames.SetConsoleCursorInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetConsoleCursorInfo(NakedWin32Handle consoleOutput, ref CONSOLE_CURSOR_INFO consoleCursorInfo); + + [DllImport(PinvokeDllNames.ReadConsoleInputDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ReadConsoleInput + ( + NakedWin32Handle consoleInput, + [Out] INPUT_RECORD[] buffer, + DWORD length, + out DWORD numberOfEventsRead + ); + + internal enum CHAR_INFO_Attributes : uint + { + COMMON_LVB_LEADING_BYTE = 0x0100, + COMMON_LVB_TRAILING_BYTE = 0x0200 + } + } + + [TraceSourceAttribute("ConsoleControl", "Console control methods")] + private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleControl", "Console control methods"); +#endif + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs new file mode 100644 index 0000000000000000000000000000000000000000..daf69d5025165918a8032e592701dd7e10e2c369 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -0,0 +1,3107 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Configuration; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Management.Automation.Remoting; +using System.Management.Automation.Remoting.Server; +using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; +using System.Management.Automation.Subsystem.Feedback; +using System.Management.Automation.Tracing; +using System.Reflection; +using System.Runtime; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.PowerShell.Commands; +using Microsoft.PowerShell.Telemetry; +#if LEGACYTELEMETRY +using Microsoft.PowerShell.Telemetry.Internal; +#endif +using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle; +using Dbg = System.Management.Automation.Diagnostics; +using Debugger = System.Management.Automation.Debugger; + +namespace Microsoft.PowerShell +{ + /// + /// Subclasses S.M.A.Host to implement a console-mode monad host. + /// + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] + internal sealed partial class ConsoleHost + : + PSHost, + IDisposable, +#if LEGACYTELEMETRY + IHostProvidesTelemetryData, +#endif + IHostSupportsInteractiveSession + { + #region static methods + + internal const int ExitCodeSuccess = 0; + internal const int ExitCodeCtrlBreak = 128 + 21; // SIGBREAK + internal const int ExitCodeInitFailure = 70; // Internal Software Error + internal const int ExitCodeBadCommandLineParameter = 64; // Command Line Usage Error +#if UNIX + internal const string DECCKM_ON = "\x1b[?1h"; + internal const string DECCKM_OFF = "\x1b[?1l"; +#endif + + /// + /// Internal Entry point in msh console host implementation. + /// + /// + /// Banner text to be displayed by ConsoleHost + /// + /// + /// Help text for minishell. This is displayed on 'minishell -?'. + /// + /// + /// True when an external caller provides an InitialSessionState object, which can conflict with '-ConfigurationFile' argument. + /// + /// + /// The exit code for the shell. + /// + /// The behavior here is related to monitor work. + /// The low word of the exit code is available for the user. The high word is reserved for the shell and monitor. + /// + /// The shell process needs to return: + /// + /// - if the shell.exe fails init, 0xFFFF0000 + /// - if the exit keyword is called with no parameter at the point of top-level prompt, 0x80000000 (e.g. 0 with the high + /// bit set) + /// - if the exit keyword is called with any int param less than or equal to 0xFFFF, then that int masked with the high + /// bit set. e.g. "exit 3" results in 0x80000003 + /// - if the script ends (in the case of msh -command or msh -commandfile), then 0x80000000. + /// - if ctrl-break is pressed, with 0xFFFE0000 + /// - if the shell.exe is passed a bad command-line parameter, with 0xFFFD0000. + /// - if the shell.exe crashes, with 0x00000000 + /// + /// The monitor process gets the exit code. If the high bit is set, then the shell process exited normally (though + /// possibly due to an error). If not, the shell process crashed. If the shell.exe exit code is x00000000 (crashed) + /// or 0xFFFE0000 (user hit ctrl-break), the monitor should restart the shell.exe. Otherwise, the monitor should exit + /// with the same exit code as the shell.exe. + /// + /// Anyone checking the exit code of the shell or monitor can mask off the high word to determine the exit code passed + /// by the script that the shell last executed. + /// + internal static int Start( + string bannerText, + string helpText, + bool issProvidedExternally) + { +#if DEBUG + if (Environment.GetEnvironmentVariable("POWERSHELL_DEBUG_STARTUP") != null) + { + while (!System.Diagnostics.Debugger.IsAttached) + { + Thread.Sleep(1000); + } + } +#endif + + // Check for external InitialSessionState configuration conflict with '-ConfigurationFile' argument. + if (issProvidedExternally && !string.IsNullOrEmpty(s_cpp.ConfigurationFile)) + { + throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStartedWithConfigConflict); + } + + // Put PSHOME in front of PATH so that calling `pwsh` within `pwsh` always starts the same running version. + string path = Environment.GetEnvironmentVariable("PATH"); + string pshome = Utils.DefaultPowerShellAppBase; + string dotnetToolsPathSegment = $"{Path.DirectorySeparatorChar}.store{Path.DirectorySeparatorChar}powershell{Path.DirectorySeparatorChar}"; + + int index = pshome.IndexOf(dotnetToolsPathSegment, StringComparison.Ordinal); + if (index > 0) + { + // We're running PowerShell global tool. In this case the real entry executable should be the 'pwsh' + // or 'pwsh.exe' within the tool folder which should be the path right before the '\.store', not what + // PSHome is pointing to. + pshome = pshome[0..index]; + } + + pshome += Path.PathSeparator; + + // To not impact startup perf, we don't remove duplicates, but we avoid adding a duplicate to the front + // we also don't handle the edge case where PATH only contains $PSHOME + if (string.IsNullOrEmpty(path)) + { + Environment.SetEnvironmentVariable("PATH", pshome); + } + else if (!path.StartsWith(pshome, StringComparison.Ordinal)) + { + Environment.SetEnvironmentVariable("PATH", pshome + path); + } + + try + { + string profileDir = Platform.CacheDirectory; + if (!string.IsNullOrEmpty(profileDir)) + { +#if !UNIX + if (!Directory.Exists(profileDir)) + { + Directory.CreateDirectory(profileDir); + } +#endif + ProfileOptimization.SetProfileRoot(profileDir); + } + } + catch + { + // It's safe to ignore errors, the guarded code is just there to try and + // improve startup performance. + } + + uint exitCode = ExitCodeSuccess; + + Thread.CurrentThread.Name = "ConsoleHost main thread"; + + try + { + // We might be able to ignore console host creation error if we are running in + // server mode, which does not require a console. + HostException hostException = null; + try + { + s_theConsoleHost = ConsoleHost.CreateSingletonInstance(); + } + catch (HostException e) + { + hostException = e; + } + + PSHostUserInterface hostUI = s_theConsoleHost?.UI ?? new NullHostUserInterface(); + s_cpp.ShowErrorHelpBanner(hostUI, bannerText, helpText); + + if (s_cpp.ShowVersion) + { + // Alternatively, we could call s_theConsoleHost.UI.WriteLine(s_theConsoleHost.Version.ToString()); + // or start up the engine and retrieve the information via $psversiontable.GitCommitId + // but this returns the semantic version and avoids executing a script + s_theConsoleHost.UI.WriteLine($"PowerShell {PSVersionInfo.GitCommitId}"); + return 0; + } + + // Servermode parameter validation check. + int serverModeCount = 0; + if (s_cpp.ServerMode) + { + serverModeCount++; + } + if (s_cpp.NamedPipeServerMode) + { + serverModeCount++; + } + if (s_cpp.SocketServerMode) + { + serverModeCount++; + } +#if !UNIX + if (s_cpp.V2SocketServerMode) + { + serverModeCount++; + } +#endif + if (serverModeCount > 1) + { + s_tracer.TraceError("Conflicting server mode parameters, parameters must be used exclusively."); + s_theConsoleHost?.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); + + return ExitCodeBadCommandLineParameter; + } + +#if !UNIX + TaskbarJumpList.CreateRunAsAdministratorJumpList(); +#endif + // First check for and handle PowerShell running in a server mode. + if (s_cpp.ServerMode) + { + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("ServerMode", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-ServerMode"); + StdIOProcessMediator.Run( + initialCommand: s_cpp.InitialCommand, + workingDirectory: s_cpp.WorkingDirectory, + configurationName: null, + configurationFile: s_cpp.ConfigurationFile, + combineErrOutStream: false); + exitCode = 0; + } + else if (s_cpp.SSHServerMode) + { + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SSHServer", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-SSHServerMode"); + StdIOProcessMediator.Run( + initialCommand: s_cpp.InitialCommand, + workingDirectory: null, + configurationName: null, + configurationFile: s_cpp.ConfigurationFile, + combineErrOutStream: true); + exitCode = 0; + } + else if (s_cpp.NamedPipeServerMode) + { + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("NamedPipe", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-NamedPipeServerMode"); + RemoteSessionNamedPipeServer.RunServerMode( + configurationName: s_cpp.ConfigurationName); + exitCode = 0; + } +#if !UNIX + else if (s_cpp.V2SocketServerMode) + { + if (s_cpp.Token == null) + { + s_tracer.TraceError("Token is required for V2SocketServerMode."); + s_theConsoleHost?.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, ConsoleHostStrings.MissingMandatoryParameter, "-Token", "-V2SocketServerMode")); + return ExitCodeBadCommandLineParameter; + } + + if (s_cpp.UTCTimestamp == null) + { + s_tracer.TraceError("UTCTimestamp is required for V2SocketServerMode."); + s_theConsoleHost?.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, ConsoleHostStrings.MissingMandatoryParameter, "-UTCTimestamp", "-v2socketservermode")); + return ExitCodeBadCommandLineParameter; + } + + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("V2SocketServerMode", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-V2SocketServerMode"); + HyperVSocketMediator.Run( + initialCommand: s_cpp.InitialCommand, + configurationName: s_cpp.ConfigurationName, + token: s_cpp.Token, + tokenCreationTime: s_cpp.UTCTimestamp.Value); + + exitCode = 0; + } +#endif + else if (s_cpp.SocketServerMode) + { + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SocketServerMode", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-SocketServerMode"); + HyperVSocketMediator.Run( + initialCommand: s_cpp.InitialCommand, + configurationName: s_cpp.ConfigurationName); + exitCode = 0; + } + else + { + // Run PowerShell in normal console mode. + if (hostException != null) + { + // Unable to create console host. + throw hostException; + } + + if (LoadPSReadline()) + { + ProfileOptimization.StartProfile("StartupProfileData-Interactive"); + + if (UpdatesNotification.CanNotifyUpdates) + { + // Start a task in the background to check for the update release. + _ = UpdatesNotification.CheckForUpdates(); + } + } + else + { + ProfileOptimization.StartProfile("StartupProfileData-NonInteractive"); + } + + s_theConsoleHost.BindBreakHandler(); + IsStdOutputRedirected = Console.IsOutputRedirected; + + // Send startup telemetry for ConsoleHost startup + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("Normal", s_cpp.ParametersUsedAsDouble); + + exitCode = s_theConsoleHost.Run(s_cpp, false); + } + } + finally + { +#pragma warning disable IDE0031 + if (s_theConsoleHost != null) + { +#if LEGACYTELEMETRY + TelemetryAPI.ReportExitTelemetry(s_theConsoleHost); +#endif +#if UNIX + if (s_theConsoleHost.IsInteractive && s_theConsoleHost.UI.SupportsVirtualTerminal) + { + // https://github.com/dotnet/runtime/issues/27626 leaves terminal in application mode + // for now, we explicitly emit DECRST 1 sequence + s_theConsoleHost.UI.Write(DECCKM_OFF); + } +#endif + s_theConsoleHost.Dispose(); + } +#pragma warning restore IDE0031 + } + + unchecked + { + return (int)exitCode; + } + } + + internal static void ParseCommandLine(string[] args) + { + s_cpp.Parse(args); + +#if !UNIX + if (s_cpp.WindowStyle.HasValue) + { + ConsoleControl.SetConsoleMode(s_cpp.WindowStyle.Value); + } +#endif + + if (s_cpp.SettingsFile is not null) + { + PowerShellConfig.Instance.SetSystemConfigFilePath(s_cpp.SettingsFile); + } + + // Check registry setting for a Group Policy ConfigurationName entry, + // and use it to override anything set by the user on the command line. + // It depends on setting file so 'SetSystemConfigFilePath()' should be called before. + s_cpp.ConfigurationName = CommandLineParameterParser.GetConfigurationNameFromGroupPolicy(); + } + + private static readonly CommandLineParameterParser s_cpp = new CommandLineParameterParser(); + +#if UNIX + /// + /// The break handler for the program. Dispatches a break event to the current Executor. + /// + private static void MyBreakHandler(object sender, ConsoleCancelEventArgs args) + { + // Set the Cancel property to true to prevent the process from terminating. + args.Cancel = true; + switch (args.SpecialKey) + { + case ConsoleSpecialKey.ControlC: + SpinUpBreakHandlerThread(shouldEndSession: false); + return; + case ConsoleSpecialKey.ControlBreak: + if (s_cpp.NonInteractive) + { + // ControlBreak mimics ControlC in Noninteractive shells + SpinUpBreakHandlerThread(shouldEndSession: true); + } + else + { + // Break into script debugger. + BreakIntoDebugger(); + } + + return; + } + } +#else + /// + /// The break handler for the program. Dispatches a break event to the current Executor. + /// + /// + /// + private static bool MyBreakHandler(ConsoleControl.ConsoleBreakSignal signal) + { + switch (signal) + { + case ConsoleControl.ConsoleBreakSignal.CtrlBreak: + if (s_cpp.NonInteractive) + { + // ControlBreak mimics ControlC in Noninteractive shells + SpinUpBreakHandlerThread(shouldEndSession: true); + } + else + { + // Break into script debugger. + BreakIntoDebugger(); + } + + return true; + + // Run the break handler... + case ConsoleControl.ConsoleBreakSignal.CtrlC: + SpinUpBreakHandlerThread(shouldEndSession: false); + return true; + + case ConsoleControl.ConsoleBreakSignal.Logoff: + // Just ignore the logoff signal. This signal is sent to console + // apps running as service anytime *any* user logs off which means + // that PowerShell couldn't be used in services/tasks if we didn't + // suppress this signal... + return true; + + case ConsoleControl.ConsoleBreakSignal.Close: + case ConsoleControl.ConsoleBreakSignal.Shutdown: + SpinUpBreakHandlerThread(shouldEndSession: true); + return false; + + default: + // Log as much sqm data as possible before we exit. + SpinUpBreakHandlerThread(shouldEndSession: true); + return false; + } + } +#endif + + private static bool BreakIntoDebugger() + { + ConsoleHost host = ConsoleHost.SingletonInstance; + Debugger debugger = null; + lock (host.hostGlobalLock) + { + if (host._runspaceRef.Runspace != null && + host._runspaceRef.Runspace.GetCurrentlyRunningPipeline() != null) + { + debugger = host._runspaceRef.Runspace.Debugger; + } + } + + if (debugger != null) + { + debugger.SetDebuggerStepMode(true); + return true; + } + + return false; + } + + /// + /// Spin up a new thread to cancel the current pipeline. This will allow subsequent break interrupts to be received even + /// if the cancellation is blocked (which can be the case when the pipeline blocks and nothing implements Cmdlet.Stop + /// properly). That is because the OS will not inject another thread when a break event occurs if one has already been + /// injected and is running. + /// + /// + /// if true, then flag the parent ConsoleHost that it should shutdown the session. If false, then only the current + /// executing instance is stopped. + /// + /// + private static void SpinUpBreakHandlerThread(bool shouldEndSession) + { + ConsoleHost host = ConsoleHost.SingletonInstance; + + Thread bht = null; + + lock (host.hostGlobalLock) + { + bht = host._breakHandlerThread; + if (!host.ShouldEndSession && shouldEndSession) + { + host.ShouldEndSession = shouldEndSession; + } + + // Creation of the thread and starting it should be an atomic operation. + // otherwise the code in Run method can get instance of the breakhandlerThread + // after it is created and before started and call join on it. This will result + // in ThreadStateException. + // NTRAID#Windows OutofBand Bugs-938289-2006/07/27-hiteshr + if (bht == null) + { + // we're not already running HandleBreak on a separate thread, so run it now. + + host._breakHandlerThread = new Thread(new ThreadStart(ConsoleHost.HandleBreak)); + host._breakHandlerThread.Name = "ConsoleHost.HandleBreak"; + host._breakHandlerThread.Start(); + } + } + } + + private static void HandleBreak() + { + ConsoleHost consoleHost = s_theConsoleHost; + if (consoleHost != null) + { + if (consoleHost.InDebugMode) + { + // Only stop a running user command, ignore prompt evaluation. + if (consoleHost.DebuggerCanStopCommand) + { + // Cancel any executing debugger command if in debug mode. + try + { + consoleHost.Runspace.Debugger.StopProcessCommand(); + } + catch (Exception) + { + } + } + } + else + { + // Cancel the reconnected debugged running pipeline command. + if (!StopPipeline(consoleHost.runningCmd)) + { + Executor.CancelCurrentExecutor(); + } + } + + if (consoleHost.ShouldEndSession) + { + var runspaceRef = ConsoleHost.SingletonInstance._runspaceRef; + if (runspaceRef != null) + { + var runspace = runspaceRef.Runspace; + runspace?.Close(); + } + } + } + + // call the console APIs directly, instead of ui.rawui.FlushInputHandle, as ui may be finalized + // already if this thread is lagging behind the main thread. + +#if !UNIX + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); + ConsoleControl.FlushConsoleInputBuffer(handle); +#endif + + ConsoleHost.SingletonInstance._breakHandlerThread = null; + } + + private static bool StopPipeline(Pipeline cmd) + { + if (cmd != null && + (cmd.PipelineStateInfo.State == PipelineState.Running || + cmd.PipelineStateInfo.State == PipelineState.Disconnected)) + { + try + { + cmd.StopAsync(); + return true; + } + catch (Exception) + { + } + } + + return false; + } + + /// + /// Create single instance of ConsoleHost. + /// + internal static ConsoleHost CreateSingletonInstance() + { + Dbg.Assert(s_theConsoleHost == null, "CreateSingletonInstance should not be called multiple times"); + s_theConsoleHost = new ConsoleHost(); + return s_theConsoleHost; + } + + internal static ConsoleHost SingletonInstance + { + get + { + Dbg.Assert(s_theConsoleHost != null, "CreateSingletonInstance should be called before calling this method"); + return s_theConsoleHost; + } + } + + #endregion static methods + + #region overrides + + /// + /// See base class. + /// + /// + /// + public override string Name + { + get + { + const string myName = "ConsoleHost"; + + // const, no lock needed. + return myName; + } + } + + /// + /// See base class. + /// + /// + /// + public override System.Version Version + { + get + { + // const, no lock needed. + return _ver; + } + } + + /// + /// See base class. + /// + /// + /// + public override System.Guid InstanceId { get; } = Guid.NewGuid(); + + /// + /// See base class. + /// + /// + /// + public override PSHostUserInterface UI + { + get + { + Dbg.Assert(ui != null, "ui should have been allocated in ctor"); + return ui; + } + } + + /// + /// See base class. + /// + public void PushRunspace(Runspace runspace) + { + if (_runspaceRef == null) + { + return; + } + + if (runspace is not RemoteRunspace remoteRunspace) + { + throw new ArgumentException(ConsoleHostStrings.PushRunspaceNotRemote, nameof(runspace)); + } + + remoteRunspace.StateChanged += HandleRemoteRunspaceStateChanged; + + // Unsubscribe the local session debugger. + if (_runspaceRef.Runspace.Debugger != null) + { + _runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; + } + + // Subscribe to debugger stop event. + if (remoteRunspace.Debugger != null) + { + remoteRunspace.Debugger.DebuggerStop += OnExecutionSuspended; + } + + // Connect a disconnected command. + this.runningCmd = EnterPSSessionCommand.ConnectRunningPipeline(remoteRunspace); + + // Push runspace. + _runspaceRef.Override(remoteRunspace, hostGlobalLock, out _isRunspacePushed); + RunspacePushed.SafeInvoke(this, EventArgs.Empty); + + if (this.runningCmd != null) + { + EnterPSSessionCommand.ContinueCommand( + remoteRunspace, + this.runningCmd, + this, + InDebugMode, + _runspaceRef.OldRunspace.ExecutionContext); + } + + this.runningCmd = null; + } + + /// + /// Handles state changed event of the remote runspace. If the remote runspace + /// gets into a broken or closed state, writes a message and pops out the + /// runspace. + /// + /// Not sure. + /// Arguments describing this event. + private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) + { + RunspaceState state = eventArgs.RunspaceStateInfo.State; + + switch (state) + { + case RunspaceState.Opening: + case RunspaceState.Opened: + { + return; + } + case RunspaceState.Closing: + case RunspaceState.Closed: + case RunspaceState.Broken: + case RunspaceState.Disconnected: + { + PopRunspace(); + } + + break; + } + } + + /// + /// See base class. + /// + public void PopRunspace() + { + if (_runspaceRef == null || + !_runspaceRef.IsRunspaceOverridden) + { + return; + } + + if (_inPushedConfiguredSession) + { + // For configured endpoint sessions, end session when configured runspace is popped. + this.ShouldEndSession = true; + } + + if (_runspaceRef.Runspace.Debugger != null) + { + // Unsubscribe pushed runspace debugger. + _runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; + + StopPipeline(this.runningCmd); + + if (this.InDebugMode) + { + ExitDebugMode(DebuggerResumeAction.Continue); + } + } + + this.runningCmd = null; + + lock (hostGlobalLock) + { + _runspaceRef.Revert(); + _isRunspacePushed = false; + } + + // Re-subscribe local runspace debugger. + _runspaceRef.Runspace.Debugger.DebuggerStop += OnExecutionSuspended; + + // raise events outside the lock + RunspacePopped.SafeInvoke(this, EventArgs.Empty); + } + + /// + /// True if a runspace is pushed; false otherwise. + /// + public bool IsRunspacePushed + { + get + { + return _isRunspacePushed; + } + } + + private bool _isRunspacePushed = false; + + /// + /// Returns the current runspace associated with this host. + /// + public Runspace Runspace + { + get + { + if (this.RunspaceRef == null) + { + return null; + } + + return this.RunspaceRef.Runspace; + } + } + + internal LocalRunspace LocalRunspace + { + get + { + if (_isRunspacePushed) + { + return RunspaceRef.OldRunspace as LocalRunspace; + } + + if (RunspaceRef == null) + { + return null; + } + + return RunspaceRef.Runspace as LocalRunspace; + } + } + + public class ConsoleColorProxy + { + private readonly ConsoleHostUserInterface _ui; + + public ConsoleColorProxy(ConsoleHostUserInterface ui) + { + ArgumentNullException.ThrowIfNull(ui); + _ui = ui; + } + + public ConsoleColor FormatAccentColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.FormatAccentColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.FormatAccentColor = value; + } + } + + public ConsoleColor ErrorAccentColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.ErrorAccentColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.ErrorAccentColor = value; + } + } + + public ConsoleColor ErrorForegroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.ErrorForegroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.ErrorForegroundColor = value; + } + } + + public ConsoleColor ErrorBackgroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.ErrorBackgroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.ErrorBackgroundColor = value; + } + } + + public ConsoleColor WarningForegroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.WarningForegroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.WarningForegroundColor = value; + } + } + + public ConsoleColor WarningBackgroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.WarningBackgroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.WarningBackgroundColor = value; + } + } + + public ConsoleColor DebugForegroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.DebugForegroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.DebugForegroundColor = value; + } + } + + public ConsoleColor DebugBackgroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.DebugBackgroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.DebugBackgroundColor = value; + } + } + + public ConsoleColor VerboseForegroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.VerboseForegroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.VerboseForegroundColor = value; + } + } + + public ConsoleColor VerboseBackgroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.VerboseBackgroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.VerboseBackgroundColor = value; + } + } + + public ConsoleColor ProgressForegroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.ProgressForegroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.ProgressForegroundColor = value; + } + } + + public ConsoleColor ProgressBackgroundColor + { + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + get + { + return _ui.ProgressBackgroundColor; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + set + { + _ui.ProgressBackgroundColor = value; + } + } + } + + /// + /// Return the actual console host object so that the user can get at + /// the unproxied methods. + /// + public override PSObject PrivateData + { + get + { + if (ui == null) + { + return null; + } + + return _consoleColorProxy ??= PSObject.AsPSObject(new ConsoleColorProxy(ui)); + } + } + + private PSObject _consoleColorProxy; + + /// + /// See base class. + /// + /// + /// + public override System.Globalization.CultureInfo CurrentCulture + { + get + { + lock (hostGlobalLock) + { + return CultureInfo.CurrentCulture; + } + } + } + + /// + /// See base class. + /// + /// + /// + public override System.Globalization.CultureInfo CurrentUICulture + { + get + { + lock (hostGlobalLock) + { + return CultureInfo.CurrentUICulture; + } + } + } + + /// + /// + /// + public override void SetShouldExit(int exitCode) + { + lock (hostGlobalLock) + { + // Check for the pushed runspace scenario. + if (this.IsRunspacePushed) + { + this.PopRunspace(); + } + else if (InDebugMode) + { + ExitDebugMode(DebuggerResumeAction.Continue); + } + else + { + _setShouldExitCalled = true; + _exitCodeFromRunspace = exitCode; + ShouldEndSession = true; + } + } + } + + /// + /// If an input loop is running, then starts a new, nested input loop. If an input loop is not running, + /// throws an exception. + /// + /// + /// If a nested prompt is entered while the host is not running at least one prompt loop. + /// + public override void EnterNestedPrompt() + { + // save the old Executor, then clear it so that a break does not cancel the pipeline from which this method + // might be called. + + Executor oldCurrent = Executor.CurrentExecutor; + + try + { + // this assignment is threadsafe -- protected in CurrentExecutor property + + Executor.CurrentExecutor = null; + lock (hostGlobalLock) + { + IsNested = oldCurrent != null || this.ui.IsCommandCompletionRunning; + } + + InputLoop.RunNewInputLoop(this, IsNested); + } + finally + { + Executor.CurrentExecutor = oldCurrent; + } + } + + /// + /// See base class. + /// + /// + /// If there is no nested prompt. + /// + public override void ExitNestedPrompt() + { + lock (hostGlobalLock) + { + IsNested = InputLoop.ExitCurrentLoop(); + } + } + + /// + /// See base class. + /// + public override void NotifyBeginApplication() + { + lock (hostGlobalLock) + { + if (++_beginApplicationNotifyCount == 1) + { + // Save the window title when first notified. + _savedWindowTitle = ui.RawUI.WindowTitle; +#if !UNIX + if (_initialConsoleMode != ConsoleControl.ConsoleModes.Unknown) + { + var outputHandle = ConsoleControl.GetActiveScreenBufferHandle(); + _savedConsoleMode = ConsoleControl.GetMode(outputHandle); + ConsoleControl.SetMode(outputHandle, _initialConsoleMode); + } +#endif + } + } + } + + /// + /// See base class + /// + /// + public override void NotifyEndApplication() + { + lock (hostGlobalLock) + { + if (--_beginApplicationNotifyCount == 0) + { + // Restore the window title when the last application started has ended. + ui.RawUI.WindowTitle = _savedWindowTitle; +#if !UNIX + if (_savedConsoleMode != ConsoleControl.ConsoleModes.Unknown) + { + ConsoleControl.SetMode(ConsoleControl.GetActiveScreenBufferHandle(), _savedConsoleMode); + if (_savedConsoleMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal)) + { + // If the console output mode we just set already has 'VirtualTerminal' turned on, + // we don't need to try turn on the VT mode separately. + return; + } + } + + if (ui.SupportsVirtualTerminal) + { + // Re-enable VT mode if it was previously enabled, as a native command may have turned it off. + ui.TryTurnOnVirtualTerminal(); + } +#endif + } + } + } + +#if LEGACYTELEMETRY + bool IHostProvidesTelemetryData.HostIsInteractive + { + get + { + return !s_cpp.NonInteractive && !s_cpp.AbortStartup && + ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit); + } + } + + double IHostProvidesTelemetryData.ProfileLoadTimeInMS { get { return _profileLoadTimeInMS; } } + + double IHostProvidesTelemetryData.ReadyForInputTimeInMS { get { return _readyForInputTimeInMS; } } + + int IHostProvidesTelemetryData.InteractiveCommandCount { get { return _interactiveCommandCount; } } + + private double _readyForInputTimeInMS; + private int _interactiveCommandCount; +#endif + + private double _profileLoadTimeInMS; + + #endregion overrides + + #region non-overrides + + /// + /// Constructs a new instance. + /// + internal ConsoleHost() + { +#if !UNIX + try + { + // Capture the initial console mode before constructing our ui - that constructor + // will change the console mode to turn on VT100 support. + _initialConsoleMode = ConsoleControl.GetMode(ConsoleControl.GetActiveScreenBufferHandle()); + } + catch (Exception) + { + // Make sure we skip setting the console mode later. + _savedConsoleMode = _initialConsoleMode = ConsoleControl.ConsoleModes.Unknown; + } +#endif + + Thread.CurrentThread.CurrentUICulture = this.CurrentUICulture; + Thread.CurrentThread.CurrentCulture = this.CurrentCulture; + // BUG: 610329. Tell PowerShell engine to apply console + // related properties while launching Pipeline Execution + // Thread. + base.ShouldSetThreadUILanguageToZero = true; + + InDebugMode = false; + _displayDebuggerBanner = true; + + this.ui = new ConsoleHostUserInterface(this); + _consoleWriter = new ConsoleTextWriter(ui); + + UnhandledExceptionEventHandler handler = new UnhandledExceptionEventHandler(UnhandledExceptionHandler); + AppDomain.CurrentDomain.UnhandledException += handler; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Accesses instance members in preprocessor branch.")] + private void BindBreakHandler() + { +#if UNIX + Console.CancelKeyPress += new ConsoleCancelEventHandler(MyBreakHandler); +#else + breakHandlerGcHandle = GCHandle.Alloc(new ConsoleControl.BreakHandler(MyBreakHandler)); + ConsoleControl.AddBreakHandler((ConsoleControl.BreakHandler)breakHandlerGcHandle.Target); +#endif + } + + private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) + { + // FYI: sender is a reference to the source app domain + + // The CLR will shut down the app as soon as this handler is complete, but just in case, we want + // to exit at our next opportunity. + + _shouldEndSession = true; + + Exception e = null; + + if (args != null) + { + e = (Exception)args.ExceptionObject; + } + + ui.WriteLine(); + ui.Write( + ConsoleColor.Red, + ui.RawUI.BackgroundColor, + ConsoleHostStrings.UnhandledExceptionShutdownMessage); + ui.WriteLine(); + } + + /// + /// Disposes of this instance, per the IDisposable pattern. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool isDisposingNotFinalizing) + { + if (!_isDisposed) + { +#if !UNIX + ConsoleControl.RemoveBreakHandler(); + if (breakHandlerGcHandle.IsAllocated) + { + breakHandlerGcHandle.Free(); + } +#endif + + if (isDisposingNotFinalizing) + { + if (IsTranscribing) + { + StopTranscribing(); + } + + _outputSerializer?.End(); + _errorSerializer?.End(); + + if (_runspaceRef != null) + { + // NTRAID#Windows Out Of Band Releases-925297-2005/12/14 + try + { + _runspaceRef.Runspace.Dispose(); + } + catch (InvalidRunspaceStateException) + { + } + } + + _runspaceRef = null; + ui = null; + } + } + + _isDisposed = true; + } + + /// + /// Finalizes an instance of the class. + /// + ~ConsoleHost() + { + Dispose(false); + } + + /// + /// Indicates if the session should be terminated or not. Typically set by the break handler for Close, Logoff, and + /// Shutdown events. Note that the only valid transition for this property is from false to true: it is not legal to + /// try to set it to false after is was set to true. + /// + /// + /// true to shut down the session. false is only allowed if the property is already false. + /// + internal bool ShouldEndSession + { + // This might get called from the main thread, or from the pipeline thread, or from a break handler thread. + get + { + bool result = false; + + lock (hostGlobalLock) + { + result = _shouldEndSession; + } + + return result; + } + + set + { + lock (hostGlobalLock) + { + // If ShouldEndSession is already true, you can't set it back + + Dbg.Assert(!_shouldEndSession || value, + "ShouldEndSession can only be set from false to true"); + + _shouldEndSession = value; + } + } + } + + /// + /// The Runspace ref object being used by this Host instance. A host only opens one Runspace. + /// + /// + internal RunspaceRef RunspaceRef + { + get + { + return _runspaceRef; + } + } + + internal WrappedSerializer.DataFormat OutputFormat { get; private set; } + + internal bool OutputFormatSpecified { get; private set; } + + internal WrappedSerializer.DataFormat InputFormat { get; private set; } + + internal WrappedDeserializer.DataFormat ErrorFormat + { + get + { + WrappedDeserializer.DataFormat format = OutputFormat; + + // If this shell is invoked in non-interactive, error is redirected, and OutputFormat was not + // specified write data in error stream in xml format assuming PowerShell->PowerShell usage. + if (!OutputFormatSpecified && !IsInteractive && Console.IsErrorRedirected && _wasInitialCommandEncoded) + { + format = Serialization.DataFormat.XML; + } + + return format; + } + } + + internal bool IsRunningAsync + { + get + { + return !IsInteractive && ((OutputFormat != Serialization.DataFormat.Text) || Console.IsInputRedirected); + } + } + + internal bool IsNested { get; private set; } + + internal WrappedSerializer OutputSerializer + { + get + { + _outputSerializer ??= + new WrappedSerializer( + OutputFormat, + "Output", + Console.IsOutputRedirected ? Console.Out : ConsoleTextWriter); + + return _outputSerializer; + } + } + + internal WrappedSerializer ErrorSerializer + { + get + { + _errorSerializer ??= + new WrappedSerializer( + ErrorFormat, + "Error", + Console.IsErrorRedirected ? Console.Error : ConsoleTextWriter); + + return _errorSerializer; + } + } + + internal bool IsInteractive + { + get + { + // we're running interactive if we're in a prompt loop, and we're not reading keyboard input from stdin. + + return _isRunningPromptLoop && !ui.ReadFromStdin; + } + } + + internal TextWriter ConsoleTextWriter + { + get + { + Dbg.Assert(_consoleWriter != null, "consoleWriter should have been initialized"); + return _consoleWriter; + } + } + + /// + /// The main run loop of the program: processes command line parameters, and starts up a runspace. + /// + /// + /// Commandline parameter parser. The commandline parameter parser is expected to parse all the + /// arguments before calling this method. + /// + /// + /// Is there any warning at startup + /// + /// + /// The process exit code to be returned by Main. + /// + private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned) + { + Dbg.Assert(cpp != null, "CommandLine parameter parser cannot be null."); + uint exitCode = ExitCodeSuccess; + + do + { + s_runspaceInitTracer.WriteLine("starting parse of command line parameters"); + + exitCode = ExitCodeSuccess; + if (!string.IsNullOrEmpty(cpp.InitialCommand) && isPrestartWarned) + { + s_tracer.TraceError("Start up warnings made command \"{0}\" not executed", cpp.InitialCommand); + string msg = StringUtil.Format(ConsoleHostStrings.InitialCommandNotExecuted, cpp.InitialCommand); + ui.WriteErrorLine(msg); + exitCode = ExitCodeInitFailure; + break; + } + + if (cpp.AbortStartup) + { + s_tracer.WriteLine("processing of cmdline args failed, exiting"); + exitCode = cpp.ExitCode; + break; + } + + OutputFormat = cpp.OutputFormat; + OutputFormatSpecified = cpp.OutputFormatSpecified; + InputFormat = cpp.InputFormat; + _wasInitialCommandEncoded = cpp.WasInitialCommandEncoded; + + ui.ReadFromStdin = cpp.ExplicitReadCommandsFromStdin || Console.IsInputRedirected; + ui.NoPrompt = cpp.NoPrompt; + ui.ThrowOnReadAndPrompt = cpp.ThrowOnReadAndPrompt; + _noExit = cpp.NoExit; + +#if !UNIX + // See if we need to change the process-wide execution + // policy + if (!string.IsNullOrEmpty(cpp.ExecutionPolicy)) + { + ExecutionPolicy executionPolicy = SecuritySupport.ParseExecutionPolicy(cpp.ExecutionPolicy); + SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, executionPolicy, null); + } +#endif + + // If the debug pipe name was specified, create the custom IPC channel. + if (!string.IsNullOrEmpty(cpp.CustomPipeName)) + { + RemoteSessionNamedPipeServer.CreateCustomNamedPipeServer(cpp.CustomPipeName); + } + + // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 + // Removed HandleUnexpectedExceptions infrastructure + exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, cpp.StaMode, cpp.ConfigurationName, cpp.ConfigurationFile); + } + while (false); + + return exitCode; + } + + /// + /// Loops over the Host's sole Runspace; opens the runspace, initializes it, then recycles it if the Runspace fails. + /// + /// + /// The process exit code to be returned by Main. + /// + private uint DoRunspaceLoop( + string initialCommand, + bool skipProfiles, + Collection initialCommandArgs, + bool staMode, + string configurationName, + string configurationFilePath) + { + ExitCode = ExitCodeSuccess; + + while (!ShouldEndSession) + { + RunspaceCreationEventArgs args = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, configurationName, configurationFilePath, initialCommandArgs); + CreateRunspace(args); + + if (ExitCode == ExitCodeInitFailure) + { + break; + } + + if (!_noExit) + { + // Wait for runspace to open, init, and run init script before + // setting ShouldEndSession, to allow debugger to work. + ShouldEndSession = true; + } + else + { + // Start nested prompt loop. + EnterNestedPrompt(); + } + + if (_setShouldExitCalled) + { + ExitCode = unchecked((uint)_exitCodeFromRunspace); + } + else + { + Executor exec = new Executor(this, false, false); + + bool dollarHook = exec.ExecuteCommandAndGetResultAsBool("$global:?") ?? false; + + if (dollarHook && (_lastRunspaceInitializationException == null)) + { + ExitCode = ExitCodeSuccess; + } + else + { + ExitCode = ExitCodeSuccess | 0x1; + } + } + + _runspaceRef.Runspace.Close(); + _runspaceRef = null; + + if (staMode) + { + // don't continue the session in STA mode + ShouldEndSession = true; + } + } + + return ExitCode; + } + + private Exception InitializeRunspaceHelper(string command, Executor exec, Executor.ExecutionOptions options) + { + Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); + Dbg.Assert(exec != null, "non-null Executor instance needed"); + + s_runspaceInitTracer.WriteLine("running command {0}", command); + + Exception e = null; + + if (IsRunningAsync) + { + exec.ExecuteCommandAsync(command, out e, options); + } + else + { + exec.ExecuteCommand(command, out e, options); + } + + if (e != null) + { + ReportException(e, exec); + } + + return e; + } + + private void CreateRunspace(RunspaceCreationEventArgs runspaceCreationArgs) + { + try + { + Dbg.Assert(runspaceCreationArgs != null, "Arguments to CreateRunspace should not be null."); + DoCreateRunspace(runspaceCreationArgs); + } + catch (ConsoleHostStartupException startupException) + { + ReportExceptionFallback(startupException.InnerException, startupException.Message); + ExitCode = ExitCodeInitFailure; + } + } + + private static bool LoadPSReadline() + { + // Don't load PSReadline if: + // * we don't think the process will be interactive, e.g. -command or -file + // - exception: when -noexit is specified, we will be interactive after the command/file finishes + // * -noninteractive: this should be obvious, they've asked that we don't ever prompt + // + // Note that PSReadline doesn't support redirected stdin/stdout, but we don't check that here because + // a future version might, and we should automatically load it at that unknown point in the future. + // PSReadline will ideally fall back to Console.ReadLine or whatever when stdin/stdout is redirected. + return ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit) && !s_cpp.NonInteractive; + } + + /// + /// Opens and Initializes the Host's sole Runspace. Processes the startup scripts and runs any command passed on the + /// command line. + /// + /// Runspace creation event arguments. + private void DoCreateRunspace(RunspaceCreationEventArgs args) + { + Dbg.Assert(_runspaceRef == null, "_runspaceRef field should be null"); + Dbg.Assert(DefaultInitialSessionState != null, "DefaultInitialSessionState should not be null"); + s_runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace"); + + // Use session configuration file if provided. + bool customConfigurationProvided = false; + if (!string.IsNullOrEmpty(args.ConfigurationFilePath)) + { + try + { + // Replace DefaultInitialSessionState with the initial state configuration defined by the file. + DefaultInitialSessionState = InitialSessionState.CreateFromSessionConfigurationFile( + path: args.ConfigurationFilePath, + roleVerifier: null, + validateFile: true); + } + catch (Exception ex) + { + throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, ex); + } + + customConfigurationProvided = true; + } + + try + { + Runspace consoleRunspace = null; + bool psReadlineFailed = false; + + // Load PSReadline by default unless there is no use: + // - we're running a command/file and just exiting + // - stdin is redirected by a parent process + // - we're not interactive + // - we're explicitly reading from stdin (the '-' argument) + // It's also important to have a scenario where PSReadline is not loaded so it can be updated, e.g. + // powershell -command "Update-Module PSReadline" + // This should work just fine as long as no other instances of PowerShell are running. + ReadOnlyCollection defaultImportModulesList = null; + if (!customConfigurationProvided && LoadPSReadline()) + { + // Create and open Runspace with PSReadline. + defaultImportModulesList = DefaultInitialSessionState.Modules; + DefaultInitialSessionState.ImportPSModule(new[] { "PSReadLine" }); + consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState); + try + { + OpenConsoleRunspace(consoleRunspace, args.StaMode); + } + catch (Exception) + { + consoleRunspace = null; + psReadlineFailed = true; + } + } + + if (consoleRunspace == null) + { + if (psReadlineFailed) + { + // Try again but without importing the PSReadline module. + DefaultInitialSessionState.ClearPSModules(); + DefaultInitialSessionState.ImportPSModule(defaultImportModulesList); + } + + consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState); + OpenConsoleRunspace(consoleRunspace, args.StaMode); + } + + Runspace.PrimaryRunspace = consoleRunspace; + _runspaceRef = new RunspaceRef(consoleRunspace); + + if (psReadlineFailed) + { + // Notify the user that PSReadline could not be loaded. + Console.Error.WriteLine(ConsoleHostStrings.CannotLoadPSReadline); + } + } + catch (Exception e) + { + // no need to do CheckForSevereException here + // since the ConsoleHostStartupException is uncaught + // higher in the call stack and the whole process + // will exit soon + throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, e); + } + finally + { + // Stop PerfTrack + PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStop, PSOpcode.WinStop, + PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); + } + +#if LEGACYTELEMETRY + // Record how long it took from process start to runspace open for telemetry. + _readyForInputTimeInMS = (DateTime.Now - Process.GetCurrentProcess().StartTime).TotalMilliseconds; +#endif + + DoRunspaceInitialization(args); + } + + private static void OpenConsoleRunspace(Runspace runspace, bool staMode) + { + if (staMode && Platform.IsWindowsDesktop) + { + runspace.ApartmentState = ApartmentState.STA; + } + + runspace.ThreadOptions = PSThreadOptions.ReuseThread; + runspace.EngineActivityId = EtwActivity.GetActivityId(); + + s_runspaceInitTracer.WriteLine("Calling Runspace.Open"); + runspace.Open(); + } + + private void DoRunspaceInitialization(RunspaceCreationEventArgs args) + { + if (_runspaceRef.Runspace.Debugger != null) + { + _runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); + _runspaceRef.Runspace.Debugger.DebuggerStop += this.OnExecutionSuspended; + } + + Executor exec = new Executor(this, false, false); + + // If working directory was specified, set it + if (s_cpp != null && s_cpp.WorkingDirectory != null) + { + Pipeline tempPipeline = exec.CreatePipeline(); + var command = new Command("Set-Location"); + command.Parameters.Add("LiteralPath", s_cpp.WorkingDirectory); + tempPipeline.Commands.Add(command); + + Exception exception; + if (IsRunningAsync) + { + exec.ExecuteCommandAsyncHelper(tempPipeline, out exception, Executor.ExecutionOptions.AddOutputter); + } + else + { + exec.ExecuteCommandHelper(tempPipeline, out exception, Executor.ExecutionOptions.AddOutputter); + } + + if (exception != null) + { + _lastRunspaceInitializationException = exception; + ReportException(exception, exec); + } + } + + if (!string.IsNullOrEmpty(args.ConfigurationName)) + { + // If an endpoint configuration is specified then create a loop-back remote runspace targeting + // the endpoint and push onto runspace ref stack. Ignore profile and configuration scripts. + try + { + RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(args.ConfigurationName, this); + remoteRunspace.ShouldCloseOnPop = true; + PushRunspace(remoteRunspace); + + // Ensure that session ends when configured remote runspace is popped. + _inPushedConfiguredSession = true; + } + catch (Exception e) + { + throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, e); + } + } + else + { + const string shellId = "Microsoft.PowerShell"; + + // If the system lockdown policy says "Enforce", do so. Do this after types / formatting, default functions, etc + // are loaded so that they are trusted. (Validation of their signatures is done in F&O). + var languageMode = Utils.EnforceSystemLockDownLanguageMode(_runspaceRef.Runspace.ExecutionContext); + // When displaying banner, also display the language mode if running in any restricted mode. + if (s_cpp.ShowBanner) + { + switch (languageMode) + { + case PSLanguageMode.ConstrainedLanguage: + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLMode); + } + else + { + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLAuditMode); + } + + break; + + case PSLanguageMode.NoLanguage: + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerNLMode); + break; + + case PSLanguageMode.RestrictedLanguage: + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerRLMode); + break; + + default: + break; + } + } + + string allUsersProfile = HostUtilities.GetFullProfileFileName(null, false); + string allUsersHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, false); + string currentUserProfile = HostUtilities.GetFullProfileFileName(null, true); + string currentUserHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, true); + + // $PROFILE has to be set from the host + // Should be "per-user,host-specific profile.ps1" + // This should be set even if -noprofile is specified + _runspaceRef.Runspace.SessionStateProxy.SetVariable("PROFILE", + HostUtilities.GetDollarProfile( + allUsersProfile, + allUsersHostSpecificProfile, + currentUserProfile, + currentUserHostSpecificProfile)); + + if (!args.SkipProfiles) + { + // Run the profiles. + // Profiles are run in the following order: + // 1. host independent profile meant for all users + // 2. host specific profile meant for all users + // 3. host independent profile of the current user + // 4. host specific profile of the current user + + var sw = new Stopwatch(); + sw.Start(); + RunProfile(allUsersProfile, exec); + RunProfile(allUsersHostSpecificProfile, exec); + RunProfile(currentUserProfile, exec); + RunProfile(currentUserHostSpecificProfile, exec); + sw.Stop(); + + var profileLoadTimeInMs = sw.ElapsedMilliseconds; + if (s_cpp.ShowBanner && !s_cpp.NoProfileLoadTime && profileLoadTimeInMs > 500) + { + Console.Error.WriteLine(ConsoleHostStrings.SlowProfileLoadingMessage, profileLoadTimeInMs); + } + + _profileLoadTimeInMS = profileLoadTimeInMs; + } + else + { + s_tracer.WriteLine("-noprofile option specified: skipping profiles"); + } + } +#if LEGACYTELEMETRY + // Startup is reported after possibly running the profile, but before running the initial command (or file) + // if one is specified. + TelemetryAPI.ReportStartupTelemetry(this); +#endif + + // If a file was specified as the argument to run, then run it... + if (s_cpp != null && s_cpp.File != null) + { + string filePath = s_cpp.File; + + s_tracer.WriteLine("running -file '{0}'", filePath); + + Pipeline tempPipeline = exec.CreatePipeline(); + Command c; +#if UNIX + // if file doesn't have .ps1 extension, we read the contents and treat it as a script to support shebang with no .ps1 extension usage + if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) + { + string script = File.ReadAllText(filePath); + c = new Command(script, isScript: true, useLocalScope: false); + } + else +#endif + { + c = new Command(filePath, false, false); + } + + tempPipeline.Commands.Add(c); + + if (args.InitialCommandArgs != null) + { + // add the args passed to the command. + + foreach (CommandParameter p in args.InitialCommandArgs) + { + c.Parameters.Add(p); + } + } + + // If we're not going to continue, then get the exit code out of the runspace and + // and indicate that it should be returned... + if (!_noExit && this.Runspace is not RemoteRunspace) + { + this.Runspace.ExecutionContext.ScriptCommandProcessorShouldRethrowExit = true; + } + + Exception e1; + + if (IsRunningAsync) + { + Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter; + + Token[] tokens; + ParseError[] errors; + + // Detect if they're using input. If so, read from it. + Ast parsedInput = Parser.ParseFile(filePath, out tokens, out errors); + if (AstSearcher.IsUsingDollarInput(parsedInput)) + { + executionOptions |= Executor.ExecutionOptions.ReadInputObjects; + + // We will consume all of the input to pass to the script, so don't try to read commands from stdin. + ui.ReadFromStdin = false; + } + + exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, executionOptions); + } + else + { + exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); + } + + // Pipeline.Invoke has thrown, that's bad. It means the script did not actually + // execute properly. These exceptions should be reflected in the exit code + if (e1 != null) + { + if (!_noExit) + { + // Set ExitCode to 0x1 + lock (hostGlobalLock) + { + _setShouldExitCalled = true; + _exitCodeFromRunspace = 0x1; + ShouldEndSession = true; + } + } + + ReportException(e1, exec); + } + } + else if (!string.IsNullOrEmpty(args.InitialCommand)) + { + // Run the command passed on the command line + + s_tracer.WriteLine("running initial command"); + + Pipeline tempPipeline = exec.CreatePipeline(args.InitialCommand, true); + + if (args.InitialCommandArgs != null) + { + // add the args passed to the command. + + foreach (CommandParameter p in args.InitialCommandArgs) + { + tempPipeline.Commands[0].Parameters.Add(p); + } + } + + Exception e1; + + if (IsRunningAsync) + { + Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter; + + Token[] tokens; + ParseError[] errors; + + // Detect if they're using input. If so, read from it. + Ast parsedInput = Parser.ParseInput(args.InitialCommand, out tokens, out errors); + if (AstSearcher.IsUsingDollarInput(parsedInput)) + { + executionOptions |= Executor.ExecutionOptions.ReadInputObjects; + + // We will consume all of the input to pass to the script, so don't try to read commands from stdin. + ui.ReadFromStdin = false; + } + + exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, executionOptions); + } + else + { + exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); + } + + if (e1 != null) + { + // Remember last exception + _lastRunspaceInitializationException = e1; + ReportException(e1, exec); + } + } + } + + private void RunProfile(string profileFileName, Executor exec) + { + if (!string.IsNullOrEmpty(profileFileName)) + { + s_runspaceInitTracer.WriteLine("checking profile" + profileFileName); + + try + { + if (File.Exists(profileFileName)) + { + InitializeRunspaceHelper( + ". '" + EscapeSingleQuotes(profileFileName) + "'", + exec, + Executor.ExecutionOptions.AddOutputter); + } + else + { + s_runspaceInitTracer.WriteLine("profile file not found"); + } + } + catch (Exception e) // Catch-all OK, 3rd party callout + { + ReportException(e, exec); + + s_runspaceInitTracer.WriteLine("Could not load profile."); + } + } + } + + /// + /// Escapes backtick and tick characters with a backtick, returns the result. + /// + /// + /// + internal static string EscapeSingleQuotes(string str) + { + // worst case we have to escape every character, so capacity is twice as large as input length + StringBuilder sb = new StringBuilder(str.Length * 2); + + for (int i = 0; i < str.Length; ++i) + { + char c = str[i]; + if (c == '\'') + { + sb.Append(c); + } + + sb.Append(c); + } + + string result = sb.ToString(); + + return result; + } + + private void WriteErrorLine(string line) + { + const ConsoleColor fg = ConsoleColor.Red; + ConsoleColor bg = UI.RawUI.BackgroundColor; + + UI.WriteLine(fg, bg, line); + } + + // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 + // Removed HandleUnexpectedExceptions infrastructure + private void ReportException(Exception e, Executor exec) + { + Dbg.Assert(e != null, "must supply an Exception"); + Dbg.Assert(exec != null, "must supply an Executor"); + + // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 + // Removed HandleUnexpectedExceptions infrastructure + + // Attempt to write the exception into the error stream so that the normal F&O machinery will + // display it according to preferences. + + object error = null; + Pipeline tempPipeline = exec.CreatePipeline(); + + // NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns + + if (e is IContainsErrorRecord icer) + { + error = icer.ErrorRecord; + } + else + { + error = (object)new ErrorRecord(e, "ConsoleHost.ReportException", ErrorCategory.NotSpecified, null); + } + + PSObject wrappedError = new PSObject(error) + { + WriteStream = WriteStreamType.Error + }; + + Exception e1 = null; + + tempPipeline.Input.Write(wrappedError); + if (IsRunningAsync) + { + exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); + } + else + { + exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); + } + + if (e1 != null) + { + // that didn't work. Write out the error ourselves as a last resort. + ReportExceptionFallback(e, null); + } + } + + /// + /// Reports an exception according to the exception reporting settings in effect. + /// + /// + /// The exception to report. + /// + /// + /// Optional header message. Empty or null means "no header" + /// + private void ReportExceptionFallback(Exception e, string header) + { + if (!string.IsNullOrEmpty(header)) + { + Console.Error.WriteLine(header); + } + + if (e is null) + { + return; + } + + // See if the exception has an error record attached to it... + ErrorRecord er = null; + if (e is IContainsErrorRecord icer) + { + er = icer.ErrorRecord; + } + + if (e is PSRemotingTransportException) + { + // For remoting errors use full fidelity error writer. + UI.WriteErrorLine(e.Message); + } + else if (e is TargetInvocationException) + { + Console.Error.WriteLine(e.InnerException.Message); + } + else + { + Console.Error.WriteLine(e.Message); + } + + // Add the position message for the error if it's available. + if (er?.InvocationInfo is { }) + { + Console.Error.WriteLine(er.InvocationInfo.PositionMessage); + } + + // Print the stack trace. + Console.Error.WriteLine($"\n--- {e.GetType().FullName} ---"); + Console.Error.WriteLine(e.StackTrace); + + Exception inner = e.InnerException; + while (inner is { }) + { + Console.Error.WriteLine($"--- inner {inner.GetType().FullName} ---"); + Console.Error.WriteLine(inner.StackTrace); + inner = inner.InnerException; + } + } + + /// + /// Raised when the host pops a runspace. + /// + internal event EventHandler RunspacePopped; + + /// + /// Raised when the host pushes a runspace. + /// + internal event EventHandler RunspacePushed; + + #endregion non-overrides + + #region debugger + + /// + /// Handler for debugger events. + /// + private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) + { + // Check local runspace internalHost to see if debugging is enabled. + LocalRunspace localrunspace = LocalRunspace; + if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) + { + return; + } + + _debuggerStopEventArgs = e; + InputLoop baseLoop = null; + + try + { + if (this.IsRunspacePushed) + { + // For remote debugging block data coming from the main (not-nested) + // running command. + baseLoop = InputLoop.GetNonNestedLoop(); + baseLoop?.BlockCommandOutput(); + } + + // + // Display the banner only once per session + // + if (_displayDebuggerBanner) + { + WriteDebuggerMessage(ConsoleHostStrings.EnteringDebugger); + WriteDebuggerMessage(string.Empty); + _displayDebuggerBanner = false; + } + + // + // If we hit a breakpoint output its info + // + if (e.Breakpoints.Count > 0) + { + string format = ConsoleHostStrings.HitBreakpoint; + + foreach (Breakpoint breakpoint in e.Breakpoints) + { + WriteDebuggerMessage(string.Format(CultureInfo.CurrentCulture, format, breakpoint)); + } + + WriteDebuggerMessage(string.Empty); + } + + // + // Write the source line + // + if (e.InvocationInfo != null) + { + // line = StringUtil.Format(ConsoleHostStrings.DebuggerSourceCodeFormat, scriptFileName, e.InvocationInfo.ScriptLineNumber, e.InvocationInfo.Line); + WriteDebuggerMessage(e.InvocationInfo.PositionMessage); + } + + // + // Start the debug mode + // + EnterDebugMode(); + } + finally + { + _debuggerStopEventArgs = null; + baseLoop?.ResumeCommandOutput(); + } + } + + /// + /// Returns true if the host is in debug mode. + /// + private bool InDebugMode { get; set; } + + /// + /// True when debugger command is user and available + /// for stopping. + /// + internal bool DebuggerCanStopCommand + { + get; + set; + } + + private Exception _lastRunspaceInitializationException = null; + internal uint ExitCode; + + /// + /// Sets the host to debug mode and enters a nested prompt. + /// + private void EnterDebugMode() + { + InDebugMode = true; + + try + { + // + // Note that we need to enter the nested prompt via the InternalHost interface. + // + + // EnterNestedPrompt must always be run on the local runspace. + Runspace runspace = _runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace; + runspace.ExecutionContext.EngineHostInterface.EnterNestedPrompt(); + } + catch (PSNotImplementedException) + { + WriteDebuggerMessage(ConsoleHostStrings.SessionDoesNotSupportDebugger); + } + finally + { + InDebugMode = false; + } + } + + /// + /// Exits the debugger's nested prompt. + /// + private void ExitDebugMode(DebuggerResumeAction resumeAction) + { + _debuggerStopEventArgs.ResumeAction = resumeAction; + + try + { + // + // Note that we need to exit the nested prompt via the InternalHost interface. + // + + // ExitNestedPrompt must always be run on the local runspace. + Runspace runspace = _runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace; + runspace.ExecutionContext.EngineHostInterface.ExitNestedPrompt(); + } + catch (ExitNestedPromptException) + { + // ignore the exception + } + } + + /// + /// Writes a line using the debugger colors. + /// + private void WriteDebuggerMessage(string line) + { + this.ui.WriteLine(this.ui.DebugForegroundColor, this.ui.DebugBackgroundColor, line); + } + + #endregion debugger + + #region aux classes + + /// + /// InputLoop represents the prompt-input-execute loop of the interactive host. Input loops can be nested, meaning that + /// one input loop can be interrupted and another started; when the second ends, the first resumes. + /// + /// Neither this class' instances nor its static data is threadsafe. Caller is responsible for ensuring threadsafe + /// access. + /// + private sealed class InputLoop + { + internal static void RunNewInputLoop(ConsoleHost parent, bool isNested) + { + // creates an instance and adds it to the stack and starts it running. + + int stackCount = s_instanceStack.Count; + + if (stackCount == PSHost.MaximumNestedPromptLevel) + { + throw PSTraceSource.NewInvalidOperationException(ConsoleHostStrings.TooManyNestedPromptsError); + } + + InputLoop il = new InputLoop(parent, isNested); + + s_instanceStack.Push(il); + il.Run(s_instanceStack.Count > 1); + + // Once the loop has finished running, remove it from the instance stack. + + InputLoop il2 = s_instanceStack.Pop(); + + Dbg.Assert(il == il2, "top of instance stack does not correspond to the instance pushed"); + } + + // Presently, this will not work if the Run loop is blocked on a ReadLine call. Whether that's a + // problem or not depends on when we expect calls to this function to be made. + /// + /// + /// True if next input loop is nested, False otherwise. + /// + /// when there is no instanceStack.Count == 0 + /// + internal static bool ExitCurrentLoop() + { + if (s_instanceStack.Count == 0) + { + throw PSTraceSource.NewInvalidOperationException(ConsoleHostStrings.InputExitCurrentLoopOutOfSyncError); + } + + InputLoop il = s_instanceStack.Peek(); + il._shouldExit = true; + + // The main (non-nested) input loop has Count == 1, + // so Count == 2 is the value that indicates the next + // popped stack input loop is non-nested. + return (s_instanceStack.Count > 2); + } + + /// + /// Returns current root (non-nested) loop only if there is no + /// nesting. This is used *only* by the debugger for remote debugging + /// where data handling on the base commands needs to be blocked + /// during remote debug stop handling. + /// + /// + internal static InputLoop GetNonNestedLoop() + { + if (s_instanceStack.Count == 1) + { + return s_instanceStack.Peek(); + } + + return null; + } + + private InputLoop(ConsoleHost parent, bool isNested) + { + _parent = parent; + _isNested = isNested; + _isRunspacePushed = parent.IsRunspacePushed; + parent.RunspacePopped += HandleRunspacePopped; + parent.RunspacePushed += HandleRunspacePushed; + _exec = new Executor(parent, isNested, false); + _promptExec = new Executor(parent, isNested, true); + } + + private void HandleRunspacePushed(object sender, EventArgs e) + { + lock (_syncObject) + { + _isRunspacePushed = true; + _runspacePopped = false; + } + } + + /// + /// When a runspace is popped, we need to reevaluate the + /// prompt. + /// + /// Sender of this event, unused. + /// Arguments describing this event, unused. + private void HandleRunspacePopped(object sender, EventArgs eventArgs) + { + lock (_syncObject) + { + _isRunspacePushed = false; + _runspacePopped = true; + } + } + + // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 + // Removed HandleUnexpectedExceptions infrastructure + /// + /// Evaluates the prompt, displays it, gets a command from the console, and executes it. Repeats until the command + /// is "exit", or until the shutdown flag is set. + /// + internal void Run(bool inputLoopIsNested) + { + PSHostUserInterface c = _parent.UI; + ConsoleHostUserInterface ui = c as ConsoleHostUserInterface; + + Dbg.Assert(ui != null, "Host.UI should return an instance."); + + bool inBlockMode = false; + // Use nullable so that we don't evaluate suggestions at startup. + bool? previousResponseWasEmpty = null; + var inputBlock = new StringBuilder(); + + while (!_parent.ShouldEndSession && !_shouldExit) + { + try + { + _parent._isRunningPromptLoop = true; + + string prompt = null; + string line = null; + + if (!ui.NoPrompt) + { + if (inBlockMode) + { + // use a special prompt that denotes block mode + prompt = ">> "; + } + else + { + // Make sure the cursor is at the start of the line - some external programs don't + // write a newline, so we do that for them. + if (ui.RawUI.CursorPosition.X != 0) + ui.WriteLine(); + + // Evaluate any suggestions + if (previousResponseWasEmpty == false) + { + EvaluateFeedbacks(ui); + } + + // Then output the prompt + if (_parent.InDebugMode) + { + prompt = EvaluateDebugPrompt(); + } + + prompt ??= EvaluatePrompt(); + } + + ui.Write(prompt); + } + +#if UNIX + if (c.SupportsVirtualTerminal) + { + // enable DECCKM as .NET requires cursor keys to emit VT for Console class + c.Write(DECCKM_ON); + } +#endif + + previousResponseWasEmpty = false; + // There could be a profile. So there could be a user defined custom readline command + line = ui.ReadLineWithTabCompletion(_exec); + + // line will be null in the case that Ctrl-C terminated the input + + if (line == null) + { + previousResponseWasEmpty = true; + + s_tracer.WriteLine("line is null"); + if (!ui.ReadFromStdin) + { + // If we're not reading from stdin, the we probably got here + // because the user hit ctrl-C. Do a writeline to clean up + // the output... + ui.WriteLine(); + } + + inBlockMode = false; + + if (Console.IsInputRedirected) + { + // null is also the result of reading stdin to EOF. + _parent.ShouldEndSession = true; + break; + } + + continue; + } + + if (string.IsNullOrWhiteSpace(line)) + { + if (inBlockMode) + { + // end block mode and execute the block accumulated block + + s_tracer.WriteLine("exiting block mode"); + line = inputBlock.ToString(); + inBlockMode = false; + } + else if (!_parent.InDebugMode) + { + previousResponseWasEmpty = true; + continue; + } + } + else + { + if (inBlockMode) + { + s_tracer.WriteLine("adding line to block"); + inputBlock.Append('\n'); + inputBlock.Append(line); + continue; + } + } + + Dbg.Assert(line != null, "line should not be null"); + Dbg.Assert(line.Length > 0 || _parent.InDebugMode, "line should not be empty unless the host is in debug mode"); + Dbg.Assert(!inBlockMode, "should not be in block mode at point of pipeline execution"); + + Exception e = null; + + if (_parent.InDebugMode) + { + DebuggerCommandResults results = ProcessDebugCommand(line, out e); + + if (results.ResumeAction != null) + { + _parent.ExitDebugMode(results.ResumeAction.Value); + } + + if (e != null) + { + var ex = e as PSInvalidOperationException; + if (e is PSRemotingTransportException || + e is RemoteException || + (ex != null && + ex.ErrorRecord != null && + ex.ErrorRecord.FullyQualifiedErrorId.Equals("Debugger:CannotProcessCommandNotStopped", StringComparison.OrdinalIgnoreCase))) + { + // Debugger session is broken. Exit nested loop. + _parent.ExitDebugMode(DebuggerResumeAction.Continue); + } + else + { + // Handle incomplete parse and other errors. + inBlockMode = HandleErrors(e, line, inBlockMode, ref inputBlock); + } + } + + continue; + } + + if (_runspacePopped) + { + string msg = StringUtil.Format(ConsoleHostStrings.CommandNotExecuted, line); + ui.WriteErrorLine(msg); + _runspacePopped = false; + } + else + { +#if UNIX + if (c.SupportsVirtualTerminal) + { + // disable DECCKM to standard mode as applications may not expect VT for cursor keys + c.Write(DECCKM_OFF); + } +#endif + + if (_parent.IsRunningAsync && !_parent.IsNested) + { + _exec.ExecuteCommandAsync(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory); + } + else + { + _exec.ExecuteCommand(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory); + } + + Thread bht = null; + + lock (_parent.hostGlobalLock) + { + bht = _parent._breakHandlerThread; + } + + bht?.Join(); + + // Once the pipeline has been executed, we toss any outstanding progress data and + // take down the display. + + ui.ResetProgress(); + + if (e != null) + { + // Handle incomplete parse and other errors. + inBlockMode = HandleErrors(e, line, inBlockMode, ref inputBlock); + + // If a remote runspace is pushed and it is not in a good state + // then pop it. + if (_isRunspacePushed && (_parent.Runspace != null) && + ((_parent.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) || + (_parent.Runspace.RunspaceAvailability != RunspaceAvailability.Available))) + { + _parent.PopRunspace(); + } + } + +#if LEGACYTELEMETRY + if (!inBlockMode) + s_theConsoleHost._interactiveCommandCount += 1; +#endif + } + } + + // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 + // Removed HandleUnexpectedExceptions infrastructure + finally + { + _parent._isRunningPromptLoop = false; + } + } + } + + internal void BlockCommandOutput() + { + if (_parent.runningCmd is RemotePipeline rCmdPipeline) + { + rCmdPipeline.DrainIncomingData(); + rCmdPipeline.SuspendIncomingData(); + } + else + { + _exec.BlockCommandOutput(); + } + } + + internal void ResumeCommandOutput() + { + if (_parent.runningCmd is RemotePipeline rCmdPipeline) + { + rCmdPipeline.ResumeIncomingData(); + } + else + { + _exec.ResumeCommandOutput(); + } + } + + private bool HandleErrors(Exception e, string line, bool inBlockMode, ref StringBuilder inputBlock) + { + Dbg.Assert(e != null, "Exception reference should not be null."); + + if (IsIncompleteParseException(e)) + { + if (!inBlockMode) + { + inBlockMode = true; + inputBlock = new StringBuilder(line); + } + else + { + inputBlock.Append(line); + } + } + else + { + // an exception occurred when the command was executed. Tell the user about it. + _parent.ReportException(e, _exec); + } + + return inBlockMode; + } + + private DebuggerCommandResults ProcessDebugCommand(string cmd, out Exception e) + { + DebuggerCommandResults results = null; + + try + { + _parent.DebuggerCanStopCommand = true; + + // Use PowerShell object to write streaming data to host. + using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) + { + PSInvocationSettings settings = new PSInvocationSettings() + { + Host = _parent + }; + + PSDataCollection output = new PSDataCollection(); + ps.AddCommand("Out-Default"); + IAsyncResult async = ps.BeginInvoke(output, settings, null, null); + + // Let debugger evaluate command and stream output data. + results = _parent.Runspace.Debugger.ProcessCommand( + new PSCommand( + new Command(cmd, true)), + output); + + output.Complete(); + ps.EndInvoke(async); + } + + e = null; + } + catch (Exception ex) + { + e = ex; + results = new DebuggerCommandResults(null, false); + } + finally + { + _parent.DebuggerCanStopCommand = false; + } + + // Exit debugger if command fails to evaluate. + return results ?? new DebuggerCommandResults(DebuggerResumeAction.Continue, false); + } + + private static bool IsIncompleteParseException(Exception e) + { + // Check e's type. + if (e is IncompleteParseException) + { + return true; + } + + // If it is remote exception ferret out the real exception. + if (e is not RemoteException remoteException || remoteException.ErrorRecord == null) + { + return false; + } + + return remoteException.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException); + } + + private void EvaluateFeedbacks(ConsoleHostUserInterface ui) + { + // Output any training suggestions + try + { + List feedbacks = FeedbackHub.GetFeedback(_parent.Runspace); + if (feedbacks is null || feedbacks.Count is 0) + { + return; + } + + HostUtilities.RenderFeedback(feedbacks, ui); + } + catch (Exception e) + { + // Catch-all OK. This is a third-party call-out. + ui.WriteErrorLine(e.Message); + + LocalRunspace localRunspace = (LocalRunspace)_parent.Runspace; + localRunspace.GetExecutionContext.AppendDollarError(e); + } + } + + private string EvaluatePrompt() + { + string promptString = _promptExec.ExecuteCommandAndGetResultAsString("prompt", out _); + + if (string.IsNullOrEmpty(promptString)) + { + promptString = ConsoleHostStrings.DefaultPrompt; + } + + // Check for the pushed runspace scenario. + if (_isRunspacePushed) + { + if (_parent.Runspace is RemoteRunspace remoteRunspace) + { + promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); + } + } + else + { + if (_runspacePopped) + { + _runspacePopped = false; + } + } + + // Return composed prompt string. + return promptString; + } + + private string EvaluateDebugPrompt() + { + PSDataCollection output = new PSDataCollection(); + + try + { + _parent.Runspace.Debugger.ProcessCommand( + new PSCommand(new Command("prompt")), + output); + } + catch (Exception ex) + { + _parent.ReportException(ex, _exec); + } + + PSObject prompt = output.ReadAndRemoveAt0(); + string promptString = (prompt != null) ? (prompt.BaseObject as string) : null; + if (promptString != null && _parent.Runspace is RemoteRunspace remoteRunspace) + { + promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); + } + + return promptString; + } + + private readonly ConsoleHost _parent; + private readonly bool _isNested; + private bool _shouldExit; + private readonly Executor _exec; + private readonly Executor _promptExec; + private readonly object _syncObject = new object(); + private bool _isRunspacePushed = false; + private bool _runspacePopped = false; + + // The instance stack is used to keep track of which InputLoop instance should be told to exit + // when PSHost.ExitNestedPrompt is called. + + // threadsafety guaranteed by enclosing class + + private static readonly Stack s_instanceStack = new Stack(); + } + + [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = + "This exception cannot be used outside of the console host application. It is not thrown by a library routine, only by an application.")] + private sealed class ConsoleHostStartupException : Exception + { + internal + ConsoleHostStartupException() + : base() + { + } + + internal + ConsoleHostStartupException(string message) + : base(message) + { + } + + internal + ConsoleHostStartupException(string message, Exception innerException) + : base(message, innerException) + { + } + } + + #endregion aux classes + + /// + /// By declaring runspace as ObjectRef<Runspace> we are able to hide the real runspace with + /// a remote runspace in the PushRunspace scenario. By declaring it as a mask, the variable + /// runspace becomes an indirect reference to the actual runspace which we can override with + /// a remote runspace while it is pushed. Also we can easily revert back to the original + /// runspace when the PopRunspace command is invoked. + /// + private RunspaceRef _runspaceRef; + +#if !UNIX + private GCHandle breakHandlerGcHandle; + + // Set to Unknown so that we avoid saving/restoring the console mode if we don't have a console. + private ConsoleControl.ConsoleModes _savedConsoleMode = ConsoleControl.ConsoleModes.Unknown; + private readonly ConsoleControl.ConsoleModes _initialConsoleMode = ConsoleControl.ConsoleModes.Unknown; +#endif + private Thread _breakHandlerThread; + private bool _isDisposed; + internal ConsoleHostUserInterface ui; + + internal Lazy ConsoleIn { get; } = new Lazy(static () => Console.In); + + private string _savedWindowTitle = string.Empty; + private readonly Version _ver = PSVersionInfo.PSVersion; + private int _exitCodeFromRunspace; + private bool _noExit = true; + private bool _setShouldExitCalled; + private bool _isRunningPromptLoop; + private bool _wasInitialCommandEncoded; + + // hostGlobalLock is used to sync public method calls (in case multiple threads call into the host) and access to + // state that persists across method calls, like progress data. It's internal because the ui object also + // uses this same object. + + internal object hostGlobalLock = new object(); + + // These members are possibly accessed from multiple threads (the break handler thread, a pipeline thread, or the main + // thread). We use hostGlobalLock to sync access to them. + + private bool _shouldEndSession; + private int _beginApplicationNotifyCount; + + private readonly ConsoleTextWriter _consoleWriter; + private WrappedSerializer _outputSerializer; + private WrappedSerializer _errorSerializer; + private bool _displayDebuggerBanner; + private DebuggerStopEventArgs _debuggerStopEventArgs; + private bool _inPushedConfiguredSession; + internal Pipeline runningCmd; + + // The ConsoleHost class is a singleton. Note that there is not a thread-safety issue with these statics as there can + // only be one console host per process. + + private static ConsoleHost s_theConsoleHost; + + internal static InitialSessionState DefaultInitialSessionState; + + [TraceSource("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost")] + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost"); + + [TraceSource("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace")] + private static readonly PSTraceSource s_runspaceInitTracer = + PSTraceSource.GetTracer("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace", false); + } + + /// + /// Defines arguments passed to ConsoleHost.CreateRunspace. + /// + internal sealed class RunspaceCreationEventArgs : EventArgs + { + /// + /// Constructs RunspaceCreationEventArgs. + /// + internal RunspaceCreationEventArgs( + string initialCommand, + bool skipProfiles, + bool staMode, + string configurationName, + string configurationFilePath, + Collection initialCommandArgs) + { + InitialCommand = initialCommand; + SkipProfiles = skipProfiles; + StaMode = staMode; + ConfigurationName = configurationName; + ConfigurationFilePath = configurationFilePath; + InitialCommandArgs = initialCommandArgs; + } + + internal string InitialCommand { get; set; } + + internal bool SkipProfiles { get; set; } + + internal bool StaMode { get; set; } + + internal string ConfigurationName { get; set; } + + internal string ConfigurationFilePath { get; set; } + + internal Collection InitialCommandArgs { get; set; } + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs new file mode 100644 index 0000000000000000000000000000000000000000..58630f5b3c0e01b7b25c36c236d70871ac4a0b67 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -0,0 +1,1693 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.ComponentModel; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Security.Principal; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle; +using Dbg = System.Management.Automation.Diagnostics; +using WORD = System.UInt16; + +namespace Microsoft.PowerShell +{ + /// + /// Implementation of RawConsole for powershell. + /// + internal sealed + class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawUserInterface + { + /// + /// + /// + /// If obtaining the buffer's foreground and background color failed + /// + internal + ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() + { + defaultForeground = ForegroundColor; + defaultBackground = BackgroundColor; + parent = mshConsole; + // cacheKeyEvent is a value type and initialized automatically + + // add "Administrator: " prefix into the window title, but don't wait for it to finish + // (we may load resources which can take some time) + Task.Run(() => + { + var identity = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(identity); + if (principal.IsInRole(WindowsBuiltInRole.Administrator)) + { + // Check if the window already has the "Administrator: " prefix (i.e. from the parent console process). + ReadOnlySpan prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix; + ReadOnlySpan windowTitle = WindowTitle; + if (!windowTitle.StartsWith(prefix)) + { + WindowTitle = string.Concat(prefix, windowTitle); + } + } + }); + } + + /// + /// See base class. + /// + /// + /// + /// If set to an invalid ConsoleColor + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// + public override + ConsoleColor + ForegroundColor + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + + ConsoleColor foreground; + + ConsoleControl.WORDToColor(bufferInfo.Attributes, out foreground, out _); + return foreground; + } + + set + { + if (ConsoleControl.IsConsoleColor(value)) + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + + // mask in the foreground from the current color. + short a = (short)bufferInfo.Attributes; + + a &= (short)~0x0f; + a = (short)((ushort)a | (ushort)value); + ConsoleControl.SetConsoleTextAttribute(handle, (WORD)a); + } + else + { + throw PSTraceSource.NewArgumentException("value", ConsoleHostRawUserInterfaceStrings.InvalidConsoleColorError); + } + } + } + + /// + /// See base class. + /// + /// + /// + /// If set to an invalid ConsoleColor + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// + public override + ConsoleColor + BackgroundColor + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + + ConsoleColor background; + + ConsoleControl.WORDToColor(bufferInfo.Attributes, out _, out background); + return background; + } + + set + { + if (ConsoleControl.IsConsoleColor(value)) + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + + // mask in the background from the current color. + short a = (short)bufferInfo.Attributes; + + a &= (short)~0xf0; + a = (short)((ushort)a | (ushort)((uint)value << 4)); + ConsoleControl.SetConsoleTextAttribute(handle, (WORD)a); + } + else + { + throw PSTraceSource.NewArgumentException("value", ConsoleHostRawUserInterfaceStrings.InvalidConsoleColorError); + } + } + } + + /// + /// See base class. + /// + /// + /// + /// If set to outside of the buffer + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleCursorPosition failed + /// + public override + Coordinates + CursorPosition + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + + Coordinates c = new Coordinates(bufferInfo.CursorPosition.X, bufferInfo.CursorPosition.Y); + return c; + } + + set + { + try + { + Console.SetCursorPosition(value.X, value.Y); + } + catch (ArgumentOutOfRangeException) + { + // if screen buffer has changed, we cannot set it anywhere reasonable as the screen buffer + // might change again, so we ignore this + } + } + } + + /// + /// See base class. + /// + /// + /// Cursor size + /// + /// + /// If set to under 0 or over 100 + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's GetConsoleCursorInfo failed + /// OR + /// Win32's SetConsoleCursorInfo failed + /// + public override + int + CursorSize + { + get + { + ConsoleHandle consoleHandle = ConsoleControl.GetActiveScreenBufferHandle(); + int size = (int)ConsoleControl.GetConsoleCursorInfo(consoleHandle).Size; + + return size; + } + + set + { + const int MinCursorSize = 0; + const int MaxCursorSize = 100; + + if (value >= MinCursorSize && value <= MaxCursorSize) + { + ConsoleHandle consoleHandle = ConsoleControl.GetActiveScreenBufferHandle(); + ConsoleControl.CONSOLE_CURSOR_INFO cursorInfo = + ConsoleControl.GetConsoleCursorInfo(consoleHandle); + + if (value == 0) + { + cursorInfo.Visible = false; + } + else + { + cursorInfo.Size = (uint)value; + cursorInfo.Visible = true; + } + + ConsoleControl.SetConsoleCursorInfo(consoleHandle, cursorInfo); + } + else + { + throw PSTraceSource.NewArgumentOutOfRangeException("value", value, + ConsoleHostRawUserInterfaceStrings.InvalidCursorSizeError); + } + } + } + + /// + /// See base class. + /// + /// + /// + /// If set outside of the buffer + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleWindowInfo failed + /// + public override + Coordinates + WindowPosition + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + + Coordinates c = new Coordinates(bufferInfo.WindowRect.Left, bufferInfo.WindowRect.Top); + + return c; + } + + set + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect; + + // the dimensions of the window can't extend past the dimensions of the screen buffer. This means that the + // X position of the window is limited to the buffer width minus one minus the window width, and the Y + // position of the window is limited to the buffer height minus one minus the window height. + int windowWidth = r.Right - r.Left + 1; + int windowHeight = r.Bottom - r.Top + 1; + + if (value.X < 0 || value.X > bufferInfo.BufferSize.X - windowWidth) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.X", value.X, + ConsoleHostRawUserInterfaceStrings.InvalidXWindowPositionError); + } + + if (value.Y < 0 || value.Y > bufferInfo.BufferSize.Y - windowHeight) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Y", value.Y, + ConsoleHostRawUserInterfaceStrings.InvalidYWindowPositionError); + } + + r.Left = (short)value.X; + r.Top = (short)value.Y; + + // subtract 1 from each dimension because the semantics of the win32 api are not "number of characters in + // span" but "starting and ending position" + r.Right = (short)(r.Left + windowWidth - 1); + r.Bottom = (short)(r.Top + windowHeight - 1); + Dbg.Assert(r.Right >= r.Left, "Window size is too narrow"); + Dbg.Assert(r.Bottom >= r.Top, "Window size is too short"); + ConsoleControl.SetConsoleWindowInfo(handle, true, r); + } + } + + /// + /// See base class. + /// + /// + /// + /// If setting to an invalid size + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleScreenBufferSize failed + /// + public override + Size + BufferSize + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + return new Size(bufferInfo.BufferSize.X, bufferInfo.BufferSize.Y); + } + + set + { + // looking in windows/core/ntcon/server/output.c, it looks like the minimum size is 1 row X however many + // characters will fit in the minimum window size system metric (SM_CXMIN). Instead of going to the effort of + // computing that minimum here, it is cleaner and cheaper to make the call to SetConsoleScreenBuffer and just + // translate any exception that might get thrown. + try + { + ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle(); + ConsoleControl.SetConsoleScreenBufferSize(handle, value); + } + catch (HostException e) + { + if (e.InnerException is Win32Exception win32exception && + win32exception.NativeErrorCode == 0x57) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value", value, + ConsoleHostRawUserInterfaceStrings.InvalidBufferSizeError); + } + else + { + throw; + } + } + } + } + + /// + /// See base class. + /// + /// + /// + /// If setting width or height to less than 1, larger than the screen buffer, + /// over the maximum window size allowed + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleWindowInfo failed + /// + public override + Size + WindowSize + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + + Size s = + new Size( + bufferInfo.WindowRect.Right - bufferInfo.WindowRect.Left + 1, + bufferInfo.WindowRect.Bottom - bufferInfo.WindowRect.Top + 1); + + return s; + } + + set + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + + // the dimensions of the window can't extend past the dimensions of the screen buffer. This means that the + // width of the window is limited to the buffer width minus one minus the window X position, and the height + // of the window is limited to the buffer height minus one minus the window Y position. + + if (value.Width < 1) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width, + ConsoleHostRawUserInterfaceStrings.WindowWidthTooSmallError); + } + + if (value.Height < 1) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Height", value.Height, + ConsoleHostRawUserInterfaceStrings.WindowHeightTooSmallError); + } + + if (value.Width > bufferInfo.BufferSize.X) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width, + ConsoleHostRawUserInterfaceStrings.WindowWidthLargerThanBufferError); + } + + if (value.Height > bufferInfo.BufferSize.Y) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Height", value.Height, + ConsoleHostRawUserInterfaceStrings.WindowHeightLargerThanBufferError); + } + + if (value.Width > bufferInfo.MaxWindowSize.X) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width, + ConsoleHostRawUserInterfaceStrings.WindowWidthTooLargeErrorTemplate, + bufferInfo.MaxWindowSize.X); + } + + if (value.Height > bufferInfo.MaxWindowSize.Y) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value.Height", value.Height, + ConsoleHostRawUserInterfaceStrings.WindowHeightTooLargeErrorTemplate, + bufferInfo.MaxWindowSize.Y); + } + + // if the new size will extend past the edge of screen buffer, then move the window position to try to + // accommodate that. + + ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect; + + // subtract 1 from each dimension because the semantics of the win32 api are not "number of characters in + // span" but "starting and ending position" + + r.Right = (short)(r.Left + value.Width - 1); + r.Bottom = (short)(r.Top + value.Height - 1); + + // Now we check if the bottom right coordinate of our window went over the coordinate of the bottom + // right of the buffer. If it did then we need to adjust the window. + + // bufferInfo.BufferSize.X - 1 will give us the rightmost coordinate of the buffer. + // r.Right - rightCoordinateOfBuffer will give us how much we need to adjust the window left and right coordinates. + // Then we can do the same for top and bottom. + short adjustLeft = (short)(r.Right - (bufferInfo.BufferSize.X - 1)); + short adjustTop = (short)(r.Bottom - (bufferInfo.BufferSize.Y - 1)); + + if (adjustLeft > 0) + { + r.Left -= adjustLeft; + r.Right -= adjustLeft; + } + + if (adjustTop > 0) + { + r.Top -= adjustTop; + r.Bottom -= adjustTop; + } + + if (r.Right < r.Left) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value", value, + ConsoleHostRawUserInterfaceStrings.WindowTooNarrowError); + } + + if (r.Bottom < r.Top) + { + throw PSTraceSource.NewArgumentOutOfRangeException("value", value, + ConsoleHostRawUserInterfaceStrings.WindowTooShortError); + } + + ConsoleControl.SetConsoleWindowInfo(handle, true, r); + } + } + + /// + /// See base class. + /// + /// + /// + /// If obtaining information about the buffer failed + /// + public override + Size + MaxWindowSize + { + get + { + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetBufferInfo(out bufferInfo); + Size s = new Size(bufferInfo.MaxWindowSize.X, bufferInfo.MaxWindowSize.Y); + + return s; + } + } + + /// + /// See base class. + /// + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's GetLargestConsoleWindowSize failed + /// + public override + Size + MaxPhysicalWindowSize + { + get + { + ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle(); + return ConsoleControl.GetLargestConsoleWindowSize(handle); + } + } + + /// + /// Helper method to create and trace PipelineStoppedException. + /// + /// + private static PipelineStoppedException NewPipelineStoppedException() + { + PipelineStoppedException e = new PipelineStoppedException(); + return e; + } + + /// + /// Used by ReadKey, cache KeyEvent based on if input.RepeatCount > 1. + /// + /// Input key event record. + /// Cache key event. + private static void CacheKeyEvent(ConsoleControl.KEY_EVENT_RECORD input, ref ConsoleControl.KEY_EVENT_RECORD cache) + { + if (input.RepeatCount > 1) + { + cache = input; + cache.RepeatCount--; + } + } + + /// + /// See base class + /// This method unwraps the repeat count in KEY_EVENT_RECORD by caching repeated keystrokes + /// in a logical queue. The implications are: + /// 1) Per discussion with Sburns on 2005/01/20, calling this method with allowCtrlC | includeKeyUp may not + /// return ctrl-c even it is pressed. This is because ctrl-c could generate the following sequence of + /// key events: {Ctrl, KeyDown}, {Ctrl-c KeyDown}, {Ctrl, KeyUp}, {c, KeyUp} if Ctrl is released before c. + /// In this case, {Ctrl, KeyUp}, {c, KeyUp} would be returned. + /// 2) If the cache is non-empty, a call to ReadLine will not return the cached keys. This + /// behavior is the same as that of System.Console.ReadKey. + /// + /// + /// + /// + /// If neither IncludeKeyDown or IncludeKeyUp is set in + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's setting input buffer mode to disregard window and mouse input failed + /// OR + /// Win32's ReadConsoleInput failed + /// + public override + KeyInfo + ReadKey(ReadKeyOptions options) + { + if ((options & (ReadKeyOptions.IncludeKeyDown | ReadKeyOptions.IncludeKeyUp)) == 0) + { + throw PSTraceSource.NewArgumentException(nameof(options), ConsoleHostRawUserInterfaceStrings.InvalidReadKeyOptionsError); + } + + // keyInfo is initialized in the below if-else statement + KeyInfo keyInfo; + + if (cachedKeyEvent.RepeatCount > 0) + { + // Ctrl-C is not allowed and Ctrl-C is cached. + if (((options & ReadKeyOptions.AllowCtrlC) == 0) && cachedKeyEvent.UnicodeChar == (char)3) + { + // Ctrl-C is in the cache, stop pipeline immediately + + cachedKeyEvent.RepeatCount--; + throw NewPipelineStoppedException(); + } + // If IncludeKeyUp is not set and cached key events are KeyUp OR + // IncludeKeyDown is not set and cached key events are KeyDown, clear the cache + if ((((options & ReadKeyOptions.IncludeKeyUp) == 0) && !cachedKeyEvent.KeyDown) || + (((options & ReadKeyOptions.IncludeKeyDown) == 0) && cachedKeyEvent.KeyDown)) + { + cachedKeyEvent.RepeatCount = 0; + } + } + + if (cachedKeyEvent.RepeatCount > 0) + { + KEY_EVENT_RECORDToKeyInfo(cachedKeyEvent, out keyInfo); + cachedKeyEvent.RepeatCount--; + } + else + { + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); + ConsoleControl.INPUT_RECORD[] inputRecords = new ConsoleControl.INPUT_RECORD[1]; + ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle); + + // set input mode to exclude mouse or window events + // turn off ProcessedInput flag to handle ctrl-c + ConsoleControl.ConsoleModes newMode = originalMode & + ~ConsoleControl.ConsoleModes.WindowInput & + ~ConsoleControl.ConsoleModes.MouseInput & + ~ConsoleControl.ConsoleModes.ProcessedInput; + + try + { + ConsoleControl.SetMode(handle, newMode); + while (true) + { + int actualNumberOfInput = ConsoleControl.ReadConsoleInput(handle, ref inputRecords); + Dbg.Assert(actualNumberOfInput == 1, + string.Create(CultureInfo.InvariantCulture, $"ReadConsoleInput returns {actualNumberOfInput} number of input event records")); + if (actualNumberOfInput == 1) + { + if (((ConsoleControl.InputRecordEventTypes)inputRecords[0].EventType) == + ConsoleControl.InputRecordEventTypes.KEY_EVENT) + { + Dbg.Assert(!inputRecords[0].KeyEvent.KeyDown || inputRecords[0].KeyEvent.RepeatCount != 0, + string.Format(CultureInfo.InvariantCulture, "ReadConsoleInput returns a KeyEvent that is KeyDown and RepeatCount 0")); + if (inputRecords[0].KeyEvent.RepeatCount == 0) + { + // Sometimes Win32 ReadConsoleInput returns a KeyEvent record whose + // RepeatCount is zero. This type of record does not + // represent a keystroke. + continue; + } + // Ctrl-C is not allowed and Ctrl-C is input + if ((options & ReadKeyOptions.AllowCtrlC) == 0 && + inputRecords[0].KeyEvent.UnicodeChar == (char)3) + { + CacheKeyEvent(inputRecords[0].KeyEvent, ref cachedKeyEvent); + throw NewPipelineStoppedException(); + } + // if KeyDown events are wanted and event is KeyDown OR + // KeyUp events are wanted and event is KeyUp + if ((((options & ReadKeyOptions.IncludeKeyDown) != 0) && + inputRecords[0].KeyEvent.KeyDown) || + (((options & ReadKeyOptions.IncludeKeyUp) != 0) && + !inputRecords[0].KeyEvent.KeyDown)) + { + CacheKeyEvent(inputRecords[0].KeyEvent, ref cachedKeyEvent); + KEY_EVENT_RECORDToKeyInfo(inputRecords[0].KeyEvent, out keyInfo); + break; + } + } + } + } + } + finally + { + ConsoleControl.SetMode(handle, originalMode); + } + } + + if ((options & ReadKeyOptions.NoEcho) == 0) + { + parent.WriteToConsole(keyInfo.Character, transcribeResult: true); + } + + return keyInfo; + } + + private static + void + KEY_EVENT_RECORDToKeyInfo(ConsoleControl.KEY_EVENT_RECORD keyEventRecord, out KeyInfo keyInfo) + { + keyInfo = new KeyInfo( + keyEventRecord.VirtualKeyCode, + keyEventRecord.UnicodeChar, + (ControlKeyStates)keyEventRecord.ControlKeyState, + keyEventRecord.KeyDown); + } + + /// + /// See base class. + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's FlushConsoleInputBuffer failed + /// + public override + void + FlushInputBuffer() + { + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); + ConsoleControl.FlushConsoleInputBuffer(handle); + + cachedKeyEvent.RepeatCount = 0; + } + + /// + /// See base class. + /// + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's GetNumberOfConsoleInputEvents failed + /// OR + /// Win32's PeekConsoleInput failed + /// + public override + bool + KeyAvailable + { + get + { + if (cachedKeyEvent.RepeatCount > 0) + { + return true; + } + + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); + ConsoleControl.INPUT_RECORD[] inputRecords = + new ConsoleControl.INPUT_RECORD[ConsoleControl.GetNumberOfConsoleInputEvents(handle)]; + + int actualNumberOfInputRecords = ConsoleControl.PeekConsoleInput(handle, ref inputRecords); + + for (int i = 0; i < actualNumberOfInputRecords; i++) + { + if (((ConsoleControl.InputRecordEventTypes)inputRecords[i].EventType) == + ConsoleControl.InputRecordEventTypes.KEY_EVENT) + { + Dbg.Assert(!inputRecords[i].KeyEvent.KeyDown || inputRecords[i].KeyEvent.RepeatCount != 0, + string.Format(CultureInfo.InvariantCulture, "PeekConsoleInput returns a KeyEvent that is KeyDown and RepeatCount 0")); + + if (inputRecords[i].KeyEvent.KeyDown && inputRecords[i].KeyEvent.RepeatCount == 0) + { + // Sometimes Win32 ReadConsoleInput returns a KeyEvent record whose + // KeyDown is true and RepeatCount is zero. This type of record does not + // represent a keystroke. + continue; + } + + return true; + } + } + + return false; + } + } + + /// + /// See base class. + /// + /// + /// + /// If set to null + /// + /// + /// If set to a string whose length is not between 1 to 1023 + /// + /// + /// If Win32's GetConsoleWindowTitle failed + /// OR + /// Win32's SetConsoleWindowTitle failed + /// + public override string WindowTitle + { + get + { + return ConsoleControl.GetConsoleWindowTitle(); + } + + set + { + const int MaxWindowTitleLength = 1023; + const int MinWindowTitleLength = 0; + + if (value != null) + { + if ( + value.Length >= MinWindowTitleLength && + value.Length <= MaxWindowTitleLength + ) + { + ConsoleControl.SetConsoleWindowTitle(value); + } + else if (value.Length < MinWindowTitleLength) + { + throw PSTraceSource.NewArgumentException("value", ConsoleHostRawUserInterfaceStrings.WindowTitleTooShortError); + } + else + { + throw PSTraceSource.NewArgumentException("value", + ConsoleHostRawUserInterfaceStrings + .WindowTitleTooLongErrorTemplate, + MaxWindowTitleLength); + } + } + else + { + throw PSTraceSource.NewArgumentNullException("value"); + } + } + } + + /// + /// See base class. + /// + /// + /// location on screen buffer where contents will be written + /// + /// + /// array of info to be written + /// + /// + /// + /// If is outside of the screen buffer. + /// OR + /// is an ill-formed BufferCell array + /// OR + /// it is illegal to write at in the buffer + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// obtaining information about the buffer failed + /// OR + /// there is not enough memory to complete calls to Win32's WriteConsoleOutput + /// + public override + void + SetBufferContents(Coordinates origin, BufferCell[,] contents) + { + if (contents == null) + { + PSTraceSource.NewArgumentNullException(nameof(contents)); + } + // the origin must be within the window. + + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + CheckCoordinateWithinBuffer(ref origin, ref bufferInfo, nameof(origin)); + + // The output is clipped by the console subsystem, so we don't have to check that the array exceeds the buffer + // boundaries. + + ConsoleControl.WriteConsoleOutput(handle, origin, contents); + } + + /// + /// If is completely outside of the screen buffer, it's a no-op. + /// + /// + /// region with all elements = -1 means "entire screen buffer" + /// + /// + /// character and attribute to fill the screen buffer + /// + /// + /// Provided for clearing regions -- less chatty than passing an array of cells. + /// Clear screen is: + /// SetBufferContents(new Rectangle(-1, -1, -1, -1), ' ', ForegroundColor, BackgroundColor); + /// CursorPosition = new Coordinates(0, 0); + /// + /// fill.Type is ignored + /// + /// + /// If 's Left exceeds Right or Bottom exceeds Top + /// OR + /// it is illegal to set in the buffer with + /// + /// + /// If Win32's CreateFile fails + /// OR + /// Win32's GetConsoleScreenBufferInfo fails + /// OR + /// there is not enough memory to complete calls to Win32's WriteConsoleOutput + /// + public override + void + SetBufferContents(Rectangle region, BufferCell fill) + { + // make sure the rect is valid + if (region.Right < region.Left) + { + throw PSTraceSource.NewArgumentException(nameof(region), + ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, + "region.Right", "region.Left"); + } + + if (region.Bottom < region.Top) + { + throw PSTraceSource.NewArgumentException(nameof(region), + ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, + "region.Bottom", "region.Top"); + } + + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + + int bufferWidth = bufferInfo.BufferSize.X; + int bufferHeight = bufferInfo.BufferSize.Y; + WORD attribute = ConsoleControl.ColorToWORD(fill.ForegroundColor, fill.BackgroundColor); + Coordinates origin = new Coordinates(0, 0); + uint codePage; + + // region == {-1, -1, -1, -1} is a special case meaning "the whole screen buffer" + if (region.Left == -1 && region.Right == -1 && region.Top == -1 && region.Bottom == -1) + { + if (bufferWidth % 2 == 1 && + ConsoleControl.IsCJKOutputCodePage(out codePage) && + LengthInBufferCells(fill.Character) == 2) + { + throw PSTraceSource.NewArgumentException(nameof(fill)); + } + + int cells = bufferWidth * bufferHeight; + + ConsoleControl.FillConsoleOutputCharacter(handle, fill.Character, cells, origin); + ConsoleControl.FillConsoleOutputAttribute(handle, attribute, cells, origin); + return; + } + + // The FillConsoleOutputXxx functions wrap at the end of a line. So we need to convert our rectangular region + // into line segments that don't extend past the end of a line. We will also clip the rectangle so that the semantics + // are the same as SetBufferContents(Coordinates, BufferCell[,]), which clips if the rectangle extends past the + // screen buffer boundaries. + if (region.Left >= bufferWidth || region.Top >= bufferHeight || region.Right < 0 || region.Bottom < 0) + { + // region is entirely outside the buffer boundaries + tracer.WriteLine("region outside boundaries"); + return; + } + + int lineStart = Math.Max(0, region.Left); + int lineEnd = Math.Min(bufferWidth - 1, region.Right); + int lineLength = lineEnd - lineStart + 1; + + origin.X = lineStart; + + int firstRow = Math.Max(0, region.Top); + int lastRow = Math.Min(bufferHeight - 1, region.Bottom); + origin.Y = firstRow; + + if (ConsoleControl.IsCJKOutputCodePage(out codePage)) + { + Rectangle existingRegion = new Rectangle(0, 0, 1, lastRow - firstRow); + int charLength = LengthInBufferCells(fill.Character); + // Check left edge + if (origin.X > 0) + { + BufferCell[,] leftExisting = new BufferCell[existingRegion.Bottom + 1, 2]; + ConsoleControl.ReadConsoleOutputCJK(handle, codePage, + new Coordinates(origin.X - 1, origin.Y), existingRegion, ref leftExisting); + for (int r = 0; r <= existingRegion.Bottom; r++) + { + if (leftExisting[r, 0].BufferCellType == BufferCellType.Leading) + { + throw PSTraceSource.NewArgumentException(nameof(fill)); + } + } + } + // Check right edge + if (lineEnd == bufferWidth - 1) + { + if (charLength == 2) + { + throw PSTraceSource.NewArgumentException(nameof(fill)); + } + } + else + { + // use ReadConsoleOutputCJK because checking the left and right edges of the existing output + // is NOT needed + BufferCell[,] rightExisting = new BufferCell[existingRegion.Bottom + 1, 2]; + ConsoleControl.ReadConsoleOutputCJK(handle, codePage, + new Coordinates(lineEnd, origin.Y), existingRegion, ref rightExisting); + if (lineLength % 2 == 0) + { + for (int r = 0; r <= existingRegion.Bottom; r++) + { + if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading) + { + throw PSTraceSource.NewArgumentException(nameof(fill)); + } + } + } + else + { + for (int r = 0; r <= existingRegion.Bottom; r++) + { + if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading ^ charLength == 2) + { + throw PSTraceSource.NewArgumentException(nameof(fill)); + } + } + } + } + + if (lineLength % 2 == 1) + { + lineLength++; + } + } + + for (int row = firstRow; row <= lastRow; ++row) + { + origin.Y = row; + + // we know that lineStart and lineEnd will always be within the buffer area because of previous boundary + // checks already done. + + ConsoleControl.FillConsoleOutputCharacter(handle, fill.Character, lineLength, origin); + ConsoleControl.FillConsoleOutputAttribute(handle, attribute, lineLength, origin); + } + } + + /// + /// See base class. + /// If the rectangle is invalid, ie, Right exceeds Left OR Bottom exceeds Top, + /// + /// + /// area on screen buffer to be read + /// + /// + /// an array of BufferCell containing screen buffer contents + /// + /// + /// If 's Left exceeds Right or Bottom exceeds Top. + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// obtaining information about the buffer failed + /// OR + /// there is not enough memory to complete calls to Win32's ReadConsoleOutput + /// + public override + BufferCell[,] GetBufferContents(Rectangle region) + { + // make sure the rect is valid + if (region.Right < region.Left) + { + throw PSTraceSource.NewArgumentException(nameof(region), + ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, + "region.Right", "region.Left"); + } + + if (region.Bottom < region.Top) + { + throw PSTraceSource.NewArgumentException(nameof(region), + ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, + "region.Bottom", "region.Top"); + } + + ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + + ConsoleHandle handle = GetBufferInfo(out bufferInfo); + int bufferWidth = bufferInfo.BufferSize.X; + int bufferHeight = bufferInfo.BufferSize.Y; + + if (region.Left >= bufferWidth || region.Top >= bufferHeight || region.Right < 0 || region.Bottom < 0) + { + // region is entirely outside the buffer boundaries + tracer.WriteLine("region outside boundaries"); + return new BufferCell[0, 0]; + } + + int colStart = Math.Max(0, region.Left); + int colEnd = Math.Min(bufferWidth - 1, region.Right); + int rowStart = Math.Max(0, region.Top); + int rowEnd = Math.Min(bufferHeight - 1, region.Bottom); + Coordinates origin = new Coordinates(colStart, rowStart); + + // contentsRegion indicates the area in contents (declared below) in which + // the data read from ReadConsoleOutput is stored. + Rectangle contentsRegion = new Rectangle(); + contentsRegion.Left = Math.Max(0, 0 - region.Left); + contentsRegion.Top = Math.Max(0, 0 - region.Top); + contentsRegion.Right = contentsRegion.Left + (colEnd - colStart); + contentsRegion.Bottom = contentsRegion.Top + (rowEnd - rowStart); + + BufferCell[,] contents = new BufferCell[region.Bottom - region.Top + 1, + region.Right - region.Left + 1]; + + ConsoleControl.ReadConsoleOutput(handle, origin, contentsRegion, ref contents); + + return contents; + } + + /// + /// See base class. + /// + /// + /// area to be moved + /// + /// + /// top left corner to which source to be moved + /// + /// + /// area to be updated caused by the move + /// + /// + /// character and attribute to fill the area vacated by the move + /// + /// + /// If obtaining the active screen buffer failed + /// OR + /// Call to Win32's ScrollConsoleScreenBuffer failed + /// + public override + void + ScrollBufferContents + ( + Rectangle source, + Coordinates destination, + Rectangle clip, + BufferCell fill + ) + { + ConsoleControl.SMALL_RECT scrollRectangle; + scrollRectangle.Left = (short)source.Left; + scrollRectangle.Right = (short)source.Right; + scrollRectangle.Top = (short)source.Top; + scrollRectangle.Bottom = (short)source.Bottom; + + ConsoleControl.SMALL_RECT clipRectangle; + clipRectangle.Left = (short)clip.Left; + clipRectangle.Right = (short)clip.Right; + clipRectangle.Top = (short)clip.Top; + clipRectangle.Bottom = (short)clip.Bottom; + + ConsoleControl.COORD origin; + origin.X = (short)destination.X; + origin.Y = (short)destination.Y; + + ConsoleControl.CHAR_INFO fillChar; + + fillChar.UnicodeChar = fill.Character; + fillChar.Attributes = ConsoleControl.ColorToWORD(fill.ForegroundColor, fill.BackgroundColor); + + ConsoleHandle consoleHandle = ConsoleControl.GetActiveScreenBufferHandle(); + ConsoleControl.ScrollConsoleScreenBuffer + ( + consoleHandle, + scrollRectangle, + clipRectangle, + origin, + fillChar + ); + } + + /// + /// See base class. + /// + /// + /// + /// + /// If Win32's WideCharToMultiByte fails + /// + public override + int LengthInBufferCells(string s) + { + return this.LengthInBufferCells(s, 0); + } + + /// + /// See base class. + /// + /// + /// + /// + /// + /// If Win32's WideCharToMultiByte fails + /// + public override + int LengthInBufferCells(string s, int offset) + { + if (s == null) + { + throw PSTraceSource.NewArgumentNullException("str"); + } + + return ConsoleControl.LengthInBufferCells(s, offset, parent.SupportsVirtualTerminal); + } + + /// + /// See base class. + /// + /// + /// + /// + /// If Win32's WideCharToMultiByte fails + /// + public override + int LengthInBufferCells(char c) + { + return ConsoleControl.LengthInBufferCells(c); + } + + #region internal + + /// + /// Clear the ReadKey cache. + /// + /// + internal void ClearKeyCache() + { + cachedKeyEvent.RepeatCount = 0; + } + + #endregion internal + + #region helpers + + // pass-by-ref for speed. + /// + /// + /// + /// + /// + /// + /// If is outside of the output buffer area + /// + private static + void + CheckCoordinateWithinBuffer(ref Coordinates c, ref ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo, string paramName) + { + if (c.X < 0 || c.X > bufferInfo.BufferSize.X) + { + throw PSTraceSource.NewArgumentOutOfRangeException( + paramName + ".X", + c.X, + ConsoleHostRawUserInterfaceStrings.CoordinateOutOfBufferErrorTemplate, bufferInfo.BufferSize); + } + + if (c.Y < 0 || c.Y > bufferInfo.BufferSize.Y) + { + throw PSTraceSource.NewArgumentOutOfRangeException( + paramName + ".Y", + c.Y, + ConsoleHostRawUserInterfaceStrings.CoordinateOutOfBufferErrorTemplate, bufferInfo.BufferSize); + } + } + + /// + /// Get output buffer info. + /// + /// + /// + /// + /// If Win32's CreateFile fails + /// OR + /// Win32's GetConsoleScreenBufferInfo fails + /// + private static + ConsoleHandle + GetBufferInfo(out ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo) + { + ConsoleHandle result = ConsoleControl.GetActiveScreenBufferHandle(); + bufferInfo = ConsoleControl.GetConsoleScreenBufferInfo(result); + return result; + } + + #endregion helpers + + private readonly ConsoleColor defaultForeground = ConsoleColor.Gray; + + private readonly ConsoleColor defaultBackground = ConsoleColor.Black; + + private readonly ConsoleHostUserInterface parent = null; + + private ConsoleControl.KEY_EVENT_RECORD cachedKeyEvent; + + [TraceSourceAttribute("ConsoleHostRawUserInterface", "Console host's subclass of S.M.A.Host.RawConsole")] + private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleHostRawUserInterface", "Console host's subclass of S.M.A.Host.RawConsole"); + } +} // namespace + +#else + +// Managed code only implementation for portability + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Management.Automation.Host; +using System.Globalization; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.PowerShell +{ + // this is all originally from https://msdn.microsoft.com/library/ee706570%28v=vs.85%29.aspx + + internal sealed class ConsoleHostRawUserInterface : PSHostRawUserInterface + { + + private readonly ConsoleHostUserInterface _parent = null; + + internal ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() + { + _parent = mshConsole; + } + + /// + /// Gets or sets the background color of the displayed text. + /// This maps to the corresponding Console.Background property. + /// + public override ConsoleColor BackgroundColor + { + get { return Console.BackgroundColor; } + + set { Console.BackgroundColor = value; } + } + + // TODO: Make wrap width user-customizable. + private static Size s_wrapSize = new Size(80, 40); + + /// + /// Gets or sets the size of the host buffer. + /// + public override Size BufferSize + { + get + { + // Console can return zero when a pseudo-TTY is allocated, which + // is useless for us. Instead, map to the wrap size. + return Console.BufferWidth == 0 || Console.BufferHeight == 0 + ? s_wrapSize + : new Size(Console.BufferWidth, Console.BufferHeight); + } + + set + { + Console.SetBufferSize(value.Width, value.Height); + } + } + + /// + /// Gets or sets the cursor position. + /// + public override Coordinates CursorPosition + { + get + { + return new Coordinates(Console.CursorLeft, Console.CursorTop); + } + + set + { + Console.SetCursorPosition(value.X < 0 ? 0 : value.X, + value.Y < 0 ? 0 : value.Y); + } + } + + /// + /// Gets or sets the size of the displayed cursor. + /// This maps to the corresponding Console.CursorSize property. + /// + public override int CursorSize + { + // Future porting note: this API throws on Windows when output is + // redirected, but never throws on Unix because it's fake. + get { return Console.CursorSize; } + + set { Console.CursorSize = value; } + } + + /// + /// Gets or sets the foreground color of the displayed text. + /// This maps to the corresponding Console.ForegroundColor property. + /// + public override ConsoleColor ForegroundColor + { + get { return Console.ForegroundColor; } + + set { Console.ForegroundColor = value; } + } + + /// + /// Gets a value indicating whether the user has pressed a key. This maps + /// to the corresponding Console.KeyAvailable property. + /// + public override bool KeyAvailable + { + get { return Console.KeyAvailable; } + } + + /// + /// Gets the dimensions of the largest window that could be rendered in + /// the current display, if the buffer was at the least that large. + /// This maps to the MaxWindowSize. + /// + public override Size MaxPhysicalWindowSize + { + get { return MaxWindowSize; } + } + + /// + /// Gets the dimensions of the largest window size that can be + /// displayed. This maps to the Console.LargestWindowWidth and + /// Console.LargestWindowHeight properties to determine the returned + /// value of this property. + /// + public override Size MaxWindowSize + { + get + { + // Console can return zero when a pseudo-TTY is allocated, which + // is useless for us. Instead, map to the wrap size. + return Console.LargestWindowWidth == 0 || Console.LargestWindowHeight == 0 + ? s_wrapSize + : new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); + } + } + + /// + /// Gets or sets the position of the displayed window. This maps to the + /// Console window position APIs to determine the returned value of this + /// property. + /// + public override Coordinates WindowPosition + { + get { return new Coordinates(Console.WindowLeft, Console.WindowTop); } + + set { Console.SetWindowPosition(value.X, value.Y); } + } + + /// + /// Gets or sets the size of the displayed window. This example + /// uses the corresponding Console window size APIs to determine the + /// returned value of this property. + /// + public override Size WindowSize + { + get + { + // Console can return zero when a pseudo-TTY is allocated, which + // is useless for us. Instead, map to the wrap size. + return Console.WindowWidth == 0 || Console.WindowHeight == 0 + ? s_wrapSize + : new Size(Console.WindowWidth, Console.WindowHeight); + } + + set + { + Console.SetWindowSize(value.Width, value.Height); + } + } + + /// + /// Cached Window Title, for systems that needs it. + /// + private string _title = string.Empty; + + /// + /// Gets or sets the title of the displayed window. The example + /// maps the Console.Title property to the value of this property. + /// + public override string WindowTitle + { + get + { + // Console throws an exception on Unix platforms, so we handle + // caching and returning the Window title ourselves. + return Platform.IsWindows ? Console.Title : _title; + } + + set + { + Console.Title = value; + _title = value; + } + } + + /// + /// This API resets the input buffer. + /// + public override void FlushInputBuffer() + { + if (!Console.IsInputRedirected) + { + Console.OpenStandardInput().Flush(); + } + } + + public void ScrollBuffer(int lines) + { + for (int i = 0; i < lines; ++i) + { + Console.Out.Write('\n'); + + } + } + + internal struct COORD + { + internal short X; + + internal short Y; + + public override string ToString() + { + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); + } + } + + internal struct SMALL_RECT + { + internal short Left; + + internal short Top; + + internal short Right; + + internal short Bottom; + + public override string ToString() + { + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}"); + } + } + + /// + /// This API returns a rectangular region of the screen buffer. In + /// this example this functionality is not needed so the method throws + /// a NotImplementException exception. + /// + /// Defines the size of the rectangle. + /// Throws a NotImplementedException exception. + public override BufferCell[,] GetBufferContents(Rectangle rectangle) + { + throw new NotImplementedException("The method or operation is not implemented."); + } + + /// + /// This API reads a pressed, released, or pressed and released keystroke + /// from the keyboard device, blocking processing until a keystroke is + /// typed that matches the specified keystroke options. + /// + /// Only NoEcho is supported. + public override KeyInfo ReadKey(ReadKeyOptions options) + { + ConsoleKeyInfo key = Console.ReadKey((options & ReadKeyOptions.NoEcho) != 0); + return new KeyInfo((int)key.Key, key.KeyChar, new ControlKeyStates(), true); + } + + /// + /// This API crops a region of the screen buffer. In this example + /// this functionality is not needed so the method throws a + /// NotImplementException exception. + /// + /// The region of the screen to be scrolled. + /// The region of the screen to receive the + /// source region contents. + /// The region of the screen to include in the operation. + /// The character and attributes to be used to fill all cell. + public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill) + { + throw new NotImplementedException("The method or operation is not implemented."); + } + + /// + /// This method copies an array of buffer cells into the screen buffer + /// at a specified location. + /// + /// The parameter used to set the origin where the buffer where begin writing to. + /// The parameter used to contain the contents to be written to the buffer. + public override void SetBufferContents(Coordinates origin, + BufferCell[,] contents) + { + // if there are no contents, there is nothing to set the buffer to + if (contents == null) + { + PSTraceSource.NewArgumentNullException("contents"); + } + // if the cursor is on the last line, we need to make more space to print the specified buffer + if (origin.Y == BufferSize.Height - 1 && origin.X >= BufferSize.Width) + { + // for each row in the buffer, create a new line + int rows = contents.GetLength(0); + ScrollBuffer(rows); + // for each row in the buffer, move the cursor y up to the beginning of the created blank space + // but not above zero + if (origin.Y >= rows) + { + origin.Y -= rows; + } + } + +#if UNIX + // Make sure that the physical cursor position matches where we think it is. + // This is a problem on *nix, because input that the user types is echoed + // and that moves the cursor. As a consequence, the cursor needs to be repositioned + // before we update the screen. + CursorPosition = origin; +#endif + + // iterate through the buffer to set + foreach (var charitem in contents) + { + // set the cursor to false to prevent cursor flicker + Console.CursorVisible = false; + + // if x is exceeding buffer width, reset to the next line + if (origin.X >= BufferSize.Width) + { + origin.X = 0; + } + + // write the character from contents + Console.Out.Write(charitem.Character); + } + + // reset the cursor to the original position + CursorPosition = origin; + // reset the cursor to visible + Console.CursorVisible = true; + } + + /// + /// This method copies a given character, foreground color, and background + /// color to a region of the screen buffer. In this example this + /// functionality is not needed so the method throws a + /// NotImplementException exception./// + /// Defines the area to be filled. + /// Defines the fill character. + public override void SetBufferContents(Rectangle rectangle, BufferCell fill) + { + throw new NotImplementedException("The method or operation is not implemented."); + } + + /// + /// See base class. + /// + /// + /// + + public override + int LengthInBufferCells(string s) + { + return this.LengthInBufferCells(s, 0); + } + + /// + /// See base class. + /// + /// + /// + /// + + public override + int LengthInBufferCells(string s, int offset) + { + if (s == null) + { + throw PSTraceSource.NewArgumentNullException("str"); + } + + return ConsoleControl.LengthInBufferCells(s, offset, _parent.SupportsVirtualTerminal); + } + } +} +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs new file mode 100644 index 0000000000000000000000000000000000000000..3ac758ff86c1a19e59d69755b8adc93c42f91da3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell +{ + internal sealed partial class ConsoleHost : PSHost, IDisposable + { + internal bool IsTranscribing + { + get + { + // no locking because the compare should be atomic + + return _isTranscribing; + } + + set + { + _isTranscribing = value; + } + } + + private bool _isTranscribing; + + /* + internal void StartTranscribing(string transcriptFilename, bool shouldAppend) + { + // lock so as not to contend with IsTranscribing and StopTranscribing + + lock (transcriptionStateLock) + { + Dbg.Assert(transcriptionWriter == null, "writer should not exist"); + this.transcriptFileName = transcriptFilename; + + transcriptionWriter = new StreamWriter(transcriptFilename, shouldAppend, new System.Text.UnicodeEncoding()); + + transcriptionWriter.AutoFlush = true; + + string format = ConsoleHostStrings.TranscriptPrologue; + string line = + StringUtil.Format( + format, + DateTime.Now, + Environment.UserDomainName, + Environment.UserName, + Environment.MachineName, + Environment.OSVersion.VersionString); + + transcriptionWriter.WriteLine(line); + + // record that we are transcribing... + isTranscribing = true; + + } + } + */ + private readonly string _transcriptFileName = string.Empty; + + internal string StopTranscribing() + { + lock (_transcriptionStateLock) + { + if (_transcriptionWriter == null) + { + return null; + } + + // The filestream *must* be closed at the end of this method. + // If it isn't and there is a pending IO error, the finalizer will + // dispose the stream resulting in an IO exception on the finalizer thread + // which will crash the process... + try + { + _transcriptionWriter.WriteLine( + StringUtil.Format(ConsoleHostStrings.TranscriptEpilogue, DateTime.Now)); + } + finally + { + try + { + _transcriptionWriter.Dispose(); + } + finally + { + _transcriptionWriter = null; + _isTranscribing = false; + } + } + + return _transcriptFileName; + } + } + + internal void WriteToTranscript(ReadOnlySpan text) + { + WriteToTranscript(text, newLine: false); + } + + internal void WriteLineToTranscript(ReadOnlySpan text) + { + WriteToTranscript(text, newLine: true); + } + + internal void WriteToTranscript(ReadOnlySpan text, bool newLine) + { + lock (_transcriptionStateLock) + { + if (_isTranscribing && _transcriptionWriter != null) + { + if (newLine) + { + _transcriptionWriter.WriteLine(text); + } + else + { + _transcriptionWriter.Write(text); + } + } + } + } + + private StreamWriter _transcriptionWriter; + private readonly object _transcriptionStateLock = new object(); + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs new file mode 100644 index 0000000000000000000000000000000000000000..f0da0d995470fda14896ab868e69f8294b9d286f --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -0,0 +1,2268 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; +using System.Runtime.CompilerServices; +using System.Security; +using System.Text; + +using Dbg = System.Management.Automation.Diagnostics; +#if !UNIX +using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle; +#endif + +namespace Microsoft.PowerShell +{ + using PowerShell = System.Management.Automation.PowerShell; + + /// + /// ConsoleHostUserInterface implements console-mode user interface for powershell. + /// + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] + internal partial class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInterface + { + /// + /// This is the char that is echoed to the console when the input is masked. This not localizable. + /// + private const char PrintToken = '*'; + + /// + /// Command completion implementation object. + /// + private PowerShell _commandCompletionPowerShell; + + /// + /// This is a test hook for programmatically reading and writing ConsoleHost I/O. + /// + private static readonly PSHostUserInterface s_h = null; + + /// + /// Return true if the console supports a VT100 like virtual terminal. + /// + public override bool SupportsVirtualTerminal { get; } + + /// + /// Constructs an instance. + /// + /// + /// + internal ConsoleHostUserInterface(ConsoleHost parent) + { + Dbg.Assert(parent != null, "parent may not be null"); + + _parent = parent; + _rawui = new ConsoleHostRawUserInterface(this); + SupportsVirtualTerminal = true; + _isInteractiveTestToolListening = false; + + // check if TERM env var is set + // `dumb` means explicitly don't use VT + // `xterm-mono` and `xtermm` means support VT, but emit plaintext + switch (Environment.GetEnvironmentVariable("TERM")) + { + case "dumb": + SupportsVirtualTerminal = false; + break; + case "xterm-mono": + case "xtermm": + PSStyle.Instance.OutputRendering = OutputRendering.PlainText; + break; + default: + break; + } + + // widely supported by CLI tools via https://no-color.org/ + if (Environment.GetEnvironmentVariable("NO_COLOR") != null) + { + PSStyle.Instance.OutputRendering = OutputRendering.PlainText; + } + + if (SupportsVirtualTerminal) + { + SupportsVirtualTerminal = TryTurnOnVirtualTerminal(); + } + } + + internal bool TryTurnOnVirtualTerminal() + { +#if UNIX + return true; +#else + try + { + // Turn on virtual terminal if possible. + // This might throw - not sure how exactly (no console), but if it does, we shouldn't fail to start. + var outputHandle = ConsoleControl.GetActiveScreenBufferHandle(); + var outputMode = ConsoleControl.GetMode(outputHandle); + + if (outputMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal)) + { + return true; + } + + outputMode |= ConsoleControl.ConsoleModes.VirtualTerminal; + if (ConsoleControl.NativeMethods.SetConsoleMode(outputHandle.DangerousGetHandle(), (uint)outputMode)) + { + // We only know if vt100 is supported if the previous call actually set the new flag, older + // systems ignore the setting. + outputMode = ConsoleControl.GetMode(outputHandle); + return outputMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal); + } + } + catch + { + // Do nothing if failed + } + + return false; +#endif + } + + /// + /// Supplies an implementation of PSHostRawUserInterface that provides low-level console mode UI facilities. + /// + /// + /// + public override PSHostRawUserInterface RawUI + { + get + { + Dbg.Assert(_rawui != null, "rawui should have been created by ctor"); + + // no locking because this is read-only, and allocated in the ctor. + + return _rawui; + } + } + + // deadcode; but could be needed in the future. + ///// + ///// gets the PSHost instance that uses this ConsoleHostUserInterface instance + ///// + ///// + ///// + + // internal + // PSHost + // Parent + // { + // get + // { + // using (tracer.TraceProperty()) + // { + // // no locking because this is read-only and set in the ctor. + + // return parent; + // } + // } + // } + + /// + /// True if command completion is currently running. + /// + internal bool IsCommandCompletionRunning + { + get + { + return _commandCompletionPowerShell != null && + _commandCompletionPowerShell.InvocationStateInfo.State == PSInvocationState.Running; + } + } + + /// + /// True if the Read* functions should read from the stdin stream instead of from the win32 console. + /// + internal bool ReadFromStdin { get; set; } + + /// + /// True if the host shouldn't write out prompts. + /// + internal bool NoPrompt { get; set; } + + #region Line-oriented interaction + + /// + /// See base class. + /// + /// + /// + /// If Win32's SetConsoleMode fails + /// OR + /// Win32's ReadConsole fails + /// OR + /// obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleCursorPosition failed + /// + public override string ReadLine() + { + HandleThrowOnReadAndPrompt(); + + // call our internal version such that it does not end input on a tab + + return ReadLine(false, string.Empty, out _, true, true); + } + + /// + /// See base class. + /// + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's setting input buffer mode to disregard window and mouse input failed + /// OR + /// Win32's ReadConsole failed + /// + /// + /// If Ctrl-C is entered by user + /// + public override SecureString ReadLineAsSecureString() + { + HandleThrowOnReadAndPrompt(); + + // we lock here so that multiple threads won't interleave the various reads and writes here. + + object result = null; + lock (_instanceLock) + { + result = ReadLineSafe(true, PrintToken); + } + + SecureString secureResult = result as SecureString; + System.Management.Automation.Diagnostics.Assert(secureResult != null, "ReadLineSafe did not return a SecureString"); + + return secureResult; + } + + /// + /// Implementation based on NT CredUI's GetPasswdStr. + /// Use Win32.ReadConsole to construct a SecureString. The advantage of ReadConsole over ReadKey is + /// Alt-ddd where d is {0-9} is allowed. + /// It also manages the cursor as keys are entered and "backspaced". However, it is possible that + /// while this method is running, the console buffer contents could change. Then, its cursor mgmt + /// will likely be messed up. + /// + /// Secondary implementation for Unix based on Console.ReadKey(), where + /// the advantage is portability through abstraction. Does not support + /// arrow key movement, but supports backspace. + /// + /// + /// True to specify reading a SecureString; false reading a string + /// + /// + /// string for output echo + /// + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's setting input buffer mode to disregard window and mouse input failed + /// OR + /// Win32's ReadConsole failed + /// OR + /// obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleCursorPosition failed + /// + /// + /// If Ctrl-C is entered by user + /// + private object ReadLineSafe(bool isSecureString, char? printToken) + { + // Don't lock (instanceLock) in here -- the caller needs to do that... + + PreRead(); + string printTokenString = printToken.HasValue ? + printToken.ToString() : + null; + SecureString secureResult = new SecureString(); + StringBuilder result = new StringBuilder(); +#if UNIX + bool treatControlCAsInput = Console.TreatControlCAsInput; +#else + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); + ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle); + bool isModeChanged = true; // assume ConsoleMode is changed so that if ReadLineSetMode + // fails to return the value correctly, the original mode is + // restored. +#endif + + try + { +#if UNIX + Console.TreatControlCAsInput = true; +#else + // Ensure that we're in the proper line-input mode. + + const ConsoleControl.ConsoleModes DesiredMode = + ConsoleControl.ConsoleModes.Extended | + ConsoleControl.ConsoleModes.QuickEdit; + + ConsoleControl.ConsoleModes m = originalMode; + bool shouldUnsetEchoInput = shouldUnsetMode(ConsoleControl.ConsoleModes.EchoInput, ref m); + bool shouldUnsetLineInput = shouldUnsetMode(ConsoleControl.ConsoleModes.LineInput, ref m); + bool shouldUnsetMouseInput = shouldUnsetMode(ConsoleControl.ConsoleModes.MouseInput, ref m); + bool shouldUnsetProcessInput = shouldUnsetMode(ConsoleControl.ConsoleModes.ProcessedInput, ref m); + + if ((m & DesiredMode) != DesiredMode || + shouldUnsetMouseInput || + shouldUnsetEchoInput || + shouldUnsetLineInput || + shouldUnsetProcessInput) + { + m |= DesiredMode; + ConsoleControl.SetMode(handle, m); + } + else + { + isModeChanged = false; + } + + _rawui.ClearKeyCache(); +#endif + + Coordinates originalCursorPos = _rawui.CursorPosition; + + // + // read one char at a time so that we don't + // end up having a immutable string holding the + // secret in memory. + // + const int CharactersToRead = 1; + Span inputBuffer = stackalloc char[CharactersToRead + 1]; + + while (true) + { +#if UNIX + ConsoleKeyInfo keyInfo = Console.ReadKey(true); +#else + string key = ConsoleControl.ReadConsole(handle, initialContentLength: 0, inputBuffer, charactersToRead: CharactersToRead, endOnTab: false, out _); +#endif + +#if UNIX + // Handle Ctrl-C ending input + if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)) +#else + if (string.IsNullOrEmpty(key) || key[0] == (char)3) +#endif + { + PipelineStoppedException e = new PipelineStoppedException(); + throw e; + } +#if UNIX + if (keyInfo.Key == ConsoleKey.Enter) +#else + if (key[0] == (char)13) +#endif + { + // + // we are done if user presses ENTER key + // + break; + } +#if UNIX + if (keyInfo.Key == ConsoleKey.Backspace) +#else + if (key[0] == (char)8) +#endif + { + // + // for backspace, remove last char appended + // + if (isSecureString && secureResult.Length > 0) + { + secureResult.RemoveAt(secureResult.Length - 1); + WriteBackSpace(originalCursorPos); + } + else if (result.Length > 0) + { + result.Remove(result.Length - 1, 1); + WriteBackSpace(originalCursorPos); + } + } +#if UNIX + else if (char.IsControl(keyInfo.KeyChar)) + { + // deny list control characters + continue; + } +#endif + else + { + // + // append the char to our string + // + if (isSecureString) + { +#if UNIX + secureResult.AppendChar(keyInfo.KeyChar); +#else + secureResult.AppendChar(key[0]); +#endif + } + else + { +#if UNIX + result.Append(keyInfo.KeyChar); +#else + result.Append(key); +#endif + } + + if (!string.IsNullOrEmpty(printTokenString)) + { + WritePrintToken(printTokenString, ref originalCursorPos); + } + } + } + } +#if UNIX + catch (InvalidOperationException) + { + // ReadKey() failed so we stop + throw new PipelineStoppedException(); + } +#endif + finally + { +#if UNIX + Console.TreatControlCAsInput = treatControlCAsInput; +#else + if (isModeChanged) + { + ConsoleControl.SetMode(handle, originalMode); + } +#endif + } + + WriteLineToConsole(); + PostRead(result.ToString()); + if (isSecureString) + { + return secureResult; + } + else + { + return result; + } + } + + /// + /// Handle writing print token with proper cursor adjustment for ReadLineSafe. + /// + /// + /// token output for each char input. It must be a one-char string + /// + /// + /// it is the cursor position where ReadLineSafe begins + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleCursorPosition failed + /// + private void WritePrintToken( + string printToken, + ref Coordinates originalCursorPosition) + { + Dbg.Assert(!string.IsNullOrEmpty(printToken), + "Calling WritePrintToken with printToken being null or empty"); + Dbg.Assert(printToken.Length == 1, + "Calling WritePrintToken with printToken's Length being " + printToken.Length); + Size consoleBufferSize = _rawui.BufferSize; + Coordinates currentCursorPosition = _rawui.CursorPosition; + + // if the cursor is currently at the lower right corner, this write will cause the screen buffer to + // scroll up. So, it is necessary to adjust the original cursor position one row up. + if (currentCursorPosition.Y >= consoleBufferSize.Height - 1 && // last row + currentCursorPosition.X >= consoleBufferSize.Width - 1) // last column + { + if (originalCursorPosition.Y > 0) + { + originalCursorPosition.Y--; + } + } + + WriteToConsole(printToken, false); + } + + /// + /// Handle backspace with proper cursor adjustment for ReadLineSafe. + /// + /// + /// it is the cursor position where ReadLineSafe begins + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleCursorPosition failed + /// + private void WriteBackSpace(Coordinates originalCursorPosition) + { + Coordinates cursorPosition = _rawui.CursorPosition; + if (cursorPosition == originalCursorPosition) + { + // at originalCursorPosition, don't move + return; + } + + if (cursorPosition.X == 0) + { + if (cursorPosition.Y <= originalCursorPosition.Y) + { + return; + } + // BufferSize.Width is 1 larger than cursor position + cursorPosition.X = _rawui.BufferSize.Width - 1; + cursorPosition.Y--; + BlankAtCursor(cursorPosition); + } + else if (cursorPosition.X > 0) + { + cursorPosition.X--; + BlankAtCursor(cursorPosition); + } + // do nothing if cursorPosition.X is left of screen + } + + /// + /// Blank out at and move rawui.CursorPosition to + /// + /// Position to blank out. + private void BlankAtCursor(Coordinates cursorPosition) + { + _rawui.CursorPosition = cursorPosition; + WriteToConsole(" ", true); + _rawui.CursorPosition = cursorPosition; + } + +#if !UNIX + /// + /// If is set on , unset it and return true; + /// otherwise return false. + /// + /// + /// a flag in ConsoleControl.ConsoleModes to be unset in + /// + /// + /// + /// + /// true if is set on + /// false otherwise + /// + private static bool shouldUnsetMode( + ConsoleControl.ConsoleModes flagToUnset, + ref ConsoleControl.ConsoleModes m) + { + if ((m & flagToUnset) > 0) + { + m &= ~flagToUnset; + return true; + } + + return false; + } +#endif + + #region WriteToConsole + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteToConsole(char c, bool transcribeResult) + { + ReadOnlySpan value = [c]; + WriteToConsole(value, transcribeResult); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteToConsole(ReadOnlySpan value, bool transcribeResult) + { + WriteToConsole(value, transcribeResult, newLine: false); + } + + private void WriteToConsole(ReadOnlySpan value, bool transcribeResult, bool newLine) + { +#if !UNIX + ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle(); + + // Ensure that we're in the proper line-output mode. We don't lock here as it does not matter if we + // attempt to set the mode from multiple threads at once. + ConsoleControl.ConsoleModes m = ConsoleControl.GetMode(handle); + + const ConsoleControl.ConsoleModes DesiredMode = + ConsoleControl.ConsoleModes.ProcessedOutput + | ConsoleControl.ConsoleModes.WrapEndOfLine; + + if ((m & DesiredMode) != DesiredMode) + { + m |= DesiredMode; + ConsoleControl.SetMode(handle, m); + } +#endif + + PreWrite(); + + // This is atomic, so we don't lock here... +#if !UNIX + ConsoleControl.WriteConsole(handle, value, newLine); +#else + ConsoleOutWriteHelper(value, newLine); +#endif + + if (_isInteractiveTestToolListening && Console.IsOutputRedirected) + { + ConsoleOutWriteHelper(value, newLine); + } + + if (transcribeResult) + { + PostWrite(value, newLine); + } + else + { + PostWrite(); + } + } + + private void WriteToConsole(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string text, bool newLine = false) + { + // Sync access so that we don't conflict on color settings if called from multiple threads. + lock (_instanceLock) + { + ConsoleColor fg = RawUI.ForegroundColor; + ConsoleColor bg = RawUI.BackgroundColor; + + RawUI.ForegroundColor = foregroundColor; + RawUI.BackgroundColor = backgroundColor; + + try + { + WriteToConsole(text, transcribeResult: true, newLine); + } + finally + { + RawUI.ForegroundColor = fg; + RawUI.BackgroundColor = bg; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConsoleOutWriteHelper(ReadOnlySpan value, bool newLine) + { + if (newLine) + { + Console.Out.WriteLine(value); + } + else + { + Console.Out.Write(value); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteLineToConsole(ReadOnlySpan value, bool transcribeResult) + { + WriteToConsole(value, transcribeResult, newLine: true); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLineToConsole(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string text) + { + WriteToConsole(foregroundColor, backgroundColor, text, newLine: true); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLineToConsole(string text) + { + WriteLineToConsole(text, transcribeResult: true); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLineToConsole() + { + WriteToConsole(Environment.NewLine, transcribeResult: true, newLine: false); + } + + #endregion WriteToConsole + + /// + /// See base class. + /// + /// + /// + /// If Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void Write(string value) + { + lock (_instanceLock) + { + WriteImpl(value, newLine: false); + } + } + + // The WriteImpl() method should always be called within a lock on _instanceLock + // to ensure thread safety and prevent issues in multi-threaded scenarios. + private void WriteImpl(string value, bool newLine) + { + if (string.IsNullOrEmpty(value) && !newLine) + { + return; + } + + // If the test hook is set, write to it and continue. + if (s_h != null) + { + if (newLine) + { + s_h.WriteLine(value); + } + else + { + s_h.Write(value); + } + } + + TextWriter writer = Console.IsOutputRedirected ? Console.Out : _parent.ConsoleTextWriter; + value = GetOutputString(value, SupportsVirtualTerminal); + + if (_parent.IsRunningAsync) + { + Dbg.Assert(writer == _parent.OutputSerializer.textWriter, "writers should be the same"); + + _parent.OutputSerializer.Serialize(value); + + if (newLine) + { + _parent.OutputSerializer.Serialize(Environment.NewLine); + } + } + else + { + if (newLine) + { + writer.WriteLine(value); + } + else + { + writer.Write(value); + } + } + } + + /// + /// See base class. + /// + /// + /// + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// OR + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) + { + Write(foregroundColor, backgroundColor, value, newLine: false); + } + + /// + /// See base class. + /// + /// + /// + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// OR + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) + { + Write(foregroundColor, backgroundColor, value, newLine: true); + } + + private void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value, bool newLine) + { + // Sync access so that we don't conflict on color settings if called from multiple threads. + lock (_instanceLock) + { + ConsoleColor fg = RawUI.ForegroundColor; + ConsoleColor bg = RawUI.BackgroundColor; + + RawUI.ForegroundColor = foregroundColor; + RawUI.BackgroundColor = backgroundColor; + + try + { + this.WriteImpl(value, newLine); + } + finally + { + RawUI.ForegroundColor = fg; + RawUI.BackgroundColor = bg; + } + } + } + + /// + /// See base class. + /// + /// + /// + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void WriteLine(string value) + { + lock (_instanceLock) + { + this.WriteImpl(value, newLine: true); + } + } + + /// + /// See base class. + /// + /// + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void WriteLine() + { + lock (_instanceLock) + { + this.WriteImpl(Environment.NewLine, newLine: false); + } + } + + #region Word Wrapping + + /// + /// This is a poor-man's word-wrapping routine. It breaks a single string into segments small enough to fit within a + /// given number of cells. A break is determined by the last occurrence of whitespace that allows all prior characters + /// on a line to be written within a given number of cells. If there is no whitespace found within that span, then the + /// largest span that will fit in the bounds is used. + /// + /// The problem is complicated by the fact that a single character may consume more than one cell. Conceptually, this + /// is the same case as placing an upper bound on the length of a line while also having a strlen function that + /// arbitrarily considers the length of any single character to be 1 or greater. + /// + /// + /// Text to be emitted. + /// Each tab character in the text is replaced with a space in the results. + /// + /// + /// Max width, in buffer cells, of a single line. Note that a single character may consume more than one cell. The + /// number of cells consumed is determined by calling ConsoleHostRawUserInterface.LengthInBufferCells. + /// + /// + /// A list of strings representing the text broken into "lines" each of which are guaranteed not to exceed + /// maxWidthInBufferCells. + /// + internal List WrapText(string text, int maxWidthInBufferCells) + { + List result = new List(); + + List words = ChopTextIntoWords(text, maxWidthInBufferCells); + if (words.Count < 1) + { + return result; + } + + IEnumerator e = words.GetEnumerator(); + bool valid = false; + int cellCounter = 0; + StringBuilder line = new StringBuilder(); + string l = null; + + do + { + valid = e.MoveNext(); + if (!valid) + { + if (line.Length > 0) + { + l = line.ToString(); + Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long"); + result.Add(l); + } + + break; + } + + if ((e.Current.Flags & WordFlags.IsNewline) > 0) + { + l = line.ToString(); + Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long"); + result.Add(l); + + // skip the newline "words" + + line = new StringBuilder(); + cellCounter = 0; + continue; + } + + // will the word fit? + + if (cellCounter + e.Current.CellCount <= maxWidthInBufferCells) + { + // yes, add it to the line. + + line.Append(e.Current.Text); + cellCounter += e.Current.CellCount; + } + else + { + // no: too long. Either start a new line, or pick off as much whitespace as we need. + + if ((e.Current.Flags & WordFlags.IsWhitespace) == 0) + { + l = line.ToString(); + Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long"); + result.Add(l); + + line = new StringBuilder(e.Current.Text); + cellCounter = e.Current.CellCount; + continue; + } + + // chop the whitespace into bits. + + int w = maxWidthInBufferCells - cellCounter; + Dbg.Assert(w < e.Current.CellCount, "width remaining should be less than size of word"); + + line.Append(e.Current.Text.AsSpan(0, w)); + + l = line.ToString(); + Dbg.Assert(RawUI.LengthInBufferCells(l) == maxWidthInBufferCells, "line should exactly fit"); + result.Add(l); + + string remaining = e.Current.Text.Substring(w); + line = new StringBuilder(remaining); + cellCounter = RawUI.LengthInBufferCells(remaining); + } + } while (valid); + + return result; + } + + /// + /// Struct used by WrapText. + /// + [Flags] + internal enum WordFlags + { + IsWhitespace = 0x01, + IsNewline = 0x02 + } + + internal struct Word + { + internal int CellCount; + internal string Text; + internal WordFlags Flags; + } + + /// + /// Chops text into "words," where a word is defined to be a sequence of whitespace characters, or a sequence of + /// non-whitespace characters, each sequence being no longer than a given maximum. Therefore, in the text "this is a + /// string" there are 7 words: 4 sequences of non-whitespace characters and 3 sequences of whitespace characters. + /// + /// Whitespace is considered to be spaces or tabs. Each tab character is replaced with a single space. + /// + /// + /// The text to be chopped up. + /// + /// + /// The maximum number of buffer cells that each word may consume. + /// + /// + /// A list of words, in the same order they appear in the source text. + /// + /// + /// This can be made faster by, instead of creating little strings for each word, creating indices of the start and end + /// range of a word. That would reduce the string allocations. + /// + internal List ChopTextIntoWords(string text, int maxWidthInBufferCells) + { + List result = new List(); + + if (string.IsNullOrEmpty(text)) + { + return result; + } + + if (maxWidthInBufferCells < 1) + { + return result; + } + + text = text.Replace('\t', ' '); + + result = new List(); + + // a "word" is a span of characters delimited by whitespace. Contiguous whitespace, too, is a word. + + int startIndex = 0; + int wordEnd = 0; + bool inWs = false; + + while (wordEnd < text.Length) + { + if (text[wordEnd] == '\n') + { + if (startIndex < wordEnd) + { + // the span up to this point needs to be saved off + + AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result); + } + + // add a nl word + + Word w = new Word(); + w.Flags = WordFlags.IsNewline; + result.Add(w); + + // skip the nl + + ++wordEnd; + startIndex = wordEnd; + + inWs = false; + continue; + } + else if (text[wordEnd] == ' ') + { + if (!inWs) + { + // span from startIndex..(wordEnd - 1) is a word + + AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result); + startIndex = wordEnd; + } + + inWs = true; + } + else + { + // not whitespace + + if (inWs) + { + AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result); + startIndex = wordEnd; + } + + inWs = false; + } + + ++wordEnd; + } + + if (startIndex != wordEnd) + { + AddWord(text, startIndex, text.Length, maxWidthInBufferCells, inWs, ref result); + } + + return result; + } + + /// + /// Helper for ChopTextIntoWords. Takes a span of characters in a string and adds it to the word list, further + /// subdividing the span as needed so that each subdivision fits within the limit. + /// + /// + /// The string of characters in which the span is to be extracted. + /// + /// + /// index into text of the start of the word to be added. + /// + /// + /// index of the char after the last char to be included in the word. + /// + /// + /// The maximum number of buffer cells that each word may consume. + /// + /// + /// true if the span is whitespace, false if not. + /// + /// + /// The list into which the words will be added. + /// + internal void AddWord(string text, int startIndex, int endIndex, + int maxWidthInBufferCells, bool isWhitespace, ref List result) + { + Dbg.Assert(endIndex >= startIndex, "startIndex must be before endIndex"); + Dbg.Assert(endIndex >= 0, "endIndex must be positive"); + Dbg.Assert(startIndex >= 0, "startIndex must be positive"); + Dbg.Assert(startIndex < text.Length, "startIndex must be within the string"); + Dbg.Assert(endIndex <= text.Length, "endIndex must be within the string"); + + while (startIndex < endIndex) + { + int i = Math.Min(endIndex, startIndex + maxWidthInBufferCells); + Word w = new Word(); + if (isWhitespace) + { + w.Flags = WordFlags.IsWhitespace; + } + + while (true) + { + w.Text = text.Substring(startIndex, i - startIndex); + w.CellCount = RawUI.LengthInBufferCells(w.Text); + if (w.CellCount <= maxWidthInBufferCells) + { + // the segment from start..i fits + + break; + } + else + { + // The segment does not fit, back off a tad until it does + + --i; + } + } + + Dbg.Assert(RawUI.LengthInBufferCells(w.Text) <= maxWidthInBufferCells, "word should not exceed max"); + result.Add(w); + + startIndex = i; + } + } + + internal string WrapToCurrentWindowWidth(string text) + { + StringBuilder sb = new StringBuilder(); + + // we leave a 1-cell margin on the end because if the very last character butts up against the + // edge of the screen buffer, then the console will wrap the line. + + List lines = WrapText(text, RawUI.WindowSize.Width - 1); + int count = 0; + foreach (string s in lines) + { + sb.Append(s); + if (++count != lines.Count) + { + sb.Append(Environment.NewLine); + } + } + + return sb.ToString(); + } + + #endregion Word Wrapping + + /// + /// See base class. + /// + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// OR + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void WriteDebugLine(string message) + { + // We should write debug to error stream only if debug is redirected.) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) + { + _parent.ErrorSerializer.Serialize(message, "debug"); + } + else + { + if (SupportsVirtualTerminal) + { + WriteLine(GetFormatStyleString(FormatStyle.Debug) + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message) + PSStyle.Instance.Reset); + } + else + { + WriteLine( + DebugForegroundColor, + DebugBackgroundColor, + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message)); + } + } + } + + /// + /// See base class. + /// + /// + public override void WriteInformation(InformationRecord record) + { + // We should write information to error stream only if redirected.) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) + { + _parent.ErrorSerializer.Serialize(record, "information"); + } + else + { + // Do nothing. The information stream is not visible by default + } + } + + /// + /// See base class. + /// + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// OR + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void WriteVerboseLine(string message) + { + // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) + { + _parent.ErrorSerializer.Serialize(message, "verbose"); + } + else + { + if (SupportsVirtualTerminal) + { + WriteLine(GetFormatStyleString(FormatStyle.Verbose) + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message) + PSStyle.Instance.Reset); + } + else + { + WriteLine( + VerboseForegroundColor, + VerboseBackgroundColor, + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message)); + } + } + } + + /// + /// See base class. + /// + /// + /// + /// If obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleTextAttribute + /// OR + /// Win32's CreateFile fails + /// OR + /// Win32's GetConsoleMode fails + /// OR + /// Win32's SetConsoleMode fails + /// OR + /// Win32's WriteConsole fails + /// + public override void WriteWarningLine(string message) + { + // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) + { + _parent.ErrorSerializer.Serialize(message, "warning"); + } + else + { + if (SupportsVirtualTerminal) + { + WriteLine(GetFormatStyleString(FormatStyle.Warning) + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message) + PSStyle.Instance.Reset); + } + else + { + WriteLine( + WarningForegroundColor, + WarningBackgroundColor, + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message)); + } + } + } + + /// + /// Invoked by CommandBase.WriteProgress to display a progress record. + /// + public override void WriteProgress(long sourceId, ProgressRecord record) + { + Dbg.Assert(record != null, "WriteProgress called with null ProgressRecord"); + + if (_parent.ErrorFormat == Serialization.DataFormat.XML) + { + PSObject obj = new PSObject(); + obj.Properties.Add(new PSNoteProperty("SourceId", sourceId)); + obj.Properties.Add(new PSNoteProperty("Record", record)); + _parent.ErrorSerializer.Serialize(obj, "progress"); + } + else if (Console.IsOutputRedirected) + { + // Do not write progress bar when the stdout is redirected. + return; + } + else + { + // We allow only one thread at a time to update the progress state.) + lock (_instanceLock) + { + HandleIncomingProgressRecord(sourceId, record); + } + } + } + + public override void WriteErrorLine(string value) + { + if (string.IsNullOrEmpty(value)) + { + return; + } + + TextWriter writer = (!Console.IsErrorRedirected || _parent.IsInteractive) + ? _parent.ConsoleTextWriter + : Console.Error; + + if (_parent.ErrorFormat == Serialization.DataFormat.XML) + { + Dbg.Assert(writer == _parent.ErrorSerializer.textWriter, "writers should be the same"); + + _parent.ErrorSerializer.Serialize(value + Environment.NewLine); + } + else + { + if (writer == _parent.ConsoleTextWriter) + { + if (SupportsVirtualTerminal) + { + WriteLine(value); + } + else + { + WriteLine(ErrorForegroundColor, ErrorBackgroundColor, value); + } + } + else + { + value = GetOutputString(value, SupportsVirtualTerminal); + Console.Error.WriteLine(value); + } + } + } + + public ConsoleColor FormatAccentColor { get; set; } = ConsoleColor.Green; + + public ConsoleColor ErrorAccentColor { get; set; } = ConsoleColor.Cyan; + + public ConsoleColor ErrorForegroundColor { get; set; } = ConsoleColor.Red; + + public ConsoleColor ErrorBackgroundColor { get; set; } = Console.BackgroundColor; + + public ConsoleColor WarningForegroundColor { get; set; } = ConsoleColor.Yellow; + + public ConsoleColor WarningBackgroundColor { get; set; } = Console.BackgroundColor; + + public ConsoleColor DebugForegroundColor { get; set; } = ConsoleColor.Yellow; + + public ConsoleColor DebugBackgroundColor { get; set; } = Console.BackgroundColor; + + public ConsoleColor VerboseForegroundColor { get; set; } = ConsoleColor.Yellow; + + public ConsoleColor VerboseBackgroundColor { get; set; } = Console.BackgroundColor; + + public ConsoleColor ProgressForegroundColor { get; set; } = ConsoleColor.Black; + + public ConsoleColor ProgressBackgroundColor { get; set; } = ConsoleColor.Yellow; + + #endregion Line-oriented interaction + + #region implementation + + // We use System.Environment.NewLine because we are platform-agnostic + + internal static readonly string Crlf = System.Environment.NewLine; + + private const string Tab = "\x0009"; + + internal enum ReadLineResult + { + endedOnEnter = 0, + endedOnTab = 1, + endedOnShiftTab = 2, + endedOnBreak = 3 + } + + private const int MaxInputLineLength = 1024; + + /// + /// Reads a line of input from the console. Returns when the user hits enter, a break key, a break event occurs. In + /// the case that stdin has been redirected, reads from the stdin stream instead of the console. + /// + /// + /// true to end input when the user hits the tab or shift-tab keys, false to only end on the enter key (or a break + /// event). Ignored if not reading from the console device. + /// + /// + /// The initial contents of the input buffer. Nice if you want to have a default result. Ignored if not reading from the + /// console device. + /// + /// + /// Receives an enum value indicating how input was ended. + /// + /// + /// TBD + /// + /// + /// true to include the results in any transcription that might be happening. + /// + /// + /// The string read from either the console or the stdin stream. null if: + /// - stdin was read and EOF was reached on the stream, or + /// - the console was read, and input was terminated with Ctrl-C, Ctrl-Break, or Close. + /// + /// + /// If Win32's SetConsoleMode fails + /// OR + /// Win32's ReadConsole fails + /// OR + /// obtaining information about the buffer failed + /// OR + /// Win32's SetConsoleCursorPosition failed + /// + internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResult result, bool calledFromPipeline, bool transcribeResult) + { + result = ReadLineResult.endedOnEnter; + + // If the test hook is set, read from it. + if (s_h != null) + { + return s_h.ReadLine(); + } + + string restOfLine = null; + + string s = ReadFromStdin + ? ReadLineFromFile(initialContent) + : ReadLineFromConsole(endOnTab, initialContent, calledFromPipeline, ref restOfLine, ref result); + + if (transcribeResult) + { + PostRead(s); + } + else + { + PostRead(); + } + + if (restOfLine != null) + s += restOfLine; + + return s; + } + + private string ReadLineFromFile(string initialContent) + { + var sb = new StringBuilder(); + if (!string.IsNullOrEmpty(initialContent)) + { + sb.Append(initialContent); + sb.Append('\n'); + } + + var consoleIn = _parent.ConsoleIn.Value; + while (true) + { + var inC = consoleIn.Read(); + if (inC == -1) + { + // EOF - we return null which tells our caller to exit + // but only if we don't have any input, we could have + // input and then stdin was closed, but never saw a newline. + return sb.Length == 0 ? null : sb.ToString(); + } + + var c = unchecked((char)inC); + if (!NoPrompt) + { + Console.Out.Write(c); + } + + if (c == '\r') + { + // Treat as newline, but consume \n if there is one. + if (consoleIn.Peek() == '\n') + { + if (!NoPrompt) + { + Console.Out.Write('\n'); + } + + consoleIn.Read(); + } + + break; + } + + if (c == '\n') + { + break; + } + + // If NoPrompt is true, we are in a sort of server mode where we shouldn't + // do anything like edit the command line - every character is part of the input. + if (c == '\b' && !NoPrompt) + { + sb.Remove(sb.Length - 1, 1); + } + else + { + sb.Append(c); + } + } + + return sb.ToString(); + } + + private string ReadLineFromConsole(bool endOnTab, string initialContent, bool calledFromPipeline, ref string restOfLine, ref ReadLineResult result) + { + PreRead(); + // Ensure that we're in the proper line-input mode. + +#if !UNIX + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); + ConsoleControl.ConsoleModes m = ConsoleControl.GetMode(handle); + + const ConsoleControl.ConsoleModes DesiredMode = + ConsoleControl.ConsoleModes.LineInput + | ConsoleControl.ConsoleModes.EchoInput + | ConsoleControl.ConsoleModes.ProcessedInput; + + if ((m & DesiredMode) != DesiredMode || (m & ConsoleControl.ConsoleModes.MouseInput) > 0) + { + m &= ~ConsoleControl.ConsoleModes.MouseInput; + m |= DesiredMode; + ConsoleControl.SetMode(handle, m); + } +#endif + + // If more characters are typed than you asked, then the next call to ReadConsole will return the + // additional characters beyond those you requested. + // + // If input is terminated with a tab key, then the buffer returned will have a tab (ascii 0x9) at the + // position where the tab key was hit. If the user has arrowed backward over existing input in the line + // buffer, the tab will overwrite whatever character was in that position. That character will be lost in + // the input buffer, but since we echo each character the user types, it's still in the active screen buffer + // and we can read the console output to get that character. + // + // If input is terminated with an enter key, then the buffer returned will have ascii 0x0D and 0x0A + // (Carriage Return and Line Feed) as the last two characters of the buffer. + // + // If input is terminated with a break key (Ctrl-C, Ctrl-Break, Close, etc.), then the buffer will be + // the empty string. + +#if UNIX + // For Unix systems, we implement a basic readline loop around Console.ReadKey(), that + // supports backspace, arrow keys, Ctrl-C, and Ctrl-D. This readline is only used for + // interactive prompts (like Read-Host), otherwise it is assumed that PSReadLine is + // available. Therefore this explicitly does not support history or tab completion. + + bool treatControlCAsInput = Console.TreatControlCAsInput; + + try + { + + ConsoleKeyInfo keyInfo; + string s = string.Empty; + int index = 0; + int cursorLeft = Console.CursorLeft; + int cursorCurrent = cursorLeft; + bool insertMode = true; + Console.TreatControlCAsInput = true; +#else + _rawui.ClearKeyCache(); + uint keyState = 0; + string s = string.Empty; + Span inputBuffer = stackalloc char[MaxInputLineLength + 1]; + if (initialContent.Length > 0) + { + initialContent.AsSpan().CopyTo(inputBuffer); + } + +#endif + while (true) + { +#if UNIX + keyInfo = Console.ReadKey(true); +#else + s += ConsoleControl.ReadConsole(handle, initialContent.Length, inputBuffer, MaxInputLineLength, endOnTab, out keyState); + Dbg.Assert(s != null, "s should never be null"); +#endif + +#if UNIX + // Handle Ctrl-C ending input + if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)) +#else + if (s.Length == 0) +#endif + { + result = ReadLineResult.endedOnBreak; + s = null; + + if (calledFromPipeline) + { + // make sure that the pipeline that called us is stopped + + throw new PipelineStoppedException(); + } + + break; + } + +#if UNIX + if (keyInfo.Key == ConsoleKey.Enter) +#else + if (s.EndsWith(Environment.NewLine, StringComparison.Ordinal)) +#endif + { + result = ReadLineResult.endedOnEnter; +#if UNIX + // We're intercepting characters, so we need to echo the newline + Console.Out.WriteLine(); +#else + s = s.Remove(s.Length - Environment.NewLine.Length); +#endif + break; + } + +#if UNIX + if (keyInfo.Key == ConsoleKey.Tab) + { + // This is unsupported + continue; + } +#else + int i = s.IndexOf(Tab, StringComparison.Ordinal); + + if (endOnTab && i != -1) + { + // then the tab we found is the completion character. bit 0x10 is set if the shift key was down + // when the key was hit. + + if ((keyState & 0x10) == 0) + { + result = ReadLineResult.endedOnTab; + } + else if ((keyState & 0x10) > 0) + { + result = ReadLineResult.endedOnShiftTab; + } + else + { + // do nothing: leave the result state as it was. This is the circumstance when we've have to + // do more than one iteration and the input ended on a tab or shift-tab, or the user hit + // enter, or the user hit ctrl-c + } + + // also clean up the screen -- if the cursor was positioned somewhere before the last character + // in the input buffer, then the characters from the tab to the end of the buffer need to be + // erased. + int leftover = RawUI.LengthInBufferCells(s.Substring(i + 1)); + + if (leftover > 0) + { + Coordinates c = RawUI.CursorPosition; + + // before cleaning up the screen, read the active screen buffer to retrieve the character that + // is overridden by the tab + char charUnderCursor = GetCharacterUnderCursor(c); + + Write(StringUtil.Padding(leftover)); + RawUI.CursorPosition = c; + + restOfLine = s[i] + (charUnderCursor + s.Substring(i + 1)); + } + else + { + restOfLine += s[i]; + } + + s = s.Remove(i); + + break; + } +#endif +#if UNIX + if (keyInfo.Key == ConsoleKey.Backspace) + { + if (index > 0) + { + int length = s.Length; + s = s.Remove(index - 1, 1); + index--; + cursorCurrent = Console.CursorLeft; + Console.CursorLeft = cursorLeft; + Console.Out.Write(s.PadRight(length)); + Console.CursorLeft = cursorCurrent - 1; + } + + continue; + } + + if (keyInfo.Key == ConsoleKey.Delete + || (keyInfo.Key == ConsoleKey.D && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + if (index < s.Length) + { + int length = s.Length; + s = s.Remove(index, 1); + cursorCurrent = Console.CursorLeft; + Console.CursorLeft = cursorLeft; + Console.Out.Write(s.PadRight(length)); + Console.CursorLeft = cursorCurrent; + } + + continue; + } + + if (keyInfo.Key == ConsoleKey.LeftArrow + || (keyInfo.Key == ConsoleKey.B && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + if (Console.CursorLeft > cursorLeft) + { + Console.CursorLeft--; + index--; + } + + continue; + } + + if (keyInfo.Key == ConsoleKey.RightArrow + || (keyInfo.Key == ConsoleKey.F && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + if (Console.CursorLeft < cursorLeft + s.Length) + { + Console.CursorLeft++; + index++; + } + + continue; + } + + if (keyInfo.Key == ConsoleKey.UpArrow + || keyInfo.Key == ConsoleKey.DownArrow + || keyInfo.Key == ConsoleKey.PageUp + || keyInfo.Key == ConsoleKey.PageDown) + { + // Arrow/Page Up/down is unimplemented, so fail gracefully + continue; + } + + if (keyInfo.Key == ConsoleKey.Home + || (keyInfo.Key == ConsoleKey.A && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + Console.CursorLeft = cursorLeft; + index = 0; + continue; + } + + if (keyInfo.Key == ConsoleKey.End + || (keyInfo.Key == ConsoleKey.E && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + Console.CursorLeft = cursorLeft + s.Length; + index = s.Length; + continue; + } + + if (keyInfo.Key == ConsoleKey.Escape) + { + Console.CursorLeft = cursorLeft; + index = s.Length; + s = string.Empty; + continue; + } + + if (keyInfo.Key == ConsoleKey.Insert) + { + // Toggle insert/overwrite mode + insertMode = !insertMode; + continue; + } + + if (char.IsControl(keyInfo.KeyChar)) + { + // deny list control characters + continue; + } + + // Handle case where terminal gets reset and the index is outside of the buffer + if (index > s.Length) + { + index = s.Length; + } + + // Modify string + if (!insertMode && index < s.Length) // then overwrite mode + { + s = s.Remove(index, 1); + } + + s = s.Insert(index, keyInfo.KeyChar.ToString()); + index++; + + // Redisplay string + cursorCurrent = Console.CursorLeft; + Console.CursorLeft = cursorLeft; + Console.Out.Write(s); + Console.CursorLeft = cursorCurrent + 1; +#endif + } + + Dbg.Assert( + (s == null && result == ReadLineResult.endedOnBreak) + || (s != null && result != ReadLineResult.endedOnBreak), + "s should only be null if input ended with a break"); + + return s; +#if UNIX + } + finally + { + Console.TreatControlCAsInput = treatControlCAsInput; + } +#endif + } + +#if !UNIX + /// + /// Get the character at the cursor when the user types 'tab' in the middle of line. + /// + /// The cursor position where 'tab' is hit. + /// + private char GetCharacterUnderCursor(Coordinates cursorPosition) + { + Rectangle region = new Rectangle(0, cursorPosition.Y, RawUI.BufferSize.Width - 1, cursorPosition.Y); + BufferCell[,] content = RawUI.GetBufferContents(region); + + for (int index = 0, column = 0; column <= cursorPosition.X; index++) + { + BufferCell cell = content[0, index]; + if (cell.BufferCellType == BufferCellType.Complete || cell.BufferCellType == BufferCellType.Leading) + { + if (column == cursorPosition.X) + { + return cell.Character; + } + + column += ConsoleControl.LengthInBufferCells(cell.Character); + } + } + + Dbg.Assert(false, "the character at the cursor should be retrieved, never gets to here"); + return '\0'; + } +#endif + + /// + /// Strip nulls from a string. + /// + /// The string to process. + /// The string with any '\0' characters removed. + private static string RemoveNulls(string input) + { + if (!input.Contains('\0')) + { + return input; + } + + StringBuilder sb = new StringBuilder(input.Length); + foreach (char c in input) + { + if (c != '\0') + { + sb.Append(c); + } + } + + return sb.ToString(); + } + + /// + /// Reads a line, and completes the input for the user if they hit tab. + /// + /// + /// The Executor instance on which to run any pipelines that are needed to find matches + /// + /// + /// null on a break event + /// the completed line otherwise + /// + internal string ReadLineWithTabCompletion(Executor exec) + { + string input = null; + string lastInput = string.Empty; + + ReadLineResult rlResult = ReadLineResult.endedOnEnter; + +#if !UNIX + ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle(); + + string lastCompletion = string.Empty; + Size screenBufferSize = RawUI.BufferSize; + + // Save the cursor position at the end of the prompt string so that we can restore it later to write the + // completed input. + + Coordinates endOfPromptCursorPos = RawUI.CursorPosition; + + CommandCompletion commandCompletion = null; + string completionInput = null; +#endif + + while (true) + { + if (TryInvokeUserDefinedReadLine(out input)) + { + break; + } + + input = ReadLine(true, lastInput, out rlResult, false, false); + + if (input == null) + { + break; + } + + if (rlResult == ReadLineResult.endedOnEnter) + { + break; + } + +#if UNIX // Portable code only ends on enter (or no input), so tab is not processed + throw new PlatformNotSupportedException("This readline state is unsupported in portable code!"); +#else + + Coordinates endOfInputCursorPos = RawUI.CursorPosition; + string completedInput = null; + + if (rlResult == ReadLineResult.endedOnTab || rlResult == ReadLineResult.endedOnShiftTab) + { + int tabIndex = input.IndexOf(Tab, StringComparison.Ordinal); + Dbg.Assert(tabIndex != -1, "tab should appear in the input"); + + string restOfLine = string.Empty; + int leftover = input.Length - tabIndex - 1; + if (leftover > 0) + { + // We are reading from the console (not redirected, b/c we don't end on tab when redirected) + // If the cursor is at the end of a line, there is actually a space character at the cursor's position and when we type tab + // at the end of a line, that space character is replaced by the tab. But when we type tab at the middle of a line, the space + // character at the end is preserved, we should remove that space character because it's not provided by the user. + input = input.Remove(input.Length - 1); + restOfLine = input.Substring(tabIndex + 1); + } + + input = input.Remove(tabIndex); + + if (input != lastCompletion || commandCompletion == null) + { + completionInput = input; + commandCompletion = GetNewCompletionResults(input); + } + + var completionResult = commandCompletion.GetNextResult(rlResult == ReadLineResult.endedOnTab); + if (completionResult != null) + { + completedInput = string.Concat(completionInput.AsSpan(0, commandCompletion.ReplacementIndex), completionResult.CompletionText); + } + else + { + completedInput = completionInput; + } + + if (restOfLine != string.Empty) + { + completedInput += restOfLine; + } + + if (completedInput.Length > (MaxInputLineLength - 2)) + { + completedInput = completedInput.Substring(0, MaxInputLineLength - 2); + } + + // Remove any nulls from the string... + completedInput = RemoveNulls(completedInput); + + // adjust the saved cursor position if the buffer scrolled as the user was typing (i.e. the user + // typed past the end of the buffer). + + int linesOfInput = (endOfPromptCursorPos.X + input.Length) / screenBufferSize.Width; + endOfPromptCursorPos.Y = endOfInputCursorPos.Y - linesOfInput; + + // replace the displayed input with the new input + try + { + RawUI.CursorPosition = endOfPromptCursorPos; + } + catch (PSArgumentOutOfRangeException) + { + // If we go a range exception, it's because + // there's no room in the buffer for the completed + // line so we'll just pretend that there was no match... + break; + } + + // When the string is written to the console, a space character is actually appended to the string + // and the cursor will flash at the position of that space character. + WriteToConsole(completedInput, false); + + Coordinates endOfCompletionCursorPos = RawUI.CursorPosition; + + // adjust the starting cursor position if the screen buffer has scrolled as a result of writing the + // completed input (i.e. writing the completed input ran past the end of the buffer). + + int linesOfCompletedInput = (endOfPromptCursorPos.X + completedInput.Length) / screenBufferSize.Width; + endOfPromptCursorPos.Y = endOfCompletionCursorPos.Y - linesOfCompletedInput; + + // blank out any "leftover" old input. That's everything between the cursor position at the time + // the user hit tab up to the current cursor position after writing the completed text. + + int deltaInput = + (endOfInputCursorPos.Y * screenBufferSize.Width + endOfInputCursorPos.X) + - (endOfCompletionCursorPos.Y * screenBufferSize.Width + endOfCompletionCursorPos.X); + + if (deltaInput > 0) + { + ConsoleControl.FillConsoleOutputCharacter(handle, ' ', deltaInput, endOfCompletionCursorPos); + } + + if (restOfLine != string.Empty) + { + lastCompletion = completedInput.Remove(completedInput.Length - restOfLine.Length); + SendLeftArrows(restOfLine.Length); + } + else + { + lastCompletion = completedInput; + } + + lastInput = completedInput; + } +#endif + } + + // Since we did not transcribe any call to ReadLine, transcribe the results here. + + if (_parent.IsTranscribing) + { + // Reads always terminate with the enter key, so add that. + + _parent.WriteLineToTranscript(input); + } + + return input; + } + +#if !UNIX + private static void SendLeftArrows(int length) + { + var inputs = new ConsoleControl.INPUT[length * 2]; + for (int i = 0; i < length; i++) + { + var down = new ConsoleControl.INPUT(); + down.Type = (uint)ConsoleControl.InputType.Keyboard; + down.Data.Keyboard = new ConsoleControl.KeyboardInput(); + down.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left; + down.Data.Keyboard.Scan = 0; + down.Data.Keyboard.Flags = 0; + down.Data.Keyboard.Time = 0; + down.Data.Keyboard.ExtraInfo = IntPtr.Zero; + + var up = new ConsoleControl.INPUT(); + up.Type = (uint)ConsoleControl.InputType.Keyboard; + up.Data.Keyboard = new ConsoleControl.KeyboardInput(); + up.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left; + up.Data.Keyboard.Scan = 0; + up.Data.Keyboard.Flags = (uint)ConsoleControl.KeyboardFlag.KeyUp; + up.Data.Keyboard.Time = 0; + up.Data.Keyboard.ExtraInfo = IntPtr.Zero; + + inputs[2 * i] = down; + inputs[2 * i + 1] = up; + } + + ConsoleControl.MimicKeyPress(inputs); + } +#endif + + private CommandCompletion GetNewCompletionResults(string input) + { + try + { + var runspace = _parent.Runspace; + var debugger = runspace.Debugger; + + if ((debugger != null) && debugger.InBreakpoint) + { + // If in debug stop mode do command completion though debugger process command. + try + { + return CommandCompletion.CompleteInputInDebugger(input, input.Length, null, debugger); + } + catch (PSInvalidOperationException) + { } + } + + if (runspace is LocalRunspace && + runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0) + { + _commandCompletionPowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); + } + else + { + _commandCompletionPowerShell = PowerShell.Create(); + _commandCompletionPowerShell.SetIsNested(_parent.IsNested); + _commandCompletionPowerShell.Runspace = runspace; + } + + return CommandCompletion.CompleteInput(input, input.Length, null, _commandCompletionPowerShell); + } + finally + { + _commandCompletionPowerShell = null; + } + } + + private const string CustomReadlineCommand = "PSConsoleHostReadLine"; + + private bool TryInvokeUserDefinedReadLine(out string input) + { + // We're using GetCommands instead of GetCommand so we don't auto-load a module should the command exist, but isn't loaded. + // The idea is that if someone hasn't defined the command (say because they started -noprofile), we shouldn't auto-load + // this function. + + var runspace = _parent.LocalRunspace; + if (runspace != null && + runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand, + CommandTypes.Function | CommandTypes.Cmdlet, nameIsPattern: false).Any()) + { + try + { + PowerShell ps; + if ((runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0) && + (Runspace.DefaultRunspace != null)) + { + ps = PowerShell.Create(RunspaceMode.CurrentRunspace); + } + else + { + ps = PowerShell.Create(); + ps.Runspace = runspace; + } + + var result = ps.AddCommand(CustomReadlineCommand).Invoke(); + if (result.Count == 1) + { + input = PSObject.Base(result[0]) as string; + return true; + } + } + catch (Exception) + { + } + } + + input = null; + return false; + } + + #endregion implementation + + // used to serialize access to instance data + + private readonly object _instanceLock = new object(); + + // If this is true, class throws on read or prompt method which require + // access to console. + internal bool ThrowOnReadAndPrompt + { + set + { + _throwOnReadAndPrompt = value; + } + } + + private bool _throwOnReadAndPrompt; + + internal void HandleThrowOnReadAndPrompt() + { + if (_throwOnReadAndPrompt) + { + throw PSTraceSource.NewInvalidOperationException(ConsoleHostUserInterfaceStrings.ReadFailsOnNonInteractiveFlag); + } + } + + // this is a test hook for the ConsoleInteractiveTestTool, which sets this field to true. + + private readonly bool _isInteractiveTestToolListening; + + // This instance data is "read-only" and need not have access serialized. + + private readonly ConsoleHostRawUserInterface _rawui; + private readonly ConsoleHost _parent; + + [TraceSource("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console")] + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console"); + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs new file mode 100644 index 0000000000000000000000000000000000000000..1c9d37ea9fbee02e2e9ba8f19c5169cd22c788c1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Threading; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + internal partial + class ConsoleHostUserInterface : PSHostUserInterface + { + /// + /// Called at the end of a prompt loop to take down any progress display that might have appeared and purge any + /// outstanding progress activity state. + /// + internal + void + ResetProgress() + { + // destroy the data structures representing outstanding progress records + // take down and destroy the progress display + + // If we have multiple runspaces on the host then any finished pipeline in any runspace will lead to call 'ResetProgress' + // so we need the lock + lock (_instanceLock) + { + if (_progPaneUpdateTimer != null) + { + // Stop update a progress pane and destroy timer + _progPaneUpdateTimer.Dispose(); + _progPaneUpdateTimer = null; + } + // We don't set 'progPaneUpdateFlag = 0' here, because: + // 1. According to MSDN, the timer callback can occur after the Dispose() method has been called. + // So we cannot guarantee the flag is truly set to 0. + // 2. When creating a new timer in 'HandleIncomingProgressRecord', we will set the flag to 1 anyway + + if (_progPane != null) + { + Dbg.Assert(_pendingProgress != null, "How can you have a progress pane and no backing data structure?"); + + _progPane.Hide(); + _progPane = null; + } + + _pendingProgress = null; + + if (SupportsVirtualTerminal && !PSHost.IsStdOutputRedirected && PSStyle.Instance.Progress.UseOSCIndicator) + { + // OSC sequence to turn off progress indicator + // https://github.com/microsoft/terminal/issues/6700 + Console.Write("\x1b]9;4;0\x1b\\"); + } + } + } + + /// + /// Invoked by ConsoleHostUserInterface.WriteProgress to update the set of outstanding activities for which + /// ProgressRecords have been received. + /// + private + void + HandleIncomingProgressRecord(long sourceId, ProgressRecord record) + { + Dbg.Assert(record != null, "record should not be null"); + + if (_pendingProgress == null) + { + Dbg.Assert(_progPane == null, "If there is no data struct, there shouldn't be a pane, either."); + + _pendingProgress = new PendingProgress(); + } + + _pendingProgress.Update(sourceId, record); + + if (_progPane == null) + { + // This is the first time we've received a progress record + // Create a progress pane + // Set up a update flag + // Create a timer for updating the flag + + _progPane = new ProgressPane(this); + + if (_progPaneUpdateTimer == null) + { + // Show a progress pane at the first time we've received a progress record + progPaneUpdateFlag = 1; + + // The timer will be auto restarted every 'UpdateTimerThreshold' ms + _progPaneUpdateTimer = new Timer(new TimerCallback(ProgressPaneUpdateTimerElapsed), null, UpdateTimerThreshold, UpdateTimerThreshold); + } + } + + if (Interlocked.CompareExchange(ref progPaneUpdateFlag, 0, 1) == 1 || record.RecordType == ProgressRecordType.Completed) + { + // Update the progress pane only when the timer set up the update flag or WriteProgress is completed. + // As a result, we do not block WriteProgress and whole script and eliminate unnecessary console locks and updates. + if (SupportsVirtualTerminal && !PSHost.IsStdOutputRedirected && PSStyle.Instance.Progress.UseOSCIndicator) + { + int percentComplete = record.PercentComplete; + if (percentComplete < 0) + { + // Write-Progress allows for negative percent complete, but not greater than 100 + // but OSC sequence is limited from 0 to 100. + percentComplete = 0; + } + + // OSC sequence to turn on progress indicator + // https://github.com/microsoft/terminal/issues/6700 + Console.Write($"\x1b]9;4;1;{percentComplete}\x1b\\"); + } + + // If VT is not supported, we change ProgressView to classic + if (!SupportsVirtualTerminal) + { + PSStyle.Instance.Progress.View = ProgressView.Classic; + } + + _progPane.Show(_pendingProgress); + } + } + + /// + /// TimerCallback for '_progPaneUpdateTimer' to update 'progPaneUpdateFlag' + /// + private + void + ProgressPaneUpdateTimerElapsed(object sender) + { + Interlocked.CompareExchange(ref progPaneUpdateFlag, 1, 0); + } + + private + void + PreWrite() + { + _progPane?.Hide(); + } + + private + void + PostWrite() + { + _progPane?.Show(); + } + + private + void + PostWrite(ReadOnlySpan value, bool newLine) + { + PostWrite(); + + if (_parent.IsTranscribing) + { + try + { + _parent.WriteToTranscript(value, newLine); + } + catch (Exception) + { + _parent.IsTranscribing = false; + } + } + } + + private + void + PreRead() + { + _progPane?.Hide(); + } + + private + void + PostRead() + { + _progPane?.Show(); + } + + private + void + PostRead(string value) + { + PostRead(); + + if (_parent.IsTranscribing) + { + try + { + // Reads always terminate with the enter key, so add that. + _parent.WriteLineToTranscript(value); + } + catch (Exception) + { + _parent.IsTranscribing = false; + } + } + } + + private ProgressPane _progPane = null; + private PendingProgress _pendingProgress = null; + // The timer set up 'progPaneUpdateFlag' every 'UpdateTimerThreshold' milliseconds to update 'ProgressPane' + private Timer _progPaneUpdateTimer = null; + + private const int UpdateTimerThreshold = 200; + + private int progPaneUpdateFlag = 0; + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs new file mode 100644 index 0000000000000000000000000000000000000000..5895dcf2b837ec37b8acbf0837f20fe7ae322016 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -0,0 +1,560 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Security; +using System.Text; + +using Dbg = System.Management.Automation.Diagnostics; +using InternalHostUserInterface = System.Management.Automation.Internal.Host.InternalHostUserInterface; + +namespace Microsoft.PowerShell +{ + internal partial + class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInterface + { + /// + /// Used by Prompt to indicate any common errors when converting the user input string to + /// the type of the parameter. + /// + private enum PromptCommonInputErrors + { + /// + /// No error or not an error prompt handles. + /// + None, + /// + /// Format error. + /// + Format, + /// + /// Overflow error. + /// + Overflow + } + + private static + bool + AtLeastOneHelpMessageIsPresent(Collection descriptions) + { + foreach (FieldDescription fd in descriptions) + { + if (fd != null) + { + if (!string.IsNullOrEmpty(fd.HelpMessage)) + { + return true; + } + } + } + + return false; + } + + /// + /// See base class. + /// + /// + /// + /// + /// + /// + /// If is null + /// OR + /// at least one FieldDescription in is null + /// + /// + /// If count is less than 1 + /// OR + /// at least one FieldDescription.AssemblyFullName in is + /// null or empty + /// + /// + /// If a FieldDescription in specifies one of SecureString or + /// PSCredential and the type can not be loaded. + /// OR + /// at least one FieldDescription in specifies an array + /// whose rank is less than 1. + /// + /// + /// If the converting the user input to the prompt field type fails unless it is caused by + /// OverflowException or FormatException + /// + public override + Dictionary + Prompt(string caption, string message, Collection descriptions) + { + // Need to implement EchoOnPrompt + HandleThrowOnReadAndPrompt(); + + if (descriptions == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(descriptions)); + } + + if (descriptions.Count < 1) + { + throw PSTraceSource.NewArgumentException(nameof(descriptions), + ConsoleHostUserInterfaceStrings.PromptEmptyDescriptionsErrorTemplate, "descriptions"); + } + + // we lock here so that multiple threads won't interleave the various reads and writes here. + + lock (_instanceLock) + { + Dictionary results = new Dictionary(); + + bool cancelInput = false; + + if (!string.IsNullOrEmpty(caption)) + { + // Should be a skin lookup + + WriteLineToConsole(); + WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); + } + + if (!string.IsNullOrEmpty(message)) + { + WriteLineToConsole(WrapToCurrentWindowWidth(message)); + } + + if (AtLeastOneHelpMessageIsPresent(descriptions)) + { + WriteLineToConsole(WrapToCurrentWindowWidth(ConsoleHostUserInterfaceStrings.PromptHelp)); + } + + int descIndex = -1; + + foreach (FieldDescription desc in descriptions) + { + descIndex++; + if (desc == null) + { + throw PSTraceSource.NewArgumentException(nameof(descriptions), + ConsoleHostUserInterfaceStrings.NullErrorTemplate, + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}]")); + } + + PSObject inputPSObject = null; + string fieldPrompt = null; + fieldPrompt = desc.Name; + + // FieldDescription.ParameterAssemblyFullName never returns null. But this is + // defense in depth. + if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) + { + string paramName = + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}].AssemblyFullName"); + throw PSTraceSource.NewArgumentException(paramName, ConsoleHostUserInterfaceStrings.NullOrEmptyErrorTemplate, paramName); + } + + Type fieldType = InternalHostUserInterface.GetFieldType(desc); + if (fieldType == null) + { + if (InternalHostUserInterface.IsSecuritySensitiveType(desc.ParameterTypeName)) + { + string errMsg = + StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptTypeLoadErrorTemplate, + desc.Name, desc.ParameterTypeFullName); + PromptingException e = new PromptingException(errMsg, + null, "BadTypeName", ErrorCategory.InvalidType); + throw e; + } + + fieldType = typeof(string); + } + + if (fieldType.GetInterface(typeof(IList).FullName) != null) + { + // field is a type implementing IList + ArrayList inputList = new ArrayList(); // stores all converted user input before + // assigned to an array + + // if the field is an array, the element type can be found; else, use Object + Type elementType = typeof(object); + if (fieldType.IsArray) + { + elementType = fieldType.GetElementType(); + int rank = fieldType.GetArrayRank(); + // This check may be redundant because it doesn't seem possible to create + // an array of zero dimension. + if (rank <= 0) + { + string msg = StringUtil.Format(ConsoleHostUserInterfaceStrings.RankZeroArrayErrorTemplate, desc.Name); + ArgumentException innerException = PSTraceSource.NewArgumentException( + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}].AssemblyFullName")); + PromptingException e = new PromptingException(msg, innerException, "ZeroRankArray", ErrorCategory.InvalidOperation); + throw e; + } + } + + StringBuilder fieldPromptList = new StringBuilder(fieldPrompt); + // fieldPromptList = fieldPrompt + "[i] :" + fieldPromptList.Append('['); + + while (true) + { + fieldPromptList.Append(CultureInfo.InvariantCulture, $"{inputList.Count}]: "); + bool endListInput = false; + object convertedObj = null; + _ = PromptForSingleItem( + elementType, + fieldPromptList.ToString(), + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: true, + out endListInput, + out cancelInput, + out convertedObj); + + if (cancelInput || endListInput) + { + break; + } + else if (!cancelInput) + { + inputList.Add(convertedObj); + // Remove the indices from the prompt + fieldPromptList.Length = fieldPrompt.Length + 1; + } + } + // if cancelInput, should throw OperationCancelException? + if (!cancelInput) + { + object tryConvertResult = null; + if (LanguagePrimitives.TryConvertTo(inputList, fieldType, out tryConvertResult)) + { + inputPSObject = PSObject.AsPSObject(tryConvertResult); + } + else + { + inputPSObject = PSObject.AsPSObject(inputList); + } + } + } + else + { + string printFieldPrompt = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptFieldPromptInputSeparatorTemplate, + fieldPrompt); + // field is not a list + object convertedObj = null; + + _ = PromptForSingleItem( + fieldType, + printFieldPrompt, + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: false, + endListInput: out _, + out cancelInput, + out convertedObj); + + if (!cancelInput) + { + inputPSObject = PSObject.AsPSObject(convertedObj); + } + } + + if (cancelInput) + { + s_tracer.WriteLine("Prompt canceled"); + WriteLineToConsole(); + results.Clear(); + break; + } + + results.Add(desc.Name, PSObject.AsPSObject(inputPSObject)); + } + + return results; + } + } + + private string PromptForSingleItem(Type fieldType, + string printFieldPrompt, + string fieldPrompt, + string caption, + string message, + FieldDescription desc, + bool fieldEchoOnPrompt, + bool listInput, + out bool endListInput, + out bool cancelInput, + out object convertedObj + ) + { + cancelInput = false; + endListInput = false; + convertedObj = null; + + if (fieldType.Equals(typeof(SecureString))) + { + WriteToConsole(printFieldPrompt, true); + SecureString secureString = ReadLineAsSecureString(); + convertedObj = secureString; + cancelInput = (convertedObj == null); + if ((secureString != null) && (secureString.Length == 0) && listInput) + { + endListInput = true; + } + } + else if (fieldType.Equals(typeof(PSCredential))) + { + WriteLineToConsole(WrapToCurrentWindowWidth(fieldPrompt)); + PSCredential credential = null; + credential = + PromptForCredential( + null, // caption already written + null, // message already written + null, + string.Empty); + convertedObj = credential; + cancelInput = (convertedObj == null); + if ((credential != null) && (credential.Password.Length == 0) && listInput) + { + endListInput = true; + } + } + else + { + string inputString = null; + do + { + inputString = PromptReadInput( + printFieldPrompt, desc, fieldEchoOnPrompt, + listInput, out endListInput, out cancelInput); + } + while (!cancelInput && !endListInput && PromptTryConvertTo(fieldType, desc.IsFromRemoteHost, inputString, out convertedObj) != + PromptCommonInputErrors.None); + return inputString; + } + + return null; + } + + /// + /// Called by Prompt. Reads user input and processes tilde commands. + /// + /// Prompt written to host for the field. + /// The field to be read. + /// True to echo user input. + /// True if the field is a list. + /// Valid only if listInput is true. set to true if the input signals end of list input. + /// True if-and-only-if the input is canceled, e.g., by Ctrl-C or Ctrl-Break. + /// Processed input string to be converted with LanguagePrimitives.ConvertTo. + private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool fieldEchoOnPrompt, + bool listInput, out bool endListInput, out bool cancelled) + { + Dbg.Assert(fieldPrompt != null, "fieldPrompt should never be null when PromptReadInput is called"); + Dbg.Assert(desc != null, "desc should never be null when PromptReadInput is called"); + + string processedInputString = null; + endListInput = false; + cancelled = false; + bool inputDone = false; + while (!inputDone) + { + WriteToConsole(fieldPrompt, true); + string rawInputString = null; + // Implement no echo here. + if (fieldEchoOnPrompt) + { + rawInputString = ReadLine(); + } + else + { + object userInput = ReadLineSafe(false, null); + string userInputString = userInput as string; + System.Management.Automation.Diagnostics.Assert(userInputString != null, "ReadLineSafe did not return a string"); + rawInputString = userInputString; + } + + if (rawInputString == null) + { + // processedInputString is null as well. No need to assign null to it. + cancelled = true; + break; + } + else + if (!string.IsNullOrEmpty(desc.Label) && rawInputString.StartsWith(PromptCommandPrefix, StringComparison.Ordinal)) + { + processedInputString = PromptCommandMode(rawInputString, desc, out inputDone); + } + else + { + if (rawInputString.Length == 0 && listInput) + { + endListInput = true; + } + + processedInputString = rawInputString; + break; + } + } + + return processedInputString; + } + + /// + /// Uses LanguagePrimitives.ConvertTo to parse inputString for fieldType. Handles two most common parse + /// exceptions: OverflowException and FormatException. + /// + /// The type that inputString is to be interpreted. + /// Is the call coming from a remote host. + /// The string to be converted. + /// if there's no error in the conversion, the converted object will be assigned here; + /// otherwise, this will be the same as the inputString + /// An object of type fieldType that inputString represents. + private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRemoteHost, string inputString, out object convertedObj) + { + Dbg.Assert(fieldType != null, "fieldType should never be null when PromptTryConvertTo is called"); + convertedObj = inputString; + + // do not do any type conversion if the prompt request is coming from a remote host + // (bug Windows 7: #381643) + its bad to have potential side effects from casting on the client (think casting to a FileStream) + if (isFromRemoteHost) + { + return PromptCommonInputErrors.None; + } + + try + { + convertedObj = LanguagePrimitives.ConvertTo(inputString, fieldType, CultureInfo.InvariantCulture); + } + catch (PSInvalidCastException e) + { + Exception innerE = e.InnerException; + if (innerE != null) + { + if (innerE is OverflowException) + { + string errMsgTemplate = + ConsoleHostUserInterfaceStrings.PromptParseOverflowErrorTemplate; + WriteLineToConsole( + WrapToCurrentWindowWidth( + string.Format(CultureInfo.CurrentCulture, errMsgTemplate, fieldType, inputString))); + return PromptCommonInputErrors.Overflow; + } + else if (innerE is FormatException) + { + // Don't output error message if the inputString is empty + if (inputString.Length > 0) + { + string errMsgTemplate = + ConsoleHostUserInterfaceStrings.PromptParseFormatErrorTemplate; + WriteLineToConsole( + WrapToCurrentWindowWidth( + string.Format(CultureInfo.CurrentCulture, errMsgTemplate, fieldType, inputString))); + } + + return PromptCommonInputErrors.Format; + } + else + { + } + } + else + { + } + } + + return PromptCommonInputErrors.None; + } + + /// + /// Handles Tilde Commands in Prompt + /// If input does not start with PromptCommandPrefix (= "!"), returns input + /// Tilde commands - + /// ! end of list, only valid for input field types that implement IList, returns string.Empty + /// !!* input !* literally, returns !* where * is any string + /// !h prints out field's Quick Help, returns null + /// All others tilde comments are invalid and return null + /// + /// returns null if-and-only-if there's nothing the caller can process. + /// + /// + /// + /// + /// + private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone) + { + Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), + string.Create(CultureInfo.InvariantCulture, $"input should start with {PromptCommandPrefix}")); + Dbg.Assert(desc != null, "desc should never be null when PromptCommandMode is called"); + string command = input.Substring(1); + + inputDone = true; + if (command.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase)) + { + return command; + } + + if (command.Length == 1) + { + if (command[0] == '?') + { + if (string.IsNullOrEmpty(desc.HelpMessage)) + { + string noHelpErrMsg = + StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptNoHelpAvailableErrorTemplate, desc.Name); + s_tracer.TraceWarning(noHelpErrMsg); + WriteLineToConsole(WrapToCurrentWindowWidth(noHelpErrMsg)); + } + else + { + WriteLineToConsole(WrapToCurrentWindowWidth(desc.HelpMessage)); + } + } + else + { + ReportUnrecognizedPromptCommand(input); + } + + inputDone = false; + return null; + } + + if (command.Length == 2) + { + if (string.Equals(command, "\"\"", StringComparison.OrdinalIgnoreCase)) + { + return string.Empty; + } + } + + if (string.Equals(command, "$null", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + else + { + ReportUnrecognizedPromptCommand(input); + inputDone = false; + return null; + } + } + + private void ReportUnrecognizedPromptCommand(string command) + { + string msg = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptUnrecognizedCommandErrorTemplate, command); + WriteLineToConsole(WrapToCurrentWindowWidth(msg)); + } + + // Prefix for command mode in Prompt + private const string PromptCommandPrefix = "!"; + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs new file mode 100644 index 0000000000000000000000000000000000000000..7e3dcfd70e09cd4927701410c9a8688901c6e810 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -0,0 +1,467 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Text; +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + internal partial class ConsoleHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleChoiceSelection + { + /// + /// See base class. + /// + /// + /// + /// + /// + /// + /// + /// If is null. + /// + /// + /// If .Count is 0. + /// + /// + /// If is greater than + /// the length of . + /// + /// + /// when prompt is canceled by, for example, Ctrl-c. + /// + public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) + { + HandleThrowOnReadAndPrompt(); + + if (choices == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(choices)); + } + + if (choices.Count == 0) + { + throw PSTraceSource.NewArgumentException(nameof(choices), + ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); + } + + if ((defaultChoice < -1) || (defaultChoice >= choices.Count)) + { + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(defaultChoice), defaultChoice, + ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceErrorTemplate, "defaultChoice", "choice"); + } + + // we lock here so that multiple threads won't interleave the various reads and writes here. + + lock (_instanceLock) + { + if (!string.IsNullOrEmpty(caption)) + { + // Should be a skin lookup + + WriteLineToConsole(); + WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); + } + + if (!string.IsNullOrEmpty(message)) + { + WriteLineToConsole(WrapToCurrentWindowWidth(message)); + } + + int result = defaultChoice; + + string[,] hotkeysAndPlainLabels = null; + HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); + + Dictionary defaultChoiceKeys = new Dictionary(); + // add the default choice key only if it is valid. -1 is used to specify + // no default. + if (defaultChoice >= 0) + { + defaultChoiceKeys.Add(defaultChoice, true); + } + + while (true) + { + WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, false); + + ReadLineResult rlResult; + string response = ReadChoiceResponse(out rlResult); + + if (rlResult == ReadLineResult.endedOnBreak) + { + string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; + PromptingException e = new PromptingException( + msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); + throw e; + } + + if (response.Length == 0) + { + // they just hit enter. + + if (defaultChoice >= 0) + { + // if there's a default, pick that one. + + result = defaultChoice; + break; + } + + continue; + } + + // decide which choice they made. + + if (response.Trim() == "?") + { + // show the help + + ShowChoiceHelp(choices, hotkeysAndPlainLabels); + continue; + } + + result = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); + + if (result >= 0) + { + break; + } + + // their input matched none of the choices, so prompt again + } + + return result; + } + } + + /// + /// Presents a dialog allowing the user to choose options from a set of options. + /// + /// + /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" + /// + /// + /// A message that describes what the choice is for. + /// + /// + /// An Collection of ChoiceDescription objects that describe each choice. + /// + /// + /// The index of the labels in the choices collection element to be presented to the user as + /// the default choice(s). + /// + /// + /// The indices of the choice elements that corresponds to the options selected. + /// + /// + public Collection PromptForChoice(string caption, + string message, + Collection choices, + IEnumerable defaultChoices) + { + HandleThrowOnReadAndPrompt(); + + if (choices == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(choices)); + } + + if (choices.Count == 0) + { + throw PSTraceSource.NewArgumentException(nameof(choices), + ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); + } + + Dictionary defaultChoiceKeys = new Dictionary(); + + if (defaultChoices != null) + { + foreach (int defaultChoice in defaultChoices) + { + if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) + { + throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, + ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, + "defaultChoice", + "choices", + defaultChoice); + } + + defaultChoiceKeys.TryAdd(defaultChoice, true); + } + } + + Collection result = new Collection(); + // we lock here so that multiple threads won't interleave the various reads and writes here. + lock (_instanceLock) + { + // write caption on the console, if present. + if (!string.IsNullOrEmpty(caption)) + { + // Should be a skin lookup + WriteLineToConsole(); + WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); + } + // write message + if (!string.IsNullOrEmpty(message)) + { + WriteLineToConsole(WrapToCurrentWindowWidth(message)); + } + + string[,] hotkeysAndPlainLabels = null; + HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); + + WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, true); + if (defaultChoiceKeys.Count > 0) + { + WriteLineToConsole(); + } + + // used to display ChoiceMessage like Choice[0],Choice[1] etc + int choicesSelected = 0; + while (true) + { + // write the current prompt + string choiceMsg = StringUtil.Format(ConsoleHostUserInterfaceStrings.ChoiceMessage, choicesSelected); + WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(choiceMsg)); + + ReadLineResult rlResult; + string response = ReadChoiceResponse(out rlResult); + + if (rlResult == ReadLineResult.endedOnBreak) + { + string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; + PromptingException e = new PromptingException( + msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); + throw e; + } + + // they just hit enter + if (response.Length == 0) + { + // this may happen when + // 1. user wants to go with the defaults + // 2. user selected some choices and wanted those + // choices to be picked. + + // user did not pick up any choices..choose the default + if (result.Count == 0) + { + // if there's a default, pick that one. + foreach (int defaultChoice in defaultChoiceKeys.Keys) + { + result.Add(defaultChoice); + } + } + // allow for no choice selection. + break; + } + + // decide which choice they made. + if (response.Trim() == "?") + { + // show the help + ShowChoiceHelp(choices, hotkeysAndPlainLabels); + continue; + } + + int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); + + if (choicePicked >= 0) + { + result.Add(choicePicked); + choicesSelected++; + } + // prompt for multiple choices + } + + return result; + } + } + + private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, + Dictionary defaultChoiceKeys, + bool shouldEmulateForMultipleChoiceSelection) + { + System.Management.Automation.Diagnostics.Assert(defaultChoiceKeys != null, "defaultChoiceKeys cannot be null."); + + ConsoleColor fg = RawUI.ForegroundColor; + ConsoleColor bg = RawUI.BackgroundColor; + int lineLenMax = RawUI.WindowSize.Width - 1; + int lineLen = 0; + + const string choiceTemplate = "[{0}] {1} "; + + for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) + { + ConsoleColor cfg = PromptColor; + if (defaultChoiceKeys.ContainsKey(i)) + { + // Should be a skin lookup + cfg = DefaultPromptColor; + } + + string choice = + string.Format( + CultureInfo.InvariantCulture, + choiceTemplate, + hotkeysAndPlainLabels[0, i], + hotkeysAndPlainLabels[1, i]); + WriteChoiceHelper(choice, cfg, bg, ref lineLen, lineLenMax); + if (shouldEmulateForMultipleChoiceSelection) + { + WriteLineToConsole(); + } + } + + WriteChoiceHelper( + ConsoleHostUserInterfaceStrings.PromptForChoiceHelp, + fg, + bg, + ref lineLen, + lineLenMax); + if (shouldEmulateForMultipleChoiceSelection) + { + WriteLineToConsole(); + } + + string defaultPrompt = string.Empty; + if (defaultChoiceKeys.Count > 0) + { + string prepend = string.Empty; + StringBuilder defaultChoicesBuilder = new StringBuilder(); + foreach (int defaultChoice in defaultChoiceKeys.Keys) + { + string defaultStr = hotkeysAndPlainLabels[0, defaultChoice]; + if (string.IsNullOrEmpty(defaultStr)) + { + defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; + } + + defaultChoicesBuilder.Append(CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); + prepend = ","; + } + + string defaultChoices = defaultChoicesBuilder.ToString(); + + if (defaultChoiceKeys.Count == 1) + { + defaultPrompt = shouldEmulateForMultipleChoiceSelection ? + StringUtil.Format(ConsoleHostUserInterfaceStrings.DefaultChoiceForMultipleChoices, defaultChoices) + : + StringUtil.Format(ConsoleHostUserInterfaceStrings.DefaultChoicePrompt, defaultChoices); + } + else + { + defaultPrompt = StringUtil.Format(ConsoleHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, + defaultChoices); + } + } + + WriteChoiceHelper(defaultPrompt, + fg, + bg, + ref lineLen, + lineLenMax); + } + + private void WriteChoiceHelper(string text, ConsoleColor fg, ConsoleColor bg, ref int lineLen, int lineLenMax) + { + int textLen = RawUI.LengthInBufferCells(text); + bool trimEnd = false; + + if (lineLen + textLen > lineLenMax) + { + WriteLineToConsole(); + trimEnd = true; + lineLen = textLen; + } + else + { + lineLen += textLen; + } + + WriteToConsole(fg, bg, trimEnd ? text.TrimEnd(null) : text); + } + + private string ReadChoiceResponse(out ReadLineResult result) + { + result = ReadLineResult.endedOnEnter; + return InternalTestHooks.ForcePromptForChoiceDefaultOption + ? string.Empty + : ReadLine( + endOnTab: false, + initialContent: string.Empty, + result: out result, + calledFromPipeline: true, + transcribeResult: true); + } + + private void ShowChoiceHelp(Collection choices, string[,] hotkeysAndPlainLabels) + { + Dbg.Assert(choices != null, "choices: expected a value"); + Dbg.Assert(hotkeysAndPlainLabels != null, "hotkeysAndPlainLabels: expected a value"); + + for (int i = 0; i < choices.Count; ++i) + { + string s; + + // If there's no hotkey, use the label as the help + + if (hotkeysAndPlainLabels[0, i].Length > 0) + { + s = hotkeysAndPlainLabels[0, i]; + } + else + { + s = hotkeysAndPlainLabels[1, i]; + } + + WriteLineToConsole( + WrapToCurrentWindowWidth( + string.Create(CultureInfo.InvariantCulture, $"{s} - {choices[i].HelpMessage}"))); + } + } + + /// + /// Guarantee a contrasting color for the prompt... + /// + private ConsoleColor PromptColor + { + get + { + switch (RawUI.BackgroundColor) + { + case ConsoleColor.White: return ConsoleColor.Black; + case ConsoleColor.Cyan: return ConsoleColor.Black; + case ConsoleColor.DarkYellow: return ConsoleColor.Black; + case ConsoleColor.Yellow: return ConsoleColor.Black; + case ConsoleColor.Gray: return ConsoleColor.Black; + case ConsoleColor.Green: return ConsoleColor.Black; + default: return ConsoleColor.White; + } + } + } + /// + /// Guarantee a contrasting color for the default prompt that is slightly + /// different from the other prompt elements. + /// + private ConsoleColor DefaultPromptColor + { + get + { + if (PromptColor == ConsoleColor.White) + return ConsoleColor.Yellow; + else + return ConsoleColor.Blue; + } + } + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs new file mode 100644 index 0000000000000000000000000000000000000000..1e934553f18cd5df714816e466f959975373148e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security; + +namespace Microsoft.PowerShell +{ + /// + /// ConsoleHostUserInterface implements console-mode user interface for powershell. + /// + internal partial + class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInterface + { + /// + /// Prompt for credentials. + /// + /// In future, when we have Credential object from the security team, + /// this function will be modified to prompt using secure-path + /// if so configured. + /// + /// Name of the user whose creds are to be prompted for. If set to null or empty string, the function will prompt for user name first. + /// Name of the target for which creds are being collected. + /// Message to be displayed. + /// Caption for the message. + /// PSCredential object. + public override PSCredential PromptForCredential( + string caption, + string message, + string userName, + string targetName) + { + return PromptForCredential(caption, + message, + userName, + targetName, + PSCredentialTypes.Default, + PSCredentialUIOptions.Default); + } + + /// + /// Prompt for credentials. + /// + /// Name of the user whose creds are to be prompted for. If set to null or empty string, the function will prompt for user name first. + /// Name of the target for which creds are being collected. + /// Message to be displayed. + /// Caption for the message. + /// What type of creds can be supplied by the user. + /// Options that control the cred gathering UI behavior. + /// PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF). + public override PSCredential PromptForCredential( + string caption, + string message, + string userName, + string targetName, + PSCredentialTypes allowedCredentialTypes, + PSCredentialUIOptions options) + { + PSCredential cred = null; + SecureString password = null; + string userPrompt = null; + string passwordPrompt = null; + + if (!string.IsNullOrEmpty(caption)) + { + // Should be a skin lookup + + WriteLineToConsole(); + WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); + } + + if (!string.IsNullOrEmpty(message)) + { + WriteLineToConsole(WrapToCurrentWindowWidth(message)); + } + + if (string.IsNullOrEmpty(userName)) + { + userPrompt = ConsoleHostUserInterfaceSecurityResources.PromptForCredential_User; + + // + // need to prompt for user name first + // + do + { + WriteToConsole(userPrompt, true); + userName = ReadLine(); + if (userName == null) + { + return null; + } + } + while (userName.Length == 0); + } + + passwordPrompt = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_Password, userName + ); + + if (!InternalTestHooks.NoPromptForPassword) + { + WriteToConsole(passwordPrompt, transcribeResult: true); + password = ReadLineAsSecureString(); + if (password == null) + { + return null; + } + + WriteLineToConsole(); + } + else + { + password = new SecureString(); + } + + if (!string.IsNullOrEmpty(targetName)) + { + userName = StringUtil.Format("{0}\\{1}", targetName, userName); + } + + cred = new PSCredential(userName, password); + + return cred; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs new file mode 100644 index 0000000000000000000000000000000000000000..ce5d5ecaef4f62b67154e7cfaaafb312bcbd48d4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +namespace Microsoft.PowerShell +{ + /// + /// This class provides an entry point which is called + /// to transfer control to console host implementation. + /// + public static class ConsoleShell + { + /// Entry point in to ConsoleShell. This method is called by main of minishell. + /// Banner text to be displayed by ConsoleHost. + /// Help text for minishell. This is displayed on 'minishell -?'. + /// Commandline parameters specified by user. + /// An integer value which should be used as exit code for the process. + public static int Start(string? bannerText, string? helpText, string[] args) + { + return StartImpl( + initialSessionState: InitialSessionState.CreateDefault2(), + bannerText, + helpText, + args, + issProvided: false); + } + + /// Entry point in to ConsoleShell. Used to create a custom Powershell console application. + /// InitialSessionState to be used by the ConsoleHost. + /// Banner text to be displayed by ConsoleHost. + /// Help text for the shell. + /// Commandline parameters specified by user. + /// An integer value which should be used as exit code for the process. + public static int Start(InitialSessionState initialSessionState, string? bannerText, string? helpText, string[] args) + { + return StartImpl( + initialSessionState, + bannerText, + helpText, + args, + issProvided: true); + } + + /// + /// Implementation of entry point to ConsoleShell. + /// Used to create a custom Powershell console application. + /// + /// InitialSessionState to be used by the ConsoleHost. + /// Banner text to be displayed by ConsoleHost. + /// Help text for the shell. + /// Commandline parameters specified by user. + /// True when the InitialSessionState object is provided by caller. + /// An integer value which should be used as exit code for the process. + private static int StartImpl( + InitialSessionState initialSessionState, + string? bannerText, + string? helpText, + string[] args, + bool issProvided) + { + if (initialSessionState == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); + } + + if (args == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(args)); + } + + ConsoleHost.ParseCommandLine(args); + ConsoleHost.DefaultInitialSessionState = initialSessionState; + + return ConsoleHost.Start(bannerText, helpText, issProvided); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs new file mode 100644 index 0000000000000000000000000000000000000000..a82156ce1c88cb1335e217bb590181a3eafef11a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Text; +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + internal + class ConsoleTextWriter : TextWriter + { + internal + ConsoleTextWriter(ConsoleHostUserInterface ui) + : base(System.Globalization.CultureInfo.CurrentCulture) + { + Dbg.Assert(ui != null, "ui needs a value"); + + _ui = ui; + } + + public override + Encoding + Encoding + { + get + { + return null; + } + } + + public override + void + Write(string value) + { + _ui.WriteToConsole(value, transcribeResult: true); + } + + public override + void + Write(ReadOnlySpan value) + { + _ui.WriteToConsole(value, transcribeResult: true); + } + + public override + void + WriteLine(string value) + { + _ui.WriteLineToConsole(value, transcribeResult: true); + } + + public override + void + WriteLine(ReadOnlySpan value) + { + _ui.WriteLineToConsole(value, transcribeResult: true); + } + + public override + void + Write(bool b) + { + if (b) + { + _ui.WriteToConsole(bool.TrueString, transcribeResult: true); + } + else + { + _ui.WriteToConsole(bool.FalseString, transcribeResult: true); + } + } + + public override + void + Write(char c) + { + ReadOnlySpan value = [c]; + _ui.WriteToConsole(value, transcribeResult: true); + } + + public override + void + Write(char[] a) + { + _ui.WriteToConsole(a, transcribeResult: true); + } + + private readonly ConsoleHostUserInterface _ui; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs new file mode 100644 index 0000000000000000000000000000000000000000..354c61fb8f312e82c1732eee28db7a35d9a71cc9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -0,0 +1,709 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// Executor wraps a Pipeline instance, and provides helper methods for executing commands in that pipeline. It is used to + /// provide bookkeeping and structure to the use of pipeline in such a way that they can be interrupted and cancelled by a + /// break event handler, and to track nesting of pipelines (which happens with interrupted input loops (aka subshells) and + /// use of tab-completion in prompts). The bookkeeping is necessary because the break handler is static and global, and + /// there is no means for tying a break handler to an instance of an object. + /// + /// The class' instance methods manage a single pipeline. The class' static methods track the outstanding instances to + /// ensure that only one instance is 'active' (and therefore cancellable) at a time. + /// + internal class Executor + { + [Flags] + internal enum ExecutionOptions + { + None = 0x0, + AddOutputter = 0x01, + AddToHistory = 0x02, + ReadInputObjects = 0x04 + } + + /// + /// Constructs a new instance. + /// + /// + /// A reference to the parent ConsoleHost that created this instance. + /// + /// + /// true if the executor is supposed to use nested pipelines; false if not. + /// + /// + /// True if the instance will be used to execute the prompt function, which will delay stopping the pipeline by some + /// milliseconds. This will prevent us from stopping the pipeline so quickly that, when the user leans on the ctrl-c + /// key, the prompt "stops working" (because it is being stopped faster than it can run to completion). + /// + internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor) + { + Dbg.Assert(parent != null, "parent should not be null"); + + _parent = parent; + this.useNestedPipelines = useNestedPipelines; + _isPromptFunctionExecutor = isPromptFunctionExecutor; + Reset(); + } + + #region async + + // called on the pipeline thread + private void OutputObjectStreamHandler(object sender, EventArgs e) + { + // e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's + // DataReady event that calls this handler, which is the PipelineReader for the Output object stream. + + PipelineReader reader = (PipelineReader)sender; + + // We use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be + // inconsistent for this method to be called when there are no objects, since it will be called synchronously on + // the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we + // prefer to take no chance of blocking. + + Collection objects = reader.NonBlockingRead(); + foreach (PSObject obj in objects) + { + _parent.OutputSerializer.Serialize(obj); + } + } + + // called on the pipeline thread + private void ErrorObjectStreamHandler(object sender, EventArgs e) + { + // e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's + // DataReady event that calls this handler, which is the PipelineReader for the Error object stream. + + PipelineReader reader = (PipelineReader)sender; + + // We use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be + // inconsistent for this method to be called when there are no objects, since it will be called synchronously on + // the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we + // prefer to take no chance of blocking. + + Collection objects = reader.NonBlockingRead(); + foreach (object obj in objects) + { + _parent.ErrorSerializer.Serialize(obj); + } + } + + /// + /// This method handles failures in executing the pipeline asynchronously. + /// + /// + private void AsyncPipelineFailureHandler(Exception ex) + { + ErrorRecord er = null; + if (ex is IContainsErrorRecord cer) + { + er = cer.ErrorRecord; + // The exception inside the error record is ParentContainsErrorRecordException, which + // doesn't have a stack trace. Replace it with the top level exception. + er = new ErrorRecord(er, ex); + } + + er ??= new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); + + _parent.ErrorSerializer.Serialize(er); + } + + private sealed class PipelineFinishedWaitHandle + { + internal PipelineFinishedWaitHandle(Pipeline p) + { + p.StateChanged += PipelineStateChangedHandler; + } + + internal void Wait() + { + _eventHandle.WaitOne(); + } + + private void PipelineStateChangedHandler(object sender, PipelineStateEventArgs e) + { + if ( + e.PipelineStateInfo.State == PipelineState.Completed + || e.PipelineStateInfo.State == PipelineState.Failed + || e.PipelineStateInfo.State == PipelineState.Stopped) + { + _eventHandle.Set(); + } + } + + private readonly System.Threading.ManualResetEvent _eventHandle = new System.Threading.ManualResetEvent(false); + } + + internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, ExecutionOptions options) + { + Dbg.Assert(!useNestedPipelines, "can't async invoke a nested pipeline"); + Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); + + bool addToHistory = (options & ExecutionOptions.AddToHistory) > 0; + Pipeline tempPipeline = _parent.RunspaceRef.CreatePipeline(command, addToHistory, false); + ExecuteCommandAsyncHelper(tempPipeline, out exceptionThrown, options); + } + + /// + /// Executes a pipeline in the console when we are running asnyc. + /// + /// + /// The pipeline to execute. + /// + /// + /// Any exception thrown trying to run the pipeline. + /// + /// + /// The options to use to execute the pipeline. + /// + 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 occur when the input is closed. This can happen + // for various reasons. For example: The command in the pipeline is invalid and + // command discovery throws an 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(); + } + } + + #endregion async + + internal Pipeline CreatePipeline() + { + if (useNestedPipelines) + { + return _parent.RunspaceRef.CreateNestedPipeline(); + } + else + { + return _parent.RunspaceRef.CreatePipeline(); + } + } + + internal Pipeline CreatePipeline(string command, bool addToHistory) + { + Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); + return _parent.RunspaceRef.CreatePipeline(command, addToHistory, useNestedPipelines); + } + + /// + /// 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. + /// + /// + /// The command line to be executed. Must be non-null. + /// + /// + /// 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. + /// + /// + /// Options to govern the execution + /// + /// + /// The object stream resulting from the execution. May be null. + /// + internal Collection ExecuteCommand(string command, out Exception exceptionThrown, ExecutionOptions options) + { + Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); + + Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0); + + return ExecuteCommandHelper(tempPipeline, out exceptionThrown, options); + } + + private static Command GetOutDefaultCommand(bool endOfStatement) + { + return new Command(command: "Out-Default", + isScript: false, + useLocalScope: true, + mergeUnclaimedPreviousErrorResults: true) + { + IsEndOfStatement = endOfStatement + }; + } + + internal Collection ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) + { + Dbg.Assert(tempPipeline != null, "command should have a value"); + + exceptionThrown = null; + + Collection 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; + } + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Needed by ProfileTests as mentioned in bug 140572")] + internal Collection ExecuteCommand(string command) + { + Collection result = null; + Exception e = null; + + do + { + result = ExecuteCommand(command, out e, ExecutionOptions.None); + if (e != null) + { + break; + } + + if (result == null) + { + break; + } + } while (false); + + return result; + } + + /// + /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a string. Any Exception + /// thrown in the course of execution is returned through the exceptionThrown parameter. + /// + /// + /// The command to execute. May be any valid monad command. + /// + /// + /// Receives the Exception thrown by the execution of the command, if any. Set to null if no exception is thrown. + /// Can be tested to see if the execution was successful or not. + /// + /// + /// The string representation of the first result object returned, or null if an exception was thrown or no objects were + /// returned by the command. + /// + internal string ExecuteCommandAndGetResultAsString(string command, out Exception exceptionThrown) + { + exceptionThrown = null; + + string result = null; + + do + { + Collection streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None); + + if (exceptionThrown != null) + { + break; + } + + if (streamResults == null || streamResults.Count == 0) + { + break; + } + + // we got back one or more objects. Pick off the first result. + if (streamResults[0] == null) + return string.Empty; + + // And convert the base object into a string. We can't use the proxied + // ToString() on the PSObject because there is no default runspace + // available. + if (streamResults[0] is PSObject msho) + result = msho.BaseObject.ToString(); + else + result = streamResults[0].ToString(); + } + while (false); + + return result; + } + + /// + /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception + /// thrown in the course of execution is caught and ignored. + /// + /// + /// The command to execute. May be any valid monad command. + /// + /// + /// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no + /// objects were returned by the command. + /// + internal bool? ExecuteCommandAndGetResultAsBool(string command) + { + bool? result = ExecuteCommandAndGetResultAsBool(command, out _); + + return result; + } + + /// + /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception + /// thrown in the course of execution is returned through the exceptionThrown parameter. + /// + /// + /// The command to execute. May be any valid monad command. + /// + /// + /// Receives the Exception thrown by the execution of the command, if any. Set to null if no exception is thrown. + /// Can be tested to see if the execution was successful or not. + /// + /// + /// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no + /// objects were returned by the command. + /// + internal bool? ExecuteCommandAndGetResultAsBool(string command, out Exception exceptionThrown) + { + exceptionThrown = null; + + Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); + + bool? result = null; + + do + { + Collection streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None); + + if (exceptionThrown != null) + { + break; + } + + if (streamResults == null || streamResults.Count == 0) + { + break; + } + + // we got back one or more objects. + + result = (streamResults.Count > 1) || (LanguagePrimitives.IsTrue(streamResults[0])); + } + while (false); + + return result; + } + + /// + /// Cancels execution of the current instance. Does nothing if the current instance is not running. Called in + /// response to a break handler, by the static Executor.Cancel method. + /// + private void Cancel() + { + // if there's a pipeline running, stop it. + + lock (_instanceStateLock) + { + if (_pipeline != null && !_cancelled) + { + _cancelled = true; + + if (_isPromptFunctionExecutor) + { + System.Threading.Thread.Sleep(100); + } + + _pipeline.Stop(); + } + } + } + + internal void BlockCommandOutput() + { + if (_pipeline is RemotePipeline remotePipeline) + { + // Waits until queued data is handled. + remotePipeline.DrainIncomingData(); + + // Blocks any new data. + remotePipeline.SuspendIncomingData(); + } + } + + internal void ResumeCommandOutput() + { + RemotePipeline remotePipeline = _pipeline as RemotePipeline; + + // Resumes data flow. + remotePipeline?.ResumeIncomingData(); + } + + /// + /// Resets the instance to its post-ctor state. Does not cancel execution. + /// + private void Reset() + { + lock (_instanceStateLock) + { + _pipeline = null; + _cancelled = false; + } + } + + /// + /// Makes the given instance the "current" instance, that is, the instance that will receive a Cancel call if the break + /// handler is triggered and calls the static Cancel method. + /// + /// + /// The instance to make current. Null is allowed. + /// + /// + /// Here are some state-transition cases to illustrate the use of CurrentExecutor + /// + /// null is current + /// p1.ExecuteCommand + /// set p1 as current + /// promptforparams + /// tab complete + /// p2.ExecuteCommand + /// set p2 as current + /// p2.Execute completes + /// restore old current to p1 + /// p1.Execute completes + /// restore null as current + /// + /// Here's another case: + /// null is current + /// p1.ExecuteCommand + /// set p1 as current + /// ShouldProcess - suspend + /// EnterNestedPrompt + /// set null as current so that break does not exit the subshell + /// evaluate prompt + /// p2.ExecuteCommand + /// set p2 as current + /// Execute completes + /// restore null as current + /// nested loop exit + /// restore p1 as current + /// + /// Summary: + /// ExecuteCommand always saves/sets/restores CurrentExecutor + /// Host.EnterNestedPrompt always saves/clears/restores CurrentExecutor + /// + internal static Executor CurrentExecutor + { + get + { + Executor result = null; + + lock (s_staticStateLock) + { + result = s_currentExecutor; + } + + return result; + } + + set + { + lock (s_staticStateLock) + { + // null is acceptable. + + s_currentExecutor = value; + } + } + } + + /// + /// Cancels the execution of the current instance (the instance last passed to PushCurrentExecutor), if any. Does + /// nothing if no instance is Current. + /// + internal static void CancelCurrentExecutor() + { + Executor temp = null; + + lock (s_staticStateLock) + { + temp = s_currentExecutor; + } + + temp?.Cancel(); + } + + // These statics are threadsafe, as there can be only one instance of ConsoleHost in a process at a time, and access + // to currentExecutor is guarded by staticStateLock, and static initializers are run by the CLR at program init time. + + private static Executor s_currentExecutor; + private static readonly object s_staticStateLock = new object(); + + private readonly ConsoleHost _parent; + private Pipeline _pipeline; + private bool _cancelled; + internal bool useNestedPipelines; + private readonly object _instanceStateLock = new object(); + private readonly bool _isPromptFunctionExecutor; + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs new file mode 100644 index 0000000000000000000000000000000000000000..acfdea0715353cb4e0a7d68d149607a7ed01957e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.ComponentModel; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Runspaces; +using System.Management.Automation.Tracing; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Microsoft.PowerShell +{ + /// + /// Defines an entry point from unmanaged code to PowerShell. + /// + public sealed class UnmanagedPSEntry + { + /// + /// Starts PowerShell. + /// + /// + /// Deprecated: Console file used to create a runspace configuration to start PowerShell + /// + /// + /// Command line arguments to the PowerShell + /// + /// + /// Length of the passed in argument array. + /// + [Obsolete("Callers should now use UnmanagedPSEntry.Start(string[], int)", error: true)] + public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] args, int argc) + { + return Start(args, argc); + } + + /// + /// Starts PowerShell. + /// + /// + /// Command line arguments to PowerShell + /// + /// + /// Length of the passed in argument array. + /// + public static int Start([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] args, int argc) + { + ArgumentNullException.ThrowIfNull(args); + +#if DEBUG + if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && args[0]!.Equals("-isswait", StringComparison.OrdinalIgnoreCase)) + { + Console.WriteLine("Attach the debugger to continue..."); + while (!System.Diagnostics.Debugger.IsAttached) + { + Thread.Sleep(100); + } + + System.Diagnostics.Debugger.Break(); + } +#endif + // Warm up some components concurrently on background threads. + EarlyStartup.Init(); + + // Windows Vista and later support non-traditional UI fallback ie., a + // user on an Arabic machine can choose either French or English(US) as + // UI fallback language. + // CLR does not support this (non-traditional) fallback mechanism. + // The currentUICulture returned NativeCultureResolver supports this non + // traditional fallback on Vista. So it is important to set currentUICulture + // in the beginning before we do anything. + Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture; + Thread.CurrentThread.CurrentCulture = NativeCultureResolver.Culture; + + ConsoleHost.ParseCommandLine(args); + + // NOTE: On Unix, logging depends on a command line parsing + // and must be just after ConsoleHost.ParseCommandLine(args) + // to allow overriding logging options. + PSEtwLog.LogConsoleStartup(); + + int exitCode = 0; + try + { + string banner = string.Format( + CultureInfo.InvariantCulture, + ManagedEntranceStrings.ShellBannerPowerShell, + PSVersionInfo.GitCommitId); + + ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); + + exitCode = ConsoleHost.Start( + bannerText: banner, + helpText: ManagedEntranceStrings.UsageHelp, + issProvidedExternally: false); + } + catch (HostException e) + { + if (e.InnerException is Win32Exception win32e) + { + // These exceptions are caused by killing conhost.exe + // 1236, network connection aborted by local system + // 0x6, invalid console handle + if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236) + { + return exitCode; + } + } + + System.Environment.FailFast(e.Message, e); + } + catch (Exception e) + { + System.Environment.FailFast(e.Message, e); + } + + return exitCode; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs new file mode 100644 index 0000000000000000000000000000000000000000..b16fb5ee14796d299cc820b2cb68ca529cbd636d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -0,0 +1,994 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// Represents all of the outstanding progress activities received by the host, and includes methods to update that state + /// upon receipt of new ProgressRecords, and to render that state into an array of strings such that ProgressPane can + /// display it. + /// + /// The set of activities that we're tracking is logically a binary tree, with siblings in one branch and children in + /// another. For ease of implementation, this tree is represented as lists of lists. We use ArrayList as out list type, + /// although List1 (generic List) would also have worked. I suspect that ArrayList is faster because there are fewer links + /// to twiddle, though I have not measured that. + /// + /// This class uses lots of nearly identical helper functions to recursively traverse the tree. If I weren't so pressed + /// for time, I would see if generic methods could be used to collapse the number of traversers. + /// + internal + class PendingProgress + { + #region Updating Code + + /// + /// Update the data structures that represent the outstanding progress records reported so far. + /// + /// + /// Identifier of the source of the event. This is used as part of the "key" for matching newly received records with + /// records that have already been received. For a record to match (meaning that they refer to the same activity), both + /// the source and activity identifiers need to match. + /// + /// + /// The ProgressRecord received that will either update the status of an activity which we are already tracking, or + /// represent a new activity that we need to track. + /// + internal + void + Update(long 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) + { + 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(); + } + + private + void + EvictNode() + { + ArrayList listWhereFound = null; + int indexWhereFound = -1; + + ProgressNode oldestNode = FindOldestLeafmostNode(out listWhereFound, out indexWhereFound); + if (oldestNode == null) + { + // Well that's a surprise. There's got to be at least one node there that's older than 0. + + Dbg.Assert(false, "Must be an old node in the tree somewhere"); + + // We'll just pick the root node, then. + + RemoveNode(_topLevelNodes, 0); + } + else + { + RemoveNode(listWhereFound, indexWhereFound); + } + } + + /// + /// Removes a node from the tree. + /// + /// + /// List in the tree from which the node is to be removed. + /// + /// + /// Index into the list of the node to be removed. + /// + private + void + RemoveNode(ArrayList nodes, int indexToRemove) + { +#if DEBUG || ASSERTIONS_TRACE + ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove]; + + Dbg.Assert(nodes != null, "can't remove nodes from a null list"); + Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); + Dbg.Assert(nodes[indexToRemove] != null, "no node at specified index"); + Dbg.Assert(nodeToRemove.Children == null || nodeToRemove.Children.Count == 0, "can't remove a node with children"); +#endif + + nodes.RemoveAt(indexToRemove); + --_nodeCount; + +#if DEBUG || ASSERTIONS_ON + Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); +#endif + } + + private + void + RemoveNodeAndPromoteChildren(ArrayList nodes, int indexToRemove) + { + ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove]; + + Dbg.Assert(nodes != null, "can't remove nodes from a null list"); + Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); + Dbg.Assert(nodeToRemove != null, "no node at specified index"); + + if (nodeToRemove == null) + { + return; + } + + if (nodeToRemove.Children != null) + { + // promote the children. + + for (int i = 0; i < nodeToRemove.Children.Count; ++i) + { + // unparent the children. If the children are ever updated again, they will be reparented. + + ((ProgressNode)nodeToRemove.Children[i]).ParentActivityId = -1; + } + + // add the children as siblings + + nodes.RemoveAt(indexToRemove); + --_nodeCount; + nodes.InsertRange(indexToRemove, nodeToRemove.Children); + +#if DEBUG || ASSERTIONS_TRACE + Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); +#endif + } + else + { + // nothing to promote + + RemoveNode(nodes, indexToRemove); + return; + } + } + + /// + /// Adds a node to the tree, first removing the oldest node if the tree is too large. + /// + /// + /// List in the tree where the node is to be added. + /// + /// + /// Node to be added. + /// + private + void + AddNode(ArrayList nodes, ProgressNode nodeToAdd) + { + nodes.Add(nodeToAdd); + ++_nodeCount; + +#if DEBUG || ASSERTIONS_TRACE + Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); + Dbg.Assert(_nodeCount <= maxNodeCount, "Too many nodes in tree!"); +#endif + } + + private sealed class FindOldestNodeVisitor : NodeVisitor + { + internal override + bool + Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound) + { + if (node.Age >= _oldestSoFar) + { + _oldestSoFar = node.Age; + FoundNode = node; + this.ListWhereFound = listWhereFound; + this.IndexWhereFound = indexWhereFound; + } + + return true; + } + + internal + ProgressNode + FoundNode; + + internal + ArrayList + ListWhereFound; + + internal + int + IndexWhereFound = -1; + + private int _oldestSoFar; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Accesses instance members in preprocessor branch.")] + private + ProgressNode + 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; + } + + private + ProgressNode + FindOldestLeafmostNode(out ArrayList listWhereFound, out int indexWhereFound) + { + listWhereFound = null; + indexWhereFound = -1; + + ProgressNode result = null; + ArrayList treeToSearch = _topLevelNodes; + + while (true) + { + result = FindOldestLeafmostNodeHelper(treeToSearch, out listWhereFound, out indexWhereFound); + if (result == null || result.Children == null || result.Children.Count == 0) + { + break; + } + + // search the subtree for the oldest child + + treeToSearch = result.Children; + } + + return result; + } + + /// + /// Convenience overload. + /// + private + ProgressNode + FindNodeById(long sourceId, int activityId) + { + ArrayList listWhereFound = null; + int indexWhereFound = -1; + return + FindNodeById(sourceId, activityId, out listWhereFound, out indexWhereFound); + } + + private sealed class FindByIdNodeVisitor : NodeVisitor + { + internal + FindByIdNodeVisitor(long sourceIdToFind, int activityIdToFind) + { + _sourceIdToFind = sourceIdToFind; + _idToFind = activityIdToFind; + } + + internal override + bool + Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound) + { + if (node.ActivityId == _idToFind && node.SourceId == _sourceIdToFind) + { + this.FoundNode = node; + this.ListWhereFound = listWhereFound; + this.IndexWhereFound = indexWhereFound; + return false; + } + + return true; + } + + internal + ProgressNode + FoundNode; + + internal + ArrayList + ListWhereFound; + + internal + int + IndexWhereFound = -1; + + private readonly int _idToFind = -1; + private readonly long _sourceIdToFind; + } + + /// + /// Finds a node with a given ActivityId in provided set of nodes. Recursively walks the set of nodes and their children. + /// + /// + /// Identifier of the source of the record. + /// + /// + /// ActivityId to search for. + /// + /// + /// Receives reference to the List where the found node was located, or null if no suitable node was found. + /// + /// + /// Receives the index into listWhereFound that indicating where in the list the node was located, or -1 if + /// no suitable node was found. + /// + /// + /// The found node, or null if no suitable node was located. + /// + private + ProgressNode + FindNodeById(long sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound) + { + listWhereFound = null; + indexWhereFound = -1; + + FindByIdNodeVisitor v = new FindByIdNodeVisitor(sourceId, activityId); + NodeVisitor.VisitNodes(_topLevelNodes, 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"); + } +#endif + return v.FoundNode; + } + + /// + /// Finds the oldest node with a given rendering style that is at least as old as a given age. + /// + /// + /// List of nodes to search. Child lists of each node in this list will also be searched. + /// + /// + /// The minimum age of the node to be located. To find the oldest node, pass 0. + /// + /// The rendering style of the node to be located. + /// + /// + /// The found node, or null if no suitable node was located. + /// + private static ProgressNode FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style) + { + if (nodes == null) + { + return null; + } + + ProgressNode found = null; + for (int i = 0; i < nodes.Count; ++i) + { + ProgressNode node = (ProgressNode)nodes[i]; + Dbg.Assert(node != null, "nodes should not contain null elements"); + + if (node.Age >= oldestSoFar && node.Style == style) + { + found = node; + oldestSoFar = found.Age; + } + + if (node.Children != null) + { + ProgressNode child = FindOldestNodeOfGivenStyle(node.Children, oldestSoFar, style); + + if (child != null) + { + // In this universe, parents can be younger than their children. We found a child older than us. + + found = child; + oldestSoFar = found.Age; + } + } + } + +#if DEBUG || ASSERTIONS_TRACE + if (found != null) + { + Dbg.Assert(found.Style == style, "unexpected style"); + Dbg.Assert(found.Age >= oldestSoFar, "unexpected age"); + } +#endif + return found; + } + + private sealed class AgeAndResetStyleVisitor : NodeVisitor + { + internal override + bool + Visit(ProgressNode node, ArrayList unused, int unusedToo) + { + node.Age = Math.Min(node.Age + 1, Int32.MaxValue - 1); + + node.Style = ProgressNode.IsMinimalProgressRenderingEnabled() + ? ProgressNode.RenderStyle.Ansi + : node.Style = ProgressNode.RenderStyle.FullPlus; + + return true; + } + } + + /// + /// Increments the age of each of the nodes in the given list, and all their children. Also sets the rendering + /// style of each node to "full." + /// + /// All nodes are aged every time a new ProgressRecord is received. + /// + private + void + AgeNodesAndResetStyle() + { + AgeAndResetStyleVisitor arsv = new AgeAndResetStyleVisitor(); + NodeVisitor.VisitNodes(_topLevelNodes, arsv); + } + + #endregion // Updating Code + + #region Rendering Code + + /// + /// Generates an array of strings representing as much of the outstanding progress activities as possible within the given + /// space. As more outstanding activities are collected, nodes are "compressed" (i.e. rendered in an increasing terse + /// fashion) in order to display as many as possible. Ultimately, some nodes may be compressed to the point of + /// invisibility. The oldest nodes are compressed first. + /// + /// + /// The maximum width (in BufferCells) that the rendering may consume. + /// + /// + /// The maximum height (in BufferCells) that the rendering may consume. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + /// + /// An array of strings containing the textual representation of the outstanding progress activities. + /// + internal + string[] + Render(int maxWidth, int maxHeight, PSHostRawUserInterface rawUI) + { + Dbg.Assert(_topLevelNodes != null, "Shouldn't need to render progress if no data exists"); + Dbg.Assert(maxWidth > 0, "maxWidth is too small"); + Dbg.Assert(maxHeight >= 3, "maxHeight is too small"); + + if (_topLevelNodes == null || _topLevelNodes.Count <= 0) + { + // we have nothing to render. + + return null; + } + + int invisible = 0; + if (TallyHeight(rawUI, maxHeight, maxWidth) > maxHeight) + { + // This will smash down nodes until the tree will fit into the allotted number of lines. If in the + // process some nodes were made invisible, we will add a line to the display to say so. + + invisible = CompressToFit(rawUI, maxHeight, maxWidth); + } + + ArrayList result = new ArrayList(); + + if (ProgressNode.IsMinimalProgressRenderingEnabled()) + { + RenderHelper(result, _topLevelNodes, indentation: 0, maxWidth, rawUI); + return (string[])result.ToArray(typeof(string)); + } + + string border = StringUtil.Padding(maxWidth); + + result.Add(border); + RenderHelper(result, _topLevelNodes, 0, maxWidth, rawUI); + if (invisible == 1) + { + result.Add( + " " + + StringUtil.Format( + ProgressNodeStrings.InvisibleNodesMessageSingular, + invisible)); + } + else if (invisible > 1) + { + result.Add( + " " + + StringUtil.Format( + ProgressNodeStrings.InvisibleNodesMessagePlural, + invisible)); + } + + result.Add(border); + + return (string[])result.ToArray(typeof(string)); + } + + /// + /// Helper function for Render(). Recursively renders nodes. + /// + /// + /// The rendered strings so far. Additional rendering will be appended. + /// + /// + /// The nodes to be rendered. All child nodes will also be rendered. + /// + /// + /// The current indentation level (in BufferCells). + /// + /// + /// The maximum number of BufferCells that the rendering can consume, horizontally. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + private static void RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI) + { + Dbg.Assert(strings != null, "strings should not be null"); + Dbg.Assert(nodes != null, "nodes should not be null"); + + if (nodes == null) + { + return; + } + + foreach (ProgressNode node in nodes) + { + int lines = strings.Count; + + node.Render(strings, indentation, maxWidth, rawUI); + + if (node.Children != null) + { + // indent only if the rendering of node actually added lines to the strings. + + int indentationIncrement = (strings.Count > lines) ? 2 : 0; + + RenderHelper(strings, node.Children, indentation + indentationIncrement, maxWidth, rawUI); + } + } + } + + private sealed class HeightTallyer : NodeVisitor + { + internal HeightTallyer(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) + { + _rawUi = rawUi; + _maxHeight = maxHeight; + _maxWidth = maxWidth; + } + + internal override + bool + Visit(ProgressNode node, ArrayList unused, int unusedToo) + { + Tally += node.LinesRequiredMethod(_rawUi, _maxWidth); + + // We don't need to walk all the nodes, once it's larger than the max height, we should stop + if (Tally > _maxHeight) + { + return false; + } + + return true; + } + + private readonly PSHostRawUserInterface _rawUi; + private readonly int _maxHeight; + private readonly int _maxWidth; + + internal int Tally; + } + + /// + /// Tallies up the number of BufferCells vertically that will be required to show all the ProgressNodes in the given + /// list, and all of their children. + /// + /// + /// The maximum height (in BufferCells) that the rendering may consume. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + /// + /// The vertical height (in BufferCells) that will be required to show all of the nodes in the given list. + /// + /// + /// + private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) + { + HeightTallyer ht = new HeightTallyer(rawUi, maxHeight, maxWidth); + NodeVisitor.VisitNodes(_topLevelNodes, ht); + return ht.Tally; + } + +#if DEBUG || ASSERTIONS_TRACE + + /// + /// Debugging code. Verifies that all of the nodes in the given list have the given style. + /// + /// + /// + /// + private static bool AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style) + { + if (nodes == null) + { + return false; + } + + for (int i = 0; i < nodes.Count; ++i) + { + ProgressNode node = (ProgressNode)nodes[i]; + Dbg.Assert(node != null, "nodes should not contain null elements"); + + if (node.Style != style) + { + return false; + } + + if (node.Children != null) + { + if (!AllNodesHaveGivenStyle(node.Children, style)) + { + return false; + } + } + } + + return true; + } + + /// + /// Debugging code. NodeVisitor that counts up the number of nodes in the tree. + /// + private + class + CountingNodeVisitor : NodeVisitor + { + internal override + bool + Visit(ProgressNode unused, ArrayList unusedToo, int unusedThree) + { + ++Count; + return true; + } + + internal + int + Count; + } + + /// + /// Debugging code. Counts the number of nodes in the tree of nodes. + /// + /// + /// The number of nodes in the tree. + /// + private + int + CountNodes() + { + CountingNodeVisitor cnv = new CountingNodeVisitor(); + NodeVisitor.VisitNodes(_topLevelNodes, cnv); + return cnv.Count; + } + +#endif + + /// + /// Helper function to CompressToFit. Considers compressing nodes from one level to another. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + /// + /// The maximum height (in BufferCells) that the rendering may consume. + /// + /// + /// The maximum width (in BufferCells) that the rendering may consume. + /// + /// + /// Receives the number of nodes that were compressed. If the result of the method is false, then this will be the total + /// number of nodes being tracked (i.e. all of them will have been compressed). + /// + /// + /// The rendering style (e.g. "compression level") that the nodes are expected to currently have. + /// + /// + /// The new rendering style that a node will have when it is compressed. If the result of the method is false, then all + /// nodes will have this rendering style. + /// + /// + /// true to indicate that the nodes are compressed to the point that their rendering will fit within the constraint, or + /// false to indicate that all of the nodes are compressed to a given level, but that the rendering still can't fit + /// within the constraint. + /// + private + bool + CompressToFitHelper( + PSHostRawUserInterface rawUi, + int maxHeight, + int maxWidth, + out int nodesCompressed, + ProgressNode.RenderStyle priorStyle, + ProgressNode.RenderStyle newStyle) + { + nodesCompressed = 0; + + while (true) + { + ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, oldestSoFar: 0, priorStyle); + if (node == null) + { + // We've compressed every node of the prior style already. + + break; + } + + node.Style = newStyle; + ++nodesCompressed; + if (TallyHeight(rawUi, maxHeight, maxWidth) <= maxHeight) + { + return true; + } + } + + // If we get all the way to here, then we've compressed all the nodes and we still don't fit. + return false; + } + + /// + /// "Compresses" the nodes representing the outstanding progress activities until their rendering will fit within a + /// "given height, or until they are compressed to a given level. The oldest nodes are compressed first. + /// + /// This is a 4-stage process -- from least compressed to "invisible". At each stage we find the oldest nodes in the + /// tree and change their rendering style to a more compact style. As soon as the rendering of the nodes will fit within + /// the maxHeight, we stop. The result is that the most recent nodes will be the least compressed, the idea being that + /// the rendering should show the most recently updated activities with the most complete rendering for them possible. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + /// + /// The maximum height (in BufferCells) that the rendering may consume. + /// + /// + /// The maximum width (in BufferCells) that the rendering may consume. + /// + /// + /// The number of nodes that were made invisible during the compression. + /// + /// + private + int + 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 passes 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; + } + + return 0; + } + + #endregion // Rendering Code + + #region Utility Code + + private abstract + class NodeVisitor + { + /// + /// Called for each node in the tree. + /// + /// + /// The node being visited. + /// + /// + /// The list in which the node resides. + /// + /// + /// The index into listWhereFound of the node. + /// + /// + /// true to continue visiting nodes, false if not. + /// + internal abstract + bool + Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound); + + internal static + void + 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); + } + } + } + } + + #endregion + + private readonly ArrayList _topLevelNodes = new ArrayList(); + private int _nodeCount; + + private const int maxNodeCount = 128; + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs new file mode 100644 index 0000000000000000000000000000000000000000..4f51820524c53c2df6c684aa68804d9628e6d5c8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -0,0 +1,611 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Text; + +using Microsoft.PowerShell.Commands.Internal.Format; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// ProgressNode is an augmentation of the ProgressRecord type that adds extra fields for the purposes of tracking + /// outstanding activities received by the host, and rendering them in the console. + /// + internal + class + ProgressNode : ProgressRecord + { + /// + /// Indicates the various layouts for rendering a particular node. + /// + internal + enum + RenderStyle + { + Invisible = 0, + Minimal = 1, + Compact = 2, + + /// + /// Allocate only one line for displaying the StatusDescription or the CurrentOperation, + /// truncate the rest if the StatusDescription or CurrentOperation doesn't fit in one line. + /// + Full = 3, + + /// + /// The node will be displayed the same as Full, plus, the whole StatusDescription and CurrentOperation will be displayed (in multiple lines if needed). + /// + FullPlus = 4, + + /// + /// The node will be displayed using ANSI escape sequences. + /// + Ansi = 5, + } + + /// + /// Constructs an instance from a ProgressRecord. + /// + internal + ProgressNode(long sourceId, ProgressRecord record) + : base(record.ActivityId, record.Activity, record.StatusDescription) + { + Dbg.Assert(record.RecordType == ProgressRecordType.Processing, "should only create node for Processing records"); + + this.ParentActivityId = record.ParentActivityId; + this.CurrentOperation = record.CurrentOperation; + this.PercentComplete = Math.Min(record.PercentComplete, 100); + this.SecondsRemaining = record.SecondsRemaining; + this.RecordType = record.RecordType; + + this.Style = IsMinimalProgressRenderingEnabled() + ? RenderStyle.Ansi + : this.Style = RenderStyle.FullPlus; + + this.SourceId = sourceId; + } + + /// + /// Renders a single progress node as strings of text according to that node's style. The text is appended to the + /// supplied list of strings. + /// + /// + /// List of strings to which the node's rendering will be appended. + /// + /// + /// The indentation level (in BufferCells) at which the node should be rendered. + /// + /// + /// The maximum number of BufferCells that the rendering is allowed to consume. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + internal + void + 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; + } + } + + /// + /// Renders a node in the "Full" style. + /// + /// + /// List of strings to which the node's rendering will be appended. + /// + /// + /// The indentation level (in BufferCells) at which the node should be rendered. + /// + /// + /// The maximum number of BufferCells that the rendering is allowed to consume. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + /// + /// Indicate if the full StatusDescription and CurrentOperation should be displayed. + /// + private + void + RenderFull(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI, bool isFullPlus) + { + string indent = StringUtil.Padding(indentation); + + // First line: the activity + + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth)); + + indentation += 3; + indent = StringUtil.Padding(indentation); + + // Second line: the status description + + RenderFullDescription(this.StatusDescription, indent, maxWidth, rawUI, strCollection, isFullPlus); + + // Third line: the percentage thermometer. The size of this is proportional to the width we're allowed + // to consume. -2 for the whitespace, -2 again for the brackets around thermo, -5 to not be too big + + if (PercentComplete >= 0) + { + int thermoWidth = Math.Max(3, maxWidth - indentation - 2 - 2 - 5); + int mercuryWidth = 0; + mercuryWidth = PercentComplete * thermoWidth / 100; + if (PercentComplete < 100 && mercuryWidth == thermoWidth) + { + // back off a tad unless we're totally complete to prevent the appearance of completion before + // the fact. + + --mercuryWidth; + } + + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, + StringUtil.Format( + " {0}[{1}{2}] ", + indent, + new string('o', mercuryWidth), + StringUtil.Padding(thermoWidth - mercuryWidth)), + maxWidth)); + } + + // Fourth line: the seconds remaining + + if (SecondsRemaining >= 0) + { + TimeSpan span = new TimeSpan(0, 0, this.SecondsRemaining); + + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, + " " + + StringUtil.Format( + ProgressNodeStrings.SecondsRemaining, + indent, + span) + + " ", + maxWidth)); + } + + // Fifth and Sixth lines: The current operation + + if (!string.IsNullOrEmpty(CurrentOperation)) + { + strCollection.Add(" "); + RenderFullDescription(this.CurrentOperation, indent, maxWidth, rawUI, strCollection, isFullPlus); + } + } + + private static void RenderFullDescription(string description, string indent, int maxWidth, PSHostRawUserInterface rawUi, ArrayList strCollection, bool isFullPlus) + { + string oldDescription = StringUtil.Format(" {0}{1} ", indent, description); + string newDescription; + + do + { + newDescription = StringUtil.TruncateToBufferCellWidth(rawUi, oldDescription, maxWidth); + strCollection.Add(newDescription); + + if (oldDescription.Length == newDescription.Length) + { + break; + } + else + { + oldDescription = StringUtil.Format(" {0}{1}", indent, oldDescription.Substring(newDescription.Length)); + } + } while (isFullPlus); + } + + /// + /// Renders a node in the "Compact" style. + /// + /// + /// List of strings to which the node's rendering will be appended. + /// + /// + /// The indentation level (in BufferCells) at which the node should be rendered. + /// + /// + /// The maximum number of BufferCells that the rendering is allowed to consume. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + private + void + RenderCompact(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) + { + string indent = StringUtil.Padding(indentation); + + // First line: the activity + + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, + StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth)); + + indentation += 3; + indent = StringUtil.Padding(indentation); + + // Second line: the status description with percentage and time remaining, if applicable. + + string percent = string.Empty; + if (PercentComplete >= 0) + { + percent = StringUtil.Format("{0}% ", PercentComplete); + } + + string secRemain = string.Empty; + if (SecondsRemaining >= 0) + { + TimeSpan span = new TimeSpan(0, 0, SecondsRemaining); + secRemain = span.ToString() + " "; + } + + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, + StringUtil.Format( + " {0}{1}{2}{3} ", + indent, + percent, + secRemain, + StatusDescription), + maxWidth)); + + // Third line: The current operation + + if (!string.IsNullOrEmpty(CurrentOperation)) + { + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, + StringUtil.Format(" {0}{1} ", indent, this.CurrentOperation), maxWidth)); + } + } + + /// + /// Renders a node in the "Minimal" style. + /// + /// + /// List of strings to which the node's rendering will be appended. + /// + /// + /// The indentation level (in BufferCells) at which the node should be rendered. + /// + /// + /// The maximum number of BufferCells that the rendering is allowed to consume. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// + private + void + RenderMinimal(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) + { + string indent = StringUtil.Padding(indentation); + + // First line: Everything mushed into one line + + string percent = string.Empty; + if (PercentComplete >= 0) + { + percent = StringUtil.Format("{0}% ", PercentComplete); + } + + string secRemain = string.Empty; + if (SecondsRemaining >= 0) + { + TimeSpan span = new TimeSpan(0, 0, SecondsRemaining); + secRemain = span.ToString() + " "; + } + + strCollection.Add( + StringUtil.TruncateToBufferCellWidth( + rawUI, + StringUtil.Format( + " {0}{1} {2}{3}{4} ", + indent, + Activity, + percent, + secRemain, + StatusDescription), + maxWidth)); + } + + internal static bool IsMinimalProgressRenderingEnabled() + { + return PSStyle.Instance.Progress.View == ProgressView.Minimal; + } + + /// + /// Renders a node in the "ANSI" style. + /// + /// + /// List of strings to which the node's rendering will be appended. + /// + /// + /// The indentation level in chars at which the node should be rendered. + /// + /// + /// The maximum number of chars that the rendering is allowed to consume. + /// + private + void + RenderAnsi(ArrayList strCollection, int indentation, int maxWidth) + { + string indent = StringUtil.Padding(indentation); + string secRemain = string.Empty; + if (SecondsRemaining >= 0) + { + secRemain = SecondsRemaining.ToString() + "s"; + } + + int secRemainLength = secRemain.Length + 1; + + // limit progress bar to 120 chars as no need to render full width + if (PSStyle.Instance.Progress.MaxWidth > 0 && maxWidth > PSStyle.Instance.Progress.MaxWidth) + { + maxWidth = PSStyle.Instance.Progress.MaxWidth; + } + + // if the activity is really long, only use up to half the width + string activity; + if (Activity.Length > maxWidth / 2) + { + activity = Activity.Substring(0, maxWidth / 2) + PSObjectHelper.Ellipsis; + } + else + { + activity = Activity; + } + + // 4 is for the extra space and square brackets below and one extra space + int barWidth = maxWidth - activity.Length - indentation - 4; + + var sb = new StringBuilder(); + int padding = maxWidth + PSStyle.Instance.Progress.Style.Length + PSStyle.Instance.Reverse.Length + PSStyle.Instance.ReverseOff.Length; + sb.Append(PSStyle.Instance.Reverse); + + int maxStatusLength = barWidth - secRemainLength - 1; + if (maxStatusLength > 0 && StatusDescription.Length > barWidth - secRemainLength) + { + sb.Append(StatusDescription.AsSpan(0, barWidth - secRemainLength - 1)); + sb.Append(PSObjectHelper.Ellipsis); + } + else + { + sb.Append(StatusDescription); + } + + int emptyPadLength = barWidth + PSStyle.Instance.Reverse.Length - sb.Length - secRemainLength; + if (emptyPadLength > 0) + { + sb.Append(string.Empty.PadRight(emptyPadLength)); + } + + sb.Append(secRemain); + + if (PercentComplete >= 0 && PercentComplete < 100 && barWidth > 0) + { + int barLength = PercentComplete * barWidth / 100; + if (barLength >= barWidth) + { + barLength = barWidth - 1; + } + + if (barLength < sb.Length) + { + sb.Insert(barLength + PSStyle.Instance.Reverse.Length, PSStyle.Instance.ReverseOff); + } + } + else + { + sb.Append(PSStyle.Instance.ReverseOff); + } + + strCollection.Add( + StringUtil.Format( + "{0}{1}{2} [{3}]{4}", + indent, + PSStyle.Instance.Progress.Style, + activity, + sb.ToString(), + PSStyle.Instance.Reset) + .PadRight(padding)); + } + + /// + /// The nodes that have this node as their parent. + /// + internal + ArrayList + Children; + + /// + /// The "age" of the node. A node's age is incremented by PendingProgress.Update each time a new ProgressRecord is + /// received by the host. A node's age is reset when a corresponding ProgressRecord is received. Thus, the age of + /// a node reflects the number of ProgressRecord that have been received since the node was last updated. + /// + /// The age is used by PendingProgress.Render to determine which nodes should be rendered on the display, and how. As the + /// display has finite size, it may be possible to have many more outstanding progress activities than will fit in that + /// space. The rendering of nodes can be progressively "compressed" into a more terse format, or not rendered at all in + /// order to fit as many nodes as possible in the available space. The oldest nodes are compressed or skipped first. + /// + internal + int + Age; + + /// + /// The style in which this node should be rendered. + /// + internal + RenderStyle + Style = RenderStyle.FullPlus; + + /// + /// Identifies the source of the progress record. + /// + internal + long + SourceId; + + /// + /// The number of vertical BufferCells that are required to render the node in its current style. + /// + /// + internal int LinesRequiredMethod(PSHostRawUserInterface rawUi, int maxWidth) + { + Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records"); + + switch (Style) + { + case RenderStyle.FullPlus: + return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: true); + + case RenderStyle.Full: + return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: false); + + case RenderStyle.Compact: + return LinesRequiredInCompactStyle; + + case RenderStyle.Minimal: + return 1; + + case RenderStyle.Invisible: + return 0; + + case RenderStyle.Ansi: + return 1; + + default: + Dbg.Assert(false, "Unknown RenderStyle value"); + break; + } + + return 0; + } + + /// + /// The number of vertical BufferCells that are required to render the node in the Full style. + /// + /// + private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int maxWidth, bool isFullPlus) + { + // Since the fields of this instance could have been changed, we compute this on-the-fly. + + // NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to + // word-wrap text fields, then this calculation will need updating. + + // Start with 1 for the Activity + int lines = 1; + // Use 5 spaces as the heuristic indent. 5 spaces stand for the indent for the CurrentOperation of the first-level child node + var indent = StringUtil.Padding(5); + var temp = new ArrayList(); + + if (isFullPlus) + { + temp.Clear(); + RenderFullDescription(StatusDescription, indent, maxWidth, rawUi, temp, isFullPlus: true); + lines += temp.Count; + } + else + { + // 1 for the Status + lines++; + } + + if (PercentComplete >= 0) + { + ++lines; + } + + if (SecondsRemaining >= 0) + { + ++lines; + } + + if (!string.IsNullOrEmpty(CurrentOperation)) + { + if (isFullPlus) + { + lines += 1; + temp.Clear(); + RenderFullDescription(CurrentOperation, indent, maxWidth, rawUi, temp, isFullPlus: true); + lines += temp.Count; + } + else + { + lines += 2; + } + } + + return lines; + } + + /// + /// The number of vertical BufferCells that are required to render the node in the Compact style. + /// + /// + private + int + LinesRequiredInCompactStyle + { + get + { + // Since the fields of this instance could have been changed, we compute this on-the-fly. + + // NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to + // word-wrap text fields, then this calculation will need updating. + + // Start with 1 for the Activity, and 1 for the Status. + + int lines = 2; + if (!string.IsNullOrEmpty(CurrentOperation)) + { + ++lines; + } + + return lines; + } + } + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs new file mode 100644 index 0000000000000000000000000000000000000000..030a359c2d822063cf975274fffceedab818a2d0 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -0,0 +1,349 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Host; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// ProgressPane is a class that represents the "window" in which outstanding activities for which the host has received + /// progress updates are shown. + /// + /// + internal + class ProgressPane + { + /// + /// Constructs a new instance. + /// + /// + /// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden. + /// + internal + ProgressPane(ConsoleHostUserInterface ui) + { + ArgumentNullException.ThrowIfNull(ui); + _ui = ui; + _rawui = ui.RawUI; + } + + /// + /// Indicates whether the pane is visible on the screen buffer or not. + /// + /// + /// true if the pane is visible, false if not. + /// + /// + internal + bool + IsShowing + { + get + { + return (_savedRegion != null); + } + } + + /// + /// Shows the pane in the screen buffer. Saves off the content of the region of the buffer that will be overwritten so + /// that it can be restored again. + /// + internal + void + Show() + { + if (!IsShowing) + { + // Get temporary reference to the progress region since it can be + // changed at any time by a call to WriteProgress. + BufferCell[,] tempProgressRegion = _progressRegion; + if (tempProgressRegion == null) + { + return; + } + + // The location where we show ourselves is always relative to the screen buffer's current window position. + + int rows = tempProgressRegion.GetLength(0); + int cols = tempProgressRegion.GetLength(1); + + if (ProgressNode.IsMinimalProgressRenderingEnabled()) + { + rows = _content.Length; + cols = PSStyle.Instance.Progress.MaxWidth; + if (cols > _bufSize.Width) + { + cols = _bufSize.Width; + } + } + + _savedCursor = _rawui.CursorPosition; + _location.X = 0; + + if (!Platform.IsWindows || ProgressNode.IsMinimalProgressRenderingEnabled()) + { + _location.Y = _rawui.CursorPosition.Y; + + // if cursor is not on left edge already move down one line + if (_rawui.CursorPosition.X != 0) + { + _location.Y++; + _rawui.CursorPosition = _location; + } + + // if the cursor is at the bottom, create screen buffer space by scrolling + int scrollRows = rows - ((_rawui.BufferSize.Height - 1) - _location.Y); + if (scrollRows > 0) + { + // Scroll the console screen up by 'scrollRows' + var bottomLocation = _location; + bottomLocation.Y = _rawui.BufferSize.Height - 1; + + _rawui.CursorPosition = bottomLocation; + for (int i = 0; i < scrollRows; i++) + { + Console.Out.Write('\n'); + } + + _location.Y -= scrollRows; + _savedCursor.Y -= scrollRows; + } + + // create cleared region to clear progress bar later + _savedRegion = tempProgressRegion; + if (PSStyle.Instance.Progress.View != ProgressView.Minimal) + { + for (int row = 0; row < rows; row++) + { + for (int col = 0; col < cols; col++) + { + _savedRegion[row, col].Character = ' '; + } + } + } + + // put cursor back to where output should be + _rawui.CursorPosition = _location; + } + else + { + _location = _rawui.WindowPosition; + + // We have to show the progress pane in the first column, as the screen buffer at any point might contain + // a CJK double-cell characters, which makes it impractical to try to find a position where the pane would + // not slice a character. Column 0 is the only place where we know for sure we can place the pane. + + _location.Y = Math.Min(_location.Y + 2, _bufSize.Height); + + // Save off the current contents of the screen buffer in the region that we will occupy + _savedRegion = + _rawui.GetBufferContents( + new Rectangle(_location.X, _location.Y, _location.X + cols - 1, _location.Y + rows - 1)); + } + + if (ProgressNode.IsMinimalProgressRenderingEnabled()) + { + WriteContent(); + } + else + { + // replace the saved region in the screen buffer with our progress display + _rawui.SetBufferContents(_location, tempProgressRegion); + } + } + } + + /// + /// Hides the pane by restoring the saved contents of the region of the buffer that the pane occupies. If the pane is + /// not showing, then does nothing. + /// + internal + void + Hide() + { + if (IsShowing) + { + if (ProgressNode.IsMinimalProgressRenderingEnabled()) + { + _rawui.CursorPosition = _location; + int maxWidth = PSStyle.Instance.Progress.MaxWidth; + if (maxWidth > _bufSize.Width) + { + maxWidth = _bufSize.Width; + } + + for (int i = 0; i < _savedRegion.GetLength(1); i++) + { + if (i < _savedRegion.GetLength(1) - 1) + { + Console.Out.WriteLine(string.Empty.PadRight(maxWidth)); + } + else + { + Console.Out.Write(string.Empty.PadRight(maxWidth)); + } + } + } + else + { + // It would be nice if we knew that the saved region could be kept for the next time Show is called, but alas, + // we have no way of knowing if the screen buffer has changed since we were hidden. By "no good way" I mean that + // detecting a change would be at least as expensive as chucking the savedRegion and rebuilding it. And it would + // be very complicated. + + _rawui.SetBufferContents(_location, _savedRegion); + } + + _savedRegion = null; + _rawui.CursorPosition = _savedCursor; + } + } + + /// + /// Updates the pane with the rendering of the supplied PendingProgress, and shows it. + /// + /// + /// A PendingProgress instance that represents the outstanding activities that should be shown. + /// + internal + void + Show(PendingProgress pendingProgress) + { + Dbg.Assert(pendingProgress != null, "pendingProgress may not be null"); + + _bufSize = _rawui.BufferSize; + + // In order to keep from slicing any CJK double-cell characters that might be present in the screen buffer, + // we use the full width of the buffer. + + int maxWidth = _bufSize.Width; + int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3); + + _content = pendingProgress.Render(maxWidth, maxHeight, _rawui); + if (_content == null) + { + // There's nothing to show. + + Hide(); + _progressRegion = null; + return; + } + + BufferCell[,] newRegion; + if (ProgressNode.IsMinimalProgressRenderingEnabled()) + { + // Legacy progress rendering relies on a BufferCell which defines a character, foreground color, and background color + // per cell. This model doesn't work with ANSI escape sequences. However, there is existing logic on rendering that + // relies on the existence of the BufferCell to know if something has been rendered previously. Here we are creating + // an empty BufferCell, but using the second dimension to capture the number of rows so that we can clear that many + // elsewhere in Hide(). + newRegion = new BufferCell[0, _content.Length]; + } + else + { + newRegion = _rawui.NewBufferCellArray(_content, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor); + } + + Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!"); + + if (_progressRegion == null) + { + // we've never shown this pane before. + + _progressRegion = newRegion; + Show(); + } + else + { + // We have shown the pane before. We have to be smart about when we restore the saved region to minimize + // flicker. We need to decide if the new contents will change the dimensions of the progress pane + // currently being shown. If it will, then restore the saved region, and show the new one. Otherwise, + // just blast the new one on top of the last one shown. + + // We're only checking size, not content, as we assume that the content will always change upon receipt + // of a new ProgressRecord. That's not guaranteed, of course, but it's a good bet. So checking content + // would usually result in detection of a change, so why bother? + + bool sizeChanged = + (newRegion.GetLength(0) != _progressRegion.GetLength(0)) + || (newRegion.GetLength(1) != _progressRegion.GetLength(1)); + + _progressRegion = newRegion; + + if (sizeChanged) + { + if (IsShowing) + { + Hide(); + } + + Show(); + } + else + { + if (ProgressNode.IsMinimalProgressRenderingEnabled()) + { + WriteContent(); + } + else + { + _rawui.SetBufferContents(_location, _progressRegion); + } + } + } + } + + private void WriteContent() + { + if (_content is not null) + { + // On Windows, we can check if the cursor is currently visible and not change it to visible + // if it is intentionally hidden. On Unix, it is not currently supported to read the cursor visibility. +#if UNIX + Console.CursorVisible = false; +#else + bool currentCursorVisible = Console.CursorVisible; + if (currentCursorVisible) + { + Console.CursorVisible = false; + } +#endif + + var currentPosition = _rawui.CursorPosition; + _rawui.CursorPosition = _location; + + for (int i = 0; i < _content.Length; i++) + { + if (i < _content.Length - 1) + { + Console.Out.WriteLine(_content[i]); + } + else + { + Console.Out.Write(_content[i]); + } + } + + _rawui.CursorPosition = currentPosition; +#if UNIX + Console.CursorVisible = true; +#else + Console.CursorVisible = currentCursorVisible; +#endif + } + } + + private Coordinates _location = new Coordinates(0, 0); + private Coordinates _savedCursor; + private Size _bufSize; + private BufferCell[,] _savedRegion; + private BufferCell[,] _progressRegion; + private string[] _content; + private readonly PSHostRawUserInterface _rawui; + private readonly ConsoleHostUserInterface _ui; + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs new file mode 100644 index 0000000000000000000000000000000000000000..5181ae636721c818efac68fb7ea0ac2f4c9932ab --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -0,0 +1,272 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Management.Automation; +using System.Xml; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell +{ + /// + /// Wraps Hitesh's xml serializer in such a way that it will select the proper serializer based on the data + /// format. + /// + internal class Serialization + { + /// + /// Describes the format of the data streamed between minishells, e.g. the allowed arguments to the minishell + /// -outputformat and -inputformat command line parameters. + /// + internal enum DataFormat + { + /// + /// Text format -- i.e. stream text just as out-default would display it. + /// + Text = 0, + + /// + /// XML-serialized format. + /// + XML = 1, + + /// + /// Indicates that the data should be discarded instead of processed. + /// + None = 2 + } + + protected + Serialization(DataFormat dataFormat, string streamName) + { + Dbg.Assert(!string.IsNullOrEmpty(streamName), "stream needs a name"); + + format = dataFormat; + this.streamName = streamName; + } + + protected static string XmlCliTag = "#< CLIXML"; + + protected string streamName; + protected DataFormat format; + } + + internal + class WrappedSerializer : Serialization + { + internal + 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; + } + } + + internal + void + Serialize(object o) + { + Serialize(o, this.streamName); + } + + internal + void + Serialize(object o, string streamName) + { + switch (format) + { + case DataFormat.None: + break; + case DataFormat.XML: + if (_firstCall) + { + _firstCall = false; + textWriter.WriteLine(Serialization.XmlCliTag); + } + + _xmlSerializer.Serialize(o, streamName); + break; + case DataFormat.Text: + default: + textWriter.Write(o.ToString()); + break; + } + } + + internal + void + End() + { + switch (format) + { + case DataFormat.None: + // do nothing + break; + + case DataFormat.XML: + _xmlSerializer.Done(); + _xmlSerializer = null; + break; + + case DataFormat.Text: + default: + // do nothing + + break; + } + } + + internal TextWriter textWriter; + private readonly XmlWriter _xmlWriter; + private Serializer _xmlSerializer; + private bool _firstCall = true; + } + + internal + class WrappedDeserializer : Serialization + { + internal + 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.Equals(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase)) + { + // 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 + object + Deserialize() + { + object o; + switch (format) + { + case DataFormat.None: + _atEnd = true; + return null; + + case DataFormat.XML: + o = _xmlDeserializer.Deserialize(out _); + break; + + case DataFormat.Text: + default: + if (_atEnd) + { + return null; + } + + if (_firstLine != null) + { + o = _firstLine; + _firstLine = null; + } + else + { + o = textReader.ReadLine(); + if (o == null) + { + _atEnd = true; + } + } + + break; + } + + return o; + } + + internal + bool + AtEnd + { + get + { + bool result = false; + switch (format) + { + case DataFormat.None: + _atEnd = true; + result = true; + break; + + case DataFormat.XML: + result = _xmlDeserializer.Done(); + break; + + case DataFormat.Text: + default: + result = _atEnd; + break; + } + + return result; + } + } + + internal + void + End() + { + switch (format) + { + case DataFormat.None: + case DataFormat.XML: + case DataFormat.Text: + default: + // do nothing + + break; + } + } + + internal TextReader textReader; + private readonly XmlReader _xmlReader; + private readonly Deserializer _xmlDeserializer; + private string _firstLine; + private bool _atEnd; + } +} // namespace diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..18725b5ddb7f668d4ae795e705c92f941528fe26 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -0,0 +1,348 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implements the start-transcript cmdlet. + /// + [Cmdlet(VerbsLifecycle.Start, "Transcript", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096485")] + [OutputType(typeof(string))] + public sealed class StartTranscriptCommand : PSCmdlet + { + /// + /// The name of the file in which to write the transcript. If not provided, the file indicated by the variable + /// $TRANSCRIPT is used. If neither the filename is supplied or $TRANSCRIPT is not set, the filename shall be $HOME/My + /// Documents/PowerShell_transcript.YYYYMMDDmmss.txt. + /// + /// + [Parameter(Position = 0, ParameterSetName = "ByPath")] + [ValidateNotNullOrEmpty] + public string Path + { + get + { + return _outFilename; + } + + set + { + _isFilenameSet = true; + _outFilename = value; + } + } + + /// + /// The literal name of the file in which to write the transcript. + /// + [Parameter(Position = 0, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + [ValidateNotNullOrEmpty] + public string LiteralPath + { + get + { + return _outFilename; + } + + set + { + _isFilenameSet = true; + _outFilename = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// The literal name of the file in which to write the transcript. + /// + [Parameter(Position = 0, ParameterSetName = "ByOutputDirectory")] + [ValidateNotNullOrEmpty] + public string OutputDirectory + { + get; set; + } + + /// + /// Describes the current state of the activity. + /// + /// + [Parameter] + public SwitchParameter Append + { + get + { + return _shouldAppend; + } + + set + { + _shouldAppend = value; + } + } + + /// + /// Property that sets force parameter. This will reset the read-only + /// attribute on an existing file. + /// + /// + /// The read-only attribute will not be replaced when the transcript is done. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// Property that prevents file overwrite. + /// + [Parameter] + [Alias("NoOverwrite")] + public SwitchParameter NoClobber + { + get + { + return _noclobber; + } + + set + { + _noclobber = value; + } + } + + private bool _noclobber; + + /// + /// Whether to include command invocation time headers between commands. + /// + [Parameter] + public SwitchParameter IncludeInvocationHeader + { + get; set; + } + + /// + /// Gets or sets whether to use minimal transcript header. + /// + [Parameter] + public SwitchParameter UseMinimalHeader + { + get; set; + } + + /// + /// Starts the transcription. + /// + protected override void BeginProcessing() + { + // If they haven't specified a path, figure out the correct output path. + if (!_isFilenameSet) + { + // read the filename from $TRANSCRIPT + object value = this.GetVariableValue("global:TRANSCRIPT", null); + + // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt) + if (value == null) + { + // If they've specified an output directory, use it. Otherwise, use "My Documents" + if (OutputDirectory != null) + { + _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false); + _isLiteralPath = true; + } + else + { + _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(); + } + } + else + { + _outFilename = (string)PSObject.Base(value); + } + } + + // Normalize outFilename here in case it is a relative path + try + { + string effectiveFilePath = ResolveFilePath(Path, _isLiteralPath); + + if (!ShouldProcess(effectiveFilePath)) + return; + + if (System.IO.File.Exists(effectiveFilePath)) + { + if (NoClobber && !Append) + { + string message = StringUtil.Format(TranscriptStrings.TranscriptFileExistsNoClobber, + effectiveFilePath, + "NoClobber"); // prevents localization + Exception uae = new UnauthorizedAccessException(message); + ErrorRecord errorRecord = new ErrorRecord( + uae, "NoClobber", ErrorCategory.ResourceExists, effectiveFilePath); + + // NOTE: this call will throw + ThrowTerminatingError(errorRecord); + } + + System.IO.FileInfo fInfo = new System.IO.FileInfo(effectiveFilePath); + if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + // Save some disk write time by checking whether file is readonly.. + if (Force) + { + // Make sure the file is not read only + // Note that we will not clear the ReadOnly flag later + fInfo.Attributes &= ~(FileAttributes.ReadOnly); + } + else + { + string errorMessage = string.Format( + System.Globalization.CultureInfo.CurrentCulture, + TranscriptStrings.TranscriptFileReadOnly, + effectiveFilePath); + Exception innerException = new ArgumentException(errorMessage); + ThrowTerminatingError(new ErrorRecord(innerException, "FileReadOnly", ErrorCategory.InvalidArgument, effectiveFilePath)); + } + } + + // If they didn't specify -Append, empty the file + if (!_shouldAppend) + { + System.IO.File.WriteAllText(effectiveFilePath, string.Empty); + } + } + + System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = + this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; + Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool(), UseMinimalHeader.IsPresent); + + // ch.StartTranscribing(effectiveFilePath, Append); + + // NTRAID#Windows Out Of Band Releases-931008-2006/03/21 + // Previous behavior was to write this even if ShouldProcess + // returned false. Why would we want that? + PSObject outputObject = new PSObject( + StringUtil.Format(TranscriptStrings.TranscriptionStarted, Path)); + outputObject.Properties.Add(new PSNoteProperty("Path", Path)); + WriteObject(outputObject); + } + catch (Exception e) + { + try + { + Host.UI.StopTranscribing(); + } + catch + { + } + + string errorMessage = string.Format( + System.Globalization.CultureInfo.CurrentCulture, + TranscriptStrings.CannotStartTranscription, + e.Message); + ErrorRecord er = new ErrorRecord( + PSTraceSource.NewInvalidOperationException(e, errorMessage), + "CannotStartTranscription", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + } + + /// resolve a user provided file name or path (including globbing characters) + /// to a fully qualified file path, using the file system provider + private string ResolveFilePath(string filePath, bool isLiteralPath) + { + string path = null; + + try + { + if (isLiteralPath) + { + path = SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath); + } + else + { + ProviderInfo provider = null; + Collection filePaths = + SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider); + + if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) + { + ReportWrongProviderType(provider.FullName); + } + + if (filePaths.Count > 1) + { + ReportMultipleFilesNotSupported(); + } + + path = filePaths[0]; + } + } + catch (ItemNotFoundException) + { + path = null; + } + + if (string.IsNullOrEmpty(path)) + { + CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(this); + ProviderInfo provider = null; + PSDriveInfo drive = null; + path = + SessionState.Path.GetUnresolvedProviderPathFromPSPath( + filePath, cmdletProviderContext, out provider, out drive); + cmdletProviderContext.ThrowFirstErrorOrDoNothing(); + if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) + { + ReportWrongProviderType(provider.FullName); + } + } + + return path; + } + + private void ReportWrongProviderType(string providerId) + { + ErrorRecord errorRecord = new ErrorRecord( + PSTraceSource.NewInvalidOperationException(TranscriptStrings.ReadWriteFileNotFileSystemProvider, providerId), + "ReadWriteFileNotFileSystemProvider", + ErrorCategory.InvalidArgument, + null); + ThrowTerminatingError(errorRecord); + } + + private void ReportMultipleFilesNotSupported() + { + ErrorRecord errorRecord = new ErrorRecord( + PSTraceSource.NewInvalidOperationException(TranscriptStrings.MultipleFilesNotSupported), + "MultipleFilesNotSupported", + ErrorCategory.InvalidArgument, + null); + ThrowTerminatingError(errorRecord); + } + + private bool _shouldAppend; + private string _outFilename; + private bool _isFilenameSet; + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs new file mode 100644 index 0000000000000000000000000000000000000000..093f7c147dcb054400739ad2b29a9c77e832c0ee --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.Internal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implements the stop-transcript cmdlet. + /// + [Cmdlet(VerbsLifecycle.Stop, "Transcript", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.None, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096798")] + [OutputType(typeof(string))] + public sealed class StopTranscriptCommand : PSCmdlet + { + /// + /// Stops the transcription. + /// + protected override + void + BeginProcessing() + { + if (!ShouldProcess(string.Empty)) + { + return; + } + + try + { + string outFilename = Host.UI.StopTranscribing(); + if (outFilename != null) + { + PSObject outputObject = new PSObject( + StringUtil.Format(TranscriptStrings.TranscriptionStopped, outFilename)); + outputObject.Properties.Add(new PSNoteProperty("Path", outFilename)); + WriteObject(outputObject); + } + } + catch (Exception e) + { + throw PSTraceSource.NewInvalidOperationException( + e, TranscriptStrings.ErrorStoppingTranscript, e.Message); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs new file mode 100644 index 0000000000000000000000000000000000000000..eb4557c04d215e28366d8b6a5c7612940b59ab64 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -0,0 +1,463 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.NetworkInformation; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Microsoft.PowerShell +{ + /// + /// A Helper class for printing notification on PowerShell startup when there is a new update. + /// + /// + /// For the detailed design, please take a look at the corresponding RFC. + /// + internal static class UpdatesNotification + { + private const string UpdateCheckEnvVar = "POWERSHELL_UPDATECHECK"; + private const string LTSBuildInfoURL = "https://aka.ms/pwsh-buildinfo-lts"; + private const string StableBuildInfoURL = "https://aka.ms/pwsh-buildinfo-stable"; + private const string PreviewBuildInfoURL = "https://aka.ms/pwsh-buildinfo-preview"; + + private const int NotificationDelayDays = 7; + private const int UpdateCheckBackoffDays = 7; + + /// + /// The version of new update is persisted using a file, not as the file content, but instead baked in the file name in the following template: + /// `update{notification-type}_{version}_{publish-date}` -- held by 's_updateFileNameTemplate', + /// while 's_updateFileNamePattern' holds the pattern of this file name. + /// + private static readonly string s_updateFileNameTemplate, s_updateFileNamePattern; + + /// + /// For each notification type, we need two files to achieve the synchronization for the update check: + /// `_sentinel{notification-type}_` -- held by 's_sentinelFileName'; + /// `sentinel{notification-type}-{year}-{month}-{day}.done` + /// -- held by 's_doneFileNameTemplate', while 's_doneFileNamePattern' holds the pattern of this file name. + /// The {notification-type} part will be the integer value of the corresponding `NotificationType` member. + /// The {year}-{month}-{day} part will be filled with the date of current day when the update check runs. + /// + private static readonly string s_sentinelFileName, s_doneFileNameTemplate, s_doneFileNamePattern; + + private static readonly string s_cacheDirectory; + private static readonly EnumerationOptions s_enumOptions; + private static readonly NotificationType s_notificationType; + + /// + /// Gets a value indicating whether update notification should be done. + /// + internal static readonly bool CanNotifyUpdates; + + static UpdatesNotification() + { + s_notificationType = GetNotificationType(); + CanNotifyUpdates = s_notificationType != NotificationType.Off + && Platform.TryDeriveFromCache(PSVersionInfo.GitCommitId, out s_cacheDirectory); + + if (CanNotifyUpdates) + { + s_enumOptions = new EnumerationOptions(); + + // Build the template/pattern strings for the configured notification type. + string typeNum = ((int)s_notificationType).ToString(); + s_sentinelFileName = $"_sentinel{typeNum}_"; + s_doneFileNameTemplate = $"sentinel{typeNum}-{{0}}-{{1}}-{{2}}.done"; + s_doneFileNamePattern = $"sentinel{typeNum}-*.done"; + s_updateFileNameTemplate = $"update{typeNum}_{{0}}_{{1}}"; + s_updateFileNamePattern = $"update{typeNum}_v*.*.*_????-??-??"; + } + } + + // Maybe we shouldn't do update check and show notification when it's from a mini-shell, meaning when + // 'ConsoleShell.Start' is not called by 'ManagedEntrance.Start'. + // But it seems so unusual that it's probably not worth bothering. Also, a mini-shell probably should + // just disable the update notification feature by setting the opt-out environment variable. + + internal static void ShowUpdateNotification(PSHostUserInterface hostUI) + { + if (!Directory.Exists(s_cacheDirectory)) + { + return; + } + + if (TryParseUpdateFile( + updateFilePath: out _, + out SemanticVersion lastUpdateVersion, + out DateTime lastUpdateDate) + && lastUpdateVersion != null) + { + DateTime today = DateTime.UtcNow; + if ((today - lastUpdateDate).TotalDays < NotificationDelayDays) + { + // The update was out less than 1 week ago and it's possible the packages are still rolling out. + // We only show the notification when the update is at least 1 week old, to reduce the chance that + // users see the notification but cannot get the new update when they try to install it. + return; + } + + string releaseTag = lastUpdateVersion.ToString(); + string notificationMsgTemplate = s_notificationType == NotificationType.LTS + ? ManagedEntranceStrings.LTSUpdateNotificationMessage + : string.IsNullOrEmpty(lastUpdateVersion.PreReleaseLabel) + ? ManagedEntranceStrings.StableUpdateNotificationMessage + : ManagedEntranceStrings.PreviewUpdateNotificationMessage; + + string notificationColor = string.Empty; + string resetColor = string.Empty; + + string line2Padding = string.Empty; + string line3Padding = string.Empty; + + // We calculate how much whitespace we need to make it look nice + if (hostUI.SupportsVirtualTerminal) + { + // Swaps foreground and background colors. + notificationColor = "\x1B[7m"; + resetColor = "\x1B[0m"; + + // The first line is longest, if the message changes, this needs to be updated + int line1Length = notificationMsgTemplate.IndexOf('\n'); + int line2Length = notificationMsgTemplate.IndexOf('\n', line1Length + 1); + int line3Length = notificationMsgTemplate.IndexOf('\n', line2Length + 1); + line3Length -= line2Length + 1; + line2Length -= line1Length + 1; + + line2Padding = line2Padding.PadRight(line1Length - line2Length + releaseTag.Length); + // 3 represents the extra placeholder in the template + line3Padding = line3Padding.PadRight(line1Length - line3Length + 3); + } + + string notificationMsg = string.Format(CultureInfo.CurrentCulture, notificationMsgTemplate, releaseTag, notificationColor, resetColor, line2Padding, line3Padding); + + hostUI.WriteLine(); + hostUI.WriteLine(notificationMsg); + } + } + + internal static async Task CheckForUpdates() + { + // Delay the update check for 3 seconds so that it has the minimal impact on startup. + await Task.Delay(3000); + + // A self-built pwsh for development purpose has the SHA1 commit hash baked in 'GitCommitId', + // which is 40 characters long. So we can quickly check the length of 'GitCommitId' to tell + // if this is a self-built pwsh, and skip the update check if so. + if (PSVersionInfo.GitCommitId.Length > 40) + { + return; + } + + // Daily builds do not support update notifications + string preReleaseLabel = PSVersionInfo.PSCurrentVersion.PreReleaseLabel; + if (preReleaseLabel != null && preReleaseLabel.StartsWith("daily", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + // If the host is not connect to a network, skip the rest of the check. + if (!NetworkInterface.GetIsNetworkAvailable()) + { + return; + } + + // Create the update cache directory if it doesn't exists + if (!Directory.Exists(s_cacheDirectory)) + { + Directory.CreateDirectory(s_cacheDirectory); + } + + bool parseSuccess = TryParseUpdateFile( + out string updateFilePath, + out SemanticVersion lastUpdateVersion, + out DateTime lastUpdateDate); + + DateTime today = DateTime.UtcNow; + if (parseSuccess && updateFilePath != null && (today - lastUpdateDate).TotalDays < UpdateCheckBackoffDays) + { + // There is an existing update file, and the last update was less than 1 week ago. + // It's unlikely a new version is released within 1 week, so we can skip this check. + return; + } + + // Construct the sentinel file paths for today's check. + string todayDoneFileName = string.Format( + CultureInfo.InvariantCulture, + s_doneFileNameTemplate, + today.Year.ToString(), + today.Month.ToString(), + today.Day.ToString()); + + string todayDoneFilePath = Path.Combine(s_cacheDirectory, todayDoneFileName); + if (File.Exists(todayDoneFilePath)) + { + // A successful update check has been done today. + // We can skip this update check. + return; + } + + try + { + // Use 's_sentinelFileName' as the file lock. + // The update-check tasks started by every 'pwsh' process of the same version will compete on holding this file. + string sentinelFilePath = Path.Combine(s_cacheDirectory, s_sentinelFileName); + using (new FileStream(sentinelFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, bufferSize: 1, FileOptions.DeleteOnClose)) + { + if (File.Exists(todayDoneFilePath)) + { + // After acquiring the file lock, it turns out a successful check has already been done for today. + // Then let's skip this update check. + return; + } + + // Now it's guaranteed that this is the only process that reaches here. + // Clean up the old '.done' file, there should be only one of it. + foreach (string oldFile in Directory.EnumerateFiles(s_cacheDirectory, s_doneFileNamePattern, s_enumOptions)) + { + File.Delete(oldFile); + } + + if (!parseSuccess) + { + // The update file is corrupted, either because more than one update files were found unexpectedly, + // or because the update file name failed to be parsed into a release version and a publish date. + // This is **very unlikely** to happen unless the file is accidentally altered manually. + // We try to recover here by cleaning up all update files for the configured notification type. + foreach (string file in Directory.EnumerateFiles(s_cacheDirectory, s_updateFileNamePattern, s_enumOptions)) + { + File.Delete(file); + } + } + + // Do the real update check: + // - Send HTTP request to query for the new release/pre-release; + // - If there is a valid new release that should be reported to the user, + // create the file `update__` when no `update` file exists, + // or rename the existing file to `update__`. + SemanticVersion baselineVersion = lastUpdateVersion ?? PSVersionInfo.PSCurrentVersion; + Release release = await QueryNewReleaseAsync(baselineVersion); + + if (release != null) + { + // The date part of the string is 'YYYY-MM-DD'. + const int dateLength = 10; + string newUpdateFileName = string.Format( + CultureInfo.InvariantCulture, + s_updateFileNameTemplate, + release.TagName, + release.PublishAt.Substring(0, dateLength)); + + string newUpdateFilePath = Path.Combine(s_cacheDirectory, newUpdateFileName); + + if (updateFilePath == null) + { + new FileStream(newUpdateFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close(); + } + else + { + File.Move(updateFilePath, newUpdateFilePath); + } + } + + // Finally, create the `todayDoneFilePath` file as an indicator that a successful update check has finished today. + new FileStream(todayDoneFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close(); + } + } + catch (Exception) + { + // There are 2 possible reason for the exception: + // 1. An update check initiated from another `pwsh` process is in progress. + // It's OK to just return and let that update check to finish the work. + // 2. The update check failed (ex. internet connectivity issue, GitHub service failure). + // It's OK to just return and let another `pwsh` do the check at later time. + } + } + + /// + /// Check for the existence of the update file and parse the file name if it exists. + /// + /// Get the exact update file path. + /// Get the version of the new release. + /// Get the publish date of the new release. + /// + /// False, when + /// 1. found more than one update files that matched the pattern; OR + /// 2. found only one update file, but failed to parse its name for version and publish date. + /// True, when + /// 1. no update file was found, namely no new updates yet; + /// 2. found only one update file, and succeeded to parse its name for version and publish date. + /// + private static bool TryParseUpdateFile( + out string updateFilePath, + out SemanticVersion lastUpdateVersion, + out DateTime lastUpdateDate) + { + updateFilePath = null; + lastUpdateVersion = null; + lastUpdateDate = default; + + var files = Directory.EnumerateFiles(s_cacheDirectory, s_updateFileNamePattern, s_enumOptions); + var enumerator = files.GetEnumerator(); + + if (!enumerator.MoveNext()) + { + // It's OK that an update file doesn't exist. This could happen when there is no new updates yet. + return true; + } + + updateFilePath = enumerator.Current; + if (enumerator.MoveNext()) + { + // More than 1 files were found that match the pattern. This is a corrupted state. + // Theoretically, there should be only one update file at any point of time. + updateFilePath = null; + return false; + } + + // OK, only found one update file for the configured notification type, which is expected. + // Now let's parse the file name. + string updateFileName = Path.GetFileName(updateFilePath); + int dateStartIndex = updateFileName.LastIndexOf('_') + 1; + + if (!DateTime.TryParse( + updateFileName.AsSpan(dateStartIndex), + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeLocal, + out lastUpdateDate)) + { + updateFilePath = null; + return false; + } + + int versionStartIndex = updateFileName.IndexOf('_') + 2; + int versionLength = dateStartIndex - versionStartIndex - 1; + string versionString = updateFileName.Substring(versionStartIndex, versionLength); + + if (SemanticVersion.TryParse(versionString, out lastUpdateVersion)) + { + return true; + } + + updateFilePath = null; + lastUpdateDate = default; + return false; + } + + private static async Task QueryNewReleaseAsync(SemanticVersion baselineVersion) + { + bool isStableRelease = string.IsNullOrEmpty(PSVersionInfo.PSCurrentVersion.PreReleaseLabel); + string[] queryUris = s_notificationType switch + { + NotificationType.LTS => new[] { LTSBuildInfoURL }, + NotificationType.Default => isStableRelease + ? new[] { StableBuildInfoURL } + : new[] { StableBuildInfoURL, PreviewBuildInfoURL }, + _ => Array.Empty() + }; + + using var client = new HttpClient(); + + string userAgent = string.Create(CultureInfo.InvariantCulture, $"PowerShell {PSVersionInfo.GitCommitId}"); + client.DefaultRequestHeaders.Add("User-Agent", userAgent); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + Release releaseToReturn = null; + SemanticVersion highestVersion = baselineVersion; + var settings = new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None }; + var serializer = JsonSerializer.Create(settings); + + foreach (string queryUri in queryUris) + { + // Query the GitHub Rest API and throw if the query fails. + HttpResponseMessage response = await client.GetAsync(queryUri); + response.EnsureSuccessStatusCode(); + + using var stream = await response.Content.ReadAsStreamAsync(); + using var reader = new StreamReader(stream); + using var jsonReader = new JsonTextReader(reader); + + JObject release = serializer.Deserialize(jsonReader); + var tagName = release["ReleaseTag"].ToString(); + var version = SemanticVersion.Parse(tagName.Substring(1)); + + if (version > highestVersion) + { + highestVersion = version; + var publishAt = release["ReleaseDate"].ToString(); + releaseToReturn = new Release(publishAt, tagName); + } + } + + return releaseToReturn; + } + + /// + /// Get the notification type setting. + /// + private static NotificationType GetNotificationType() + { + string str = Environment.GetEnvironmentVariable(UpdateCheckEnvVar); + if (string.IsNullOrEmpty(str)) + { + return NotificationType.Default; + } + + if (Enum.TryParse(str, ignoreCase: true, out NotificationType type)) + { + return type; + } + + return NotificationType.Default; + } + + /// + /// Notification type that can be configured. + /// + private enum NotificationType + { + /// + /// Turn off the update notification. + /// + Off = 0, + + /// + /// Give you the default behaviors: + /// - the preview version 'pwsh' checks for the new preview version and the new GA version. + /// - the GA version 'pwsh' checks for the new GA version only. + /// + Default = 1, + + /// + /// Both preview and GA version 'pwsh' checks for the new LTS version only. + /// + LTS = 2 + } + + private sealed class Release + { + internal Release(string publishAt, string tagName) + { + PublishAt = publishAt; + TagName = tagName; + } + + /// + /// The datetime stamp is in UTC. For example: 2019-03-28T18:42:02Z. + /// + internal string PublishAt { get; } + + /// + /// The release tag name. + /// + internal string TagName { get; } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..33445ceebd2eda122020a30cbe584cf1aaff3d90 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx @@ -0,0 +1,231 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot process command because a command is already specified with -Command, -CommandWithArgs, or -EncodedCommand. + + + Cannot process the command because of a missing parameter. A command must follow -Command. + + + Unrecognized parameter: '{0}'. + + + '-' was specified with the -Command parameter; no other arguments to -Command are permitted. + + + '-' was specified as the argument to -Command but standard input has not been redirected for this process. + + + The command cannot be run because no argument has been supplied for the OutputFormat parameter. +Specify one of the following formats for this parameter: +{0} + + + Cannot process the command because the -InputFormat parameter requires an argument. Specify a valid format argument for this parameter. +Valid formats are: +{0} + + + Cannot process the command because of an incorrect parameter value. "{0}" is not a valid format. +Valid formats are: +{1} + + + Cannot process the command because arguments to -Command or -EncodedCommand have already been specified with -EncodedArguments. + + + Cannot process the command because -EncodedArguments requires a value. Specify a value for the -EncodedArguments parameter. + + + The command cannot be run because the File parameter requires a file path. Supply a path for the File parameter and then try the command again. + + + Cannot process the command because -WindowStyle requires an argument that is normal, hidden, minimized or maximized. Specify one of these argument values and try again. + + + Processing -File '{0}' failed: {1} Specify a valid path for the -File parameter. + + + Processing -WindowStyle '{0}' failed: {1}. + + + Processing -File '{0}' failed because the file does not have a '.ps1' extension. Specify a valid PowerShell script file name, and then try again. + + + The argument '{0}' is not recognized as the name of a script file. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. + + + Cannot process the command because the value specified with -EncodedArguments is not properly encoded. The value must be Base64 encoded. + + + Cannot process the command because the value specified with -EncodedCommand is not properly encoded. The value must be Base64 encoded. + + + Cannot process the execution policy because of a missing policy name. A policy name must follow -ExecutionPolicy. + + + Cannot process the command because -STA and -MTA are both specified. Specify either -STA or -MTA. + + + Cannot process the command because -ConfigurationName requires an argument that is a remote endpoint configuration name. Specify this argument and try again. + + + Cannot process the command because -ConfigurationFile requires an argument that is a session configuration (.pssc) file path. Specify this argument and try again. + + + Cannot process the command because -CustomPipeName requires an argument that is a name of the pipe you want to use. Specify this argument and try again. + + + Cannot process the command because -CustomPipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + Cannot process the command because -SettingsFile requires an argument that is a file path. + + + Processing -SettingsFile '{0}' failed: {1}. Specify a valid path for the -SettingsFile parameter. + + + The argument '{0}' passed to the -SettingsFile does not exist. Provide the path to an existing json file as an argument to the -SettingsFile parameter. + + + Invalid argument '{0}', did you mean: + + + Parameter -WindowStyle is not implemented on this platform. + + + Cannot process the command because -WorkingDirectory requires an argument that is a directory path. + + + Parameter -MTA is not supported on this platform. + + + Parameter -STA is not supported on this platform. + + + The specified arguments must not contain null elements. + + + Invalid ExecutionPolicy value '{0}'. + + + An argument is required to be supplied to the '{0}' parameter. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..bf1a8f84bfdd11c94405ebef7479e5f122a8a143 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx @@ -0,0 +1,201 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The Win32 internal error "{0}" 0x{1:X} occurred when adding a break handler. Contact Microsoft Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while trying to remove a break handler. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting input about the console handle. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while retrieving the handle for the active console output buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting the console mode. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while setting the console mode. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while reading characters from the console input buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while reading input records from the console input buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while reading the contents of the console input buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting the number of events in the console input buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while flushing the console input buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting console output buffer information. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while setting the console output buffer size. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while writing to the console output buffer. Contact Microsoft Customer Support Services. + + + Win32 internal error "{0}" 0x{1:X} occurred while reading the console output buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while filling the console output buffer with characters. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while filling the console output buffer with attributes. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while scrolling the console output buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while setting the console window information. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting the largest console window size. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while setting the console window title. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while writing to the console output buffer at the current cursor position. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while setting character attributes for the console output buffer. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting cursor information. Contact Microsoft Customer Support Services. + + + Win32 internal error "{0}" 0x{1:X} occurred while setting cursor information.Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while getting console font information. Contact Microsoft Customer Support Services. + + + The Win32 internal error "{0}" 0x{1:X} occurred while sending keyboard input. Contact Microsoft Customer Support Services. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..c640b2c4a89e42446c93380e2715480a94680ff2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot process the operation because the supplied coordinate is not valid. Specify a coordinate within the buffer area of {0}. + + + Cannot set the buffer size because the size specified is too large or too small. + + + Cannot set the console color because the value specified is not valid. Specify a valid color as defined by the System.ConsoleColor type. + + + Cannot process CursorSize because the cursor size specified is not valid. + + + Cannot read key options. To read options, set one or both of the following: IncludeKeyDown, IncludeKeyUp. + + + {0} should be greater than or equal to {1}. + + + Cannot use the specified Window X (column) position because it extends past the width of the screen buffer. Specify another X position, starting with 0 as the left most column of the buffer. + + + Cannot use the specified Window Y (row) position because it extends past the height of the screen buffer. Specify another Y position, starting with 0 as the top-most row of the buffer. + + + Window width cannot be less than 1. + + + Window height must be at least 1. + + + Window cannot be wider than the screen buffer. + + + Window cannot be taller than the screen buffer. + + + Window cannot be wider than {0}. + + + Window cannot be taller than {0}. + + + Window size is too narrow. + + + Window size is too short. + + + Window title cannot be empty. + + + Window title cannot be longer than {0} characters. + + + Administrator: + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..9bc06e0d42f074170b874314fab268fc773e66aa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx @@ -0,0 +1,191 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot display prompt because too many nested prompts are already running. + + + Cannot process input loop. ExitCurrentLoop was called when no InputLoops were running. + + + PS> + + + The shell cannot be started. A failure occurred during initialization: + + + The shell cannot be started. An InitialSessionState object has been provided along with a -ConfigurationFile argument. Both configuration directives cannot be used at the same time. + + + An error has occurred that was not properly handled. Additional information is shown below. The PowerShell process will exit. + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username : {1}\{2} +Machine : {3} ({4}) +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + Command '{0}' could not be run because some PowerShell Snap-Ins did not load. + + + Command '{0}' was not run as the session in which it was intended to run was either closed or broken + + + Entering debug mode. Use h or ? for help. + + + Hit {0} + + + {0}:{1,-3} {2} + + + +The current session does not support debugging; execution will continue. + + + + + Cannot load PSReadline module. Console is running without PSReadline. + + + More than one server mode parameter was specified. Server mode parameters must be used exclusively. + + + Loading personal and system profiles took {0}ms. + + + Run as Administrator + + + PushRunspace can only push a remote runspace. + + + The '{0}' parameter is mandatory and must be specified when using the '{1}' parameter. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..6c383d5052f6eb67a19ea2d79985ce73e457a690 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + User: + + + Password for user {0}: + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..7a2f61022f5b2df09f9eb0d83a0e4dd1343c2796 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The "{0}" collection must have at least one element. + + + Cannot recognize "{1}" as a {0} due to an overflow error. + + + Cannot recognize "{1}" as a {0} due to a format error. + + + "{0}" cannot be recognized as a valid Prompt command. + + + No help is available for {0}. + + + {0}: + + + The field "{0}" is a zero rank array. + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}" or -1 for no default choice. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + [?] Help + + + The prompt was canceled. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + Cannot display the prompt for "{0}" because type "{1}" cannot be loaded. + + + "{0}" cannot be null or empty. + + + "{0}" cannot be null. + + + (Type !? for Help.) + + + (default is "{0}"): + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + DEBUG: {0} + + + VERBOSE: {0} + + + WARNING: {0} + + + PowerShell is in NonInteractive mode. Read and Prompt functionality is not available. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..7cfdd2f63b521e56b059e93a1a5476d94ede281c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This PowerShell snap-in contains cmdlets (such as Start-Transcript and Stop-Transcript) that are provided for use with the PowerShell console host. + + + Microsoft Corporation + + + Host PowerShell Snap-In. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..44ebf0fb5385e8c187d378a44c34b6a7c8856fe8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -0,0 +1,493 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + PowerShell {0} + + + [Constrained Language Mode] + + + [Constrained Language AUDIT Mode : No Restrictions] + + + [No Language Mode] + + + [Restricted Language Mode] + + + {1} A new PowerShell preview release is available: v{0} {2} + {1} Upgrade now, or check out the release page at:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} A new PowerShell stable release is available: v{0} {2} + {1} Upgrade now, or check out the release page at:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} A new PowerShell LTS release is available: v{0} {2} + {1} Upgrade now, or check out the release page at:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]] + [-Command { - | <script-block> [-args <arg-array>] + | <string> [<CommandParameters>] } ] + [-CommandWithArgs <string> [<CommandParameters>] + [-ConfigurationName <string>] [-ConfigurationFile <filePath>] + [-CustomPipeName <string>] [-EncodedCommand <Base64EncodedCommand>] + [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}] + [-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile] + [-NoProfileLoadTime] [-OutputFormat {Text | XML}] + [-SettingsFile <filePath>] [-SSHServerMode] [-STA] + [-Version] [-WindowStyle <style>] + [-WorkingDirectory <directoryPath>] + + pwsh[.exe] -h | -Help | -? | /? + +PowerShell Online Help https://aka.ms/powershell-docs + +All parameters are case-insensitive. + + + + +-File | -f + + If the value of File is "-", the command text is read from standard input. + Running "pwsh -File -" without redirected standard input starts a regular + session. This is the same as not specifying the File parameter at all. + + This is the default parameter if no parameters are present but values are + present in the command line. The specified script runs in the local scope + ("dot-sourced"), so that the functions and variables that the script + creates are available in the current session. Enter the script file path + and any parameters. File must be the last parameter in the command, because + all characters typed after the File parameter name are interpreted as the + script file path followed by the script parameters. + + Typically, the switch parameters of a script are either included or + omitted. For example, the following command uses the All parameter of the + Get-Script.ps1 script file: "-File .\Get-Script.ps1 -All" + + In rare cases, you might need to provide a BOOLEAN value for a switch + parameter. To provide a BOOLEAN value for a switch parameter in the value + of the FILE parameter, Use the parameter normally followed immediately by a + colon and the boolean value, such as the following: + "-File .\Get-Script.ps1 -All:$False". + + Parameters passed to the script are passed as literal strings, after + interpretation by the current shell. For example, if you are in cmd.exe and + want to pass an environment variable value, you would use the cmd.exe + syntax: "pwsh -File .\test.ps1 -TestParam %windir%" + + In contrast, running "pwsh -File .\test.ps1 -TestParam $env:windir" in + cmd.exe results in the script receiving the literal string "$env:windir" + because it has no special meaning to the current cmd.exe shell. The + "$env:windir" style of environment variable reference can be used inside a + Command parameter, since there it is interpreted as PowerShell code. + + Similarly, if you want to execute the same command from a Batch script, + you would use "%~dp0" instead of ".\" or "$PSScriptRoot" to represent the current + execution directory: "pwsh -File %~dp0test.ps1 -TestParam %windir%". If you + instead used ".\test.ps1", PowerShell would throw an error because it cannot + find the literal path ".\test.ps1". + + When the script file invoked terminates with an exit command, the process + exit code is set to the numeric argument used with the exit command. With + normal termination, the exit code is always 0. + + Similar to -Command, when a script-terminating error occurs, the exit code + is set to 1. However, unlike with -Command, when the execution is + interrupted with Ctrl-C the exit code is 0. + +-Command | -c + + Executes the specified commands (and any parameters) as though they were + typed at the PowerShell command prompt, and then exits, unless the NoExit + parameter is specified. + + The value of Command can be "-", a script block, or a string. If the value + of Command is "-", the command text is read from standard input. + + The Command parameter only accepts a script block for execution when it can + recognize the value passed to Command as a ScriptBlock type. This is only + possible when running pwsh from another PowerShell host. The ScriptBlock + type may be contained in an existing variable, returned from an expression, + or parsed by the PowerShell host as a literal script block enclosed in + curly braces "{}", before being passed to pwsh. + + pwsh -Command {Get-WinEvent -LogName security} + + In cmd.exe, there is no such thing as a script block (or ScriptBlock type), + so the value passed to Command will always be a string. You can write a + script block inside the string, but instead of being executed it will + behave exactly as though you typed it at a typical PowerShell prompt, + printing the contents of the script block back out to you. + + A string passed to Command is still executed as PowerShell script, so the + script block curly braces are often not required in the first place when + running from cmd.exe. To execute an inline script block defined inside a + string, the call operator "&" can be used: + + pwsh -Command "& {Get-WinEvent -LogName security}" + + If the value of Command is a string, Command must be the last parameter for + pwsh, because all arguments following it are interpreted as part of the + command to execute. + + When called from within an existing PowerShell session, the results are + returned to the parent shell as deserialized XML objects, not live objects. + For other shells, the results are returned as strings. + + If the value of Command is "-", the command text is read from standard + input. You must redirect standard input when using the Command parameter + with standard input. For example: + + @' + "in" + + "hi" | + % { "$_ there" } + + "out" + '@ | powershell -NoProfile -Command - + + This example produces the following output: + + in + hi there + out + + The process exit code is determined by status of the last (executed) + command within the script block. The exit code is 0 when $? is $true or 1 + when $? is $false. If the last command is an external program or a + PowerShell script that explicitly sets an exit code other than 0 or 1, that + exit code is converted to 1 for process exit code. To preserve the specific + exit code, add exit $LASTEXITCODE to your command string or script block. + + Similarly, the value 1 is returned when a script-terminating + (runspace-terminating) error, such as a throw or -ErrorAction Stop, occurs + or when execution is interrupted with Ctrl-C. + +-CommandWithArgs | -cwa + + [Experimental] + Executes a PowerShell command with arguments. Unlike `-Command`, this + parameter populates the `$args built-in variable which can be used by the + command. + + The first string is the command and subsequent strings delimited by whitespace + are the arguments. + + For example: + + pwsh -CommandWithArgs '$args | % { "arg: $_" }' arg1 arg2 + + This example produces the following output: + + arg: arg1 + arg: arg2 + +-ConfigurationName | -config + + Specifies a configuration endpoint in which PowerShell is run. This can be + any endpoint registered on the local machine including the default + PowerShell remoting endpoints or a custom endpoint having specific user + role capabilities. + + Example: "pwsh -ConfigurationName AdminRoles" + +-ConfigurationFile + + Specifies a session configuration (.pssc) file path. The configuration + contained in the configuration file will be applied to the PowerShell + session. + + Example: "pwsh -ConfigurationFile "C:\ProgramData\PowerShell\MyConfig.pssc" + +-CustomPipeName + + Specifies the name to use for an additional IPC server (named pipe) used + for debugging and other cross-process communication. This offers a + predictable mechanism for connecting to other PowerShell instances. + Typically used with the CustomPipeName parameter on "Enter-PSHostProcess". + + This parameter was introduced in PowerShell 6.2. + + For example: + + # PowerShell instance 1 + pwsh -CustomPipeName mydebugpipe + # PowerShell instance 2 + Enter-PSHostProcess -CustomPipeName mydebugpipe + +-EncodedCommand | -e | -ec + + Accepts a Base64-encoded string version of a command. Use this parameter to + submit commands to PowerShell that require complex, nested quoting. The + Base64 representation must be a UTF-16 encoded string. + + For example: + + $command = 'dir "c:\program files" ' + $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) + $encodedCommand = [Convert]::ToBase64String($bytes) + pwsh -encodedcommand $encodedCommand + +-ExecutionPolicy | -ex | -ep + + Sets the default execution policy for the current session and saves it in + the $env:PSExecutionPolicyPreference environment variable. This parameter + does not change the persistently configured execution policies. + + This parameter only applies to Windows computers. The + $env:PSExecutionPolicyPreference environment variable does not exist on + non-Windows platforms. + +-InputFormat | -inp | -if + + Describes the format of data sent to PowerShell. Valid values are "Text" + (text strings) or "XML" (serialized CLIXML format). + +-Interactive | -i + + Present an interactive prompt to the user. Inverse for NonInteractive + parameter. + +-Login | -l + + On Linux and macOS, starts PowerShell as a login shell, using /bin/sh to + execute login profiles such as /etc/profile and ~/.profile. On Windows, + this switch does nothing. + + [!IMPORTANT] This parameter must come first to start PowerShell as a login + shell. The parameter is ignored if passed in any other position. + + To set up pwsh as the login shell on UNIX-like operating systems: + + - Verify that the full absolute path to pwsh is listed under /etc/shells + + - This path is usually something like /usr/bin/pwsh on Linux or + /usr/local/bin/pwsh on macOS + - With some installation methods, this entry will be added + automatically at installation time + - If pwsh is not present in /etc/shells, use an editor to append the + path to pwsh on the last line. This requires elevated privileges to + edit. + + - Use the chsh utility to set your current user's shell to pwsh: + + chsh -s /usr/bin/pwsh + + [!WARNING] Setting pwsh as the login shell is currently not supported on + Windows Subsystem for Linux (WSL), and attempting to set pwsh as the + login shell there may lead to being unable to start WSL interactively. + +-MTA + + Start PowerShell using a multi-threaded apartment. This switch is only + available on Windows. + +-NoExit | -noe + + Does not exit after running startup commands. + + Example: "pwsh -NoExit -Command Get-Date" + +-NoLogo | -nol + + Hides the banner text at startup of interactive sessions. + +-NonInteractive | -noni + + This switch is used to create sessions that shouldn't require user input. + This is useful for scripts that run in scheduled tasks or CI/CD pipelines. + Any attempts to use interactive features, like 'Read-Host' or confirmation + prompts, result in statement terminating errors rather than hanging. + +-NoProfile | -nop + + Does not load the PowerShell profiles. + +-NoProfileLoadTime + + Hides the PowerShell profile load time text shown at startup when the load + time exceeds 500 milliseconds. + +-OutputFormat | -o | -of + + Determines how output from PowerShell is formatted. Valid values are "Text" + (text strings) or "XML" (serialized CLIXML format). + + Example: "pwsh -o XML -c Get-Date" + + When called within a PowerShell session, you get deserialized objects as + output rather plain strings. When called from other shells, the output is + string data formatted as CLIXML text. + +-SettingsFile | -settings + + Overrides the system-wide "powershell.config.json" settings file for the + session. By default, system-wide settings are read from the + "powershell.config.json" in the "$PSHOME" directory. + + Note that these settings are not used by the endpoint specified by the + "-ConfigurationName" argument. + + Example: "pwsh -SettingsFile c:\myproject\powershell.config.json" + +-SSHServerMode | -sshs + + Used in sshd_config for running PowerShell as an SSH subsystem. It is not + intended or supported for any other use. + +-STA + + Start PowerShell using a single-threaded apartment. This is the default. + This switch is only available on Windows. + +-Version | -v + + Displays the version of PowerShell. Additional parameters are ignored. + +-WindowStyle | -w + + Sets the window style for the session. Valid values are Normal, Minimized, + Maximized, and Hidden. + +-WorkingDirectory | -wd + + Sets the initial working directory by executing at startup. Any valid + PowerShell file path is supported. + + To start PowerShell in your home directory, use: pwsh -WorkingDirectory ~ + +-Help, -?, /? + + Displays help for pwsh. If you are typing a pwsh command in PowerShell, + prepend the command parameters with a hyphen (-), not a forward slash (/). + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..b4e9785add6d737eadc633f1248e233e695891d7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}{1} remaining. + + + {0} activity not shown... + + + {0} activities not shown... + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..9fe6f988e58467864c9698be9ae8e1de8bc9aa89 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Transcript started, output file is {0} + + + Transcript stopped, output file is {0} + + + Transcription cannot be started due to the error: {0} + + + The current provider ({0}) cannot open a file. + + + File {0} is read-only. Cannot write to this file. "Start-Transcript -Force" will clear the read-only attribute. + + + Cannot perform operation because the path resolved to more than one file. This command cannot operate on multiple files. + + + File {0} already exists and {1} was specified. + + + An error occurred stopping transcription: {0} + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs new file mode 100644 index 0000000000000000000000000000000000000000..ec2b702a144d46cdd6736374c03c02ae102d34dc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.PowerShell +{ + /// + /// EngineInstaller is a class for facilitating registry of necessary + /// information for PowerShell engine. + /// + /// At install time, installation utilities (like InstallUtil.exe) will + /// call install this engine assembly based on the implementation in + /// this class. + /// + /// This class derives from base class PSInstaller. PSInstaller will + /// handle the details about how information got written into registry. + /// Here, the information about registry content is provided. + /// + [RunInstaller(true)] + public sealed class EngineInstaller : PSInstaller + { + /// + /// Constructor. + /// + public EngineInstaller() + : base() + { + } + + /// + /// + internal sealed override string RegKey + { + get + { + return RegistryStrings.MonadEngineKey; + } + } + + private static string EngineVersion + { + get + { + return PSVersionInfo.FeatureVersionString; + } + } + + private Dictionary _regValues = null; + /// + /// + internal sealed override Dictionary RegValues + { + get + { + if (_regValues == null) + { + _regValues = new Dictionary(); + _regValues[RegistryStrings.MonadEngine_MonadVersion] = EngineVersion; + _regValues[RegistryStrings.MonadEngine_ApplicationBase] = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + _regValues[RegistryStrings.MonadEngine_ConsoleHostAssemblyName] = Assembly.GetExecutingAssembly().FullName; + _regValues[RegistryStrings.MonadEngine_ConsoleHostModuleName] = Assembly.GetExecutingAssembly().Location; + _regValues[RegistryStrings.MonadEngine_RuntimeVersion] = Assembly.GetExecutingAssembly().ImageRuntimeVersion; + } + + return _regValues; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs new file mode 100644 index 0000000000000000000000000000000000000000..e1132d75751348183885002946799e1be0b28348 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Management.Automation; + +namespace Microsoft.PowerShell +{ + /// + /// PSHostPSSnapIn is a class for facilitating registry + /// of necessary information for PowerShell host PSSnapin. + /// + [RunInstaller(true)] + public sealed class PSHostPSSnapIn : PSSnapIn + { + /// + /// Create an instance of this class. + /// + public PSHostPSSnapIn() + : base() + { + } + + /// + /// Get name of this PSSnapin. + /// + public override string Name + { + get + { + return RegistryStrings.HostMshSnapinName; + } + } + + /// + /// Get the default vendor string for this PSSnapin. + /// + public override string Vendor + { + get + { + return "Microsoft"; + } + } + + /// + /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. + /// + public override string VendorResource + { + get + { + return "HostMshSnapInResources,Vendor"; + } + } + + /// + /// Get the default description string for this PSSnapin. + /// + public override string Description + { + get + { + return "This PSSnapIn contains cmdlets used by the MSH host."; + } + } + + /// + /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. + /// + public override string DescriptionResource + { + get + { + return "HostMshSnapInResources,Description"; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..2a5b6533d180c4835d0b377c99ef51e59c8a9cfa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("System.Management.Automation,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs new file mode 100644 index 0000000000000000000000000000000000000000..723832979f8c80e7cc4e246c1b8e86cf95803b39 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Runtime.InteropServices; + +namespace System.Diagnostics.Eventing +{ + [StructLayout(LayoutKind.Explicit, Size = 16)] + public readonly struct EventDescriptor + { + [FieldOffset(0)] + private readonly ushort _id; + + [FieldOffset(2)] + private readonly byte _version; + + [FieldOffset(3)] + private readonly byte _channel; + + [FieldOffset(4)] + private readonly byte _level; + + [FieldOffset(5)] + private readonly byte _opcode; + + [FieldOffset(6)] + private readonly ushort _task; + + [FieldOffset(8)] + private readonly long _keywords; + + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] + public EventDescriptor( + int id, + byte version, + byte channel, + byte level, + byte opcode, + int task, + long keywords + ) + { + if (id < 0) + { + throw new ArgumentOutOfRangeException(nameof(id), DotNetEventingStrings.ArgumentOutOfRange_NeedNonNegNum); + } + + if (id > ushort.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(id), string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); + } + + _id = (ushort)id; + _version = version; + _channel = channel; + _level = level; + _opcode = opcode; + _keywords = keywords; + + if (task < 0) + { + throw new ArgumentOutOfRangeException(nameof(task), DotNetEventingStrings.ArgumentOutOfRange_NeedNonNegNum); + } + + if (task > ushort.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(task), string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); + } + + _task = (ushort)task; + } + + public int EventId + { + get + { + return _id; + } + } + + public byte Version + { + get + { + return _version; + } + } + + public byte Channel + { + get + { + return _channel; + } + } + + public byte Level + { + get + { + return _level; + } + } + + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] + public byte Opcode + { + get + { + return _opcode; + } + } + + public int Task + { + get + { + return _task; + } + } + + public long Keywords + { + get + { + return _keywords; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..32ce9993cfb82286cb60cef961c83e3b0456becd --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -0,0 +1,783 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Security; +using System.Threading; + +namespace System.Diagnostics.Eventing +{ + public class EventProvider : IDisposable + { + [SecurityCritical] + private UnsafeNativeMethods.EtwEnableCallback _etwCallback; // Trace Callback function + + private long _regHandle; // Trace Registration Handle + private byte _level; // Tracing Level + private long _anyKeywordMask; // Trace Enable Flags + private long _allKeywordMask; // Match all keyword + private int _enabled; // Enabled flag from Trace callback + private readonly Guid _providerId; // Control Guid + private int _disposed; // when 1, provider has unregister + + [ThreadStatic] + private static WriteEventErrorCode t_returnCode; // thread slot to keep last error + + [ThreadStatic] + private static Guid t_activityId; + + private const int s_basicTypeAllocationBufferSize = 16; + private const int s_etwMaxNumberArguments = 32; + private const int s_etwAPIMaxStringCount = 8; + private const int s_maxEventDataDescriptors = 128; + private const int s_traceEventMaximumSize = 65482; + private const int s_traceEventMaximumStringSize = 32724; + + [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] + public enum WriteEventErrorCode : int + { + // check mapping to runtime codes + NoError = 0, + NoFreeBuffers = 1, + EventTooBig = 2 + } + + [StructLayout(LayoutKind.Explicit, Size = 16)] + private struct EventData + { + [FieldOffset(0)] + internal ulong DataPointer; + + [FieldOffset(8)] + internal uint Size; + + [FieldOffset(12)] + internal int Reserved; + } + + private enum ActivityControl : uint + { + EVENT_ACTIVITY_CTRL_GET_ID = 1, + EVENT_ACTIVITY_CTRL_SET_ID = 2, + EVENT_ACTIVITY_CTRL_CREATE_ID = 3, + EVENT_ACTIVITY_CTRL_GET_SET_ID = 4, + EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5 + } + + /// + /// Constructor for EventProvider class. + /// + /// + /// Unique GUID among all trace sources running on a system + /// + [SecuritySafeCritical] + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] + public EventProvider(Guid providerGuid) + { + _providerId = providerGuid; + + // + // EtwRegister the ProviderId with ETW + // + EtwRegister(); + } + + /// + /// This method registers the controlGuid of this class with ETW. + /// We need to be running on Vista or above. If not an + /// PlatformNotSupported exception will be thrown. + /// If for some reason the ETW EtwRegister call failed + /// a NotSupported exception will be thrown. + /// + [System.Security.SecurityCritical] + private unsafe void EtwRegister() + { + uint status; + + _etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack); + + status = UnsafeNativeMethods.EventRegister(in _providerId, _etwCallback, null, ref _regHandle); + if (status != 0) + { + throw new Win32Exception((int)status); + } + } + + // + // implement Dispose Pattern to early deregister from ETW instead of waiting for + // the finalizer to call deregistration. + // Once the user is done with the provider it needs to call Close() or Dispose() + // If neither are called the finalizer will unregister the provider anyway + // + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + [System.Security.SecuritySafeCritical] + protected virtual void Dispose(bool disposing) + { + // + // explicit cleanup is done by calling Dispose with true from + // Dispose() or Close(). The disposing argument is ignored because there + // are no unmanaged resources. + // The finalizer calls Dispose with false. + // + + // + // check if the object has been already disposed + // + if (_disposed == 1) + { + return; + } + + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + // somebody is already disposing the provider + return; + } + + // + // Disables Tracing in the provider, then unregister + // + + _enabled = 0; + + Deregister(); + } + + /// + /// This method deregisters the controlGuid of this class with ETW. + /// + public virtual void Close() + { + Dispose(); + } + + ~EventProvider() + { + Dispose(false); + } + + /// + /// This method un-registers from ETW. + /// + [System.Security.SecurityCritical] + private unsafe void Deregister() + { + // + // Unregister from ETW using the RegHandle saved from + // the register call. + // + + if (_regHandle != 0) + { + UnsafeNativeMethods.EventUnregister(_regHandle); + _regHandle = 0; + } + } + + [System.Security.SecurityCritical] + private unsafe void EtwEnableCallBack( + [In] ref System.Guid sourceId, + [In] int isEnabled, + [In] byte setLevel, + [In] long anyKeyword, + [In] long allKeyword, + [In] void* filterData, + [In] void* callbackContext + ) + { + _enabled = isEnabled; + _level = setLevel; + _anyKeywordMask = anyKeyword; + _allKeywordMask = allKeyword; + return; + } + + /// + /// IsEnabled, method used to test if provider is enabled. + /// + public bool IsEnabled() + { + return _enabled != 0; + } + + /// + /// IsEnabled, method used to test if event is enabled. + /// + /// + /// Level to test + /// + /// + /// Keyword to test + /// + public bool IsEnabled(byte level, long keywords) + { + // + // If not enabled at all, return false. + // + + if (_enabled == 0) + { + return false; + } + + // This also covers the case of Level == 0. + if ((level <= _level) || + (_level == 0)) + { + // + // Check if Keyword is enabled + // + + if ((keywords == 0) || + (((keywords & _anyKeywordMask) != 0) && + ((keywords & _allKeywordMask) == _allKeywordMask))) + { + return true; + } + } + + return false; + } + + public static WriteEventErrorCode GetLastWriteEventError() + { + return t_returnCode; + } + + // + // Helper function to set the last error on the thread + // + private static void SetLastError(int error) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_ARITHMETIC_OVERFLOW: + case UnsafeNativeMethods.ERROR_MORE_DATA: + t_returnCode = WriteEventErrorCode.EventTooBig; + break; + case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY: + t_returnCode = WriteEventErrorCode.NoFreeBuffers; + break; + } + } + + [System.Security.SecurityCritical] + private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer) + /*++ + + Routine Description: + + This routine is used by WriteEvent to unbox the object type and + to fill the passed in ETW data descriptor. + + Arguments: + + data - argument to be decoded + + dataDescriptor - pointer to the descriptor to be filled + + dataBuffer - storage buffer for storing user data, needed because cant get the address of the object + + Return Value: + + null if the object is a basic type other than string. String otherwise + + --*/ + { + dataDescriptor->Reserved = 0; + + if (data is string sRet) + { + dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); + return sRet; + } + + if (data == null) + { + dataDescriptor->Size = 0; + dataDescriptor->DataPointer = 0; + } + else if (data is IntPtr) + { + dataDescriptor->Size = (uint)sizeof(IntPtr); + IntPtr* intptrPtr = (IntPtr*)dataBuffer; + *intptrPtr = (IntPtr)data; + dataDescriptor->DataPointer = (ulong)intptrPtr; + } + else if (data is int) + { + dataDescriptor->Size = (uint)sizeof(int); + int* intptrPtr = (int*)dataBuffer; + *intptrPtr = (int)data; + dataDescriptor->DataPointer = (ulong)intptrPtr; + } + else if (data is long) + { + dataDescriptor->Size = (uint)sizeof(long); + long* longptr = (long*)dataBuffer; + *longptr = (long)data; + dataDescriptor->DataPointer = (ulong)longptr; + } + else if (data is uint) + { + dataDescriptor->Size = (uint)sizeof(uint); + uint* uintptr = (uint*)dataBuffer; + *uintptr = (uint)data; + dataDescriptor->DataPointer = (ulong)uintptr; + } + else if (data is ulong) + { + dataDescriptor->Size = (uint)sizeof(ulong); + ulong* ulongptr = (ulong*)dataBuffer; + *ulongptr = (ulong)data; + dataDescriptor->DataPointer = (ulong)ulongptr; + } + else if (data is char) + { + dataDescriptor->Size = (uint)sizeof(char); + char* charptr = (char*)dataBuffer; + *charptr = (char)data; + dataDescriptor->DataPointer = (ulong)charptr; + } + else if (data is byte) + { + dataDescriptor->Size = (uint)sizeof(byte); + byte* byteptr = (byte*)dataBuffer; + *byteptr = (byte)data; + dataDescriptor->DataPointer = (ulong)byteptr; + } + else if (data is short) + { + dataDescriptor->Size = (uint)sizeof(short); + short* shortptr = (short*)dataBuffer; + *shortptr = (short)data; + dataDescriptor->DataPointer = (ulong)shortptr; + } + else if (data is sbyte) + { + dataDescriptor->Size = (uint)sizeof(sbyte); + sbyte* sbyteptr = (sbyte*)dataBuffer; + *sbyteptr = (sbyte)data; + dataDescriptor->DataPointer = (ulong)sbyteptr; + } + else if (data is ushort) + { + dataDescriptor->Size = (uint)sizeof(ushort); + ushort* ushortptr = (ushort*)dataBuffer; + *ushortptr = (ushort)data; + dataDescriptor->DataPointer = (ulong)ushortptr; + } + else if (data is float) + { + dataDescriptor->Size = (uint)sizeof(float); + float* floatptr = (float*)dataBuffer; + *floatptr = (float)data; + dataDescriptor->DataPointer = (ulong)floatptr; + } + else if (data is double) + { + dataDescriptor->Size = (uint)sizeof(double); + double* doubleptr = (double*)dataBuffer; + *doubleptr = (double)data; + dataDescriptor->DataPointer = (ulong)doubleptr; + } + else if (data is bool) + { + dataDescriptor->Size = (uint)sizeof(bool); + bool* boolptr = (bool*)dataBuffer; + *boolptr = (bool)data; + dataDescriptor->DataPointer = (ulong)boolptr; + } + else if (data is Guid) + { + dataDescriptor->Size = (uint)sizeof(Guid); + Guid* guidptr = (Guid*)dataBuffer; + *guidptr = (Guid)data; + dataDescriptor->DataPointer = (ulong)guidptr; + } + else if (data is decimal) + { + dataDescriptor->Size = (uint)sizeof(decimal); + decimal* decimalptr = (decimal*)dataBuffer; + *decimalptr = (decimal)data; + dataDescriptor->DataPointer = (ulong)decimalptr; + } + else + { + // To our eyes, everything else is a just a string + sRet = data.ToString(); + dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); + return sRet; + } + + return null; + } + + /// + /// WriteMessageEvent, method to write a string with level and Keyword. + /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId(). + /// + /// + /// Message to write + /// + /// + /// Level to test + /// + /// + /// Keyword to test + /// + [System.Security.SecurityCritical] + public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKeywords) + { + int status = 0; + + ArgumentNullException.ThrowIfNull(eventMessage); + + if (IsEnabled(eventLevel, eventKeywords)) + { + if (eventMessage.Length > s_traceEventMaximumStringSize) + { + t_returnCode = WriteEventErrorCode.EventTooBig; + return false; + } + + unsafe + { + fixed (char* pdata = eventMessage) + { + status = (int)UnsafeNativeMethods.EventWriteString(_regHandle, eventLevel, eventKeywords, pdata); + } + + if (status != 0) + { + SetLastError(status); + return false; + } + } + } + + return true; + } + + /// + /// WriteMessageEvent, method to write a string with level=0 and Keyword=0 + /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId(). + /// + /// + /// Message to log + /// + public bool WriteMessageEvent(string eventMessage) + { + return WriteMessageEvent(eventMessage, 0, 0); + } + + /// + /// WriteEvent method to write parameters with event schema properties. + /// + /// + /// Event Descriptor for this event. + /// + /// + /// + public bool WriteEvent(in EventDescriptor eventDescriptor, params object[] eventPayload) + { + return WriteTransferEvent(in eventDescriptor, Guid.Empty, eventPayload); + } + + /// + /// WriteEvent, method to write a string with event schema properties. + /// + /// + /// Event Descriptor for this event. + /// + /// + /// string to log. + /// + [System.Security.SecurityCritical] + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] + public bool WriteEvent(in EventDescriptor eventDescriptor, string data) + { + uint status = 0; + + ArgumentNullException.ThrowIfNull(data); + + if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) + { + if (data.Length > s_traceEventMaximumStringSize) + { + t_returnCode = WriteEventErrorCode.EventTooBig; + return false; + } + + EventData userData; + + userData.Size = (uint)((data.Length + 1) * 2); + userData.Reserved = 0; + + unsafe + { + fixed (char* pdata = data) + { + Guid activityId = GetActivityId(); + userData.DataPointer = (ulong)pdata; + + status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, + in eventDescriptor, + (activityId == Guid.Empty) ? null : &activityId, + null, + 1, + &userData); + } + } + } + + if (status != 0) + { + SetLastError((int)status); + return false; + } + + return true; + } + + /// + /// WriteEvent, method to be used by generated code on a derived class. + /// + /// + /// Event Descriptor for this event. + /// + /// + /// number of event descriptors + /// + /// + /// pointer do the event data + /// + [System.Security.SecurityCritical] + protected bool WriteEvent(in EventDescriptor eventDescriptor, int dataCount, IntPtr data) + { + uint status = 0; + + unsafe + { + Guid activityId = GetActivityId(); + + status = UnsafeNativeMethods.EventWriteTransfer( + _regHandle, + in eventDescriptor, + (activityId == Guid.Empty) ? null : &activityId, + null, + (uint)dataCount, + (void*)data); + } + + if (status != 0) + { + SetLastError((int)status); + return false; + } + + return true; + } + + /// + /// WriteTransferEvent, method to write a parameters with event schema properties. + /// + /// + /// Event Descriptor for this event. + /// + /// + /// + /// + /// + [System.Security.SecurityCritical] + public bool WriteTransferEvent(in EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload) + { + uint status = 0; + + if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) + { + Guid activityId = GetActivityId(); + + unsafe + { + int argCount = 0; + EventData* userDataPtr = null; + + if ((eventPayload != null) && (eventPayload.Length != 0)) + { + argCount = eventPayload.Length; + if (argCount > s_etwMaxNumberArguments) + { + // + // too many arguments to log + // + throw new ArgumentOutOfRangeException(nameof(eventPayload), + string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxNumberArguments)); + } + + uint totalEventSize = 0; + int index; + int stringIndex = 0; + int[] stringPosition = new int[s_etwAPIMaxStringCount]; // used to keep the position of strings in the eventPayload parameter + string[] dataString = new string[s_etwAPIMaxStringCount]; // string arrays from the eventPayload parameter + EventData* userData = stackalloc EventData[argCount]; // allocation for the data descriptors + userDataPtr = (EventData*)userData; + byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // 16 byte for unboxing non-string argument + byte* currentBuffer = dataBuffer; + + // + // The loop below goes through all the arguments and fills in the data + // descriptors. For strings save the location in the dataString array. + // Calculates the total size of the event by adding the data descriptor + // size value set in EncodeObjec method. + // + for (index = 0; index < eventPayload.Length; index++) + { + string isString; + isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer); + currentBuffer += s_basicTypeAllocationBufferSize; + totalEventSize += userDataPtr->Size; + userDataPtr++; + if (isString != null) + { + if (stringIndex < s_etwAPIMaxStringCount) + { + dataString[stringIndex] = isString; + stringPosition[stringIndex] = index; + stringIndex++; + } + else + { + throw new ArgumentOutOfRangeException(nameof(eventPayload), + string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount)); + } + } + } + + if (totalEventSize > s_traceEventMaximumSize) + { + t_returnCode = WriteEventErrorCode.EventTooBig; + return false; + } + + fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3], + v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7]) + { + userDataPtr = (EventData*)userData; + if (dataString[0] != null) + { + userDataPtr[stringPosition[0]].DataPointer = (ulong)v0; + } + + if (dataString[1] != null) + { + userDataPtr[stringPosition[1]].DataPointer = (ulong)v1; + } + + if (dataString[2] != null) + { + userDataPtr[stringPosition[2]].DataPointer = (ulong)v2; + } + + if (dataString[3] != null) + { + userDataPtr[stringPosition[3]].DataPointer = (ulong)v3; + } + + if (dataString[4] != null) + { + userDataPtr[stringPosition[4]].DataPointer = (ulong)v4; + } + + if (dataString[5] != null) + { + userDataPtr[stringPosition[5]].DataPointer = (ulong)v5; + } + + if (dataString[6] != null) + { + userDataPtr[stringPosition[6]].DataPointer = (ulong)v6; + } + + if (dataString[7] != null) + { + userDataPtr[stringPosition[7]].DataPointer = (ulong)v7; + } + } + } + + status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, + in eventDescriptor, + (activityId == Guid.Empty) ? null : &activityId, + (relatedActivityId == Guid.Empty) ? null : &relatedActivityId, + (uint)argCount, + userDataPtr); + } + } + + if (status != 0) + { + SetLastError((int)status); + return false; + } + + return true; + } + + [System.Security.SecurityCritical] + protected bool WriteTransferEvent(in EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data) + { + uint status = 0; + + Guid activityId = GetActivityId(); + + unsafe + { + status = UnsafeNativeMethods.EventWriteTransfer( + _regHandle, + in eventDescriptor, + (activityId == Guid.Empty) ? null : &activityId, + &relatedActivityId, + (uint)dataCount, + (void*)data); + } + + if (status != 0) + { + SetLastError((int)status); + return false; + } + + return true; + } + + [System.Security.SecurityCritical] + private static Guid GetActivityId() + { + return t_activityId; + } + + [System.Security.SecurityCritical] + public static void SetActivityId(ref Guid id) + { + t_activityId = id; + UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref id); + } + + [System.Security.SecurityCritical] + public static Guid CreateActivityId() + { + Guid newId = new(); + UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newId); + return newId; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs new file mode 100644 index 0000000000000000000000000000000000000000..1c82891b654e865d76e72fbf6b3a627b7703f72c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; + +namespace System.Diagnostics.Eventing +{ + public class EventProviderTraceListener : TraceListener + { + // + // The listener uses the EtwProvider base class. + // Because Listener data is not schematized at the moment the listener will + // log events using WriteMessageEvent method. + // + // Because WriteMessageEvent takes a string as the event payload + // all the overridden logging methods convert the arguments into strings. + // Event payload is "delimiter" separated, which can be configured + // + // + private EventProvider _provider; + + private const string s_nullStringValue = "null"; + private const string s_nullStringComaValue = "null,"; + private const string s_nullCStringValue = ": null"; + + private string _delimiter = ";"; + + private const uint s_keyWordMask = 0xFFFFFF00; + private const int s_defaultPayloadSize = 512; + + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] + public string Delimiter + { + get + { + return _delimiter; + } + + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] + set + { + ArgumentNullException.ThrowIfNull(value, nameof(Delimiter)); + + if (value.Length == 0) + throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); + + _delimiter = value; + } + } + + /// + /// This method creates an instance of the ETW provider. + /// The guid argument must be a valid GUID or a format exception will be + /// thrown when creating an instance of the ControlGuid. + /// We need to be running on Vista or above. If not an + /// PlatformNotSupported exception will be thrown by the EventProvider. + /// + public EventProviderTraceListener(string providerId) + { + InitProvider(providerId); + } + + public EventProviderTraceListener(string providerId, string name) + : base(name) + { + InitProvider(providerId); + } + + public EventProviderTraceListener(string providerId, string name, string delimiter) + : base(name) + { + ArgumentNullException.ThrowIfNull(delimiter); + + if (delimiter.Length == 0) + throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); + + _delimiter = delimiter; + InitProvider(providerId); + } + + private void InitProvider(string providerId) + { + Guid controlGuid = new(providerId); + // + // Create The ETW TraceProvider + // + + _provider = new EventProvider(controlGuid); + } + + // + // override Listener methods + // + public sealed override void Flush() + { + } + + public sealed override bool IsThreadSafe + { + get + { + return true; + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _provider.Close(); + } + } + + public sealed override void Write(string message) + { + if (!_provider.IsEnabled()) + { + return; + } + + _provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0); + } + + public sealed override void WriteLine(string message) + { + Write(message); + } + + // + // For all the methods below the string to be logged contains: + // m_delimiter separated data converted to string + // + // The source parameter is ignored. + // + public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) + { + if (!_provider.IsEnabled()) + { + return; + } + + if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + { + return; + } + + StringBuilder dataString = new(s_defaultPayloadSize); + + if (data != null) + { + dataString.Append(data.ToString()); + } + else + { + dataString.Append(s_nullCStringValue); + } + + _provider.WriteMessageEvent(dataString.ToString(), + (byte)eventType, + (long)eventType & s_keyWordMask); + } + + public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) + { + if (!_provider.IsEnabled()) + { + return; + } + + if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + { + return; + } + + int index; + StringBuilder dataString = new(s_defaultPayloadSize); + + if ((data != null) && (data.Length > 0)) + { + for (index = 0; index < (data.Length - 1); index++) + { + if (data[index] != null) + { + dataString.Append(data[index].ToString()); + dataString.Append(Delimiter); + } + else + { + dataString.Append(s_nullStringComaValue); + } + } + + if (data[index] != null) + { + dataString.Append(data[index].ToString()); + } + else + { + dataString.Append(s_nullStringValue); + } + } + else + { + dataString.Append(s_nullStringValue); + } + + _provider.WriteMessageEvent(dataString.ToString(), + (byte)eventType, + (long)eventType & s_keyWordMask); + } + + public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) + { + if (!_provider.IsEnabled()) + { + return; + } + + if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + { + return; + } + + _provider.WriteMessageEvent(string.Empty, + (byte)eventType, + (long)eventType & s_keyWordMask); + } + + public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) + { + if (!_provider.IsEnabled()) + { + return; + } + + if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + { + return; + } + + StringBuilder dataString = new(s_defaultPayloadSize); + dataString.Append(message); + + _provider.WriteMessageEvent(dataString.ToString(), + (byte)eventType, + (long)eventType & s_keyWordMask); + } + + public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) + { + if (!_provider.IsEnabled()) + { + return; + } + + if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + { + return; + } + + if (args == null) + { + _provider.WriteMessageEvent(format, + (byte)eventType, + (long)eventType & s_keyWordMask); + } + else + { + _provider.WriteMessageEvent(string.Format(CultureInfo.InvariantCulture, format, args), + (byte)eventType, + (long)eventType & s_keyWordMask); + } + } + + public override void Fail(string message, string detailMessage) + { + StringBuilder failMessage = new(message); + if (detailMessage != null) + { + failMessage.Append(' '); + failMessage.Append(detailMessage); + } + + this.TraceEvent(null, null, TraceEventType.Error, 0, failMessage.ToString()); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs new file mode 100644 index 0000000000000000000000000000000000000000..d26c629d54e6c054e272f1095a0ffb7f48fd1025 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/*============================================================ +** +** +** Purpose: +** This internal class is a SafeHandle implementation over a +** native CoTaskMem allocated via StringToCoTaskMemAuto. +** +============================================================*/ + +using System.Runtime.InteropServices; + +namespace System.Diagnostics.Eventing.Reader +{ + // + // Marked as SecurityCritical due to link demands from inherited + // SafeHandle members. + // + [System.Security.SecurityCritical] + internal sealed class CoTaskMemSafeHandle : SafeHandle + { + internal CoTaskMemSafeHandle() + : base(IntPtr.Zero, true) + { + } + + internal void SetMemory(IntPtr handle) + { + SetHandle(handle); + } + + internal IntPtr GetMemory() + { + return handle; + } + + public override bool IsInvalid + { + get + { + return IsClosed || handle == IntPtr.Zero; + } + } + + protected override bool ReleaseHandle() + { + Marshal.FreeCoTaskMem(handle); + handle = IntPtr.Zero; + return true; + } + + // + // DONT compare CoTaskMemSafeHandle with CoTaskMemSafeHandle.Zero + // use IsInvalid instead. Zero is provided where a NULL handle needed + // + + public static CoTaskMemSafeHandle Zero + { + get + { + return new CoTaskMemSafeHandle(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b9c9e44ebc2d0149d814da11769c4702e7e94ad --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/*============================================================ +** +** +** Purpose: +** This internal class is a SafeHandle implementation over a +** native CoTaskMem allocated via SecureStringToCoTaskMemUnicode. +** +============================================================*/ + +using System.Runtime.InteropServices; + +namespace System.Diagnostics.Eventing.Reader +{ + // + // Marked as SecurityCritical due to link demands from inherited + // SafeHandle members. + // + [System.Security.SecurityCritical] + internal sealed class CoTaskMemUnicodeSafeHandle : SafeHandle + { + internal CoTaskMemUnicodeSafeHandle() + : base(IntPtr.Zero, true) + { + } + + internal CoTaskMemUnicodeSafeHandle(IntPtr handle, bool ownsHandle) + : base(IntPtr.Zero, ownsHandle) + { + SetHandle(handle); + } + + internal void SetMemory(IntPtr handle) + { + SetHandle(handle); + } + + internal IntPtr GetMemory() + { + return handle; + } + + public override bool IsInvalid + { + get + { + return IsClosed || handle == IntPtr.Zero; + } + } + + protected override bool ReleaseHandle() + { + Marshal.ZeroFreeCoTaskMemUnicode(handle); + handle = IntPtr.Zero; + return true; + } + + // DONT compare CoTaskMemUnicodeSafeHandle with CoTaskMemUnicodeSafeHandle.Zero + // use IsInvalid instead. Zero is provided where a NULL handle needed + public static CoTaskMemUnicodeSafeHandle Zero + { + get + { + return new CoTaskMemUnicodeSafeHandle(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs new file mode 100644 index 0000000000000000000000000000000000000000..b9956b3068113424cea6c73df2d2b3476bbe806c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/*============================================================ +** +** +** Purpose: +** This internal class is a SafeHandle implementation over a +** native EVT_HANDLE - obtained from EventLog Native Methods. +** +============================================================*/ + +using System.Runtime.InteropServices; + +namespace System.Diagnostics.Eventing.Reader +{ + // + // Marked as SecurityCritical due to link demands from inherited + // SafeHandle members. + // + + // marked as Safe since the only real operation that is performed + // by this class is NativeWrapper.EvtClose and that is protected + // by a full Demand() before doing any work. + [System.Security.SecuritySafeCritical] + internal sealed class EventLogHandle : SafeHandle + { + // Called by P/Invoke when returning SafeHandles + private EventLogHandle() + : base(IntPtr.Zero, true) + { + } + + internal EventLogHandle(IntPtr handle, bool ownsHandle) + : base(IntPtr.Zero, ownsHandle) + { + SetHandle(handle); + } + + public override bool IsInvalid + { + get + { + return IsClosed || handle == IntPtr.Zero; + } + } + + protected override bool ReleaseHandle() + { + NativeWrapper.EvtClose(handle); + handle = IntPtr.Zero; + return true; + } + + // DONT compare EventLogHandle with EventLogHandle.Zero + // use IsInvalid instead. Zero is provided where a NULL handle needed + public static EventLogHandle Zero + { + get + { + return new EventLogHandle(); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs new file mode 100644 index 0000000000000000000000000000000000000000..df2b064ebd542da75b461a008871f79c3a7b204e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -0,0 +1,1473 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/*============================================================ +** +** +** Purpose: +** This internal class contains wrapper methods over the Native +** Methods of the Eventlog API. Unlike the raw Native Methods, +** these methods throw EventLogExceptions, check platform +** availability and perform additional helper functionality +** specific to function. Also, all methods of this class expose +** the Link Demand for Unmanaged Permission to callers. +** +============================================================*/ + +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; + +namespace System.Diagnostics.Eventing.Reader +{ + internal static class NativeWrapper + { + public class SystemProperties + { + // indicates if the SystemProperties values were already computed (for this event Instance, surely). + public bool filled = false; + + public ushort? Id = null; + public byte? Version = null; + public ushort? Qualifiers = null; + public byte? Level = null; + public ushort? Task = null; + public byte? Opcode = null; + public ulong? Keywords = null; + public ulong? RecordId = null; + public string ProviderName = null; + public Guid? ProviderId = null; + public string ChannelName = null; + public uint? ProcessId = null; + public uint? ThreadId = null; + public string ComputerName = null; + public System.Security.Principal.SecurityIdentifier UserId = null; + public DateTime? TimeCreated = null; + public Guid? ActivityId = null; + public Guid? RelatedActivityId = null; + + public SystemProperties() + { + } + } + + private static void ThrowEventLogException(int errorCode) + { + string message = new Win32Exception(errorCode).Message; + + switch (errorCode) + { + case 2: + case 3: + case 15007: + case 15027: + case 15028: + case 15002: + throw new EventLogNotFoundException(message); + + case 13: + case 15005: + throw new EventLogInvalidDataException(message); + + case 1818: // RPC_S_CALL_CANCELED is converted to ERROR_CANCELLED + case 1223: + throw new OperationCanceledException(); + + case 15037: + throw new EventLogProviderDisabledException(message); + + case 5: + throw new UnauthorizedAccessException(); + + case 15011: + case 15012: + throw new EventLogReadingException(message); + + default: + throw new EventLogException(message); + } + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtQuery( + EventLogHandle session, + string path, + string query, + int flags) + { + EventLogHandle handle = UnsafeNativeMethods.EvtQuery(session, path, query, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + ThrowEventLogException(win32Error); + return handle; + } + + [System.Security.SecurityCritical] + public static void EvtSeek( + EventLogHandle resultSet, + long position, + EventLogHandle bookmark, + int timeout, + UnsafeNativeMethods.EvtSeekFlags flags) + { + bool status = UnsafeNativeMethods.EvtSeek(resultSet, position, bookmark, timeout, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + + [System.Security.SecurityCritical] + public static bool EvtNext( + EventLogHandle queryHandle, + int eventSize, + IntPtr[] events, + int timeout, + int flags, + ref int returned) + { + bool status = UnsafeNativeMethods.EvtNext(queryHandle, eventSize, events, timeout, flags, ref returned); + int win32Error = Marshal.GetLastWin32Error(); + if (!status && win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) + ThrowEventLogException(win32Error); + return win32Error == 0; + } + + [System.Security.SecuritySafeCritical] + public static void EvtCancel(EventLogHandle handle) + { + if (!UnsafeNativeMethods.EvtCancel(handle)) + { + int win32Error = Marshal.GetLastWin32Error(); + ThrowEventLogException(win32Error); + } + } + + [System.Security.SecurityCritical] + public static void EvtClose(IntPtr handle) + { + // + // purposely don't check and throw - this is + // always called in cleanup / finalize / etc.. + // + UnsafeNativeMethods.EvtClose(handle); + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenProviderMetadata( + EventLogHandle session, + string ProviderId, + string logFilePath, + int locale, + int flags) + { + // + // ignore locale and pass 0 instead: that way, the thread locale will be retrieved in the API layer + // and the "strict rendering" flag will NOT be set. Otherwise, the fall back logic is broken and the descriptions + // are not returned if the exact locale is not present on the server. + // + EventLogHandle handle = UnsafeNativeMethods.EvtOpenPublisherMetadata(session, ProviderId, logFilePath, 0, flags); + + int win32Error = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + ThrowEventLogException(win32Error); + return handle; + } + + [System.Security.SecurityCritical] + public static int EvtGetObjectArraySize(EventLogHandle objectArray) + { + int arraySize; + bool status = UnsafeNativeMethods.EvtGetObjectArraySize(objectArray, out arraySize); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + return arraySize; + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenEventMetadataEnum(EventLogHandle ProviderMetadata, int flags) + { + EventLogHandle emEnumHandle = UnsafeNativeMethods.EvtOpenEventMetadataEnum(ProviderMetadata, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (emEnumHandle.IsInvalid) + ThrowEventLogException(win32Error); + return emEnumHandle; + } + + // returns null if EOF + [System.Security.SecurityCritical] + public static EventLogHandle EvtNextEventMetadata(EventLogHandle eventMetadataEnum, int flags) + { + EventLogHandle emHandle = UnsafeNativeMethods.EvtNextEventMetadata(eventMetadataEnum, flags); + int win32Error = Marshal.GetLastWin32Error(); + + if (emHandle.IsInvalid) + { + if (win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) + ThrowEventLogException(win32Error); + return null; + } + + return emHandle; + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenChannelEnum(EventLogHandle session, int flags) + { + EventLogHandle channelEnum = UnsafeNativeMethods.EvtOpenChannelEnum(session, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (channelEnum.IsInvalid) + ThrowEventLogException(win32Error); + return channelEnum; + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenProviderEnum(EventLogHandle session, int flags) + { + EventLogHandle pubEnum = UnsafeNativeMethods.EvtOpenPublisherEnum(session, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (pubEnum.IsInvalid) + ThrowEventLogException(win32Error); + return pubEnum; + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenChannelConfig(EventLogHandle session, string channelPath, int flags) + { + EventLogHandle handle = UnsafeNativeMethods.EvtOpenChannelConfig(session, channelPath, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + ThrowEventLogException(win32Error); + return handle; + } + + [System.Security.SecuritySafeCritical] + public static void EvtSaveChannelConfig(EventLogHandle channelConfig, int flags) + { + bool status = UnsafeNativeMethods.EvtSaveChannelConfig(channelConfig, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenLog(EventLogHandle session, string path, PathType flags) + { + EventLogHandle logHandle = UnsafeNativeMethods.EvtOpenLog(session, path, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (logHandle.IsInvalid) + ThrowEventLogException(win32Error); + return logHandle; + } + + [System.Security.SecuritySafeCritical] + public static void EvtExportLog( + EventLogHandle session, + string channelPath, + string query, + string targetFilePath, + int flags) + { + bool status; + status = UnsafeNativeMethods.EvtExportLog(session, channelPath, query, targetFilePath, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + + [System.Security.SecuritySafeCritical] + public static void EvtArchiveExportedLog( + EventLogHandle session, + string logFilePath, + int locale, + int flags) + { + bool status; + status = UnsafeNativeMethods.EvtArchiveExportedLog(session, logFilePath, locale, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + + [System.Security.SecuritySafeCritical] + public static void EvtClearLog( + EventLogHandle session, + string channelPath, + string targetFilePath, + int flags) + { + bool status; + status = UnsafeNativeMethods.EvtClearLog(session, channelPath, targetFilePath, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtCreateRenderContext( + int valuePathsCount, + string[] valuePaths, + UnsafeNativeMethods.EvtRenderContextFlags flags) + { + EventLogHandle renderContextHandleValues = UnsafeNativeMethods.EvtCreateRenderContext(valuePathsCount, valuePaths, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (renderContextHandleValues.IsInvalid) + ThrowEventLogException(win32Error); + return renderContextHandleValues; + } + + [System.Security.SecurityCritical] + public static void EvtRender( + EventLogHandle context, + EventLogHandle eventHandle, + UnsafeNativeMethods.EvtRenderFlags flags, + StringBuilder buffer) + { + int buffUsed; + int propCount; + bool status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); + int win32Error = Marshal.GetLastWin32Error(); + + if (!status) + { + if (win32Error == UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + { + // reallocate the new RenderBuffer with the right size. + buffer.Capacity = buffUsed; + status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); + win32Error = Marshal.GetLastWin32Error(); + } + + if (!status) + { + ThrowEventLogException(win32Error); + } + } + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtOpenSession(UnsafeNativeMethods.EvtLoginClass loginClass, ref UnsafeNativeMethods.EvtRpcLogin login, int timeout, int flags) + { + EventLogHandle handle = UnsafeNativeMethods.EvtOpenSession(loginClass, ref login, timeout, flags); + int win32Error = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + ThrowEventLogException(win32Error); + return handle; + } + + [System.Security.SecurityCritical] + public static EventLogHandle EvtCreateBookmark(string bookmarkXml) + { + EventLogHandle handle = UnsafeNativeMethods.EvtCreateBookmark(bookmarkXml); + int win32Error = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + ThrowEventLogException(win32Error); + return handle; + } + + [System.Security.SecurityCritical] + public static void EvtUpdateBookmark(EventLogHandle bookmark, EventLogHandle eventHandle) + { + bool status = UnsafeNativeMethods.EvtUpdateBookmark(bookmark, eventHandle); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + + [System.Security.SecuritySafeCritical] + public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods.EvtEventPropertyId enumType) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + bool status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, 0, IntPtr.Zero, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + if (!status) + { + if (error == UnsafeNativeMethods.ERROR_SUCCESS) { } + else + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(error); + + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecurityCritical] + public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods.EvtQueryPropertyId enumType) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded = 0; + try + { + bool status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, 0, IntPtr.Zero, ref bufferNeeded); + int error = Marshal.GetLastWin32Error(); + if (!status) + { + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, bufferNeeded, buffer, ref bufferNeeded); + error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(error); + + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecuritySafeCritical] + public static object EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + bool status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, 0, IntPtr.Zero, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + if (!status) + { + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(error); + + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecurityCritical] + internal static EventLogHandle EvtGetPublisherMetadataPropertyHandle(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) + { + IntPtr buffer = IntPtr.Zero; + try + { + int bufferNeeded; + bool status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, 0, IntPtr.Zero, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + if (!status) + { + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(error); + + // + // note: there is a case where returned variant does have allocated native resources + // associated with (e.g. ConfigArrayHandle). If PtrToStructure throws, then we would + // leak that resource - fortunately PtrToStructure only throws InvalidArgument which + // is a logic error - not a possible runtime condition here. Other System exceptions + // shouldn't be handled anyhow and the application will terminate. + // + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToSafeHandle(varVal); + } + finally + { + if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); + } + } + + // implies UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId flag. + [System.Security.SecurityCritical] + public static string EvtFormatMessage(EventLogHandle handle, uint msgId) + { + int bufferNeeded; + + StringBuilder sb = new(null); + bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, sb, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + + // ERROR_EVT_UNRESOLVED_VALUE_INSERT and its cousins are commonly returned for raw message text. + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT + && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_PARAMETER_INSERT + && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return null; + } + + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + sb.EnsureCapacity(bufferNeeded); + status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, bufferNeeded, sb, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT + && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_PARAMETER_INSERT + && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return null; + } + + if (error == UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { + return null; + } + + ThrowEventLogException(error); + } + + return sb.ToString(); + } + + [System.Security.SecurityCritical] + public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + bool status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, 0, IntPtr.Zero, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + + if (!status) + { + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, bufferNeeded, buffer, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(error); + + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecurityCritical] + public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNativeMethods.EvtEventMetadataPropertyId enumType) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + bool status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, 0, IntPtr.Zero, out bufferNeeded); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + { + if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(win32Error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded); + win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecuritySafeCritical] + public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + bool status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, 0, IntPtr.Zero, out bufferNeeded); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + { + if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(win32Error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded); + win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + // + // note: there is a case where returned variant does have allocated native resources + // associated with (e.g. ConfigArrayHandle). If PtrToStructure throws, then we would + // leak that resource - fortunately PtrToStructure only throws InvalidArgument which + // is a logic error - not a possible runtime condition here. Other System exceptions + // shouldn't be handled anyhow and the application will terminate. + // + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecuritySafeCritical] + public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val) + { + UnsafeNativeMethods.EvtVariant varVal = new(); + + CoTaskMemSafeHandle taskMem = new(); + + using (taskMem) + { + if (val != null) + { + switch (enumType) + { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; + if ((bool)val) varVal.Bool = 1; + else varVal.Bool = 0; + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; + taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); + varVal.StringVal = taskMem.GetMemory(); + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; + taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); + varVal.StringVal = taskMem.GetMemory(); + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; + varVal.ULong = (ulong)((long)val); + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32; + varVal.UInteger = (uint)((int)val); + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; + varVal.ULong = (ulong)((long)val); + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; + if ((bool)val) varVal.Bool = 1; + else varVal.Bool = 0; + } + + break; + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; + if ((bool)val) varVal.Bool = 1; + else varVal.Bool = 0; + } + + break; + default: + throw new InvalidOperationException(); + } + } + else + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull; + } + + bool status = UnsafeNativeMethods.EvtSetChannelConfigProperty(handle, enumType, 0, ref varVal); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + } + } + + [System.Security.SecurityCritical] + public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) + { + StringBuilder sb = new(null); + int channelNameNeeded; + + bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, sb, out channelNameNeeded); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + { + if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) + { + finish = true; + return null; + } + + if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(win32Error); + } + + sb.EnsureCapacity(channelNameNeeded); + status = UnsafeNativeMethods.EvtNextChannelPath(handle, channelNameNeeded, sb, out channelNameNeeded); + win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + return sb.ToString(); + } + + [System.Security.SecurityCritical] + public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) + { + StringBuilder sb = new(null); + int ProviderIdNeeded; + + bool status = UnsafeNativeMethods.EvtNextPublisherId(handle, 0, sb, out ProviderIdNeeded); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + { + if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) + { + finish = true; + return null; + } + + if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(win32Error); + } + + sb.EnsureCapacity(ProviderIdNeeded); + status = UnsafeNativeMethods.EvtNextPublisherId(handle, ProviderIdNeeded, sb, out ProviderIdNeeded); + win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + return sb.ToString(); + } + + [System.Security.SecurityCritical] + public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + bool status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, 0, IntPtr.Zero, out bufferNeeded); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + { + if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(win32Error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); + win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); + return ConvertToObject(varVal); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecuritySafeCritical] + public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtRenderFlags flag, SystemProperties systemProperties, int SYSTEM_PROPERTY_COUNT) + { + IntPtr buffer = IntPtr.Zero; + IntPtr pointer = IntPtr.Zero; + int bufferNeeded; + int propCount; + + try + { + bool status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); + if (!status) + { + int error = Marshal.GetLastWin32Error(); + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + if (propCount != SYSTEM_PROPERTY_COUNT) + throw new InvalidOperationException("We do not have " + SYSTEM_PROPERTY_COUNT + " variants given for the UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues flag. (System Properties)"); + + pointer = buffer; + // read each Variant structure + for (int i = 0; i < propCount; i++) + { + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(pointer); + switch (i) + { + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderName: + systemProperties.ProviderName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderGuid: + systemProperties.ProviderId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventID: + systemProperties.Id = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemQualifiers: + systemProperties.Qualifiers = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemLevel: + systemProperties.Level = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTask: + systemProperties.Task = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemOpcode: + systemProperties.Opcode = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemKeywords: + systemProperties.Keywords = (ulong?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTimeCreated: + systemProperties.TimeCreated = (DateTime?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventRecordId: + systemProperties.RecordId = (ulong?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemActivityID: + systemProperties.ActivityId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemRelatedActivityID: + systemProperties.RelatedActivityId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProcessID: + systemProperties.ProcessId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemThreadID: + systemProperties.ThreadId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemChannel: + systemProperties.ChannelName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemComputer: + systemProperties.ComputerName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemUserID: + systemProperties.UserId = (SecurityIdentifier)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid); + break; + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemVersion: + systemProperties.Version = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); + break; + } + + pointer = new IntPtr(((long)pointer + Marshal.SizeOf(varVal))); + } + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + // EvtRenderContextFlags can be both: EvtRenderContextFlags.EvtRenderContextUser and EvtRenderContextFlags.EvtRenderContextValues + // Render with Context = ContextUser or ContextValues (with user defined Xpath query strings) + [System.Security.SecuritySafeCritical] + public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) + { + IntPtr buffer = IntPtr.Zero; + IntPtr pointer = IntPtr.Zero; + int bufferNeeded; + int propCount; + const UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; + + try + { + bool status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); + if (!status) + { + int error = Marshal.GetLastWin32Error(); + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount); + int win32Error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(win32Error); + + List valuesList = new(propCount); + if (propCount > 0) + { + pointer = buffer; + for (int i = 0; i < propCount; i++) + { + UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(pointer); + valuesList.Add(ConvertToObject(varVal)); + pointer = new IntPtr(((long)pointer + Marshal.SizeOf(varVal))); + } + } + + return valuesList; + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecuritySafeCritical] + public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) + { + int bufferNeeded; + StringBuilder sb = new(null); + + bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, sb, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { + // + // ERROR_EVT_UNRESOLVED_VALUE_INSERT can be returned. It means + // message may have one or more unsubstituted strings. This is + // not an exception, but we have no way to convey the partial + // success out to enduser. + // + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return null; + } + + if (error != (int)UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + sb.EnsureCapacity(bufferNeeded); + status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, bufferNeeded, sb, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return null; + } + + ThrowEventLogException(error); + } + + return sb.ToString(); + } + + // The EvtFormatMessage used for the obtaining of the Keywords names. + [System.Security.SecuritySafeCritical] + public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + + try + { + List keywordsList = new(); + bool status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, 0, IntPtr.Zero, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + + if (!status) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return keywordsList.AsReadOnly(); + } + + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal(bufferNeeded * 2); + status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, bufferNeeded, buffer, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + if (!status) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return keywordsList; + } + + ThrowEventLogException(error); + } + + IntPtr pointer = buffer; + + while (true) + { + string s = Marshal.PtrToStringUni(pointer); + if (string.IsNullOrEmpty(s)) + break; + keywordsList.Add(s); + // nr of bytes = # chars * 2 + 2 bytes for character '\0'. + pointer = new IntPtr((long)pointer + (s.Length * 2) + 2); + } + + return keywordsList.AsReadOnly(); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + [System.Security.SecurityCritical] + public static string EvtRenderBookmark(EventLogHandle eventHandle) + { + IntPtr buffer = IntPtr.Zero; + int bufferNeeded; + int propCount; + const UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; + + try + { + bool status = UnsafeNativeMethods.EvtRender(EventLogHandle.Zero, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); + int error = Marshal.GetLastWin32Error(); + if (!status) + { + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + buffer = Marshal.AllocHGlobal((int)bufferNeeded); + status = UnsafeNativeMethods.EvtRender(EventLogHandle.Zero, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount); + error = Marshal.GetLastWin32Error(); + if (!status) + ThrowEventLogException(error); + + return Marshal.PtrToStringUni(buffer); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + + // Get the formatted description, using the msgId for FormatDescription(string []) + [System.Security.SecuritySafeCritical] + public static string EvtFormatMessageFormatDescription(EventLogHandle handle, EventLogHandle eventHandle, string[] values) + { + int bufferNeeded; + + UnsafeNativeMethods.EvtStringVariant[] stringVariants = new UnsafeNativeMethods.EvtStringVariant[values.Length]; + for (int i = 0; i < values.Length; i++) + { + stringVariants[i].Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; + stringVariants[i].StringVal = values[i]; + } + + StringBuilder sb = new(null); + bool status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, 0, sb, out bufferNeeded); + int error = Marshal.GetLastWin32Error(); + + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { + // + // ERROR_EVT_UNRESOLVED_VALUE_INSERT can be returned. It means + // message may have one or more unsubstituted strings. This is + // not an exception, but we have no way to convey the partial + // success out to enduser. + // + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return null; + } + + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + ThrowEventLogException(error); + } + + sb.EnsureCapacity(bufferNeeded); + status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, bufferNeeded, sb, out bufferNeeded); + error = Marshal.GetLastWin32Error(); + + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { + switch (error) + { + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: + case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + return null; + } + + ThrowEventLogException(error); + } + + return sb.ToString(); + } + + [System.Security.SecurityCritical] + private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) + { + switch (val.Type) + { + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32: + return val.UInteger; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32: + return val.Integer; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16: + return val.UShort; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16: + return val.SByte; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte: + return val.UInt8; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte: + return val.SByte; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64: + return val.ULong; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64: + return val.Long; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64: + return val.ULong; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32: + return val.Integer; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle: + return val.Single; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble: + return val.Double; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull: + return null; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString: + return ConvertToString(val); + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString: + return ConvertToAnsiString(val); + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid: + return (val.SidVal == IntPtr.Zero) ? null : new SecurityIdentifier(val.SidVal); + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid: + return (val.GuidReference == IntPtr.Zero) ? Guid.Empty : Marshal.PtrToStructure(val.GuidReference); + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeEvtHandle: + return ConvertToSafeHandle(val); + case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime: + return DateTime.FromFileTime((long)val.FileTime); + case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime: + UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(val.SystemTime); + return new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); + case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT: + return val.SizeT; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean: + if (val.Bool != 0) return true; + else return false; + case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary: + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte): + if (val.Reference == IntPtr.Zero) return Array.Empty(); + byte[] arByte = new byte[val.Count]; + Marshal.Copy(val.Reference, arByte, 0, (int)val.Count); + return arByte; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16): + if (val.Reference == IntPtr.Zero) return Array.Empty(); + short[] arInt16 = new short[val.Count]; + Marshal.Copy(val.Reference, arInt16, 0, (int)val.Count); + return arInt16; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32): + if (val.Reference == IntPtr.Zero) return Array.Empty(); + int[] arInt32 = new int[val.Count]; + Marshal.Copy(val.Reference, arInt32, 0, (int)val.Count); + return arInt32; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64): + if (val.Reference == IntPtr.Zero) return Array.Empty(); + long[] arInt64 = new long[val.Count]; + Marshal.Copy(val.Reference, arInt64, 0, (int)val.Count); + return arInt64; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle): + if (val.Reference == IntPtr.Zero) return Array.Empty(); + float[] arSingle = new float[val.Count]; + Marshal.Copy(val.Reference, arSingle, 0, (int)val.Count); + return arSingle; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble): + if (val.Reference == IntPtr.Zero) return Array.Empty(); + double[] arDouble = new double[val.Count]; + Marshal.Copy(val.Reference, arDouble, 0, (int)val.Count); + return arDouble; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte): + return ConvertToArray(val, sizeof(sbyte)); // not CLS-compliant + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16): + return ConvertToArray(val, sizeof(ushort)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64): + return ConvertToArray(val, sizeof(ulong)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32): + return ConvertToArray(val, sizeof(uint)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString): + return ConvertToStringArray(val, false); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString): + return ConvertToStringArray(val, true); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean): + return ConvertToBoolArray(val); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid): + return ConvertToArray(val, 16 * sizeof(byte)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime): + return ConvertToFileTimeArray(val); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime): + return ConvertToSysTimeArray(val); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary): // both length and count in the manifest: tracrpt supports, Crimson APIs don't + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT): // unused: array of win:pointer is returned as HexIntXX + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid): // unsupported by native APIs + default: + throw new EventLogInvalidDataException(); + } + } + + [System.Security.SecurityCritical] + public static object ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeNativeMethods.EvtVariantType desiredType) + { + if (val.Type == (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull) return null; + if (val.Type != (int)desiredType) + throw new EventLogInvalidDataException(); + + return ConvertToObject(val); + } + + [System.Security.SecurityCritical] + public static string ConvertToString(UnsafeNativeMethods.EvtVariant val) + { + if (val.StringVal == IntPtr.Zero) + return string.Empty; + else + return Marshal.PtrToStringUni(val.StringVal); + } + + [System.Security.SecurityCritical] + public static string ConvertToAnsiString(UnsafeNativeMethods.EvtVariant val) + { + if (val.AnsiString == IntPtr.Zero) + return string.Empty; + else + return Marshal.PtrToStringAnsi(val.AnsiString); + } + + [System.Security.SecurityCritical] + public static EventLogHandle ConvertToSafeHandle(UnsafeNativeMethods.EvtVariant val) + { + if (val.Handle == IntPtr.Zero) + return EventLogHandle.Zero; + else + return new EventLogHandle(val.Handle, true); + } + + [System.Security.SecurityCritical] + public static Array ConvertToArray(UnsafeNativeMethods.EvtVariant val, int size) where T : struct + { + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { + return Array.CreateInstance(typeof(T), 0); + } + else + { + Array array = Array.CreateInstance(typeof(T), (int)val.Count); + for (int i = 0; i < val.Count; i++) + { + array.SetValue(Marshal.PtrToStructure(ptr), i); + ptr = new IntPtr((long)ptr + size); + } + + return array; + } + } + + [System.Security.SecurityCritical] + public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) + { + // NOTE: booleans are padded to 4 bytes in ETW + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { + return Array.Empty(); + } + else + { + bool[] array = new bool[val.Count]; + for (int i = 0; i < val.Count; i++) + { + bool value = Marshal.ReadInt32(ptr) != 0; + array[i] = value; + ptr = new IntPtr((long)ptr + 4); + } + + return array; + } + } + + [System.Security.SecurityCritical] + public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) + { + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { + return Array.Empty(); + } + else + { + DateTime[] array = new DateTime[val.Count]; + for (int i = 0; i < val.Count; i++) + { + array[i] = DateTime.FromFileTime(Marshal.ReadInt64(ptr)); + ptr = new IntPtr((long)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes + } + + return array; + } + } + + [System.Security.SecurityCritical] + public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) + { + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { + return Array.Empty(); + } + else + { + DateTime[] array = new DateTime[val.Count]; + for (int i = 0; i < val.Count; i++) + { + UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(ptr); + array[i] = new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); + ptr = new IntPtr((long)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes + } + + return array; + } + } + + [System.Security.SecurityCritical] + public static string[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, bool ansi) + { + if (val.Reference == IntPtr.Zero) + { + return Array.Empty(); + } + else + { + IntPtr ptr = val.Reference; + IntPtr[] pointersToString = new IntPtr[val.Count]; + Marshal.Copy(ptr, pointersToString, 0, (int)val.Count); + string[] stringArray = new string[val.Count]; + for (int i = 0; i < val.Count; i++) + { + stringArray[i] = ansi ? Marshal.PtrToStringAnsi(pointersToString[i]) : Marshal.PtrToStringUni(pointersToString[i]); + } + + return stringArray; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs new file mode 100644 index 0000000000000000000000000000000000000000..b7beee133ed9842f8772826dcf6d9a8ef85d2eb4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -0,0 +1,926 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.Eventing.Reader; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; + +namespace System.Diagnostics.Eventing +{ + internal static class UnsafeNativeMethods + { + private const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-0.dll"; + private const string EventProviderDllName = "api-ms-win-eventing-provider-l1-1-0.dll"; + private const string WEVTAPI = "wevtapi.dll"; + + private static readonly IntPtr s_NULL = IntPtr.Zero; + + // WinError.h codes: + internal const int ERROR_SUCCESS = 0x0; + internal const int ERROR_FILE_NOT_FOUND = 0x2; + internal const int ERROR_PATH_NOT_FOUND = 0x3; + internal const int ERROR_ACCESS_DENIED = 0x5; + internal const int ERROR_INVALID_HANDLE = 0x6; + + // Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough. + // This happens when the disk is slow and event traffic is heavy. + // Eventually, there are no more free (empty) buffers and the event is dropped. + internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; + + internal const int ERROR_INVALID_DRIVE = 0xF; + internal const int ERROR_NO_MORE_FILES = 0x12; + internal const int ERROR_NOT_READY = 0x15; + internal const int ERROR_BAD_LENGTH = 0x18; + internal const int ERROR_SHARING_VIOLATION = 0x20; + internal const int ERROR_LOCK_VIOLATION = 0x21; // 33 + internal const int ERROR_HANDLE_EOF = 0x26; // 38 + internal const int ERROR_FILE_EXISTS = 0x50; + internal const int ERROR_INVALID_PARAMETER = 0x57; // 87 + internal const int ERROR_BROKEN_PIPE = 0x6D; // 109 + internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122 + internal const int ERROR_INVALID_NAME = 0x7B; + internal const int ERROR_BAD_PATHNAME = 0xA1; + internal const int ERROR_ALREADY_EXISTS = 0xB7; + internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; + internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long + internal const int ERROR_PIPE_BUSY = 0xE7; // 231 + internal const int ERROR_NO_DATA = 0xE8; // 232 + internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233 + internal const int ERROR_MORE_DATA = 0xEA; + internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259 + internal const int ERROR_PIPE_CONNECTED = 0x217; // 535 + internal const int ERROR_PIPE_LISTENING = 0x218; // 536 + internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation + internal const int ERROR_IO_PENDING = 0x3E5; // 997 + internal const int ERROR_NOT_FOUND = 0x490; // 1168 + + // The event size is larger than the allowed maximum (64k - header). + internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534 + internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815 + + // Event log specific codes: + internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027; + internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028; + internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029; + internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030; + internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031; + internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033; + internal const int ERROR_MUI_FILE_NOT_FOUND = 15100; + + // ErrorCode & format + // for win32 error message formatting + private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; + private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; + private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; + + [DllImport(FormatMessageDllName, CharSet = CharSet.Unicode, BestFitMapping = false)] + [SecurityCritical] + internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, + int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, + int nSize, IntPtr va_list_arguments); + + // Gets an error message for a Win32 error code. + [SecurityCritical] + internal static string GetMessage(int errorCode) + { + StringBuilder sb = new(512); + int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, + UnsafeNativeMethods.s_NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.s_NULL); + if (result != 0) + { + // result is the # of characters copied to the StringBuilder on NT, + // but on Win9x, it appears to be the number of MBCS buffer. + // Just give up and return the String as-is... + string s = sb.ToString(); + return s; + } + else + { + return "UnknownError_Num " + errorCode; + } + } + + // ETW Methods + // Callback + [SecurityCritical] + internal unsafe delegate void EtwEnableCallback( + [In] ref Guid sourceId, + [In] int isEnabled, + [In] byte level, + [In] long matchAnyKeywords, + [In] long matchAllKeywords, + [In] void* filterData, + [In] void* callbackContext + ); + + // Registration APIs + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern unsafe uint EventRegister( + [In] in Guid providerId, + [In] EtwEnableCallback enableCallback, + [In] void* callbackContext, + [In][Out] ref long registrationHandle + ); + + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern int EventUnregister([In] long registrationHandle); + + // Control (Is Enabled) APIs + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern int EventEnabled([In] long registrationHandle, [In] in System.Diagnostics.Eventing.EventDescriptor eventDescriptor); + + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventProviderEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern int EventProviderEnabled([In] long registrationHandle, [In] byte level, [In] long keywords); + + // Writing (Publishing/Logging) APIs + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern unsafe uint EventWrite( + [In] long registrationHandle, + [In] in EventDescriptor eventDescriptor, + [In] uint userDataCount, + [In] void* userData + ); + + // Writing (Publishing/Logging) APIs + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern unsafe uint EventWrite( + [In] long registrationHandle, + [In] EventDescriptor* eventDescriptor, + [In] uint userDataCount, + [In] void* userData + ); + + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern unsafe uint EventWriteTransfer( + [In] long registrationHandle, + [In] in EventDescriptor eventDescriptor, + [In] Guid* activityId, + [In] Guid* relatedActivityId, + [In] uint userDataCount, + [In] void* userData + ); + + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern unsafe uint EventWriteString( + [In] long registrationHandle, + [In] byte level, + [In] long keywords, + [In] char* message + ); + + // ActivityId Control APIs + [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + [SecurityCritical] + internal static extern unsafe uint EventActivityIdControl([In] int ControlCode, [In][Out] ref Guid ActivityId); + + // EventLog + [Flags] + internal enum EvtQueryFlags + { + EvtQueryChannelPath = 0x1, + EvtQueryFilePath = 0x2, + EvtQueryForwardDirection = 0x100, + EvtQueryReverseDirection = 0x200, + EvtQueryTolerateQueryErrors = 0x1000 + } + + /// + /// Evt Variant types. + /// + internal enum EvtVariantType + { + EvtVarTypeNull = 0, + EvtVarTypeString = 1, + EvtVarTypeAnsiString = 2, + EvtVarTypeSByte = 3, + EvtVarTypeByte = 4, + EvtVarTypeInt16 = 5, + EvtVarTypeUInt16 = 6, + EvtVarTypeInt32 = 7, + EvtVarTypeUInt32 = 8, + EvtVarTypeInt64 = 9, + EvtVarTypeUInt64 = 10, + EvtVarTypeSingle = 11, + EvtVarTypeDouble = 12, + EvtVarTypeBoolean = 13, + EvtVarTypeBinary = 14, + EvtVarTypeGuid = 15, + EvtVarTypeSizeT = 16, + EvtVarTypeFileTime = 17, + EvtVarTypeSysTime = 18, + EvtVarTypeSid = 19, + EvtVarTypeHexInt32 = 20, + EvtVarTypeHexInt64 = 21, + // these types used internally + EvtVarTypeEvtHandle = 32, + EvtVarTypeEvtXml = 35, + // Array = 128 + EvtVarTypeStringArray = 129, + EvtVarTypeUInt32Array = 136 + } + + internal enum EvtMasks + { + EVT_VARIANT_TYPE_MASK = 0x7f, + EVT_VARIANT_TYPE_ARRAY = 128 + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SystemTime + { + [MarshalAs(UnmanagedType.U2)] + public short Year; + + [MarshalAs(UnmanagedType.U2)] + public short Month; + + [MarshalAs(UnmanagedType.U2)] + public short DayOfWeek; + + [MarshalAs(UnmanagedType.U2)] + public short Day; + + [MarshalAs(UnmanagedType.U2)] + public short Hour; + + [MarshalAs(UnmanagedType.U2)] + public short Minute; + + [MarshalAs(UnmanagedType.U2)] + public short Second; + + [MarshalAs(UnmanagedType.U2)] + public short Milliseconds; + } + + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] + [SecurityCritical] + internal struct EvtVariant + { + [FieldOffset(0)] + public uint UInteger; + + [FieldOffset(0)] + public int Integer; + + [FieldOffset(0)] + public byte UInt8; + + [FieldOffset(0)] + public short Short; + + [FieldOffset(0)] + public ushort UShort; + + [FieldOffset(0)] + public uint Bool; + + [FieldOffset(0)] + public byte ByteVal; + + [FieldOffset(0)] + public byte SByte; + + [FieldOffset(0)] + public ulong ULong; + + [FieldOffset(0)] + public long Long; + + [FieldOffset(0)] + public float Single; + + [FieldOffset(0)] + public double Double; + + [FieldOffset(0)] + public IntPtr StringVal; + + [FieldOffset(0)] + public IntPtr AnsiString; + + [FieldOffset(0)] + public IntPtr SidVal; + + [FieldOffset(0)] + public IntPtr Binary; + + [FieldOffset(0)] + public IntPtr Reference; + + [FieldOffset(0)] + public IntPtr Handle; + + [FieldOffset(0)] + public IntPtr GuidReference; + + [FieldOffset(0)] + public ulong FileTime; + + [FieldOffset(0)] + public IntPtr SystemTime; + + [FieldOffset(0)] + public IntPtr SizeT; + + [FieldOffset(8)] + public uint Count; // number of elements (not length) in bytes. + + [FieldOffset(12)] + public uint Type; + } + + internal enum EvtEventPropertyId + { + EvtEventQueryIDs = 0, + EvtEventPath = 1 + } + + /// + /// The query flags to get information about query. + /// + internal enum EvtQueryPropertyId + { + EvtQueryNames = 0, // String; // Variant will be array of EvtVarTypeString + EvtQueryStatuses = 1 // UInt32; // Variant will be Array of EvtVarTypeUInt32 + } + + /// + /// Publisher Metadata properties. + /// + internal enum EvtPublisherMetadataPropertyId + { + EvtPublisherMetadataPublisherGuid = 0, // EvtVarTypeGuid + EvtPublisherMetadataResourceFilePath = 1, // EvtVarTypeString + EvtPublisherMetadataParameterFilePath = 2, // EvtVarTypeString + EvtPublisherMetadataMessageFilePath = 3, // EvtVarTypeString + EvtPublisherMetadataHelpLink = 4, // EvtVarTypeString + EvtPublisherMetadataPublisherMessageID = 5, // EvtVarTypeUInt32 + + EvtPublisherMetadataChannelReferences = 6, // EvtVarTypeEvtHandle, ObjectArray + EvtPublisherMetadataChannelReferencePath = 7, // EvtVarTypeString + EvtPublisherMetadataChannelReferenceIndex = 8, // EvtVarTypeUInt32 + EvtPublisherMetadataChannelReferenceID = 9, // EvtVarTypeUInt32 + EvtPublisherMetadataChannelReferenceFlags = 10, // EvtVarTypeUInt32 + EvtPublisherMetadataChannelReferenceMessageID = 11, // EvtVarTypeUInt32 + + EvtPublisherMetadataLevels = 12, // EvtVarTypeEvtHandle, ObjectArray + EvtPublisherMetadataLevelName = 13, // EvtVarTypeString + EvtPublisherMetadataLevelValue = 14, // EvtVarTypeUInt32 + EvtPublisherMetadataLevelMessageID = 15, // EvtVarTypeUInt32 + + EvtPublisherMetadataTasks = 16, // EvtVarTypeEvtHandle, ObjectArray + EvtPublisherMetadataTaskName = 17, // EvtVarTypeString + EvtPublisherMetadataTaskEventGuid = 18, // EvtVarTypeGuid + EvtPublisherMetadataTaskValue = 19, // EvtVarTypeUInt32 + EvtPublisherMetadataTaskMessageID = 20, // EvtVarTypeUInt32 + + EvtPublisherMetadataOpcodes = 21, // EvtVarTypeEvtHandle, ObjectArray + EvtPublisherMetadataOpcodeName = 22, // EvtVarTypeString + EvtPublisherMetadataOpcodeValue = 23, // EvtVarTypeUInt32 + EvtPublisherMetadataOpcodeMessageID = 24, // EvtVarTypeUInt32 + + EvtPublisherMetadataKeywords = 25, // EvtVarTypeEvtHandle, ObjectArray + EvtPublisherMetadataKeywordName = 26, // EvtVarTypeString + EvtPublisherMetadataKeywordValue = 27, // EvtVarTypeUInt64 + EvtPublisherMetadataKeywordMessageID = 28 // EvtVarTypeUInt32 + // EvtPublisherMetadataPropertyIdEND + } + + internal enum EvtChannelReferenceFlags + { + EvtChannelReferenceImported = 1 + } + + internal enum EvtEventMetadataPropertyId + { + EventMetadataEventID, // EvtVarTypeUInt32 + EventMetadataEventVersion, // EvtVarTypeUInt32 + EventMetadataEventChannel, // EvtVarTypeUInt32 + EventMetadataEventLevel, // EvtVarTypeUInt32 + EventMetadataEventOpcode, // EvtVarTypeUInt32 + EventMetadataEventTask, // EvtVarTypeUInt32 + EventMetadataEventKeyword, // EvtVarTypeUInt64 + EventMetadataEventMessageID, // EvtVarTypeUInt32 + EventMetadataEventTemplate // EvtVarTypeString + // EvtEventMetadataPropertyIdEND + } + + // CHANNEL CONFIGURATION + internal enum EvtChannelConfigPropertyId + { + EvtChannelConfigEnabled = 0, // EvtVarTypeBoolean + EvtChannelConfigIsolation, // EvtVarTypeUInt32, EVT_CHANNEL_ISOLATION_TYPE + EvtChannelConfigType, // EvtVarTypeUInt32, EVT_CHANNEL_TYPE + EvtChannelConfigOwningPublisher, // EvtVarTypeString + EvtChannelConfigClassicEventlog, // EvtVarTypeBoolean + EvtChannelConfigAccess, // EvtVarTypeString + EvtChannelLoggingConfigRetention, // EvtVarTypeBoolean + EvtChannelLoggingConfigAutoBackup, // EvtVarTypeBoolean + EvtChannelLoggingConfigMaxSize, // EvtVarTypeUInt64 + EvtChannelLoggingConfigLogFilePath, // EvtVarTypeString + EvtChannelPublishingConfigLevel, // EvtVarTypeUInt32 + EvtChannelPublishingConfigKeywords, // EvtVarTypeUInt64 + EvtChannelPublishingConfigControlGuid, // EvtVarTypeGuid + EvtChannelPublishingConfigBufferSize, // EvtVarTypeUInt32 + EvtChannelPublishingConfigMinBuffers, // EvtVarTypeUInt32 + EvtChannelPublishingConfigMaxBuffers, // EvtVarTypeUInt32 + EvtChannelPublishingConfigLatency, // EvtVarTypeUInt32 + EvtChannelPublishingConfigClockType, // EvtVarTypeUInt32, EVT_CHANNEL_CLOCK_TYPE + EvtChannelPublishingConfigSidType, // EvtVarTypeUInt32, EVT_CHANNEL_SID_TYPE + EvtChannelPublisherList, // EvtVarTypeString | EVT_VARIANT_TYPE_ARRAY + EvtChannelConfigPropertyIdEND + } + + // LOG INFORMATION + internal enum EvtLogPropertyId + { + EvtLogCreationTime = 0, // EvtVarTypeFileTime + EvtLogLastAccessTime, // EvtVarTypeFileTime + EvtLogLastWriteTime, // EvtVarTypeFileTime + EvtLogFileSize, // EvtVarTypeUInt64 + EvtLogAttributes, // EvtVarTypeUInt32 + EvtLogNumberOfLogRecords, // EvtVarTypeUInt64 + EvtLogOldestRecordNumber, // EvtVarTypeUInt64 + EvtLogFull, // EvtVarTypeBoolean + } + + internal enum EvtExportLogFlags + { + EvtExportLogChannelPath = 1, + EvtExportLogFilePath = 2, + EvtExportLogTolerateQueryErrors = 0x1000 + } + + // RENDERING + internal enum EvtRenderContextFlags + { + EvtRenderContextValues = 0, // Render specific properties + EvtRenderContextSystem = 1, // Render all system properties (System) + EvtRenderContextUser = 2 // Render all user properties (User/EventData) + } + + internal enum EvtRenderFlags + { + EvtRenderEventValues = 0, // Variants + EvtRenderEventXml = 1, // XML + EvtRenderBookmark = 2 // Bookmark + } + + internal enum EvtFormatMessageFlags + { + EvtFormatMessageEvent = 1, + EvtFormatMessageLevel = 2, + EvtFormatMessageTask = 3, + EvtFormatMessageOpcode = 4, + EvtFormatMessageKeyword = 5, + EvtFormatMessageChannel = 6, + EvtFormatMessageProvider = 7, + EvtFormatMessageId = 8, + EvtFormatMessageXml = 9 + } + + internal enum EvtSystemPropertyId + { + EvtSystemProviderName = 0, // EvtVarTypeString + EvtSystemProviderGuid, // EvtVarTypeGuid + EvtSystemEventID, // EvtVarTypeUInt16 + EvtSystemQualifiers, // EvtVarTypeUInt16 + EvtSystemLevel, // EvtVarTypeUInt8 + EvtSystemTask, // EvtVarTypeUInt16 + EvtSystemOpcode, // EvtVarTypeUInt8 + EvtSystemKeywords, // EvtVarTypeHexInt64 + EvtSystemTimeCreated, // EvtVarTypeFileTime + EvtSystemEventRecordId, // EvtVarTypeUInt64 + EvtSystemActivityID, // EvtVarTypeGuid + EvtSystemRelatedActivityID, // EvtVarTypeGuid + EvtSystemProcessID, // EvtVarTypeUInt32 + EvtSystemThreadID, // EvtVarTypeUInt32 + EvtSystemChannel, // EvtVarTypeString + EvtSystemComputer, // EvtVarTypeString + EvtSystemUserID, // EvtVarTypeSid + EvtSystemVersion, // EvtVarTypeUInt8 + EvtSystemPropertyIdEND + } + + // SESSION + internal enum EvtLoginClass + { + EvtRpcLogin = 1 + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct EvtRpcLogin + { + [MarshalAs(UnmanagedType.LPWStr)] + public string Server; + + [MarshalAs(UnmanagedType.LPWStr)] + public string User; + + [MarshalAs(UnmanagedType.LPWStr)] + public string Domain; + + [SecurityCritical] + public CoTaskMemUnicodeSafeHandle Password; + + public int Flags; + } + + // SEEK + [Flags] + internal enum EvtSeekFlags + { + EvtSeekRelativeToFirst = 1, + EvtSeekRelativeToLast = 2, + EvtSeekRelativeToCurrent = 3, + EvtSeekRelativeToBookmark = 4, + EvtSeekOriginMask = 7, + EvtSeekStrict = 0x10000 + } + + [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtQuery( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string path, + [MarshalAs(UnmanagedType.LPWStr)] string query, + int flags); + + // SEEK + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtSeek( + EventLogHandle resultSet, + long position, + EventLogHandle bookmark, + int timeout, + [MarshalAs(UnmanagedType.I4)] EvtSeekFlags flags + ); + + [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtNext( + EventLogHandle queryHandle, + int eventSize, + [MarshalAs(UnmanagedType.LPArray)] IntPtr[] events, + int timeout, + int flags, + ref int returned); + + [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtCancel(EventLogHandle handle); + + [DllImport(WEVTAPI)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtClose(IntPtr handle); + + /* + [DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)] + public static extern bool EvtClose( + IntPtr eventHandle + ); + */ + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetEventInfo( + EventLogHandle eventHandle, + // int propertyId + [MarshalAs(UnmanagedType.I4)] EvtEventPropertyId propertyId, + int bufferSize, + IntPtr bufferPtr, + out int bufferUsed + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetQueryInfo( + EventLogHandle queryHandle, + [MarshalAs(UnmanagedType.I4)] EvtQueryPropertyId propertyId, + int bufferSize, + IntPtr buffer, + ref int bufferRequired + ); + + // PUBLISHER METADATA + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenPublisherMetadata( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string publisherId, + [MarshalAs(UnmanagedType.LPWStr)] string logFilePath, + int locale, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetPublisherMetadataProperty( + EventLogHandle publisherMetadataHandle, + [MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId, + int flags, + int publisherMetadataPropertyBufferSize, + IntPtr publisherMetadataPropertyBuffer, + out int publisherMetadataPropertyBufferUsed + ); + + // NEW + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetObjectArraySize( + EventLogHandle objectArray, + out int objectArraySize + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetObjectArrayProperty( + EventLogHandle objectArray, + int propertyId, + int arrayIndex, + int flags, + int propertyValueBufferSize, + IntPtr propertyValueBuffer, + out int propertyValueBufferUsed + ); + + // NEW 2 + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenEventMetadataEnum( + EventLogHandle publisherMetadata, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + // public static extern IntPtr EvtNextEventMetadata( + internal static extern EventLogHandle EvtNextEventMetadata( + EventLogHandle eventMetadataEnum, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetEventMetadataProperty( + EventLogHandle eventMetadata, + [MarshalAs(UnmanagedType.I4)] EvtEventMetadataPropertyId propertyId, + int flags, + int eventMetadataPropertyBufferSize, + IntPtr eventMetadataPropertyBuffer, + out int eventMetadataPropertyBufferUsed + ); + + // Channel Configuration Native Api + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenChannelEnum( + EventLogHandle session, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtNextChannelPath( + EventLogHandle channelEnum, + int channelPathBufferSize, + // StringBuilder channelPathBuffer, + [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder channelPathBuffer, + out int channelPathBufferUsed + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenPublisherEnum( + EventLogHandle session, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtNextPublisherId( + EventLogHandle publisherEnum, + int publisherIdBufferSize, + [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder publisherIdBuffer, + out int publisherIdBufferUsed + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenChannelConfig( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string channelPath, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtSaveChannelConfig( + EventLogHandle channelConfig, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtSetChannelConfigProperty( + EventLogHandle channelConfig, + [MarshalAs(UnmanagedType.I4)] EvtChannelConfigPropertyId propertyId, + int flags, + ref EvtVariant propertyValue + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetChannelConfigProperty( + EventLogHandle channelConfig, + [MarshalAs(UnmanagedType.I4)] EvtChannelConfigPropertyId propertyId, + int flags, + int propertyValueBufferSize, + IntPtr propertyValueBuffer, + out int propertyValueBufferUsed + ); + + // Log Information Native API + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenLog( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string path, + [MarshalAs(UnmanagedType.I4)] PathType flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtGetLogInfo( + EventLogHandle log, + [MarshalAs(UnmanagedType.I4)] EvtLogPropertyId propertyId, + int propertyValueBufferSize, + IntPtr propertyValueBuffer, + out int propertyValueBufferUsed + ); + + // LOG MANIPULATION + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtExportLog( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string channelPath, + [MarshalAs(UnmanagedType.LPWStr)] string query, + [MarshalAs(UnmanagedType.LPWStr)] string targetFilePath, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtArchiveExportedLog( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string logFilePath, + int locale, + int flags + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtClearLog( + EventLogHandle session, + [MarshalAs(UnmanagedType.LPWStr)] string channelPath, + [MarshalAs(UnmanagedType.LPWStr)] string targetFilePath, + int flags + ); + + // RENDERING + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtCreateRenderContext( + int valuePathsCount, + [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] + string[] valuePaths, + [MarshalAs(UnmanagedType.I4)] EvtRenderContextFlags flags + ); + + [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtRender( + EventLogHandle context, + EventLogHandle eventHandle, + EvtRenderFlags flags, + int buffSize, + [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, + out int buffUsed, + out int propCount + ); + + [DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtRender( + EventLogHandle context, + EventLogHandle eventHandle, + EvtRenderFlags flags, + int buffSize, + IntPtr buffer, + out int buffUsed, + out int propCount + ); + + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] + internal struct EvtStringVariant + { + [MarshalAs(UnmanagedType.LPWStr), FieldOffset(0)] + public string StringVal; + + [FieldOffset(8)] + public uint Count; + + [FieldOffset(12)] + public uint Type; + } + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtFormatMessage( + EventLogHandle publisherMetadataHandle, + EventLogHandle eventHandle, + uint messageId, + int valueCount, + EvtStringVariant[] values, + [MarshalAs(UnmanagedType.I4)] EvtFormatMessageFlags flags, + int bufferSize, + [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, + out int bufferUsed + ); + + [DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtFormatMessageBuffer( + EventLogHandle publisherMetadataHandle, + EventLogHandle eventHandle, + uint messageId, + int valueCount, + IntPtr values, + [MarshalAs(UnmanagedType.I4)] EvtFormatMessageFlags flags, + int bufferSize, + IntPtr buffer, + out int bufferUsed + ); + + // SESSION + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtOpenSession( + [MarshalAs(UnmanagedType.I4)] EvtLoginClass loginClass, + ref EvtRpcLogin login, + int timeout, + int flags + ); + + // BOOKMARK + [DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + internal static extern EventLogHandle EvtCreateBookmark( + [MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml + ); + + [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] + [SecurityCritical] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool EvtUpdateBookmark( + EventLogHandle bookmark, + EventLogHandle eventHandle + ); + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj new file mode 100644 index 0000000000000000000000000000000000000000..1a63891ef77fc673a2066773de26de3f099697ce --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -0,0 +1,14 @@ + + + + PowerShell's Microsoft.PowerShell.CoreCLR.Eventing project + $(NoWarn);CS1591;CA1416 + Microsoft.PowerShell.CoreCLR.Eventing + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..b801e091abd756f117aa3f65a74fff78e0daa59c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Non negative number is required. + + + The ID parameter must be in the range {0} through {1}. + + + The total number of parameters must not exceed {0}. + + + The number of String parameters must not exceed {0}. + + + Delimiter cannot be an empty string. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs b/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs new file mode 100644 index 0000000000000000000000000000000000000000..356cde68152366a4746601cabaaa4ac69083a3cb --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; + +namespace Microsoft.PowerShell.GlobalTool.Shim +{ + /// + /// Shim layer to chose the appropriate runtime for PowerShell DotNet Global tool. + /// + public static class EntryPoint + { + private const string PwshDllName = "pwsh.dll"; + + private const string WinFolderName = "win"; + + private const string UnixFolderName = "unix"; + + /// + /// Entry point for the global tool. + /// + /// Arguments passed to the global tool.' + /// Exit code returned by pwsh. + public static int Main(string[] args) + { + var currentPath = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Directory.FullName; + var isWindows = OperatingSystem.IsWindows(); + + string platformFolder = isWindows ? WinFolderName : UnixFolderName; + + var arguments = new List(args.Length + 1); + var pwshPath = Path.Combine(currentPath, platformFolder, PwshDllName); + arguments.Add(pwshPath); + arguments.AddRange(args); + + if (File.Exists(pwshPath)) + { + Console.CancelKeyPress += (sender, e) => + { + e.Cancel = true; + }; + + var process = System.Diagnostics.Process.Start("dotnet", arguments); + process.WaitForExit(); + return process.ExitCode; + } + else + { + throw new FileNotFoundException(pwshPath); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj b/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj new file mode 100644 index 0000000000000000000000000000000000000000..d0203344cc2431e56441de51d8b8e4a7c3ba69f6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj @@ -0,0 +1,18 @@ + + + + + Shim for global tool to select appropriate runtime + Microsoft.PowerShell.GlobalTool.Shim + EXE + Microsoft.PowerShell.GlobalTool.Shim + False + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json b/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json new file mode 100644 index 0000000000000000000000000000000000000000..4a5e3e367ecc83cb418e90f99314f4dfe364ffe4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json @@ -0,0 +1,4 @@ +// This is required to roll forward to supported minor.patch versions of the runtime. +{ + "rollForwardOnNoCandidateFx": 1 +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..59cb3067efc0bf7ddd4c2d64c276c3829fafb30b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Security.Principal; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Add-LocalGroupMember cmdlet adds one or more users or groups to a local + /// group. + /// + [Cmdlet(VerbsCommon.Add, "LocalGroupMember", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717987")] + [Alias("algm")] + public class AddLocalGroupMemberCommand : PSCmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Group". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = "Group")] + [ValidateNotNull] + public Microsoft.PowerShell.Commands.LocalGroup Group + { + get { return this.group;} + + set { this.group = value; } + } + + private Microsoft.PowerShell.Commands.LocalGroup group; + + /// + /// The following is the definition of the input parameter "Member". + /// Specifies one or more users or groups to add to this local group. You can + /// identify users or groups by specifying their names or SIDs, or by passing + /// Microsoft.PowerShell.Commands.LocalPrincipal objects. + /// + [Parameter(Mandatory = true, + Position = 1, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.PowerShell.Commands.LocalPrincipal[] Member + { + get { return this.member;} + + set { this.member = value; } + } + + private Microsoft.PowerShell.Commands.LocalPrincipal[] member; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + if (Group != null) + ProcessGroup(Group); + else if (Name != null) + ProcessName(Name); + else if (SID != null) + ProcessSid(SID); + } + catch (GroupNotFoundException ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + + /// + /// Creates a list of objects + /// ready to be processed by the cmdlet. + /// + /// + /// Name or SID (as a string) of the group we'll be adding to. + /// This string is used primarily for specifying the target + /// in WhatIf scenarios. + /// + /// + /// LocalPrincipal object to be processed + /// + /// + /// A LocalPrincipal Object to be added to the group + /// + /// + /// + /// LocalPrincipal objects in the Member parameter may not be complete, + /// particularly those created from a name or a SID string given to the + /// Member cmdlet parameter. The object returned from this method contains + /// , at the very least, a valid SID. + /// + /// + /// Any Member objects provided by name or SID string will be looked up + /// to ensure that such an object exists. If an object is not found, + /// an error message is displayed by PowerShell and null will be returned + /// + /// + /// This method also handles the WhatIf scenario. If the Cmdlet's + /// ShouldProcess method returns false on any Member object, + /// that object will not be included in the returned List. + /// + /// + private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) + { + LocalPrincipal principal = null; + // if the member has a SID, we can use it directly + if (member.SID != null) + { + principal = member; + } + else // otherwise it must have been constructed by name + { + SecurityIdentifier sid = this.TrySid(member.Name); + + if (sid != null) + { + member.SID = sid; + principal = member; + } + else + { + try + { + principal = sam.LookupAccount(member.Name); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + if (CheckShouldProcess(principal, groupId)) + return principal; + + return null; + } + + /// + /// Determine if a principal should be processed. + /// Just a wrapper around Cmdlet.ShouldProcess, with localized string + /// formatting. + /// + /// Name of the principal to be added. + /// + /// Name of the group to which the members will be added. + /// + /// + /// True if the principal should be processed, false otherwise. + /// + private bool CheckShouldProcess(LocalPrincipal principal, string groupName) + { + if (principal == null) + return false; + + string msg = StringUtil.Format(Strings.ActionAddGroupMember, principal.ToString()); + + return ShouldProcess(groupName, msg); + } + + /// + /// Add members to a group. + /// + /// + /// A object representing the group to which + /// the members will be added. + /// + private void ProcessGroup(LocalGroup group) + { + string groupId = group.Name ?? group.SID.ToString(); + foreach (var member in this.Member) + { + LocalPrincipal principal = MakePrincipal(groupId, member); + if (principal != null) + { + var ex = sam.AddLocalGroupMember(group, principal); + if (ex != null) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Add members to a group specified by name. + /// + /// + /// The name of the group to which the members will be added. + /// + private void ProcessName(string name) + { + ProcessGroup(sam.GetLocalGroup(name)); + } + + /// + /// Add members to a group specified by SID. + /// + /// + /// A object identifying the group + /// to which the members will be added. + /// + private void ProcessSid(SecurityIdentifier groupSid) + { + foreach (var member in this.Member) + { + LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); + if (principal != null) + { + var ex = sam.AddLocalGroupMember(groupSid, principal); + if (ex != null) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..592c77726fe5a872516655b750c7ac465f546b28 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Disable-LocalUser cmdlet disables local user accounts. When a user + /// account is disabled, the user is not permitted to log on. When a user + /// account is enabled, the user is permitted to log on normally. + /// + [Cmdlet(VerbsLifecycle.Disable, "LocalUser", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717986")] + [Alias("dlu")] + public class DisableLocalUserCommand : Cmdlet + { + #region Constants + private const Enabling enabling = Enabling.Disable; + #endregion Constants + + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the of the local user accounts to disable in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.PowerShell.Commands.LocalUser[] InputObject + { + get { return this.inputobject; } + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalUser[] inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the names of the local user accounts to disable in the local + /// Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return this.name; } + + set { this.name = value; } + } + + private string[] name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies the LocalUser accounts to disable by + /// System.Security.Principal.SecurityIdentifier. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Security.Principal.SecurityIdentifier[] SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier[] sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + ProcessUsers(); + ProcessNames(); + ProcessSids(); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process users requested by -Name. + /// + /// + /// All arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// + private void ProcessNames() + { + if (Name != null) + { + foreach (var name in Name) + { + try + { + if (CheckShouldProcess(name)) + sam.EnableLocalUser(sam.GetLocalUser(name), enabling); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users requested by -SID. + /// + private void ProcessSids() + { + if (SID != null) + { + foreach (var sid in SID) + { + try + { + if (CheckShouldProcess(sid.ToString())) + sam.EnableLocalUser(sid, enabling); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users requested by -InputObject. + /// + private void ProcessUsers() + { + if (InputObject != null) + { + foreach (var user in InputObject) + { + try + { + if (CheckShouldProcess(user.Name)) + sam.EnableLocalUser(user, enabling); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionDisableUser); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..88627ba2e332bc7bd7dab752398dfd98d643a2aa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Enable-LocalUser cmdlet enables local user accounts. When a user account + /// is disabled, the user is not permitted to log on. When a user account is + /// enabled, the user is permitted to log on normally. + /// + [Cmdlet(VerbsLifecycle.Enable, "LocalUser", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717985")] + [Alias("elu")] + public class EnableLocalUserCommand : Cmdlet + { + #region Constants + private const Enabling enabling = Enabling.Enable; + #endregion Constants + + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the of the local user accounts to enable in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.PowerShell.Commands.LocalUser[] InputObject + { + get { return this.inputobject; } + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalUser[] inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local user accounts to enable in the local Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return this.name; } + + set { this.name = value; } + } + + private string[] name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies the LocalUser accounts to enable by + /// System.Security.Principal.SecurityIdentifier. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Security.Principal.SecurityIdentifier[] SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier[] sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + ProcessUsers(); + ProcessNames(); + ProcessSids(); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process users requested by -Name. + /// + /// + /// All arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// + private void ProcessNames() + { + if (Name != null) + { + foreach (var name in Name) + { + try + { + if (CheckShouldProcess(name)) + sam.EnableLocalUser(sam.GetLocalUser(name), enabling); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users requested by -SID. + /// + private void ProcessSids() + { + if (SID != null) + { + foreach (var sid in SID) + { + try + { + if (CheckShouldProcess(sid.ToString())) + sam.EnableLocalUser(sid, enabling); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users requested by -InputObject. + /// + private void ProcessUsers() + { + if (InputObject != null) + { + foreach (var user in InputObject) + { + try + { + if (CheckShouldProcess(user.Name)) + sam.EnableLocalUser(user, enabling); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionEnableUser); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..4c11a3c4c36e64ab0aa5052dbb462b07ba571a3c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; +using System.Security.Principal; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Get-LocalGroup cmdlet gets local groups from the Windows Security + /// Accounts manager. + /// + [Cmdlet(VerbsCommon.Get, "LocalGroup", + DefaultParameterSetName = "Default", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717974")] + [Alias("glg")] + public class GetLocalGroupCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local groups to get from the local Security Accounts Manager. + /// + [Parameter(Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return this.name; } + + set { this.name = value; } + } + + private string[] name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a local group from the local Security Accounts Manager. + /// + [Parameter(Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Security.Principal.SecurityIdentifier[] SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier[] sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + if (Name == null && SID == null) + { + foreach (var group in sam.GetAllLocalGroups()) + WriteObject(group); + + return; + } + + ProcessNames(); + ProcessSids(); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process groups requested by -Name. + /// + /// + /// All arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// Groups may be specified using wildcards. + /// + private void ProcessNames() + { + if (Name != null) + { + foreach (var name in Name) + { + try + { + if (WildcardPattern.ContainsWildcardCharacters(name)) + { + var pattern = new WildcardPattern(name, WildcardOptions.Compiled + | WildcardOptions.IgnoreCase); + + foreach (var group in sam.GetMatchingLocalGroups(n => pattern.IsMatch(n))) + WriteObject(group); + } + else + { + WriteObject(sam.GetLocalGroup(name)); + } + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process groups requested by -SID. + /// + private void ProcessSids() + { + if (SID != null) + { + foreach (var sid in SID) + { + try + { + WriteObject(sam.GetLocalGroup(sid)); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..0b3625f6ef7bc5a5cadad46838590ebc905e9ffd --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Security.Principal; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Get-LocalGroupMember cmdlet gets the members of a local group. + /// + [Cmdlet(VerbsCommon.Get, "LocalGroupMember", + DefaultParameterSetName = "Default", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717988")] + [Alias("glgm")] + public class GetLocalGroupMemberCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Group". + /// The security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Group")] + [ValidateNotNull] + public Microsoft.PowerShell.Commands.LocalGroup Group + { + get { return this.group;} + + set { this.group = value; } + } + + private Microsoft.PowerShell.Commands.LocalGroup group; + + /// + /// The following is the definition of the input parameter "Member". + /// Specifies the name of the user or group that is a member of this group. If + /// this parameter is not specified, all members of the specified group are + /// returned. This accepts a name, SID, or wildcard string. + /// + [Parameter(Position = 1)] + [ValidateNotNullOrEmpty] + public string Member + { + get { return this.member;} + + set { this.member = value; } + } + + private string member; + + /// + /// The following is the definition of the input parameter "Name". + /// The security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "SID". + /// The security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNullOrEmpty] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + IEnumerable principals = null; + + if (Group != null) + principals = ProcessGroup(Group); + else if (Name != null) + principals = ProcessName(Name); + else if (SID != null) + principals = ProcessSid(SID); + + if (principals != null) + WriteObject(principals, true); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + private IEnumerable ProcessesMembership(IEnumerable membership) + { + List rv; + + // if no members are specified, return all of them + if (Member == null) + { + // return membership; + rv = new List(membership); + } + else + { + // var rv = new List(); + rv = new List(); + + if (WildcardPattern.ContainsWildcardCharacters(Member)) + { + var pattern = new WildcardPattern(Member, WildcardOptions.Compiled + | WildcardOptions.IgnoreCase); + + foreach (var m in membership) + if (pattern.IsMatch(sam.StripMachineName(m.Name))) + rv.Add(m); + } + else + { + var sid = this.TrySid(Member); + + if (sid != null) + { + foreach (var m in membership) + { + if (m.SID == sid) + { + rv.Add(m); + break; + } + } + } + else + { + foreach (var m in membership) + { + if (sam.StripMachineName(m.Name).Equals(Member, StringComparison.CurrentCultureIgnoreCase)) + { + rv.Add(m); + break; + } + } + } + + if (rv.Count == 0) + { + var ex = new PrincipalNotFoundException(member, member); + WriteError(ex.MakeErrorRecord()); + } + } + } + + // sort the resulting principals by mane + rv.Sort(static (p1, p2) => string.Compare(p1.Name, p2.Name, StringComparison.CurrentCultureIgnoreCase)); + + return rv; + } + + private IEnumerable ProcessGroup(LocalGroup group) + { + return ProcessesMembership(sam.GetLocalGroupMembers(group)); + } + + private IEnumerable ProcessName(string name) + { + return ProcessGroup(sam.GetLocalGroup(name)); + } + + private IEnumerable ProcessSid(SecurityIdentifier groupSid) + { + return ProcessesMembership(sam.GetLocalGroupMembers(groupSid)); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..9f8d3b9311b77a01e64c9e96261ff73b14f06fe6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Get-LocalUser cmdlet gets local user accounts from the Windows Security + /// Accounts Manager. This includes local accounts that have been connected to a + /// Microsoft account. + /// + [Cmdlet(VerbsCommon.Get, "LocalUser", + DefaultParameterSetName = "Default", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717980")] + [Alias("glu")] + public class GetLocalUserCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local user accounts to get from the local Security Accounts + /// Manager. This accepts a name or wildcard string. + /// + [Parameter(Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return this.name; } + + set { this.name = value; } + } + + private string[] name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a user from the local Security Accounts Manager. + /// + [Parameter(Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Security.Principal.SecurityIdentifier[] SID + { + get { return this.sid; } + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier[] sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + if (Name == null && SID == null) + { + foreach (var user in sam.GetAllLocalUsers()) + WriteObject(user); + + return; + } + + ProcessNames(); + ProcessSids(); + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process users requested by -Name. + /// + /// + /// All arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// Users may be specified using wildcards. + /// + private void ProcessNames() + { + if (Name != null) + { + foreach (var nm in Name) + { + try + { + if (WildcardPattern.ContainsWildcardCharacters(nm)) + { + var pattern = new WildcardPattern(nm, WildcardOptions.Compiled + | WildcardOptions.IgnoreCase); + + foreach (var user in sam.GetMatchingLocalUsers(n => pattern.IsMatch(n))) + WriteObject(user); + } + else + { + WriteObject(sam.GetLocalUser(nm)); + } + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users requested by -SID. + /// + private void ProcessSids() + { + if (SID != null) + { + foreach (var s in SID) + { + try + { + WriteObject(sam.GetLocalUser(s)); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..b709d22a4850be5b4f01ee58e9be0314cb28d82d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The New-LocalGroup Cmdlet can be used to create a new local security group + /// in the Windows Security Accounts Manager. + /// + [Cmdlet(VerbsCommon.New, "LocalGroup", + SupportsShouldProcess = true, + HelpUri ="https://go.microsoft.com/fwlink/?LinkId=717990")] + [Alias("nlg")] + public class NewLocalGroupCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Description". + /// A descriptive comment. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNull] + public string Description + { + get { return this.description;} + + set { this.description = value; } + } + + private string description; + + /// + /// The following is the definition of the input parameter "Name". + /// The group name for the local security group. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [ValidateLength(1, 256)] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + if (CheckShouldProcess(Name)) + { + var group = sam.CreateLocalGroup(new LocalGroup + { + Description = Description, + Name = Name + }); + + WriteObject(group); + } + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionNewGroup); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..d3402b5a4c9579c61ff141cecaadb26f041ccfd7 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The New-LocalUser cmdlet creates a new local user account. + /// + [Cmdlet(VerbsCommon.New, "LocalUser", + DefaultParameterSetName = "Password", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717981")] + [Alias("nlu")] + public class NewLocalUserCommand : PSCmdlet + { + #region Static Data + // Names of object- and boolean-type parameters. + // Switch parameters don't need to be included. + private static string[] parameterNames = new string[] + { + "AccountExpires", + "Description", + "Disabled", + "FullName", + "Password", + "UserMayNotChangePassword" + }; + #endregion Static Data + + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "AccountExpires". + /// Specifies when the user account will expire. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public System.DateTime AccountExpires + { + get { return this.accountexpires;} + + set { this.accountexpires = value; } + } + + private System.DateTime accountexpires; + + // This parameter added by hand (copied from SetLocalUserCommand), not by Cmdlet Designer + /// + /// The following is the definition of the input parameter "AccountNeverExpires". + /// Specifies that the account will not expire. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public System.Management.Automation.SwitchParameter AccountNeverExpires + { + get { return this.accountneverexpires;} + + set { this.accountneverexpires = value; } + } + + private System.Management.Automation.SwitchParameter accountneverexpires; + + /// + /// The following is the definition of the input parameter "Description". + /// A descriptive comment for this user account. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNull] + public string Description + { + get { return this.description;} + + set { this.description = value; } + } + + private string description; + + /// + /// The following is the definition of the input parameter "Disabled". + /// Specifies whether this user account is enabled or disabled. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public System.Management.Automation.SwitchParameter Disabled + { + get { return this.disabled;} + + set { this.disabled = value; } + } + + private System.Management.Automation.SwitchParameter disabled; + + /// + /// The following is the definition of the input parameter "FullName". + /// Specifies the full name of the user account. This is different from the + /// username of the user account. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNull] + public string FullName + { + get { return this.fullname;} + + set { this.fullname = value; } + } + + private string fullname; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the user name for the local user account. This can be a local user + /// account or a local user account that is connected to a Microsoft Account. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [ValidateLength(1, 20)] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "Password". + /// Specifies the password for the local user account. A password can contain up + /// to 127 characters. + /// + [Parameter(Mandatory = true, + ParameterSetName = "Password", + ValueFromPipelineByPropertyName = true)] + [ValidateNotNull] + public System.Security.SecureString Password + { + get { return this.password;} + + set { this.password = value; } + } + + private System.Security.SecureString password; + + /// + /// The following is the definition of the input parameter "PasswordChangeableDate". + /// Specifies that the new User account has no password. + /// + [Parameter(Mandatory = true, + ParameterSetName = "NoPassword", + ValueFromPipelineByPropertyName = true)] + public System.Management.Automation.SwitchParameter NoPassword + { + get { return this.nopassword; } + + set { this.nopassword = value; } + } + + private System.Management.Automation.SwitchParameter nopassword; + + /// + /// The following is the definition of the input parameter "PasswordNeverExpires". + /// Specifies that the password will not expire. + /// + [Parameter(ParameterSetName = "Password", + ValueFromPipelineByPropertyName = true)] + public System.Management.Automation.SwitchParameter PasswordNeverExpires + { + get { return this.passwordneverexpires; } + + set { this.passwordneverexpires = value; } + } + + private System.Management.Automation.SwitchParameter passwordneverexpires; + + /// + /// The following is the definition of the input parameter "UserMayNotChangePassword". + /// Specifies whether the user is allowed to change the password on this + /// account. The default value is True. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + public System.Management.Automation.SwitchParameter UserMayNotChangePassword + { + get { return this.usermaynotchangepassword;} + + set { this.usermaynotchangepassword = value; } + } + + private System.Management.Automation.SwitchParameter usermaynotchangepassword; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + if (this.HasParameter("AccountExpires") && AccountNeverExpires.IsPresent) + { + InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); + ThrowTerminatingError(ex.MakeErrorRecord()); + } + + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + if (CheckShouldProcess(Name)) + { + var user = new LocalUser + { + Name = Name, + Description = Description, + Enabled = true, + FullName = FullName, + UserMayChangePassword = true + }; + + foreach (var paramName in parameterNames) + { + if (this.HasParameter(paramName)) + { + switch (paramName) + { + case "AccountExpires": + user.AccountExpires = AccountExpires; + break; + + case "Disabled": + user.Enabled = !Disabled; + break; + + case "UserMayNotChangePassword": + user.UserMayChangePassword = !UserMayNotChangePassword; + break; + } + } + } + + if (AccountNeverExpires.IsPresent) + user.AccountExpires = null; + + // Password will be null if NoPassword was given + user = sam.CreateLocalUser(user, Password, PasswordNeverExpires.IsPresent); + + WriteObject(user); + } + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionNewUser); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..981643cf04cd65f53ee79d34eb6507669a88a1b4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Remove-LocalGroup cmdlet deletes a security group from the Windows + /// Security Accounts manager. + /// + [Cmdlet(VerbsCommon.Remove, "LocalGroup", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717975")] + [Alias("rlg")] + public class RemoveLocalGroupCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies security groups from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.PowerShell.Commands.LocalGroup[] InputObject + { + get { return this.inputobject; } + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalGroup[] inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local groups to be deleted from the local Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return this.name; } + + set { this.name = value; } + } + + private string[] name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies the LocalGroup accounts to remove by + /// System.Security.Principal.SecurityIdentifier. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Security.Principal.SecurityIdentifier[] SID + { + get { return this.sid; } + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier[] sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + ProcessGroups(); + ProcessNames(); + ProcessSids(); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process groups requested by -Name. + /// + /// + /// All arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// + private void ProcessNames() + { + if (Name != null) + { + foreach (var name in Name) + { + try + { + if (CheckShouldProcess(name)) + sam.RemoveLocalGroup(sam.GetLocalGroup(name)); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process groups requested by -SID. + /// + private void ProcessSids() + { + if (SID != null) + { + foreach (var sid in SID) + { + try + { + if (CheckShouldProcess(sid.ToString())) + sam.RemoveLocalGroup(sid); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process groups given through -InputObject. + /// + private void ProcessGroups() + { + if (InputObject != null) + { + foreach (var group in InputObject) + { + try + { + if (CheckShouldProcess(group.Name)) + sam.RemoveLocalGroup(group); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionRemoveGroup); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..47d0a77784e7ce23a7fa81f1578483d315f791cf --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Collections.Generic; +using System.Management.Automation; +using System.Security.Principal; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Remove-LocalGroupMember cmdlet removes one or more members (users or + /// groups) from a local security group. + /// + [Cmdlet(VerbsCommon.Remove, "LocalGroupMember", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717989")] + [Alias("rlgm")] + public class RemoveLocalGroupMemberCommand : PSCmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Group". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = "Group")] + [ValidateNotNull] + public Microsoft.PowerShell.Commands.LocalGroup Group + { + get { return this.group;} + + set { this.group = value; } + } + + private Microsoft.PowerShell.Commands.LocalGroup group; + + /// + /// The following is the definition of the input parameter "Member". + /// Specifies one or more users or groups to remove from this local group. You can + /// identify users or groups by specifying their names or SIDs, or by passing + /// Microsoft.PowerShell.Commands.LocalPrincipal objects. + /// + [Parameter(Mandatory = true, + Position = 1, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.PowerShell.Commands.LocalPrincipal[] Member + { + get { return this.member;} + + set { this.member = value; } + } + + private Microsoft.PowerShell.Commands.LocalPrincipal[] member; + + /// + /// The following is the definition of the input parameter "Name". + /// The security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + if (Group != null) + ProcessGroup(Group); + else if (Name != null) + ProcessName(Name); + else if (SID != null) + ProcessSid(SID); + } + catch (GroupNotFoundException ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + + /// + /// Creates a list of objects + /// ready to be processed by the cmdlet. + /// + /// + /// Name or SID (as a string) of the group we'll be removing from. + /// This string is used primarily for specifying the target + /// in WhatIf scenarios. + /// + /// + /// LocalPrincipal object to be processed + /// + /// + /// LocalPrincipal object processed and ready to be removed + /// + /// + /// + /// LocalPrincipal object in the Member parameter may not be complete, + /// particularly those created from a name or a SID string given to the + /// Member cmdlet parameter. The object returned from this method contains at the very least, contain a valid SID. + /// + /// + /// Any Member object provided by name or SID string will be looked up + /// to ensure that such an object exists. If an object is not found, + /// an error message is displayed by PowerShell and null will be returned from this method + /// + /// + /// This method also handles the WhatIf scenario. If the Cmdlet's + /// ShouldProcess method returns false on any Member object + /// + /// + private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) + { + LocalPrincipal principal = null; + + // if the member has a SID, we can use it directly + if (member.SID != null) + { + principal = member; + } + else // otherwise it must have been constructed by name + { + SecurityIdentifier sid = this.TrySid(member.Name); + + if (sid != null) + { + member.SID = sid; + principal = member; + } + else + { + try + { + principal = sam.LookupAccount(member.Name); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + if (CheckShouldProcess(principal, groupId)) + return principal; + + return null; + } + + /// + /// Determine if a principal should be processed. + /// Just a wrapper around Cmdlet.ShouldProcess, with localized string + /// formatting. + /// + /// Name of the principal to be removed. + /// + /// Name of the group from which the members will be removed. + /// + /// + /// True if the principal should be processed, false otherwise. + /// + private bool CheckShouldProcess(LocalPrincipal principal, string groupName) + { + if (principal == null) + return false; + + string msg = StringUtil.Format(Strings.ActionRemoveGroupMember, principal.ToString()); + + return ShouldProcess(groupName, msg); + } + + /// + /// Remove members from a group. + /// + /// + /// A object representing the group from which + /// the members will be removed. + /// + private void ProcessGroup(LocalGroup group) + { + string groupId = group.Name ?? group.SID.ToString(); + foreach (var member in this.Member) + { + LocalPrincipal principal = MakePrincipal(groupId, member); + if (principal != null) + { + var ex = sam.RemoveLocalGroupMember(group, principal); + if (ex != null) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Remove members from a group specified by name. + /// + /// + /// The name of the group from which the members will be removed. + /// + private void ProcessName(string name) + { + ProcessGroup(sam.GetLocalGroup(name)); + } + + /// + /// Remove members from a group specified by SID. + /// + /// + /// A object identifying the group + /// from which the members will be removed. + /// + private void ProcessSid(SecurityIdentifier groupSid) + { + foreach (var member in this.Member) + { + LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); + if (principal != null) + { + var ex = sam.RemoveLocalGroupMember(groupSid, principal); + if (ex != null) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..6d6081fef7ea4e2147c6d2c1f071e9fbb2be82bc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Remove-LocalUser cmdlet deletes a user account from the Windows Security + /// Accounts manager. + /// + [Cmdlet(VerbsCommon.Remove, "LocalUser", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717982")] + [Alias("rlu")] + public class RemoveLocalUserCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the of the local user accounts to remove in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public Microsoft.PowerShell.Commands.LocalUser[] InputObject + { + get { return this.inputobject;} + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalUser[] inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the user accounts to be deleted from the local Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Name + { + get { return this.name; } + + set { this.name = value; } + } + + private string[] name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies the local user accounts to remove by + /// System.Security.Principal.SecurityIdentifier. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public System.Security.Principal.SecurityIdentifier[] SID + { + get { return this.sid; } + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier[] sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + ProcessUsers(); + ProcessNames(); + ProcessSids(); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process users requested by -Name. + /// + /// + /// All arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// + private void ProcessNames() + { + if (Name != null) + { + foreach (var name in Name) + { + try + { + if (CheckShouldProcess(name)) + sam.RemoveLocalUser(sam.GetLocalUser(name)); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users requested by -SID. + /// + private void ProcessSids() + { + if (SID != null) + { + foreach (var sid in SID) + { + try + { + if (CheckShouldProcess(sid.ToString())) + sam.RemoveLocalUser(sid); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + /// + /// Process users given through -InputObject. + /// + private void ProcessUsers() + { + if (InputObject != null) + { + foreach (var user in InputObject) + { + try + { + if (CheckShouldProcess(user.Name)) + sam.RemoveLocalUser(user); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + } + + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionRemoveUser); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..c594fccb889ae6e1b85144d1c0d9801d9d2a6b61 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Rename-LocalGroup cmdlet renames a local security group in the Security + /// Accounts Manager. + /// + [Cmdlet(VerbsCommon.Rename, "LocalGroup", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717978")] + [Alias("rnlg")] + public class RenameLocalGroupCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the of the local group account to rename in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNullOrEmpty] + public Microsoft.PowerShell.Commands.LocalGroup InputObject + { + get { return this.inputobject;} + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalGroup inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local group to be renamed in the local Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "NewName". + /// Specifies the new name for the local security group in the Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 1)] + [ValidateNotNullOrEmpty] + public string NewName + { + get { return this.newname;} + + set { this.newname = value; } + } + + private string newname; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNullOrEmpty] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + ProcessGroup(); + ProcessName(); + ProcessSid(); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process group requested by -Name. + /// + /// + /// Arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// + private void ProcessName() + { + if (Name != null) + { + try + { + if (CheckShouldProcess(Name, NewName)) + sam.RenameLocalGroup(sam.GetLocalGroup(Name), NewName); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + /// + /// Process group requested by -SID. + /// + private void ProcessSid() + { + if (SID != null) + { + try + { + if (CheckShouldProcess(SID.ToString(), NewName)) + sam.RenameLocalGroup(SID, NewName); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + /// + /// Process group given through -InputObject. + /// + private void ProcessGroup() + { + if (InputObject != null) + { + try + { + if (CheckShouldProcess(InputObject.Name, NewName)) + sam.RenameLocalGroup(InputObject, NewName); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + /// + /// Determine if a group should be processed. + /// Just a wrapper around Cmdlet.ShouldProcess, with localized string + /// formatting. + /// + /// + /// Name of the group to rename. + /// + /// + /// New name for the group. + /// + /// + /// True if the group should be processed, false otherwise. + /// + private bool CheckShouldProcess(string groupName, string newName) + { + string msg = StringUtil.Format(Strings.ActionRenameGroup, newName); + + return ShouldProcess(groupName, msg); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..c23cf41ac617b811251572b19a2ddd038f323b8d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Rename-LocalUser cmdlet renames a local user account in the Security + /// Accounts Manager. + /// + [Cmdlet(VerbsCommon.Rename, "LocalUser", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=717983")] + [Alias("rnlu")] + public class RenameLocalUserCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the of the local user account to rename in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNull] + public Microsoft.PowerShell.Commands.LocalUser InputObject + { + get { return this.inputobject;} + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalUser inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local user account to be renamed in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNullOrEmpty] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "NewName". + /// Specifies the new name for the local user account in the Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 1)] + [ValidateNotNullOrEmpty] + public string NewName + { + get { return this.newname;} + + set { this.newname = value; } + } + + private string newname; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies the local user to rename. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + ProcessUser(); + ProcessName(); + ProcessSid(); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + /// + /// Process user requested by -Name. + /// + /// + /// Arguments to -Name will be treated as names, + /// even if a name looks like a SID. + /// + private void ProcessName() + { + if (Name != null) + { + try + { + if (CheckShouldProcess(Name, NewName)) + sam.RenameLocalUser(sam.GetLocalUser(Name), NewName); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + /// + /// Process user requested by -SID. + /// + private void ProcessSid() + { + if (SID != null) + { + try + { + if (CheckShouldProcess(SID.ToString(), NewName)) + sam.RenameLocalUser(SID, NewName); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + /// + /// Process group given through -InputObject. + /// + private void ProcessUser() + { + if (InputObject != null) + { + try + { + if (CheckShouldProcess(InputObject.Name, NewName)) + sam.RenameLocalUser(InputObject, NewName); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + } + + /// + /// Determine if a user should be processed. + /// Just a wrapper around Cmdlet.ShouldProcess, with localized string + /// formatting. + /// + /// + /// Name of the user to rename. + /// + /// + /// New name for the user. + /// + /// + /// True if the user should be processed, false otherwise. + /// + private bool CheckShouldProcess(string userName, string newName) + { + string msg = StringUtil.Format(Strings.ActionRenameUser, newName); + + return ShouldProcess(userName, msg); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..49ae31dacc7041e1ed39db1be7d3d176d197856a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Set-LocalGroup cmdlet modifies the properties of a local security group + /// in the Windows Security Accounts Manager. + /// + [Cmdlet(VerbsCommon.Set, "LocalGroup", + SupportsShouldProcess = true, + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717979")] + [Alias("slg")] + public class SetLocalGroupCommand : Cmdlet + { + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "Description". + /// A descriptive comment. + /// + [Parameter(Mandatory = true)] + [ValidateNotNull] + public string Description + { + get { return this.description;} + + set { this.description = value; } + } + + private string description; + + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the local group account to modify in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNull] + public Microsoft.PowerShell.Commands.LocalGroup InputObject + { + get { return this.inputobject;} + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalGroup inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local group to be renamed in the local Security Accounts + /// Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Default")] + [ValidateNotNull] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a security group from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + LocalGroup group = null; + + if (InputObject != null) + { + if (CheckShouldProcess(InputObject.ToString())) + group = InputObject; + } + else if (Name != null) + { + group = sam.GetLocalGroup(Name); + + if (!CheckShouldProcess(Name)) + group = null; + } + else if (SID != null) + { + group = sam.GetLocalGroup(SID); + + if (!CheckShouldProcess(SID.ToString())) + group = null; + } + + if (group != null) + { + var delta = group.Clone(); + + delta.Description = Description; + sam.UpdateLocalGroup(group, delta); + } + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionSetGroup); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs new file mode 100644 index 0000000000000000000000000000000000000000..3bfdc24ac036428f0c571ea72c9190a3607e693c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives +using System; +using System.Management.Automation; + +using System.Management.Automation.SecurityAccountsManager; +using System.Management.Automation.SecurityAccountsManager.Extensions; + +using Microsoft.PowerShell.LocalAccounts; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// The Set-LocalUser cmdlet changes the properties of a user account in the + /// local Windows Security Accounts Manager. It can also reset the password of a + /// local user account. + /// + [Cmdlet(VerbsCommon.Set, "LocalUser", + SupportsShouldProcess = true, + DefaultParameterSetName = "Name", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717984")] + [Alias("slu")] + public class SetLocalUserCommand : PSCmdlet + { + #region Static Data + // Names of object- and boolean-type parameters. + // Switch parameters don't need to be included. + private static string[] parameterNames = new string[] + { + "AccountExpires", + "Description", + "FullName", + "Password", + "UserMayChangePassword", + "PasswordNeverExpires" + }; + #endregion Static Data + + #region Instance Data + private Sam sam = null; + #endregion Instance Data + + #region Parameter Properties + /// + /// The following is the definition of the input parameter "AccountExpires". + /// Specifies when the user account will expire. Set to null to indicate that + /// the account will never expire. The default value is null (account never + /// expires). + /// + [Parameter] + public System.DateTime AccountExpires + { + get { return this.accountexpires;} + + set { this.accountexpires = value; } + } + + private System.DateTime accountexpires; + + /// + /// The following is the definition of the input parameter "AccountNeverExpires". + /// Specifies that the account will not expire. + /// + [Parameter] + public System.Management.Automation.SwitchParameter AccountNeverExpires + { + get { return this.accountneverexpires;} + + set { this.accountneverexpires = value; } + } + + private System.Management.Automation.SwitchParameter accountneverexpires; + + /// + /// The following is the definition of the input parameter "Description". + /// A descriptive comment for this user account. + /// + [Parameter] + [ValidateNotNull] + public string Description + { + get { return this.description;} + + set { this.description = value; } + } + + private string description; + + /// + /// The following is the definition of the input parameter "FullName". + /// Specifies the full name of the user account. This is different from the + /// username of the user account. + /// + [Parameter] + [ValidateNotNull] + public string FullName + { + get { return this.fullname;} + + set { this.fullname = value; } + } + + private string fullname; + /// + /// The following is the definition of the input parameter "InputObject". + /// Specifies the of the local user account to modify in the local Security + /// Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "InputObject")] + [ValidateNotNull] + public Microsoft.PowerShell.Commands.LocalUser InputObject + { + get { return this.inputobject;} + + set { this.inputobject = value; } + } + + private Microsoft.PowerShell.Commands.LocalUser inputobject; + + /// + /// The following is the definition of the input parameter "Name". + /// Specifies the local user account to change. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "Name")] + [ValidateNotNullOrEmpty] + public string Name + { + get { return this.name;} + + set { this.name = value; } + } + + private string name; + + /// + /// The following is the definition of the input parameter "Password". + /// Specifies the password for the local user account. + /// + [Parameter] + [ValidateNotNull] + public System.Security.SecureString Password + { + get { return this.password;} + + set { this.password = value; } + } + + private System.Security.SecureString password; + + /// + /// The following is the definition of the input parameter "PasswordNeverExpires". + /// Specifies that the password will not expire. + /// + [Parameter] + public bool PasswordNeverExpires + { + get { return this.passwordneverexpires; } + + set { this.passwordneverexpires = value; } + } + + private bool passwordneverexpires; + + /// + /// The following is the definition of the input parameter "SID". + /// Specifies a user from the local Security Accounts Manager. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + ParameterSetName = "SecurityIdentifier")] + [ValidateNotNull] + public System.Security.Principal.SecurityIdentifier SID + { + get { return this.sid;} + + set { this.sid = value; } + } + + private System.Security.Principal.SecurityIdentifier sid; + + /// + /// The following is the definition of the input parameter "UserMayChangePassword". + /// Specifies whether the user is allowed to change the password on this + /// account. The default value is True. + /// + [Parameter] + public bool UserMayChangePassword + { + get { return this.usermaychangepassword;} + + set { this.usermaychangepassword = value; } + } + + private bool usermaychangepassword; + #endregion Parameter Properties + + #region Cmdlet Overrides + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + if (this.HasParameter("AccountExpires") && AccountNeverExpires.IsPresent) + { + InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); + ThrowTerminatingError(ex.MakeErrorRecord()); + } + + sam = new Sam(); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + LocalUser user = null; + + if (InputObject != null) + { + if (CheckShouldProcess(InputObject.ToString())) + user = InputObject; + } + else if (Name != null) + { + user = sam.GetLocalUser(Name); + + if (!CheckShouldProcess(Name)) + user = null; + } + else if (SID != null) + { + user = sam.GetLocalUser(SID); + + if (!CheckShouldProcess(SID.ToString())) + user = null; + } + + if (user == null) + return; + + // We start with what already exists + var delta = user.Clone(); + bool? passwordNeverExpires = null; + + foreach (var paramName in parameterNames) + { + if (this.HasParameter(paramName)) + { + switch (paramName) + { + case "AccountExpires": + delta.AccountExpires = this.AccountExpires; + break; + + case "Description": + delta.Description = this.Description; + break; + + case "FullName": + delta.FullName = this.FullName; + break; + + case "UserMayChangePassword": + delta.UserMayChangePassword = this.UserMayChangePassword; + break; + + case "PasswordNeverExpires": + passwordNeverExpires = this.PasswordNeverExpires; + break; + } + } + } + + if (AccountNeverExpires.IsPresent) + delta.AccountExpires = null; + + sam.UpdateLocalUser(user, delta, Password, passwordNeverExpires); + } + catch (Exception ex) + { + WriteError(ex.MakeErrorRecord()); + } + } + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + if (sam != null) + { + sam.Dispose(); + sam = null; + } + } + #endregion Cmdlet Overrides + + #region Private Methods + private bool CheckShouldProcess(string target) + { + return ShouldProcess(target, Strings.ActionSetUser); + } + #endregion Private Methods + } + +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs new file mode 100644 index 0000000000000000000000000000000000000000..1c7a7630ea393f0604eb3489ed09ecf5db8aebc6 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs @@ -0,0 +1,689 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Management.Automation.SecurityAccountsManager; +using System.Runtime.Serialization; + +using Microsoft.PowerShell.LocalAccounts; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Base class for cmdlet-specific exceptions. + /// + public class LocalAccountsException : Exception + { +#region Public Properties + /// + /// Gets the + /// value for this exception. + /// + public ErrorCategory ErrorCategory + { + get; + private set; + } + + /// + /// Gets the target object for this exception. This is used as + /// the TargetObject member of a PowerShell + /// object. + /// + public object Target + { + get; + private set; + } + + /// + /// Gets the error name. This is used as the ErrorId parameter when + /// constructing a PowerShell + /// oject. + /// + public string ErrorName + { + get + { + string exname = "Exception"; + var exlen = exname.Length; + var name = this.GetType().Name; + + if (name.EndsWith(exname, StringComparison.OrdinalIgnoreCase) && name.Length > exlen) + name = name.Substring(0, name.Length - exlen); + return name; + } + } +#endregion Public Properties + + internal LocalAccountsException(string message, object target, ErrorCategory errorCategory) + : base(message) + { + ErrorCategory = errorCategory; + Target = target; + } + + /// + /// Compliance Constructor. + /// + public LocalAccountsException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public LocalAccountsException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public LocalAccountsException(string message, Exception ex) : base(message, ex) { } + + /// + /// Compliance Constructor. + /// + /// + /// + protected LocalAccountsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating an error occurred during one of the internal + /// operations such as opening or closing a handle. + /// + public class InternalException : LocalAccountsException + { +#region Public Properties + /// + /// Gets the NTSTATUS code for this exception. + /// + public UInt32 StatusCode + { + get; + private set; + } +#endregion Public Properties + + internal InternalException(UInt32 ntStatus, + string message, + object target, + ErrorCategory errorCategory = ErrorCategory.NotSpecified) + : base(message, target, errorCategory) + { + StatusCode = ntStatus; + } + + internal InternalException(UInt32 ntStatus, + object target, + ErrorCategory errorCategory = ErrorCategory.NotSpecified) + : this(ntStatus, + StringUtil.Format(Strings.UnspecifiedErrorNtStatus, ntStatus), + target, + errorCategory) + { + } + + /// + /// Compliance Constructor. + /// + public InternalException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public InternalException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public InternalException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected InternalException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating an error occurred when a native function + /// is called that returns a Win32 error code as opposed to an + /// NT Status code. + /// + public class Win32InternalException : LocalAccountsException + { +#region Public Properties + /// + /// The Win32 error code for this exception. + /// + public int NativeErrorCode + { + get; + private set; + } +#endregion Public Properties + + internal Win32InternalException(int errorCode, + string message, + object target, + ErrorCategory errorCategory = ErrorCategory.NotSpecified) + : base(message, target, errorCategory) + { + NativeErrorCode = errorCode; + } + + internal Win32InternalException(int errorCode, + object target, + ErrorCategory errorCategory = ErrorCategory.NotSpecified) + : this(errorCode, + StringUtil.Format(Strings.UnspecifiedErrorWin32Error, errorCode), + target, + errorCategory) + { + } + + /// + /// Compliance Constructor. + /// + public Win32InternalException() : base() {} + /// + /// Compliance Constructor. + /// + /// + public Win32InternalException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public Win32InternalException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected Win32InternalException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating an invalid password. + /// + public class InvalidPasswordException : LocalAccountsException + { + /// + /// Generates with a default invalid password message. + /// + public InvalidPasswordException() + : base(Strings.InvalidPassword, null, ErrorCategory.InvalidArgument) + { + } + + /// + /// Generates the exception with the specified message. + /// + /// + public InvalidPasswordException(string message) + : base(message, null, ErrorCategory.InvalidArgument) + { + } + + /// + /// Creates a message from the specified error code. + /// + /// + public InvalidPasswordException(uint errorCode) + : base(StringUtil.GetSystemMessage(errorCode), null, ErrorCategory.InvalidArgument) + { + } + + /// + /// Compliance Constructor. + /// + /// + /// + public InvalidPasswordException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected InvalidPasswordException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception thrown when invalid parameter pairing is detected. + /// + public class InvalidParametersException : LocalAccountsException + { + /// + /// Creates InvalidParametersException using the specified message. + /// + /// + public InvalidParametersException(string message) + : base(message, null, ErrorCategory.InvalidArgument) + { + } + + internal InvalidParametersException(string parameterA, string parameterB) + : this(StringUtil.Format(Strings.InvalidParameterPair, parameterA, parameterB)) + { + } + + /// + /// Compliance Constructor. + /// + public InvalidParametersException() : base() { } + /// + /// Compliance Constructor. + /// + /// + /// + public InvalidParametersException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected InvalidParametersException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating permission denied. + /// + public class AccessDeniedException : LocalAccountsException + { + internal AccessDeniedException(object target) + : base(Strings.AccessDenied, target, ErrorCategory.PermissionDenied) + { + } + + /// + /// Compliance Constructor. + /// + public AccessDeniedException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public AccessDeniedException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public AccessDeniedException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected AccessDeniedException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that the name of a user or group is invalid. + /// + public class InvalidNameException : LocalAccountsException + { + internal InvalidNameException(string name, object target) + : base(StringUtil.Format(Strings.InvalidName, name), target, ErrorCategory.InvalidArgument) + { + } + + /// + /// Compliance Constructor. + /// + public InvalidNameException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public InvalidNameException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public InvalidNameException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected InvalidNameException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that the specified name is already in use. + /// + public class NameInUseException : LocalAccountsException + { + internal NameInUseException(string name, object target) + : base(StringUtil.Format(Strings.NameInUse, name), target, ErrorCategory.InvalidArgument) + { + } + + /// + /// Compliance Constructor. + /// + public NameInUseException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public NameInUseException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public NameInUseException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected NameInUseException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that an entity of some kind was not found. + /// Also serves as a base class for more specific object-not-found errors. + /// + public class NotFoundException : LocalAccountsException + { + internal NotFoundException(string message, object target) + : base(message, target, ErrorCategory.ObjectNotFound) + { + } + + /// + /// Compliance Constructor. + /// + public NotFoundException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public NotFoundException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public NotFoundException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected NotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that a principal was not Found. + /// + public class PrincipalNotFoundException : NotFoundException + { + internal PrincipalNotFoundException(string principal, object target) + : base(StringUtil.Format(Strings.PrincipalNotFound, principal), target) + { + } + + /// + /// Compliance Constructor. + /// + public PrincipalNotFoundException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public PrincipalNotFoundException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public PrincipalNotFoundException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected PrincipalNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that a group was not found. + /// + public class GroupNotFoundException : NotFoundException + { + internal GroupNotFoundException(string group, object target) + : base(StringUtil.Format(Strings.GroupNotFound, group), target) + { + } + + /// + /// Compliance Constructor. + /// + public GroupNotFoundException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public GroupNotFoundException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public GroupNotFoundException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected GroupNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that a user was not found. + /// + public class UserNotFoundException : NotFoundException + { + internal UserNotFoundException(string user, object target) + : base(StringUtil.Format(Strings.UserNotFound, user), target) + { + } + + /// + /// Compliance Constructor. + /// + public UserNotFoundException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public UserNotFoundException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public UserNotFoundException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected UserNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that a group member was not found. + /// + public class MemberNotFoundException : NotFoundException + { + internal MemberNotFoundException(string member, string group) + : base(StringUtil.Format(Strings.MemberNotFound, member, group), member) + { + } + + /// + /// Compliance Constructor. + /// + public MemberNotFoundException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public MemberNotFoundException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public MemberNotFoundException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected MemberNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that an entity of some kind already exists. + /// Also serves as a base class for more specific object-exists errors. + /// + public class ObjectExistsException : LocalAccountsException + { + internal ObjectExistsException(string message, object target) + : base(message, target, ErrorCategory.ResourceExists) + { + } + + /// + /// Compliance Constructor. + /// + public ObjectExistsException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public ObjectExistsException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public ObjectExistsException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected ObjectExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that a group already exists. + /// + public class GroupExistsException : ObjectExistsException + { + internal GroupExistsException(string group, object target) + : base(StringUtil.Format(Strings.GroupExists, group), target) + { + } + + /// + /// Compliance Constructor. + /// + public GroupExistsException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public GroupExistsException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public GroupExistsException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected GroupExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that a group already exists. + /// + public class UserExistsException : ObjectExistsException + { + internal UserExistsException(string user, object target) + : base(StringUtil.Format(Strings.UserExists, user), target) + { + } + + /// + /// Compliance Constructor. + /// + public UserExistsException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public UserExistsException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public UserExistsException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected UserExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } + + /// + /// Exception indicating that an object already exists as a group member. + /// + public class MemberExistsException : ObjectExistsException + { + internal MemberExistsException(string member, string group, object target) + : base(StringUtil.Format(Strings.MemberExists, member, group), target) + { + } + + /// + /// Compliance Constructor. + /// + public MemberExistsException() : base() { } + /// + /// Compliance Constructor. + /// + /// + public MemberExistsException(string message) : base(message) { } + /// + /// Compliance Constructor. + /// + /// + /// + public MemberExistsException(string message, Exception ex) : base(message, ex) { } + /// + /// Compliance Constructor. + /// + /// + /// + protected MemberExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs new file mode 100644 index 0000000000000000000000000000000000000000..007966cb0a803e508440c8343c80a01ec71cb432 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Principal; +using System.Text.RegularExpressions; + +using Microsoft.PowerShell.Commands; +using Microsoft.PowerShell.LocalAccounts; + +namespace System.Management.Automation.SecurityAccountsManager.Extensions +{ + /// + /// Provides extension methods for the Cmdlet class. + /// + internal static class CmdletExtensions + { + /// + /// Attempt to create a SID from a string. + /// + /// The cmdlet being extended with this method. + /// The string to be converted to a SID. + /// + /// A boolean indicating whether SID constants, such as "BA", are considered. + /// + /// + /// A object if the conversion was successful, + /// null otherwise. + /// + internal static SecurityIdentifier TrySid(this Cmdlet cmdlet, + string s, + bool allowSidConstants = false) + { + if (!allowSidConstants) + if (!(s.Length > 2 && s.StartsWith("S-", StringComparison.Ordinal) && char.IsDigit(s[2]))) + return null; + + SecurityIdentifier sid = null; + + try + { + sid = new SecurityIdentifier(s); + } + catch (ArgumentException) + { + // do nothing here, just fall through to the return + } + + return sid; + } + } + + /// + /// Provides extension methods for the PSCmdlet class. + /// + internal static class PSExtensions + { + /// + /// Determine if a given parameter was provided to the cmdlet. + /// + /// + /// The object to check. + /// + /// + /// A string containing the name of the parameter. This should be in the + /// same letter-casing as the defined parameter. + /// + /// + /// True if the specified parameter was given on the cmdlet invocation, + /// false otherwise. + /// + internal static bool HasParameter(this PSCmdlet cmdlet, string parameterName) + { + var invocation = cmdlet.MyInvocation; + if (invocation != null) + { + var parameters = invocation.BoundParameters; + + if (parameters != null) + { + // PowerShell sets the parameter names in the BoundParameters dictionary + // to their "proper" casing, so we don't have to do a case-insensitive search. + if (parameters.ContainsKey(parameterName)) + return true; + } + } + + return false; + } + } + + /// + /// Provides extension methods for the SecurityIdentifier class. + /// + internal static class SidExtensions + { + /// + /// Get the Relative ID (RID) from a object. + /// + /// The SecurityIdentifier containing the desired Relative ID. + /// + /// A UInt32 value containing the Relative ID in the SecurityIdentifier. + /// + internal static UInt32 GetRid(this SecurityIdentifier sid) + { + byte[] sidBinary = new byte[sid.BinaryLength]; + sid.GetBinaryForm(sidBinary, 0); + + return System.BitConverter.ToUInt32(sidBinary, sidBinary.Length-4); + } + + /// + /// Gets the Identifier Authority portion of a + /// + /// The SecurityIdentifier containing the desired Authority. + /// + /// A long integer value containing the SecurityIdentifier's Identifier Authority value. + /// + /// + /// This method is used primarily for determining the Source of a Principal. + /// The Win32 API LsaLookupUserAccountType function does not (yet) properly + /// identify MicrosoftAccount principals. + /// + internal static long GetIdentifierAuthority(this SecurityIdentifier sid) + { + byte[] sidBinary = new byte[sid.BinaryLength]; + + sid.GetBinaryForm(sidBinary, 0); + + // The Identifier Authority is six bytes wide, + // in big-endian format, starting at the third byte + long authority = (long) (((long)sidBinary[2]) << 40) + + (((long)sidBinary[3]) << 32) + + (((long)sidBinary[4]) << 24) + + (((long)sidBinary[5]) << 16) + + (((long)sidBinary[6]) << 8) + + (((long)sidBinary[7]) ); + + return authority; + } + + internal static bool IsMsaAccount(this SecurityIdentifier sid) + { + return sid.GetIdentifierAuthority() == 11; + } + } + + internal static class SecureStringExtensions + { + /// + /// Extension method to extract clear text from a + /// object. + /// + /// + /// This SecureString object, containing encrypted text. + /// + /// + /// A string containing the SecureString object's original text. + /// + internal static string AsString(this SecureString str) + { +#if CORECLR + IntPtr buffer = SecureStringMarshal.SecureStringToCoTaskMemUnicode(str); + string clear = Marshal.PtrToStringUni(buffer); + Marshal.ZeroFreeCoTaskMemUnicode(buffer); +#else + var bstr = Marshal.SecureStringToBSTR(str); + string clear = Marshal.PtrToStringAuto(bstr); + Marshal.ZeroFreeBSTR(bstr); +#endif + return clear; + } + } + + internal static class ExceptionExtensions + { + internal static ErrorRecord MakeErrorRecord(this Exception ex, + string errorId, + ErrorCategory errorCategory, + object target = null) + { + return new ErrorRecord(ex, errorId, errorCategory, target); + } + + internal static ErrorRecord MakeErrorRecord(this Exception ex, object target = null) + { + // This part is somewhat less than beautiful, but it prevents + // having to have multiple exception handlers in every cmdlet command. + var exTemp = ex as LocalAccountsException; + + if (exTemp != null) + return MakeErrorRecord(exTemp, target ?? exTemp.Target); + + return new ErrorRecord(ex, + Strings.UnspecifiedError, + ErrorCategory.NotSpecified, + target); + } + + internal static ErrorRecord MakeErrorRecord(this LocalAccountsException ex, object target = null) + { + return ex.MakeErrorRecord(ex.ErrorName, ex.ErrorCategory, target ?? ex.Target); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs new file mode 100644 index 0000000000000000000000000000000000000000..b43904fb7737ef092468e4196518762f08444e2c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +using Microsoft.PowerShell.LocalAccounts; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Describes a Local Group. + /// Objects of this type are provided to and returned from group-related Cmdlets. + /// + public class LocalGroup : LocalPrincipal + { + #region Public Properties + /// + /// A short description of the Group. + /// + public string Description { get; set; } + #endregion Public Properties + + #region Construction + /// + /// Initializes a new LocalGroup object. + /// + public LocalGroup() + { + ObjectClass = Strings.ObjectClassGroup; + } + + /// + /// Initializes a new LocalUser object with the specified name. + /// + /// Name of the new LocalGroup. + public LocalGroup(string name) + : base(name) + { + ObjectClass = Strings.ObjectClassGroup; + } + + /// + /// Construct a new LocalGroup object that is a copy of another. + /// + /// + private LocalGroup(LocalGroup other) + : this(other.Name) + { + Description = other.Description; + } + #endregion Construction + + #region Public Methods + /// + /// Provides a string representation of the LocalGroup object. + /// + /// + /// A string containing the Group Name. + /// + public override string ToString() + { + return Name ?? SID.ToString(); + } + + /// + /// Create a copy of a LocalGroup object. + /// + /// + /// A new LocalGroup object with the same property values as this one. + /// + public LocalGroup Clone() + { + return new LocalGroup(this); + } + #endregion Public Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs new file mode 100644 index 0000000000000000000000000000000000000000..dcfec24631be18557aeb815903bb3db2d0ac7298 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Security.Principal; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the source of a Principal. + /// + public enum PrincipalSource + { + /// + /// The principal source is unknown or could not be determined. + /// + Unknown = 0, + + /// + /// The principal is sourced from the local Windows Security Accounts Manager. + /// + Local, + + /// + /// The principal is sourced from an Active Directory domain. + /// + ActiveDirectory, + + /// + /// The principal is sourced from Azure Active Directory. + /// + AzureAD, + + /// + /// The principal is a Microsoft Account, such as + /// MicrosoftAccount\user@domain.com + /// + MicrosoftAccount + } + + /// + /// Represents a Principal. Serves as a base class for Users and Groups. + /// + public class LocalPrincipal + { + #region Public Properties + /// + /// The account name of the Principal. + /// + public string Name { get; set; } + + /// + /// The Security Identifier that uniquely identifies the Principal/ + /// + public SecurityIdentifier SID { get; set; } + + /// + /// Indicates the account store from which the principal is sourced. + /// One of the PrincipalSource enumerations. + /// + public PrincipalSource? PrincipalSource { get; set; } + + /// + /// The object class that represents this principal. + /// This can be User or Group. + /// + public string ObjectClass { get; set; } + #endregion Public Properties + + #region Construction + /// + /// Initializes a new LocalPrincipal object. + /// + public LocalPrincipal() + { + } + + /// + /// Initializes a new LocalPrincipal object with the specified name. + /// + /// Name of the new LocalPrincipal. + public LocalPrincipal(string name) + { + Name = name; + } + #endregion Construction + + #region Public Methods + /// + /// Provides a string representation of the Principal. + /// + /// + /// A string, in SDDL form, representing the Principal. + /// + public override string ToString() + { + return Name ?? SID.ToString(); + } + #endregion Public Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs new file mode 100644 index 0000000000000000000000000000000000000000..9cad9777cac6ffa73883a72e7aa74572b72e2574 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +using Microsoft.PowerShell.LocalAccounts; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Describes a Local User. + /// Objects of this type are provided to and returned from user-related Cmdlets. + /// + public class LocalUser : LocalPrincipal + { + #region Public Properties + /// + /// The date and time at which this user account expires. + /// A value of null indicates that the account never expires. + /// + public DateTime? AccountExpires { get; set; } + + /// + /// A short description of the User. + /// + public string Description { get; set; } + + /// + /// Indicates whether the user account is enabled (true) or disabled (false). + /// + public bool Enabled { get; set; } + + /// + /// The user's full name. Not the same as the User name. + /// + public string FullName { get; set; } + + /// + /// The date and time at which this user account password is allowed + /// to be changed. The password cannot be changed before this time. + /// A value of null indicates that the password can be changed anytime. + /// + public DateTime? PasswordChangeableDate { get; set; } + + /// + /// The date and time at which this user account password must be changed + /// to a new password. A value of null indicates that the password will + /// never expire. + /// + public DateTime? PasswordExpires { get; set; } + + /// + /// Indicates whether the user is allowed to change the password (true) + /// or not (false). + /// + public bool UserMayChangePassword { get; set; } + + /// + /// Indicates whether the user must have a password (true) or not (false). + /// + public bool PasswordRequired { get; set; } + + /// + /// The date and time at which this user last changed the account password. + /// + public DateTime? PasswordLastSet { get; set; } + + /// + /// The date and time at which the user last logged on to the machine. + /// + public DateTime? LastLogon { get; set; } + #endregion Public Properties + + #region Construction + /// + /// Initializes a new LocalUser object. + /// + public LocalUser() + { + ObjectClass = Strings.ObjectClassUser; + } + + /// + /// Initializes a new LocalUser object with the specified name. + /// + /// Name of the new LocalUser. + public LocalUser(string name) + : base(name) + { + ObjectClass = Strings.ObjectClassUser; + } + + /// + /// Construct a new LocalUser object that is a copy of another. + /// + /// The LocalUser object to copy. + private LocalUser(LocalUser other) + : this(other.Name) + { + SID = other.SID; + PrincipalSource = other.PrincipalSource; + ObjectClass = other.ObjectClass; + + AccountExpires = other.AccountExpires; + Description = other.Description; + Enabled = other.Enabled; + FullName = other.FullName; + PasswordChangeableDate = other.PasswordChangeableDate; + PasswordExpires = other.PasswordExpires; + UserMayChangePassword = other.UserMayChangePassword; + + PasswordRequired = other.PasswordRequired; + PasswordLastSet = other.PasswordLastSet; + LastLogon = other.LastLogon; + } + #endregion Construction + + #region Public Methods + /// + /// Provides a string representation of the LocalUser object. + /// + /// + /// A string containing the User Name. + /// + public override string ToString() + { + return Name ?? SID.ToString(); + } + + /// + /// Create a copy of a LocalUser object. + /// + /// + /// A new LocalUser object with the same property values as this one. + /// + public LocalUser Clone() + { + return new LocalUser(this); + } + #endregion Public Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs new file mode 100644 index 0000000000000000000000000000000000000000..c34dbcd64d8d4c16661c4dbe5d563d941b00f18d --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs @@ -0,0 +1,424 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace System.Management.Automation.SecurityAccountsManager.Native +{ + #region Enums + internal enum POLICY_INFORMATION_CLASS + { + PolicyAuditLogInformation = 1, + PolicyAuditEventsInformation, + PolicyPrimaryDomainInformation, + PolicyPdAccountInformation, + PolicyAccountDomainInformation, + PolicyLsaServerRoleInformation, + PolicyReplicaSourceInformation, + PolicyDefaultQuotaInformation, + PolicyModificationInformation, + PolicyAuditFullSetInformation, + PolicyAuditFullQueryInformation, + PolicyDnsDomainInformation + } + + [Flags] + internal enum LSA_AccessPolicy : long + { + POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, + POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, + POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, + POLICY_TRUST_ADMIN = 0x00000008L, + POLICY_CREATE_ACCOUNT = 0x00000010L, + POLICY_CREATE_SECRET = 0x00000020L, + POLICY_CREATE_PRIVILEGE = 0x00000040L, + POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, + POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, + POLICY_AUDIT_LOG_ADMIN = 0x00000200L, + POLICY_SERVER_ADMIN = 0x00000400L, + POLICY_LOOKUP_NAMES = 0x00000800L, + POLICY_NOTIFICATION = 0x00001000L + } + + internal enum SID_NAME_USE + { + SidTypeUser = 1, + SidTypeGroup, + SidTypeDomain, + SidTypeAlias, + SidTypeWellKnownGroup, + SidTypeDeletedAccount, + SidTypeInvalid, + SidTypeUnknown, + SidTypeComputer, + SidTypeLabel + } + + internal enum LSA_USER_ACCOUNT_TYPE + { + UnknownUserAccountType = 0, + LocalUserAccountType, + PrimaryDomainUserAccountType, + ExternalDomainUserAccountType, + LocalConnectedUserAccountType, // Microsoft Account + AADUserAccountType, + InternetUserAccountType, // Generic internet User (eg. if the SID supplied is MSA's internet SID) + MSAUserAccountType // !!! NOT YET IN THE ENUM SPECIFIED IN THE C API !!! + + } + #endregion Enums + + #region Structures + [StructLayout(LayoutKind.Sequential)] + internal struct SECURITY_DESCRIPTOR + { + public byte Revision; + public byte Sbz1; + public UInt16 Control; // SECURITY_DESCRIPTOR_CONTROL + public IntPtr Owner; + public IntPtr Group; + public IntPtr Sacl; + public IntPtr Dacl; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct ACL + { + public byte AclRevision; + public byte Sbz1; + public UInt16 AclSize; + public UInt16 AceCount; + public UInt16 Sbz2; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct USER_INFO_1 + { + public string name; + public string password; + public int password_age; + public int priv; + public string home_dir; + public string comment; + public uint flags; + public string script_path; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_INFO_1008 + { + public uint flags; + } + + /// + /// The UNICODE_STRING structure is passed to a number of the SAM and LSA + /// API functions. This adds cleanup and managed-string conversion behaviors. + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct UNICODE_STRING + { + public UInt16 Length; + public UInt16 MaximumLength; + [MarshalAs(UnmanagedType.LPWStr)] + private string buffer; + + public UNICODE_STRING(string s) + { + buffer = string.IsNullOrEmpty(s) ? string.Empty : s; + Length = (UInt16)(2 * buffer.Length); + MaximumLength = Length; + } + + public override string ToString() + { + // UNICODE_STRING structures that were populated by unmanaged code + // often have buffers that point to junk if Length = 0, or that + // point to non-null-terminated strings, resulting in marshaled + // String objects that have more characters than they should. + return Length == 0 ? string.Empty + : buffer.Substring(0, Length / 2); + } + } + + [StructLayout(LayoutKind.Sequential)] + internal struct OBJECT_ATTRIBUTES : IDisposable + { + public int Length; + public IntPtr RootDirectory; + public uint Attributes; + public IntPtr SecurityDescriptor; + public IntPtr SecurityQualityOfService; + + private IntPtr objectName; + public UNICODE_STRING ObjectName; + + public void Dispose() + { + if (objectName != IntPtr.Zero) + { + Marshal.DestroyStructure(objectName); + Marshal.FreeHGlobal(objectName); + objectName = IntPtr.Zero; + } + } + } + +// These structures are filled in by Marshalling, so fields will be initialized +// invisibly to the C# compiler, and some fields will not be used in C# code. +#pragma warning disable 0649, 0169 + [StructLayout(LayoutKind.Explicit, Size = 8)] + struct LARGE_INTEGER + { + [FieldOffset(0)] + public Int64 QuadPart; + [FieldOffset(0)] + public UInt32 LowPart; + [FieldOffset(4)] + public Int32 HighPart; + } +#pragma warning restore 0649, 0169 + #endregion Structures + + internal static class Win32 + { + #region Constants + // The following are masks for the predefined standard access types + internal const UInt32 DELETE = 0x00010000; + internal const UInt32 READ_CONTROL = 0x00020000; + internal const UInt32 WRITE_DAC = 0x00040000; + internal const UInt32 WRITE_OWNER = 0x00080000; + internal const UInt32 SYNCHRONIZE = 0x00100000; + + internal const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000; + + internal const UInt32 STANDARD_RIGHTS_READ = READ_CONTROL; + internal const UInt32 STANDARD_RIGHTS_WRITE = READ_CONTROL; + internal const UInt32 STANDARD_RIGHTS_EXECUTE = READ_CONTROL; + + internal const UInt32 STANDARD_RIGHTS_ALL = 0x001F0000; + + internal const UInt32 SPECIFIC_RIGHTS_ALL = 0x0000FFFF; + + internal const UInt32 ACCESS_SYSTEM_SECURITY = 0x01000000; + + internal const UInt32 MAXIMUM_ALLOWED = 0x02000000; + + internal const UInt32 GENERIC_READ = 0x80000000; + internal const UInt32 GENERIC_WRITE = 0x40000000; + internal const UInt32 GENERIC_EXECUTE = 0x20000000; + internal const UInt32 GENERIC_ALL = 0x10000000; + + // These constants control the behavior of the FormatMessage Windows API function + internal const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; + internal const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; + internal const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; + internal const uint FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; + internal const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; + internal const uint FORMAT_MESSAGE_FROM_STRING = 0x00000400; + + #region Win32 Error Codes + // + // MessageText: + // + // The operation completed successfully. + // + internal const Int32 ERROR_SUCCESS = 0; + internal const Int32 NO_ERROR = ERROR_SUCCESS; + + // + // MessageId: ERROR_ACCESS_DENIED + // + // MessageText: + // + // Access is denied. + // + internal const int ERROR_ACCESS_DENIED = 5; + + // + // MessageId: ERROR_BAD_NETPATH + // + // MessageText: + // + // The network path was not found. + // + internal const int ERROR_BAD_NETPATH = 53; + + // + // MessageId: ERROR_NETWORK_ACCESS_DENIED + // + // MessageText: + // + // Network access is denied. + // + internal const int ERROR_NETWORK_ACCESS_DENIED = 65; + + // + // MessageId: ERROR_INVALID_PARAMETER + // + // MessageText: + // + // The parameter is incorrect. + // + internal const int ERROR_INVALID_PARAMETER = 87; + + // + // MessageText: + // + // The file name is too long. + // + internal const Int32 ERROR_BUFFER_OVERFLOW = 111; + + // + // MessageText: + // + // The data area passed to a system call is too small. + // + internal const Int32 ERROR_INSUFFICIENT_BUFFER = 122; + + // + // MessageId: ERROR_INVALID_LEVEL + // + // MessageText: + // + // The system call level is not correct. + // + internal const int ERROR_INVALID_LEVEL = 124; + + // + // MessageId: ERROR_INVALID_FLAGS + // + // MessageText: + // + // Invalid flags. + // + internal const Int32 ERROR_INVALID_FLAGS = 1004; + + // + // MessageId: ERROR_ILL_FORMED_PASSWORD + // + // MessageText: + // + // Unable to update the password. The value provided for the new password contains values that are not allowed in passwords. + // + internal const UInt32 ERROR_ILL_FORMED_PASSWORD = 1324; + + // + // MessageId: ERROR_PASSWORD_RESTRICTION + // + // MessageText: + // + // Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain. + // + internal const UInt32 ERROR_PASSWORD_RESTRICTION = 1325; + + // + // MessageText: + // + // No mapping between account names and security IDs was done. + // + internal const Int32 ERROR_NONE_MAPPED = 1332; + + internal const int NERR_Success = 0; + // NERR_BASE is the base of error codes from network utilities, + // chosen to avoid conflict with system and redirector error codes. + // 2100 is a value that has been assigned to us by system. + internal const int NERR_BASE = 2100; + + internal const int NERR_BadPassword = NERR_BASE + 103; // The password parameter is invalid. + internal const int NERR_UserNotFound = NERR_BASE + 121; // The user name could not be found. + internal const int NERR_NotPrimary = NERR_BASE + 126; // This operation is only allowed on the primary domain controller of the domain. + internal const int NERR_SpeGroupOp = NERR_BASE + 134; // This operation is not allowed on this special group. + internal const int NERR_PasswordTooShort = NERR_BASE + 145; // The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. + internal const int NERR_InvalidComputer = NERR_BASE + 251; // This computer name is invalid. + internal const int NERR_LastAdmin = NERR_BASE + 352; // This operation is not allowed on the last administrative account. + #endregion Win32 Error Codes + + #region SECURITY_DESCRIPTOR Control Flags + internal const UInt16 SE_DACL_PRESENT = 0x0004; + internal const UInt16 SE_SELF_RELATIVE = 0x8000; + #endregion SECURITY_DESCRIPTOR Control Flags + + #region SECURITY_INFORMATION Values + internal const int DACL_SECURITY_INFORMATION = 0x00000004; + #endregion SECURITY_INFORMATION Values + #endregion Constants + + #region Win32 Functions + [DllImport(PInvokeDllNames.LookupAccountSidDllName, CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool LookupAccountSid(string systemName, + byte[] accountSid, + StringBuilder accountName, + ref Int32 nameLength, + StringBuilder domainName, + ref Int32 domainNameLength, + out SID_NAME_USE use); + + [DllImport(PInvokeDllNames.LookupAccountNameDllName, CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool LookupAccountName(string systemName, + string accountName, + [MarshalAs(UnmanagedType.LPArray)] + byte[] sid, + ref uint sidLength, + StringBuilder domainName, + ref uint domainNameLength, + out SID_NAME_USE peUse); + + [DllImport(PInvokeDllNames.GetSecurityDescriptorDaclDllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, + [MarshalAs(UnmanagedType.Bool)] + out bool bDaclPresent, + out IntPtr pDacl, + [MarshalAs(UnmanagedType.Bool)] + out bool bDaclDefaulted); + + [DllImport(PInvokeDllNames.SetSecurityDescriptorDaclDllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, + [MarshalAs(UnmanagedType.Bool)] + bool bDaclPresent, + IntPtr pDacl, + [MarshalAs(UnmanagedType.Bool)] + bool bDaclDefaulted); + + [DllImport(PInvokeDllNames.FormatMessageDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern uint FormatMessage(uint dwFlags, + IntPtr lpSource, + uint dwMessageId, + uint dwLanguageId, + [Out] StringBuilder lpBuffer, + uint nSize, + string[] Arguments); + + [DllImport("ntdll.dll")] + internal static extern uint RtlNtStatusToDosError(uint ntStatus); + #endregion Win32 Functions + + #region LSA Functions + [DllImport(PInvokeDllNames.LsaOpenPolicyDllName, CharSet = CharSet.Unicode)] + internal static extern UInt32 LsaOpenPolicy(ref UNICODE_STRING SystemName, + ref OBJECT_ATTRIBUTES ObjectAttributes, + uint DesiredAccess, + out IntPtr PolicyHandle); + + [DllImport(PInvokeDllNames.LsaQueryInformationPolicyDllName, CharSet = CharSet.Unicode)] + internal static extern UInt32 LsaQueryInformationPolicy(IntPtr lsaHandle, + POLICY_INFORMATION_CLASS infoClass, + out IntPtr buffer); + + [DllImport(PInvokeDllNames.LsaFreeMemoryDllName)] + internal static extern UInt32 LsaFreeMemory(IntPtr buffer); + + [DllImport(PInvokeDllNames.LsaCloseDllName)] + internal static extern UInt32 LsaClose(IntPtr handle); + + [DllImport("api-ms-win-security-lsalookup-l1-1-2.dll")] + internal static extern UInt32 LsaLookupUserAccountType([MarshalAs(UnmanagedType.LPArray)] byte[] Sid, + out LSA_USER_ACCOUNT_TYPE accountType); + #endregion LSA Functions + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs new file mode 100644 index 0000000000000000000000000000000000000000..654d221a69bac720e8f3b9c41504c9c9fb58433c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs @@ -0,0 +1,519 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; + +namespace System.Management.Automation.SecurityAccountsManager.Native +{ + internal static class NtStatus + { + #region Constants + // + // These values are taken from ntstatus.h + // + + // + // Severity codes + // + public const UInt32 STATUS_SEVERITY_WARNING = 0x2; + public const UInt32 STATUS_SEVERITY_SUCCESS = 0x0; + public const UInt32 STATUS_SEVERITY_INFORMATIONAL = 0x1; + public const UInt32 STATUS_SEVERITY_ERROR = 0x3; + + public const UInt32 STATUS_SUCCESS = 0x00000000; + // + // MessageText: + // + // Returned by enumeration APIs to indicate more information is available to successive calls. + // + public const UInt32 STATUS_MORE_ENTRIES = 0x00000105; + + + ///////////////////////////////////////////////////////////////////////// + // + // Standard Information values + // + ///////////////////////////////////////////////////////////////////////// + + // + // MessageText: + // + // {Object Exists} + // An attempt was made to create an object and the object name already existed. + // + public const UInt32 STATUS_OBJECT_NAME_EXISTS = 0x40000000; + + // + // MessageText: + // + // {Password Too Complex} + // The Windows password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string. + // + public const UInt32 STATUS_NULL_LM_PASSWORD = 0x4000000D; + + // + // MessageText: + // + // {Access Denied} + // A process has requested access to an object, but has not been granted those access rights. + // + public const UInt32 STATUS_ACCESS_DENIED = 0xC0000022; + + // + // MessageText: + // + // The name provided is not a properly formed account name. + // + public const UInt32 STATUS_INVALID_ACCOUNT_NAME = 0xC0000062; + + // + // MessageText: + // + // The specified account already exists. + // + public const UInt32 STATUS_USER_EXISTS = 0xC0000063; + + // + // MessageText: + // + // The specified account does not exist. + // + public const UInt32 STATUS_NO_SUCH_USER = 0xC0000064; // ntsubauth + + // + // MessageText: + // + // The specified group already exists. + // + public const UInt32 STATUS_GROUP_EXISTS = 0xC0000065; + + // + // MessageText: + // + // The specified group does not exist. + // + public const UInt32 STATUS_NO_SUCH_GROUP = 0xC0000066; + + // + // MessageText: + // + // The specified user account is already in the specified group account. Also used to indicate a group cannot be deleted because it contains a member. + // + public const UInt32 STATUS_MEMBER_IN_GROUP = 0xC0000067; + + // + // MessageText: + // + // The specified user account is not a member of the specified group account. + // + public const UInt32 STATUS_MEMBER_NOT_IN_GROUP = 0xC0000068; + + // + // MessageText: + // + // Indicates the requested operation would disable, delete or could prevent logon for an administration account. + // This is not allowed to prevent creating a situation in which the system cannot be administrated. + // + public const UInt32 STATUS_LAST_ADMIN = 0xC0000069; + + // + // MessageText: + // + // When trying to update a password, this return status indicates that the value provided as the current password is not correct. + // + public const UInt32 STATUS_WRONG_PASSWORD = 0xC000006A; // ntsubauth + + // + // MessageText: + // + // When trying to update a password, this return status indicates that the value provided for the new password contains values that are not allowed in passwords. + // + public const UInt32 STATUS_ILL_FORMED_PASSWORD = 0xC000006B; + + // + // MessageText: + // + // When trying to update a password, this status indicates that some password update rule has been violated. For example, the password may not meet length criteria. + // + public const UInt32 STATUS_PASSWORD_RESTRICTION = 0xC000006C; // ntsubauth + + // + // MessageText: + // + // The user account's password has expired. + // + public const UInt32 STATUS_PASSWORD_EXPIRED = 0xC0000071; // ntsubauth + + // + // MessageText: + // + // The referenced account is currently disabled and may not be logged on to. + // + public const UInt32 STATUS_ACCOUNT_DISABLED = 0xC0000072; // ntsubauth + + // + // MessageText: + // + // None of the information to be translated has been translated. + // + public const UInt32 STATUS_NONE_MAPPED = 0xC0000073; + + // + // MessageText: + // + // Indicates the sub-authority value is invalid for the particular use. + // + public const UInt32 STATUS_INVALID_SUB_AUTHORITY = 0xC0000076; + + // + // MessageText: + // + // Indicates the ACL structure is not valid. + // + public const UInt32 STATUS_INVALID_ACL = 0xC0000077; + + // + // MessageText: + // + // Indicates the SID structure is not valid. + // + public const UInt32 STATUS_INVALID_SID = 0xC0000078; + + // + // MessageText: + // + // Indicates the SECURITY_DESCRIPTOR structure is not valid. + // + public const UInt32 STATUS_INVALID_SECURITY_DESCR = 0xC0000079; + + // + // Network specific errors. + // + // + // + // MessageText: + // + // The request is not supported. + // + public const UInt32 STATUS_NOT_SUPPORTED = 0xC00000BB; + + // + // MessageText: + // + // This remote computer is not listening. + // + public const UInt32 STATUS_REMOTE_NOT_LISTENING = 0xC00000BC; + + // + // MessageText: + // + // Network access is denied. + // + public const UInt32 STATUS_NETWORK_ACCESS_DENIED = 0xC00000CA; + + // + // MessageText: + // + // Indicates an attempt was made to operate on the security of an object that does not have security associated with it. + // + public const UInt32 STATUS_NO_SECURITY_ON_OBJECT = 0xC00000D7; + + // + // MessageText: + // + // An internal error occurred. + // + public const UInt32 STATUS_INTERNAL_ERROR = 0xC00000E5; + + // + // MessageText: + // + // Indicates a security descriptor is not in the necessary format (absolute or self-relative). + // + public const UInt32 STATUS_BAD_DESCRIPTOR_FORMAT = 0xC00000E7; + + // + // MessageText: + // + // A specified name string is too long for its intended use. + // + public const UInt32 STATUS_NAME_TOO_LONG = 0xC0000106; + + // + // MessageText: + // + // Indicates a name specified as a remote computer name is syntactically invalid. + // + public const UInt32 STATUS_INVALID_COMPUTER_NAME = 0xC0000122; + + // + // MessageText: + // + // Indicates an operation has been attempted on a built-in (special) SAM account which is incompatible with built-in accounts. For example, built-in accounts cannot be deleted. + // + public const UInt32 STATUS_SPECIAL_ACCOUNT = 0xC0000124; + + // + // MessageText: + // + // The operation requested may not be performed on the specified group because it is a built-in special group. + // + public const UInt32 STATUS_SPECIAL_GROUP = 0xC0000125; + + // + // MessageText: + // + // The operation requested may not be performed on the specified user because it is a built-in special user. + // + public const UInt32 STATUS_SPECIAL_USER = 0xC0000126; + + // + // MessageText: + // + // Indicates a member cannot be removed from a group because the group is currently the member's primary group. + // + public const UInt32 STATUS_MEMBERS_PRIMARY_GROUP = 0xC0000127; + + // + // MessageText: + // + // The specified local group does not exist. + // + public const UInt32 STATUS_NO_SUCH_ALIAS = 0xC0000151; + + // + // MessageText: + // + // The specified account name is not a member of the group. + // + public const UInt32 STATUS_MEMBER_NOT_IN_ALIAS = 0xC0000152; + + // + // MessageText: + // + // The specified account name is already a member of the group. + // + public const UInt32 STATUS_MEMBER_IN_ALIAS = 0xC0000153; + + // + // MessageText: + // + // The specified local group already exists. + // + public const UInt32 STATUS_ALIAS_EXISTS = 0xC0000154; + + // + // MessageText: + // + // A member could not be added to or removed from the local group because the member does not exist. + // + public const UInt32 STATUS_NO_SUCH_MEMBER = 0xC000017A; + + // + // MessageText: + // + // A new member could not be added to a local group because the member has the wrong account type. + // + public const UInt32 STATUS_INVALID_MEMBER = 0xC000017B; + + // + // MessageText: + // + // The user's account has expired. + // + public const UInt32 STATUS_ACCOUNT_EXPIRED = 0xC0000193; // ntsubauth + + // + // MessageText: + // + // {Invalid ACE Condition} + // The specified access control entry (ACE) contains an invalid condition. + // + public const UInt32 STATUS_INVALID_ACE_CONDITION = 0xC00001A2; + + // + // MessageText: + // + // The user's password must be changed before signing in. + // + public const UInt32 STATUS_PASSWORD_MUST_CHANGE = 0xC0000224; // ntsubauth + + // + // MessageText: + // + // The object was not found. + // + public const UInt32 STATUS_NOT_FOUND = 0xC0000225; + + // + // MessageText: + // + // Could not find a domain controller for this domain. + // + public const UInt32 STATUS_DOMAIN_CONTROLLER_NOT_FOUND = 0xC0000233; + + // + // MessageText: + // + // The user account has been automatically locked because too many invalid logon attempts or password change attempts have been requested. + // + public const UInt32 STATUS_ACCOUNT_LOCKED_OUT = 0xC0000234; // ntsubauth + + // + // MessageText: + // + // The password provided is too short to meet the policy of your user account. Please choose a longer password. + // + public const UInt32 STATUS_PWD_TOO_SHORT = 0xC000025A; + + // + // MessageText: + // + // The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned. + // + public const UInt32 STATUS_PWD_TOO_RECENT = 0xC000025B; + + // + // MessageText: + // + // You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Please select a password that you have not previously used. + // + public const UInt32 STATUS_PWD_HISTORY_CONFLICT = 0xC000025C; + + // + // MessageText: + // + // The password provided is too long to meet the policy of your user account. Please choose a shorter password. + // + public const UInt32 STATUS_PWD_TOO_LONG = 0xC000027A; + + // + // MessageText: + // + // Only an administrator can modify the membership list of an administrative group. + // + public const UInt32 STATUS_DS_SENSITIVE_GROUP_VIOLATION = 0xC00002CD; + + // + // MessageText: + // + // The specified group type is invalid. + // + public const UInt32 STATUS_DS_INVALID_GROUP_TYPE = 0xC00002D4; + + // + // MessageText: + // + // A local group cannot have another cross domain local group as a member. + // + public const UInt32 STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 0xC00002DB; + + // + // MessageText: + // + // Cannot change to security disabled group because of having primary members in this group. + // + public const UInt32 STATUS_DS_HAVE_PRIMARY_MEMBERS = 0xC00002DC; + + // + // MessageText: + // + // EAS policy requires that the user change their password before this operation can be performed. + // + public const UInt32 STATUS_PASSWORD_CHANGE_REQUIRED = 0xC000030C; + + #endregion Constants + + #region Public Methods + /// + /// Determine if an NTSTATUS value indicates Success. + /// + /// The NTSTATUS value returned from native functions. + /// + /// True if the NTSTATUS value indicates success, false otherwise. + /// + public static bool IsSuccess(UInt32 ntstatus) + { + return Severity(ntstatus) == STATUS_SEVERITY_SUCCESS; + } + + /// + /// Determine if an NTSTATUS value indicates an Error. + /// + /// The NTSTATUS value returned from native functions. + /// + /// True if the NTSTATUS value indicates an error, false otherwise. + /// + public static bool IsError(UInt32 ntstatus) + { + return Severity(ntstatus) == STATUS_SEVERITY_ERROR; + } + + /// + /// Determine if an NTSTATUS value indicates a Warning. + /// + /// The NTSTATUS value returned from native functions. + /// + /// True if the NTSTATUS value indicates a warning, false otherwise. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public static bool IsWarning(UInt32 ntstatus) + { + return Severity(ntstatus) == STATUS_SEVERITY_WARNING; + } + + /// + /// Determine if an NTSTATUS value indicates that the value is Informational. + /// + /// The NTSTATUS value returned from native functions. + /// + /// True if the NTSTATUS value indicates that it is informational, false otherwise. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public static bool IsInformational(UInt32 ntstatus) + { + return Severity(ntstatus) == STATUS_SEVERITY_INFORMATIONAL; + } + + /// + /// Return the Severity part of an NTSTATUS value. + /// + /// The NTSTATUS value returned from native functions. + /// + /// One of the STATUS_SEVERITY_* values + /// + public static uint Severity(UInt32 ntstatus) + { + return ntstatus >> 30; + } + + /// + /// Return the Facility part of an NSTATUS value. + /// + /// The NTSTATUS value returned from native functions. + /// + /// The value of the Facility portion of an NTSTATUS value. + /// + + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public static uint Facility(UInt32 ntstatus) + { + return (ntstatus >> 16) & 0x0FFF; + } + + /// + /// Return the Code part of an NTSTATUS value. + /// + /// The NTSTATUS value returned from native functions. + /// + /// The value of the Code portion of an NTSTATUS value. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public static uint Code(UInt32 ntstatus) + { + return ntstatus & 0xFFFF; + } + + #endregion Public Methods + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs new file mode 100644 index 0000000000000000000000000000000000000000..68a7d31e8335439db5b4f4d66a8b8840cb94e5fa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace System.Management.Automation +{ + /// + /// PinvokeDllNames contains the DLL names to be use for PInvoke in FullCLR/CoreCLR powershell. + /// + /// * When adding a new DLL name here, make sure that you add both the FullCLR and CoreCLR version + /// of it. Add the comment '/*COUNT*/' with the new DLL name, and make sure the 'COUNT' is the + /// same for both FullCLR and CoreCLR DLL names. + /// + internal static class PInvokeDllNames + { + internal const string GetLastErrorDllName = "api-ms-win-core-errorhandling-l1-1-0.dll"; /* 1*/ + internal const string LookupAccountSidDllName = "api-ms-win-security-lsalookup-l2-1-1.dll"; /* 2*/ + internal const string IsValidSidDllName = "api-ms-win-security-base-l1-2-0.dll"; /* 3*/ + internal const string GetLengthSidDllName = "api-ms-win-security-base-l1-2-0.dll"; /* 4*/ + internal const string LsaFreeMemoryDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 5*/ + internal const string LsaOpenPolicyDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 6*/ + internal const string LsaQueryInformationPolicyDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 7*/ + internal const string LsaCloseDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 8*/ + internal const string LookupAccountNameDllName = "api-ms-win-security-lsalookup-l2-1-1.dll"; /* 9*/ + internal const string GetComputerNameDllName = "api-ms-win-downlevel-kernel32-l2-1-0.dll"; /*10*/ + internal const string GetSecurityDescriptorDaclDllName = "api-ms-win-security-base-l1-2-0"; /*11*/ + internal const string SetSecurityDescriptorDaclDllName = "api-ms-win-security-base-l1-2-0"; /*12*/ + internal const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-1"; /*13*/ + internal const string GetVersionExDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; /*14*/ + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs new file mode 100644 index 0000000000000000000000000000000000000000..3e6bbcafd10559bef8327c7674f86d2614433ede --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -0,0 +1,3275 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; + +using Microsoft.PowerShell.Commands; +using System.Management.Automation.SecurityAccountsManager.Extensions; +using System.Management.Automation.SecurityAccountsManager.Native; +using System.Management.Automation.SecurityAccountsManager.Native.NtSam; +using System.Text; + +using Microsoft.PowerShell.LocalAccounts; +using System.Diagnostics.CodeAnalysis; + +[module: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant")] + +namespace System.Management.Automation.SecurityAccountsManager +{ + /// + /// Defines enumeration constants for enabling and disabling something. + /// + internal enum Enabling + { + Disable = 0, + Enable + } + + /// + /// Managed version of the SAM_RID_ENUMERATION native structure, + /// to be returned from the EnumerateLocalUsers method of Sam. + /// Contains the original structure's members along with additional + /// members of use. + /// + internal class SamRidEnumeration + { +#region Original struct members + public string Name; + public UInt32 RelativeId; +#endregion Original struct members + +#region Additional members + public IntPtr domainHandle; // The domain handle used to acquire the data. +#endregion Additional members + } + + /// + /// Provides methods for manipulating local Users and Groups. + /// + internal class Sam : IDisposable + { +#region Enums + [Flags] + private enum GroupProperties + { + Name = 0x0001, // NOT changeable through Set-LocalGroup + Description = 0x0002, + + AllSetable = Description, + AllReadable = AllSetable | Name + } + + /// + /// Defines a set of flags, each corresponding to a member of LocalUser, + /// which indicate fields to be updated. + /// + /// + /// Although password can be set through Create-LocalUser and Set-LocalUser, + /// it is not a member of LocalUser so does not appear in this enumeration. + /// + [Flags] + private enum UserProperties + { + None = 0x0000, // not actually a LocalUser member + Name = 0x0001, // NOT changeable through Set-LocalUser + AccountExpires = 0x0002, + Description = 0x0004, + Enabled = 0x0008, // NOT changeable through Set-LocalUser + FullName = 0x0010, + PasswordChangeableDate = 0x0020, + PasswordExpires = 0x0040, + PasswordNeverExpires = 0x0080, + UserMayChangePassword = 0x0100, + PasswordRequired = 0x0200, + PasswordLastSet = 0x0400, // CANNOT be set by cmdlet + LastLogon = 0x0800, // CANNOT be set by cmdlet + + // All properties that can be set through Set-LocalUser + AllSetable = AccountExpires + | Description + | FullName + | PasswordChangeableDate + | PasswordExpires + | PasswordNeverExpires + | UserMayChangePassword + | PasswordRequired, + + // Properties that can be set by Create-LocalUser + AllCreateable = AllSetable | Name | Enabled, + + // Properties that can be read by e.g., Get-LocalUser + AllReadable = AllCreateable | PasswordLastSet | LastLogon + } + + private enum PasswordExpiredState + { + Unchanged = -1, + NotExpired = 0, + Expired = 1 + } + + [Flags] + internal enum ObjectAccess : uint + { + AliasRead = Win32.STANDARD_RIGHTS_READ + | ALIAS_LIST_MEMBERS, + ALiasWrite = Win32.STANDARD_RIGHTS_WRITE + | ALIAS_WRITE_ACCOUNT + | ALIAS_ADD_MEMBER + | ALIAS_REMOVE_MEMBER, + + UserAllAccess = Win32.STANDARD_RIGHTS_REQUIRED + | USER_READ_PREFERENCES + | USER_READ_LOGON + | USER_LIST_GROUPS + | USER_READ_GROUP_INFORMATION + | USER_WRITE_PREFERENCES + | USER_CHANGE_PASSWORD + | USER_FORCE_PASSWORD_CHANGE + | USER_READ_GENERAL + | USER_READ_ACCOUNT + | USER_WRITE_ACCOUNT + | USER_WRITE_GROUP_INFORMATION, + UserRead = Win32.STANDARD_RIGHTS_READ + | USER_READ_GENERAL // not in original USER_READ + | USER_READ_PREFERENCES + | USER_READ_LOGON + | USER_READ_ACCOUNT + | USER_LIST_GROUPS + | USER_READ_GROUP_INFORMATION, + UserWrite = Win32.STANDARD_RIGHTS_WRITE + | USER_WRITE_PREFERENCES + | USER_CHANGE_PASSWORD + } + + [Flags] + internal enum DomainAccess : uint + { + AllAccess = Win32.STANDARD_RIGHTS_REQUIRED + | DOMAIN_READ_OTHER_PARAMETERS + | DOMAIN_WRITE_OTHER_PARAMETERS + | DOMAIN_WRITE_PASSWORD_PARAMS + | DOMAIN_CREATE_USER + | DOMAIN_CREATE_GROUP + | DOMAIN_CREATE_ALIAS + | DOMAIN_GET_ALIAS_MEMBERSHIP + | DOMAIN_LIST_ACCOUNTS + | DOMAIN_READ_PASSWORD_PARAMETERS + | DOMAIN_LOOKUP + | DOMAIN_ADMINISTER_SERVER, + + Read = Win32.STANDARD_RIGHTS_READ + | DOMAIN_LIST_ACCOUNTS + | DOMAIN_GET_ALIAS_MEMBERSHIP + | DOMAIN_READ_OTHER_PARAMETERS, + + Write = Win32.STANDARD_RIGHTS_WRITE + | DOMAIN_WRITE_OTHER_PARAMETERS + | DOMAIN_WRITE_PASSWORD_PARAMS + | DOMAIN_CREATE_USER + | DOMAIN_CREATE_GROUP + | DOMAIN_CREATE_ALIAS + | DOMAIN_ADMINISTER_SERVER, + + Max = Win32.MAXIMUM_ALLOWED + } + + /// + /// The operation under way. Used in the class. + /// + private enum ContextOperation + { + New = 1, + Enable, + Disable, + Get, + Remove, + Rename, + Set, + AddMember, + GetMember, + RemoveMember + } + + /// + /// The type of object currently operating with. + /// used in the class. + /// + private enum ContextObjectType + { + User = 1, + Group + } +#endregion Enums + +#region Internal Classes + /// + /// Holds information about the underway operation. + /// + /// + /// Used primarily by the private ThrowOnFailure method when building + /// Exception objects to throw. + /// + private sealed class Context + { + public ContextOperation operation; + public ContextObjectType type; + public object target; + public string objectId; + public string memberId; + + /// + /// Initialize a new Context object. + /// + /// + /// One of the enumerations indicating + /// the type of operation under way. + /// + /// + /// One of the enumerations indicating + /// the type of object (user or group) being used. + /// + /// + /// A string containing the name of the object. This may be either a + /// user/group name or a string representation of a SID. + /// + /// + /// The target being operated on. + /// + /// + /// A string containing the name of the member being added or removed + /// from a group. Used only in such cases. + /// + public Context(ContextOperation operation, + ContextObjectType objectType, + string objectIdentifier, + object target, + string memberIdentifier = null) + { + this.operation = operation; + this.type = objectType; + this.objectId = objectIdentifier; + this.target = target; + this.memberId = memberIdentifier; + } + + /// + /// Default constructor. + /// + public Context() + { + } + /// + /// Gets a string containing the type of operation under way. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public string OperationName + { + get { return operation.ToString(); } + } + + /// + /// Gets a string containing the type of object ("User" or "Group") + /// being used. + /// + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public string TypeNamne + { + get { return type.ToString(); } + } + + /// + /// Gets a string containing the name of the object being used. + /// + public string ObjectName + { + get { return objectId; } + } + + /// + /// Gets a string containing the name of the member being added to + /// or removed from a group. Returns null if the operation does not + /// involve group members. + /// + public string MemberName + { + get { return memberId; } + } + } + + /// + /// Contains basic information about an Account. + /// + /// + /// AccountInfo is the return type from the private + /// LookupAccountInfo method. + /// + private sealed class AccountInfo + { + public string AccountName; + public string DomainName; + public SecurityIdentifier Sid; + public Native.SID_NAME_USE Use; + + public override string ToString() + { + if (!string.IsNullOrEmpty(DomainName)) + return DomainName + '\\' + AccountName; + else + return AccountName; + } + } +#endregion Internal Classes + +#region Constants + // + // Access rights + // + private const UInt32 ALIAS_ADD_MEMBER = 0x0001; + private const UInt32 ALIAS_REMOVE_MEMBER = 0x0002; + private const UInt32 ALIAS_LIST_MEMBERS = 0x0004; + private const UInt32 ALIAS_READ_INFORMATION = 0x0008; + private const UInt32 ALIAS_WRITE_ACCOUNT = 0x0010; + + private const UInt32 USER_READ_GENERAL = 0x0001; + private const UInt32 USER_READ_PREFERENCES = 0x0002; + private const UInt32 USER_WRITE_PREFERENCES = 0x0004; + private const UInt32 USER_READ_LOGON = 0x0008; + private const UInt32 USER_READ_ACCOUNT = 0x0010; + private const UInt32 USER_WRITE_ACCOUNT = 0x0020; + private const UInt32 USER_CHANGE_PASSWORD = 0x0040; + private const UInt32 USER_FORCE_PASSWORD_CHANGE = 0x0080; + private const UInt32 USER_LIST_GROUPS = 0x0100; + private const UInt32 USER_READ_GROUP_INFORMATION = 0x0200; + private const UInt32 USER_WRITE_GROUP_INFORMATION = 0x0400; + + private const UInt32 DOMAIN_READ_PASSWORD_PARAMETERS = 0x0001; + private const UInt32 DOMAIN_WRITE_PASSWORD_PARAMS = 0x0002; + private const UInt32 DOMAIN_READ_OTHER_PARAMETERS = 0x0004; + private const UInt32 DOMAIN_WRITE_OTHER_PARAMETERS = 0x0008; + private const UInt32 DOMAIN_CREATE_USER = 0x0010; + private const UInt32 DOMAIN_CREATE_GROUP = 0x0020; + private const UInt32 DOMAIN_CREATE_ALIAS = 0x0040; + private const UInt32 DOMAIN_GET_ALIAS_MEMBERSHIP = 0x0080; + private const UInt32 DOMAIN_LIST_ACCOUNTS = 0x0100; + private const UInt32 DOMAIN_LOOKUP = 0x0200; + private const UInt32 DOMAIN_ADMINISTER_SERVER = 0x0400; +#endregion Constants + +#region Static Data + private static SecurityIdentifier worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); +#endregion Static Data + +#region Instance Data + private IntPtr samHandle = IntPtr.Zero; + private IntPtr localDomainHandle = IntPtr.Zero; + private IntPtr builtinDomainHandle = IntPtr.Zero; + private Context context = null; + private string machineName = string.Empty; +#endregion Instance Data + +#region Construction + internal Sam() + { + OpenHandles(); + + // CoreCLR does not have Environment.MachineName, + // so we'll use this instead. + machineName = System.Net.Dns.GetHostName(); + } +#endregion Construction + +#region Public (Internal) Methods + public string StripMachineName(string name) + { + var mn = machineName + '\\'; + + if (name.StartsWith(mn, StringComparison.CurrentCultureIgnoreCase)) + return name.Substring(mn.Length); + + return name; + } +#region Local Groups + /// + /// Retrieve a named local group. + /// + /// Name of the desired local group. + /// + /// A object containing information about + /// the local group. + /// + /// + /// Thrown when the named group cannot be found. + /// + internal LocalGroup GetLocalGroup(string groupName) + { + context = new Context(ContextOperation.Get, ContextObjectType.Group, groupName, groupName); + + foreach (var sre in EnumerateGroups()) + if (sre.Name.Equals(groupName, StringComparison.CurrentCultureIgnoreCase)) + return MakeLocalGroupObject(sre); // return a populated group + + throw new GroupNotFoundException(groupName, context.target); + } + + /// + /// Retrieve a local group by SID. + /// + /// + /// A object identifying the desired group. + /// + /// + /// A object containing information about + /// the local group. + /// + /// + /// Thrown when the specified group cannot be found. + /// + internal LocalGroup GetLocalGroup(SecurityIdentifier sid) + { + context = new Context(ContextOperation.Get, ContextObjectType.Group, sid.ToString(), sid); + + foreach (var sre in EnumerateGroups()) + if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) + return MakeLocalGroupObject(sre); // return a populated group + + throw new GroupNotFoundException(sid.ToString(), context.target); + } + + /// + /// Create a local group. + /// + /// A object containing + /// information about the local group to be created. + /// + /// + /// A new LocalGroup object containing information about the newly + /// created local group. + /// + /// + /// Thrown when an attempt is made to create a local group that already + /// exists. + /// + internal LocalGroup CreateLocalGroup(LocalGroup group) + { + context = new Context(ContextOperation.New, ContextObjectType.Group, group.Name, group.Name); + + return CreateGroup(group, localDomainHandle); + } + + /// + /// Update a local group with new property values. + /// + /// + /// A object representing the group to be updated. + /// + /// + /// A LocalGroup object containing the desired changes. + /// + /// + /// Currently, a group's description is the only changeable property. + /// + internal void UpdateLocalGroup(LocalGroup group, LocalGroup changed) + { + context = new Context(ContextOperation.Set, ContextObjectType.Group, group.Name, group); + + UpdateGroup(group, changed); + } + + /// + /// Remove a local group. + /// + /// + /// A object identifying the + /// local group to be removed. + /// + /// + /// Thrown when the specified group cannot be found. + /// + internal void RemoveLocalGroup(SecurityIdentifier sid) + { + context = new Context(ContextOperation.Remove, ContextObjectType.Group, sid.ToString(), sid); + + RemoveGroup(sid); + } + + /// + /// Remove a local group. + /// + /// + /// A object containing + /// information about the local group to be removed. + /// + /// + /// Thrown when the specified group cannot be found. + /// + internal void RemoveLocalGroup(LocalGroup group) + { + context = new Context(ContextOperation.Remove, ContextObjectType.Group, group.Name, group); + + if (group.SID == null) + context.target = group = GetLocalGroup(group.Name); + + RemoveGroup(group.SID); + } + + /// + /// Rename a local group. + /// + /// + /// A object identifying + /// the local group to be renamed. + /// + /// + /// A string containing the new name for the local group. + /// + /// + /// Thrown when the specified group cannot be found. + /// + internal void RenameLocalGroup(SecurityIdentifier sid, string newName) + { + context = new Context(ContextOperation.Rename, ContextObjectType.Group, sid.ToString(), sid); + + RenameGroup(sid, newName); + } + + /// + /// Rename a local group. + /// + /// + /// A object containing + /// information about the local group to be renamed. + /// + /// + /// A string containing the new name for the local group. + /// + /// + /// Thrown when the specified group cannot be found. + /// + internal void RenameLocalGroup(LocalGroup group, string newName) + { + context = new Context(ContextOperation.Rename, ContextObjectType.Group, group.Name, group); + + if (group.SID == null) + context.target = group = GetLocalGroup(group.Name); + + RenameGroup(group.SID, newName); + } + + /// + /// Get all local groups whose names satisfy the specified predicate. + /// + /// + /// Predicate that determines whether a group satisfies the conditions. + /// + /// + /// An object containing LocalGroup + /// objects that satisfy the predicate condition. + /// + internal IEnumerable GetMatchingLocalGroups(Predicate pred) + { + context = new Context(ContextOperation.Get, ContextObjectType.Group, string.Empty, null); + + foreach (var sre in EnumerateGroups()) + { + + if (pred(sre.Name)) + { + context.target = sre.Name; + yield return MakeLocalGroupObject(sre); + } + } + } + + /// + /// Get all local groups. + /// + /// + /// An object containing a + /// LocalGroup object for each local group. + /// + internal IEnumerable GetAllLocalGroups() + { + context = new Context(ContextOperation.Get, ContextObjectType.Group, string.Empty, null); + + foreach (var sre in EnumerateGroups()) + { + context.target = sre.Name; + yield return MakeLocalGroupObject(sre); + } + } + + /// + /// Add members to a local group. + /// + /// + /// A object identifying the group to + /// which to add members. + /// + /// + /// An object of type identifying + /// the member to be added. + /// + /// + /// An Exception object indicating any errors encountered. + /// + /// + /// Thrown if the group could not be found. + /// + internal Exception AddLocalGroupMember(LocalGroup group, LocalPrincipal member) + { + context = new Context(ContextOperation.AddMember, ContextObjectType.Group, group.Name, group); + if (group.SID == null) + context.target = group = GetLocalGroup(group.Name); + + return AddGroupMember(group.SID, member); + } + + /// + /// Add members to a local group. + /// + /// + /// A object identifying the group to + /// which to add members. + /// + /// + /// An object of type identifying + /// the member to be added. + /// + /// + /// An Exception object indicating any errors encountered. + /// + /// + /// Thrown if the group could not be found. + /// + internal Exception AddLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) + { + context = new Context(ContextOperation.AddMember, ContextObjectType.Group, groupSid.ToString(), groupSid); + + return AddGroupMember(groupSid, member); + } + + /// + /// Retrieve members of a Local group. + /// + /// + /// A object identifying the group whose members + /// are requested. + /// + /// + /// An IEnumerable of objects containing the group's + /// members. + /// + internal IEnumerable GetLocalGroupMembers(LocalGroup group) + { + context = new Context(ContextOperation.GetMember, ContextObjectType.Group, group.Name, group); + + if (group.SID == null) + context.target = group = GetLocalGroup(group.Name); + + return GetGroupMembers(group.SID); + } + + /// + /// Retrieve members of a Local group. + /// + /// + /// A object identifying the group whose members + /// are requested. + /// + /// + /// An IEnumerable of objects containing the group's + /// members. + /// + internal IEnumerable GetLocalGroupMembers(SecurityIdentifier groupSid) + { + context = new Context(ContextOperation.GetMember, ContextObjectType.Group, groupSid.ToString(), groupSid); + + return GetGroupMembers(groupSid); + } + + /// + /// Remove members from a local group. + /// + /// + /// A object identifying the group from + /// which to remove members + /// + /// + /// An object of type identifying + /// the member to be removed. + /// + /// + /// An Exception object indicating any errors encountered. + /// + /// + /// Thrown if the group could not be found. + /// + internal Exception RemoveLocalGroupMember(LocalGroup group, LocalPrincipal member) + { + context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, group.Name, group); + + if (group.SID == null) + context.target = group = GetLocalGroup(group.Name); + + return RemoveGroupMember(group.SID, member); + } + + /// + /// Remove members from a local group. + /// + /// + /// A object identifying the group from + /// which to remove members + /// + /// + /// An Object of type identifying + /// the member to be removed. + /// + /// + /// An Exception object indicating any errors encountered. + /// + /// + /// Thrown if the group could not be found. + /// + internal Exception RemoveLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) + { + context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, groupSid.ToString(), groupSid); + + return RemoveGroupMember(groupSid, member); + } +#endregion Local Groups + +#region Local Users + /// + /// Retrieve a named local user. + /// + /// Name of the desired local user. + /// + /// A object containing information about + /// the local user. + /// + /// + /// Thrown when the named user cannot be found. + /// + internal LocalUser GetLocalUser(string userName) + { + context = new Context(ContextOperation.Get, ContextObjectType.User, userName, userName); + + foreach (var sre in EnumerateUsers()) + if (sre.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase)) + return MakeLocalUserObject(sre); + + throw new UserNotFoundException(userName, userName); + } + + /// + /// Retrieve a local user by SID. + /// + /// + /// A object identifying the desired user. + /// + /// + /// A object containing information about + /// the local user. + /// + /// + /// Thrown when the specified user cannot be found. + /// + internal LocalUser GetLocalUser(SecurityIdentifier sid) + { + context = new Context(ContextOperation.Get, ContextObjectType.User, sid.ToString(), sid); + + foreach (var sre in EnumerateUsers()) + if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) + return MakeLocalUserObject(sre); // return a populated user + + throw new UserNotFoundException(sid.ToString(), sid); + } + + /// + /// Create a local user. + /// + /// A object containing + /// information about the local user to be created. + /// + /// A containing + /// the initial password to be set for the new local user. If this parameter is null, + /// no password is set. + /// + /// + /// Indicates whether PasswordNeverExpires was specified + /// + /// + /// A new LocalGroup object containing information about the newly + /// created local user. + /// + /// + /// Thrown when an attempt is made to create a local user that already + /// exists. + /// + internal LocalUser CreateLocalUser(LocalUser user, System.Security.SecureString password, bool setPasswordNeverExpires) + { + context = new Context(ContextOperation.New, ContextObjectType.User, user.Name, user); + + return CreateUser(user, password, localDomainHandle, setPasswordNeverExpires); + } + + /// + /// Remove a local user. + /// + /// + /// A object identifying + /// the local user to be removed. + /// + /// + /// Thrown when the specified user cannot be found. + /// + internal void RemoveLocalUser(SecurityIdentifier sid) + { + context = new Context(ContextOperation.Remove, ContextObjectType.User, sid.ToString(), sid); + + RemoveUser(sid); + } + + /// + /// Remove a local user. + /// + /// + /// A object containing + /// information about the local user to be removed. + /// + /// + /// Thrown when the specified user cannot be found. + /// + internal void RemoveLocalUser(LocalUser user) + { + context = new Context(ContextOperation.Remove, ContextObjectType.User, user.Name, user); + + if (user.SID == null) + context.target = user = GetLocalUser(user.Name); + + RemoveUser(user.SID); + } + + /// + /// Rename a local user. + /// + /// + /// A objects identifying + /// the local user to be renamed. + /// + /// + /// A string containing the new name for the local user. + /// + /// + /// Thrown when the specified user cannot be found. + /// + internal void RenameLocalUser(SecurityIdentifier sid, string newName) + { + context = new Context(ContextOperation.Rename, ContextObjectType.User, sid.ToString(), sid); + + RenameUser(sid, newName); + } + + /// + /// Rename a local user. + /// + /// + /// A objects containing + /// information about the local user to be renamed. + /// + /// + /// A string containing the new name for the local user. + /// + /// + /// Thrown when the specified user cannot be found. + /// + internal void RenameLocalUser(LocalUser user, string newName) + { + context = new Context(ContextOperation.Rename, ContextObjectType.User, user.Name, user); + + if (user.SID == null) + context.target = user = GetLocalUser(user.Name); + + RenameUser(user.SID, newName); + } + + /// + /// Enable or disable a Local User. + /// + /// + /// A object identifying the user to enable or disable. + /// + /// + /// One of the enumeration values, indicating whether to + /// enable or disable the user. + /// + internal void EnableLocalUser(SecurityIdentifier sid, Enabling enable) + { + context = new Context(enable == Enabling.Enable ? ContextOperation.Enable + : ContextOperation.Disable, + ContextObjectType.User, sid.ToString(), + sid); + + EnableUser(sid, enable); + } + + /// + /// Enable or disable a Local User. + /// + /// + /// A object representing the user to enable or disable. + /// + /// + /// One of the enumeration values, indicating whether to + /// enable or disable the user. + /// + internal void EnableLocalUser(LocalUser user, Enabling enable) + { + context = new Context(enable == Enabling.Enable ? ContextOperation.Enable + : ContextOperation.Disable, + ContextObjectType.User, user.Name, + user); + + if (user.SID == null) + context.target = user = GetLocalUser(user.Name); + + EnableUser(user.SID, enable); + } + + /// + /// Update a local user with new properties. + /// + /// + /// A object representing the user to be updated. + /// + /// + /// A LocalUser object containing the desired changes. + /// + /// A + /// object containing the new password. A null value in this parameter + /// indicates that the password is not to be changed. + /// + /// + /// Specifies whether the PasswordNeverExpires parameter was set. + /// + /// + /// Call this overload when intending to leave the password-expired + /// marker in its current state. To set the password and the + /// password-expired state, call the overload with a boolean as the + /// fourth parameter + /// + internal void UpdateLocalUser(LocalUser user, LocalUser changed, System.Security.SecureString password, bool? setPasswordNeverExpires) + { + context = new Context(ContextOperation.Set, ContextObjectType.User, user.Name, user); + + UpdateUser(user, changed, password, PasswordExpiredState.Unchanged, setPasswordNeverExpires); + } + + /// + /// Get all local users whose names satisfy the specified predicate. + /// + /// + /// Predicate that determines whether a user satisfies the conditions. + /// + /// + /// An object containing LocalUser + /// objects that satisfy the predicate condition. + /// + internal IEnumerable GetMatchingLocalUsers(Predicate pred) + { + context = new Context(ContextOperation.Get, ContextObjectType.User, string.Empty, null); + + foreach (var sre in EnumerateUsers()) + { + if (pred(sre.Name)) + { + context.target = sre.Name; + yield return MakeLocalUserObject(sre); + } + } + } + + /// + /// Get all local users. + /// + /// + /// An object containing a + /// LocalUser object for each local user. + /// + internal IEnumerable GetAllLocalUsers() + { + context = new Context(ContextOperation.Get, ContextObjectType.User, null, null); + + foreach (var sre in EnumerateUsers()) + yield return MakeLocalUserObject(sre); + } +#endregion Local Users + +#region Local Principals + internal LocalPrincipal LookupAccount(string name) + { + var info = LookupAccountInfo(name); + + if (info == null) + throw new PrincipalNotFoundException(name, name); + + return MakeLocalPrincipalObject(info); + } +#endregion Local Principals +#endregion Public (Internal) Methods + +#region Private Methods + /// + /// Open the handles stored by Sam instances. + /// + private void OpenHandles() + { + var systemName = new UNICODE_STRING(); + var oa = new OBJECT_ATTRIBUTES(); + IntPtr pInfo = IntPtr.Zero; + IntPtr pSid = IntPtr.Zero; + IntPtr lsaHandle = IntPtr.Zero; + UInt32 status = 0; + + try + { + status = Win32.LsaOpenPolicy(ref systemName, ref oa, (UInt32)LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION, out lsaHandle); + ThrowOnFailure(status); + + POLICY_PRIMARY_DOMAIN_INFO domainInfo; + + status = Win32.LsaQueryInformationPolicy(lsaHandle, + POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation, + out pInfo); + ThrowOnFailure(status); + status = Win32.LsaClose(lsaHandle); + ThrowOnFailure(status); + + lsaHandle = IntPtr.Zero; + + domainInfo = Marshal.PtrToStructure(pInfo); + + status = SamApi.SamConnect(ref systemName, out samHandle, SamApi.SAM_SERVER_LOOKUP_DOMAIN, ref oa); + ThrowOnFailure(status); + + // Open the local domain + status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, domainInfo.Sid, out localDomainHandle); + ThrowOnFailure(status); + + // Open the "BuiltIn" domain + SecurityIdentifier sid = new SecurityIdentifier("S-1-5-32"); + byte[] bSid = new byte[sid.BinaryLength]; + int size = Marshal.SizeOf() * bSid.Length; + + pSid = Marshal.AllocHGlobal(size); + + sid.GetBinaryForm(bSid, 0); + Marshal.Copy(bSid, 0, pSid, bSid.Length); + + status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, pSid, out builtinDomainHandle); + + ThrowOnFailure(status); + } + finally + { + if (pInfo != IntPtr.Zero) + status = Win32.LsaFreeMemory(pInfo); + + Marshal.FreeHGlobal(pSid); + + if (lsaHandle != IntPtr.Zero) + status = Win32.LsaClose(lsaHandle); + } + } + + /// + /// Find a group by SID and return a object + /// representing the group. + /// + /// A object identifying + /// the group to search for. + /// + /// A SamRidEnumeration object representing the group. + /// + /// + /// Thrown when the specified group is not found. + /// + /// + /// This method saves some time and effort over the GetGroup method + /// because it does not have to open a group to populate a full Group + /// object. + /// + private SamRidEnumeration GetGroupSre(SecurityIdentifier sid) + { + foreach (var sre in EnumerateGroups()) + if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) + return sre; + + throw new GroupNotFoundException(sid.ToString(), sid); + } + + /// + /// Find a user by SID and return a object + /// representing the user. + /// + /// A object identifying + /// the user to search for. + /// + /// A SamRidEnumeration object representing the user. + /// + /// + /// Thrown when the specified user is not found. + /// + /// + /// This method saves some time and effort over the GetUser method + /// because it does not have to open a user to populate a full LocalUser + /// object. + /// + private SamRidEnumeration GetUserSre(SecurityIdentifier sid) + { + foreach (var sre in EnumerateUsers()) + if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) + return sre; + + throw new UserNotFoundException(sid.ToString(), sid); + } + + /// + /// Enumerate local users with native SAM functions. + /// + /// Handle to the domain to enumerate over. + /// + /// An IEnumerable of SamRidEnumeration objects, one for each local user. + /// + /// + /// This is a "generator" method. Rather than returning an entire collection, + /// it uses 'yield return' to return each object in turn. + /// + private static IEnumerable EnumerateUsersInDomain(IntPtr domainHandle) + { + UInt32 status = 0; + UInt32 context = 0; + IntPtr buffer = IntPtr.Zero; + UInt32 countReturned; + + do + { + status = SamApi.SamEnumerateUsersInDomain(domainHandle, + ref context, + 0, + out buffer, + 1, + out countReturned); + + if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1) + { + if (buffer != IntPtr.Zero) + { + SAM_RID_ENUMERATION sre; + + sre = Marshal.PtrToStructure(buffer); + + SamApi.SamFreeMemory(buffer); + buffer = IntPtr.Zero; + + yield return new SamRidEnumeration + { + Name = sre.Name.ToString(), + RelativeId = sre.RelativeId, + + domainHandle = domainHandle + }; + } + } + } while (Succeeded(status) && status != 0 && countReturned != 0); + } + + /// + /// Enumerate user objects in both the local and builtin domains. + /// + /// + /// An IEnumerable of SamRidEnumeration objects, one for each local user. + /// + /// + /// This is a "generator" method. Rather than returning an entire collection, + /// it uses 'yield return' to return each object in turn. + /// + private IEnumerable EnumerateUsers() + { + foreach (var sre in EnumerateUsersInDomain(localDomainHandle)) + yield return sre; + + foreach (var sre in EnumerateUsersInDomain(builtinDomainHandle)) + yield return sre; + } + + /// + /// Create a new user in the specified domain. + /// + /// + /// A object containing information about the new user. + /// + /// A containing + /// the initial password to be set for the new local user. If this parameter is null, + /// no password is set. + /// + /// + /// Handle to the domain in which to create the new user. + /// + /// + /// Indicates whether PasswordNeverExpires was specified + /// + /// + /// A LocalUser object that represents the newly-created user + /// + private LocalUser CreateUser(LocalUser userInfo, System.Security.SecureString password, IntPtr domainHandle, bool setPasswordNeverExpires) + { + IntPtr userHandle = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + UNICODE_STRING str = new UNICODE_STRING(); + UInt32 status = 0; + + try + { + UInt32 relativeId = 0; + UInt32 grantedAccess = 0; + + str = new UNICODE_STRING(userInfo.Name); + + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(str)); + Marshal.StructureToPtr(str, buffer, false); + + status = SamApi.SamCreateUser2InDomain(domainHandle, + ref str, + (int) SamApi.USER_NORMAL_ACCOUNT, + Win32.MAXIMUM_ALLOWED, + out userHandle, + out grantedAccess, + out relativeId); + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + buffer = IntPtr.Zero; + ThrowOnFailure(status); + + // set the various properties of the user. A SID is required because some + // operations depend on it. + userInfo.SID = RidToSid(domainHandle, relativeId); + + SetUserData(userHandle, userInfo, UserProperties.AllCreateable, password, PasswordExpiredState.NotExpired, setPasswordNeverExpires); + + return MakeLocalUserObject(new SamRidEnumeration + { + domainHandle = domainHandle, + Name = userInfo.Name, + RelativeId = relativeId + }, + userHandle); + } + catch (Exception) + { + if (IntPtr.Zero != userHandle) + { + SamApi.SamDeleteUser(userHandle); + } + + throw; + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + if (userHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(userHandle); + } + } + + /// + /// Remove a group identified by SID. + /// + /// + /// A object identifying the + /// group to be removed. + /// + private void RemoveGroup(SecurityIdentifier sid) + { + var sre = GetGroupSre(sid); + + IntPtr aliasHandle = IntPtr.Zero; + UInt32 status; + try + { + status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + ThrowOnFailure(status); + + status = SamApi.SamDeleteAlias(aliasHandle); + ThrowOnFailure(status); + + aliasHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteAlias succeeds + } + finally + { + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + } + + /// + /// Rename a group identified by SID. + /// + /// + /// A object identifying + /// the local group to be renamed. + /// + /// + /// A string containing the new name for the group. + /// + /// + /// Thrown when the specified group cannot be found. + /// + private void RenameGroup(SecurityIdentifier sid, string newName) + { + var sre = GetGroupSre(sid); + + IntPtr aliasHandle = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + UInt32 status = 0; + + status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + ThrowOnFailure(status); + + try + { + ALIAS_NAME_INFORMATION info = new ALIAS_NAME_INFORMATION(); + + info.Name = new UNICODE_STRING(newName); + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); + Marshal.StructureToPtr(info, buffer, false); + + status = SamApi.SamSetInformationAlias(aliasHandle, + ALIAS_INFORMATION_CLASS.AliasNameInformation, + buffer); + ThrowOnFailure(status, + new Context { + objectId = newName, + operation = context.operation, + type = context.type + } + ); + } + finally + { + if (buffer != IntPtr.Zero) + { + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + } + + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + } + + /// + /// Add members to a group. + /// + /// + /// A object identifying the group to + /// which to add members. + /// + /// + /// An object of type identifying + /// the member to be added. + /// + /// + /// An Exception object indicating any errors encountered. + /// + /// + /// Thrown if the group could not be found. + /// + private Exception AddGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) + { + var sre = GetGroupSre(groupSid); // We'll let this throw if necessary + + IntPtr aliasHandle = IntPtr.Zero; + UInt32 status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + ThrowOnFailure(status); + Exception ex = null; + try + { + var sid = member.SID; + var binarySid = new byte[sid.BinaryLength]; + + sid.GetBinaryForm(binarySid, 0); + status = SamApi.SamAddMemberToAlias(aliasHandle, binarySid); + ex = MakeException(status, + new Context + { + memberId = member.ToString(), + objectId = context.objectId, + operation = context.operation, + target = context.target, + type = context.type + } + ); + + } + finally + { + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + + return ex; + } + + /// + /// Retrieve members of a group. + /// + /// + /// A object representing the group whose members + /// are requested. + /// + /// + /// An IEnumerable of objects containing the group's + /// members. + /// + private IEnumerable GetGroupMembers(SecurityIdentifier groupSid) + { + var sre = GetGroupSre(groupSid); + + IntPtr aliasHandle = IntPtr.Zero; + IntPtr memberIds = IntPtr.Zero; + UInt32 status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + ThrowOnFailure(status); + + try + { + UInt32 memberCount = 0; + + status = SamApi.SamGetMembersInAlias(aliasHandle, out memberIds, out memberCount); + ThrowOnFailure(status); + + if (memberCount != 0) + { + IntPtr[] idArray = new IntPtr[memberCount]; + + Marshal.Copy(memberIds, idArray, 0, (int)memberCount); + + for (int i=0; i < memberCount; i++) + { + var sid = new SecurityIdentifier(idArray[i]); + yield return MakeLocalPrincipalObject(LookupAccountInfo(sid)); + } + } + } + finally + { + if (aliasHandle != IntPtr.Zero) + SamApi.SamCloseHandle(aliasHandle); + + if (memberIds != IntPtr.Zero) + SamApi.SamFreeMemory(memberIds); + } + } + + /// + /// Remove members from a group. + /// + /// + /// A object identifying the group from + /// which to remove members + /// + /// + /// An object of type identifying + /// the member to be removed. + /// + /// + /// An IEnumerable of Exception objects indicating any errors encountered. + /// + /// + /// Thrown if the group could not be found. + /// + private Exception RemoveGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) + { + var sre = GetGroupSre(groupSid); // We'll let this throw if necessary + + IntPtr aliasHandle = IntPtr.Zero; + UInt32 status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + ThrowOnFailure(status); + + // Now we're processing each member, so any further exceptions will + // be stored in the collection and returned later. + var rv = new List(); + Exception ex = null; + try + { + var sid = member.SID; + var binarySid = new byte[sid.BinaryLength]; + + sid.GetBinaryForm(binarySid, 0); + status = SamApi.SamRemoveMemberFromAlias(aliasHandle, binarySid); + + ex = MakeException(status, + new Context { + memberId = member.ToString(), + objectId = context.objectId, + operation = context.operation, + target = context.target, + type = context.type + } + ); + } + finally + { + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + + return ex; + } + + /// + /// Create a populated LocalUser object from a SamRidEnumeration object. + /// + /// + /// A object containing minimal information + /// about a local user. + /// + /// + /// A LocalUser object, populated with user information. + /// + private LocalUser MakeLocalUserObject(SamRidEnumeration sre) + { + IntPtr userHandle = IntPtr.Zero; + var status = SamApi.SamOpenUser(sre.domainHandle, + (UInt32)ObjectAccess.UserRead, + sre.RelativeId, + out userHandle); + + ThrowOnFailure(status); + + try + { + return MakeLocalUserObject(sre, userHandle); + } + finally + { + if (userHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(userHandle); + } + } + + /// + /// Create a populated LocalUser object from a SamRidEnumeration object, + /// using an already-opened SAM user handle. + /// + /// + /// A object containing minimal information + /// about a local user. + /// + /// + /// Handle to an open SAM user. + /// + /// + /// A LocalUser object, populated with user information. + /// + private LocalUser MakeLocalUserObject(SamRidEnumeration sre, IntPtr userHandle) + { + IntPtr buffer = IntPtr.Zero; + UInt32 status = 0; + + try + { + USER_ALL_INFORMATION allInfo; + + status = SamApi.SamQueryInformationUser(userHandle, + USER_INFORMATION_CLASS.UserAllInformation, + out buffer); + ThrowOnFailure(status); + allInfo = Marshal.PtrToStructure(buffer); + + var userSid = RidToSid(sre.domainHandle, sre.RelativeId); + LocalUser user = new LocalUser() + { + PrincipalSource = GetPrincipalSource(sre), + SID = userSid, + + Name = allInfo.UserName.ToString(), + FullName = allInfo.FullName.ToString(), + Description = allInfo.AdminComment.ToString(), + + // TODO: why is this coming up as 864000000000 (number of ticks per day)? + PasswordChangeableDate = DateTimeFromSam(allInfo.PasswordCanChange.QuadPart), + + PasswordExpires = DateTimeFromSam(allInfo.PasswordMustChange.QuadPart), + + // TODO: why is this coming up as 0X7FFFFFFFFFFFFFFF (largest signed 64-bit, and well out of range of DateTime)? + AccountExpires = DateTimeFromSam(allInfo.AccountExpires.QuadPart), + LastLogon = DateTimeFromSam(allInfo.LastLogon.QuadPart), + PasswordLastSet = DateTimeFromSam(allInfo.PasswordLastSet.QuadPart), + + UserMayChangePassword = GetUserMayChangePassword(userHandle, userSid), + + PasswordRequired = (allInfo.UserAccountControl & SamApi.USER_PASSWORD_NOT_REQUIRED) == 0, + + Enabled = !((allInfo.UserAccountControl & SamApi.USER_ACCOUNT_DISABLED) == SamApi.USER_ACCOUNT_DISABLED) + }; + + return user; + } + finally + { + if (buffer != IntPtr.Zero) + status = SamApi.SamFreeMemory(buffer); + } + } + + /// + /// Enable or disable a user. + /// + /// + /// A object identifying the user to be + /// enabled or disabled. + /// + /// + /// One of the enumeration values indicating + /// whether the user is to be enabled or disabled. + /// + private void EnableUser(SecurityIdentifier sid, Enabling enable) + { + IntPtr userHandle = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + UInt32 status = 0; + + var sre = GetUserSre(sid); + + status = SamApi.SamOpenUser(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out userHandle); + ThrowOnFailure(status); + + try + { + USER_ALL_INFORMATION info; + + status = SamApi.SamQueryInformationUser(userHandle, + USER_INFORMATION_CLASS.UserAllInformation, + out buffer); + ThrowOnFailure(status); + info = Marshal.PtrToStructure(buffer); + status = SamApi.SamFreeMemory(buffer); + buffer = IntPtr.Zero; + + UInt32 uac = info.UserAccountControl; + UInt32 enabled_state = uac & SamApi.USER_ACCOUNT_DISABLED; + + if (enable == Enabling.Enable && enabled_state == SamApi.USER_ACCOUNT_DISABLED) + uac &= ~SamApi.USER_ACCOUNT_DISABLED; + else if (enable == Enabling.Disable && enabled_state != SamApi.USER_ACCOUNT_DISABLED) + uac |= SamApi.USER_ACCOUNT_DISABLED; + else + return; + + if (uac != info.UserAccountControl) + { + info.UserAccountControl = uac; + info.WhichFields = SamApi.USER_ALL_USERACCOUNTCONTROL; + + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); + Marshal.StructureToPtr(info, buffer, false); + status = SamApi.SamSetInformationUser(userHandle, + USER_INFORMATION_CLASS.UserAllInformation, + buffer); + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + buffer = IntPtr.Zero; + ThrowOnFailure(status); + } + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + if (userHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(userHandle); + } + } + + /// + /// Rename a user. + /// + /// + /// A object identifying the user to be + /// renamed. + /// + /// The new user name. + private void RenameUser(SecurityIdentifier sid, string newName) + { + IntPtr userHandle = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + UInt32 status = 0; + + var sre = GetUserSre(sid); + + status = SamApi.SamOpenUser(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out userHandle); + ThrowOnFailure(status); + + try + { + USER_ACCOUNT_NAME_INFORMATION info = new USER_ACCOUNT_NAME_INFORMATION(); + + info.UserName = new UNICODE_STRING(newName); + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); + Marshal.StructureToPtr(info, buffer, false); + + status = SamApi.SamSetInformationUser(userHandle, + USER_INFORMATION_CLASS.UserAccountNameInformation, + buffer); + ThrowOnFailure(status, + new Context { + objectId = newName, + operation = context.operation, + type = context.type + } + ); + } + finally + { + if (buffer != IntPtr.Zero) + { + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + } + + if (userHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(userHandle); + } + } + + /// + /// Delete a user. + /// + /// + /// A object identifying the user to be + /// removed. + /// + private void RemoveUser(SecurityIdentifier sid) + { + IntPtr userHandle = IntPtr.Zero; + + var sre = GetUserSre(sid); + UInt32 status; + + try + { + status = SamApi.SamOpenUser(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out userHandle); + ThrowOnFailure(status); + + status = SamApi.SamDeleteUser(userHandle); + ThrowOnFailure(status); + + userHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteUser succeeds + } + finally + { + if (userHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(userHandle); + } + } + + /// + /// Enumerate local users with native SAM functions. + /// + /// Handle to the domain to enumerate over. + /// + /// An IEnumerable of SamRidEnumeration objects, one for each local user. + /// + /// + /// This is a "generator" method. Rather than returning an entire collection, + /// it uses 'yield return' to return each object in turn. + /// + private static IEnumerable EnumerateGroupsInDomain(IntPtr domainHandle) + { + UInt32 status = 0; + UInt32 context = 0; + IntPtr buffer = IntPtr.Zero; + UInt32 countReturned; + + do + { + // Although the method name indicates that we are operating with "groups", + // it actually uses the SAM API's SamEnumerateAliasesInDomain function. + status = SamApi.SamEnumerateAliasesInDomain(domainHandle, + ref context, + out buffer, + 1, + out countReturned); + + if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1) + { + if (buffer != IntPtr.Zero) + { + SAM_RID_ENUMERATION sre; + + sre = Marshal.PtrToStructure(buffer); + + SamApi.SamFreeMemory(buffer); + buffer = IntPtr.Zero; + + yield return new SamRidEnumeration + { + Name = sre.Name.ToString(), + RelativeId = sre.RelativeId, + + domainHandle = domainHandle + }; + } + } + } while (Succeeded(status) && status != 0 && countReturned != 0); + } + + /// + /// Enumerate group objects in both the local and builtin domains. + /// + /// + /// An IEnumerable of SamRidEnumeration objects, one for each local group. + /// + /// + /// This is a "generator" method. Rather than returning an entire collection, + /// it uses 'yield return' to return each object in turn. + /// + internal IEnumerable EnumerateGroups() + { + foreach (var sre in EnumerateGroupsInDomain(localDomainHandle)) + yield return sre; + + foreach (var sre in EnumerateGroupsInDomain(builtinDomainHandle)) + yield return sre; + } + + /// + /// Create a new group in the specified domain. + /// + /// + /// A object containing information about the new group. + /// + /// Handle to the domain in which to create the new group. + /// + /// A LocalGroup object that represents the newly-created group. + /// + private LocalGroup CreateGroup(LocalGroup groupInfo, IntPtr domainHandle) + { + IntPtr aliasHandle = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + UNICODE_STRING str = new UNICODE_STRING(); + UInt32 status; + + try + { + UInt32 relativeId; + + str = new UNICODE_STRING(groupInfo.Name); + + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(str)); + Marshal.StructureToPtr(str, buffer, false); + + status = SamApi.SamCreateAliasInDomain(domainHandle, + buffer, + Win32.MAXIMUM_ALLOWED, + out aliasHandle, + out relativeId); + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + buffer = IntPtr.Zero; + ThrowOnFailure(status); + + if (!string.IsNullOrEmpty(groupInfo.Description)) + { + ALIAS_ADM_COMMENT_INFORMATION info = new ALIAS_ADM_COMMENT_INFORMATION(); + + info.AdminComment = new UNICODE_STRING(groupInfo.Description); + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); + Marshal.StructureToPtr(info, buffer, false); + + status = SamApi.SamSetInformationAlias(aliasHandle, + ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation, + buffer); + + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + buffer = IntPtr.Zero; + ThrowOnFailure(status); + } + + return MakeLocalGroupObject(new SamRidEnumeration + { + domainHandle = domainHandle, + Name = groupInfo.Name, + RelativeId = relativeId + }, + aliasHandle); + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + } + + /// + /// Update a local group with new property values. This method provides + /// the actual implementation. + /// + /// + /// A object representing the group to be updated. + /// + /// + /// A LocalGroup object containing the desired changes. + /// + /// + /// Currently, a group's description is the only changeable property. + /// + private void UpdateGroup(LocalGroup group, LocalGroup changed) + { + // Only description may be changed + if (group.Description == changed.Description) + return; + + IntPtr aliasHandle = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + + if (group.SID == null) + group = GetLocalGroup(group.Name); + + var sre = GetGroupSre(group.SID); + UInt32 status; + + try + { + status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + ThrowOnFailure(status); + + ALIAS_ADM_COMMENT_INFORMATION info = new ALIAS_ADM_COMMENT_INFORMATION(); + + info.AdminComment = new UNICODE_STRING(changed.Description); + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); + Marshal.StructureToPtr(info, buffer, false); + + status = SamApi.SamSetInformationAlias(aliasHandle, + ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation, + buffer); + + ThrowOnFailure(status); + } + finally + { + if (buffer != IntPtr.Zero) + { + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + } + + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + } + + /// + /// Create a populated LocalGroup object from a SamRidEnumeration object. + /// + /// + /// A object containing minimal information + /// about a local group. + /// + /// + /// A LocalGroup object, populated with group information. + /// + private LocalGroup MakeLocalGroupObject(SamRidEnumeration sre) + { + IntPtr aliasHandle = IntPtr.Zero; + var status = SamApi.SamOpenAlias(sre.domainHandle, + Win32.MAXIMUM_ALLOWED, + sre.RelativeId, + out aliasHandle); + + ThrowOnFailure(status); + + try + { + return MakeLocalGroupObject(sre, aliasHandle); + } + finally + { + if (aliasHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(aliasHandle); + } + } + + /// + /// Create a populated LocalGroup object from a SamRidEnumeration object, + /// using an already-opened SAM alias handle. + /// + /// + /// A object containing minimal information + /// about a local group. + /// + /// + /// Handle to an open SAM alias. + /// + /// + /// A LocalGroup object, populated with group information. + /// + private LocalGroup MakeLocalGroupObject(SamRidEnumeration sre, IntPtr aliasHandle) + { + IntPtr buffer = IntPtr.Zero; + UInt32 status = 0; + + try + { + ALIAS_GENERAL_INFORMATION generalInfo; + + status = SamApi.SamQueryInformationAlias(aliasHandle, + ALIAS_INFORMATION_CLASS.AliasGeneralInformation, + out buffer); + ThrowOnFailure(status); + generalInfo = Marshal.PtrToStructure(buffer); + + LocalGroup group = new LocalGroup() + { + PrincipalSource = GetPrincipalSource(sre), + SID = RidToSid(sre.domainHandle, sre.RelativeId), + + Name = generalInfo.Name.ToString(), + Description = generalInfo.AdminComment.ToString() + }; + + return group; + } + finally + { + if (buffer != IntPtr.Zero) + status = SamApi.SamFreeMemory(buffer); + } + } + + /// + /// Update a local user with new properties. + /// + /// + /// A object representing the user to be updated. + /// + /// + /// A LocalUser object containing the desired changes. + /// + /// A + /// object containing the new password. A null value in this parameter + /// indicates that the password is not to be changed. + /// + /// One of the + /// enumeration values indicating + /// whether the password-expired state is to be explicitly set or + /// left as is. + /// If the parameter is null, this parameter + /// is ignored. + /// + /// + /// Indicates whether the PasswordNeverExpires parameter was specified. + /// + private void UpdateUser(LocalUser user, + LocalUser changed, + System.Security.SecureString password, + PasswordExpiredState passwordExpired, + bool? setPasswordNeverExpires) + { + UserProperties properties = UserProperties.None; + + if (user.AccountExpires != changed.AccountExpires) + properties |= UserProperties.AccountExpires; + + if (user.Description != changed.Description) + properties |= UserProperties.Description; + + if (user.FullName != changed.FullName) + properties |= UserProperties.FullName; + + if (setPasswordNeverExpires.HasValue) + properties |= UserProperties.PasswordNeverExpires; + + if (user.UserMayChangePassword != changed.UserMayChangePassword) + properties |= UserProperties.UserMayChangePassword; + + if (user.PasswordRequired != changed.PasswordRequired) + properties |= UserProperties.PasswordRequired; + + if ( properties != UserProperties.None + || passwordExpired != PasswordExpiredState.Unchanged + || password != null) + { + IntPtr userHandle = IntPtr.Zero; + UInt32 status = 0; + + try + { + status = SamApi.SamOpenUser(localDomainHandle, + Win32.MAXIMUM_ALLOWED, + user.SID.GetRid(), + out userHandle); + ThrowOnFailure(status); + + SetUserData(userHandle, changed, properties, password, passwordExpired, setPasswordNeverExpires); + } + finally + { + if (userHandle != IntPtr.Zero) + status = SamApi.SamCloseHandle(userHandle); + } + } + } + + /// + /// Set selected properties of a user. + /// + /// Handle to an open SAM user. + /// + /// A object containing the data to set into the user. + /// + /// + /// A combination of values indicating the properties to be set. + /// + /// A + /// object containing the new password. + /// + /// One of the + /// enumeration values indicating + /// whether the password-expired state is to be explicitly set or + /// left as is. If the parameter is null, + /// this parameter is ignored. + /// + /// + /// Nullable value the specifies whether the PasswordNeverExpires bit should be flipped + /// + private void SetUserData(IntPtr userHandle, + LocalUser sourceUser, + UserProperties setFlags, + System.Security.SecureString password, + PasswordExpiredState passwordExpired, + bool? setPasswordNeverExpires) + { + IntPtr buffer = IntPtr.Zero; + + try + { + UInt32 which = 0; + UInt32 status = 0; + UInt32 uac = GetUserAccountControl(userHandle); + USER_ALL_INFORMATION info = new USER_ALL_INFORMATION(); + + if (setFlags.HasFlag(UserProperties.AccountExpires)) + { + which |= SamApi.USER_ALL_ACCOUNTEXPIRES; + info.AccountExpires.QuadPart = sourceUser.AccountExpires.HasValue + ? sourceUser.AccountExpires.Value.ToFileTime() + : 0L; + } + + if (setFlags.HasFlag(UserProperties.Description)) + { + which |= SamApi.USER_ALL_ADMINCOMMENT; + info.AdminComment = new UNICODE_STRING(sourceUser.Description); + } + + if (setFlags.HasFlag(UserProperties.Enabled)) + { + which |= SamApi.USER_ALL_USERACCOUNTCONTROL; + if (sourceUser.Enabled) + uac &= ~SamApi.USER_ACCOUNT_DISABLED; + else + uac |= SamApi.USER_ACCOUNT_DISABLED; + } + + if (setFlags.HasFlag(UserProperties.FullName)) + { + which |= SamApi.USER_ALL_FULLNAME; + info.FullName = new UNICODE_STRING(sourceUser.FullName); + } + + if (setFlags.HasFlag(UserProperties.PasswordNeverExpires)) + { + // Only modify the bit if a change was requested + if (setPasswordNeverExpires.HasValue) + { + which |= SamApi.USER_ALL_USERACCOUNTCONTROL; + if (setPasswordNeverExpires.Value) + uac |= SamApi.USER_DONT_EXPIRE_PASSWORD; + else + uac &= ~SamApi.USER_DONT_EXPIRE_PASSWORD; + } + } + + if (setFlags.HasFlag(UserProperties.PasswordRequired)) + { + which |= SamApi.USER_ALL_USERACCOUNTCONTROL; + if (sourceUser.PasswordRequired) + uac &= ~SamApi.USER_PASSWORD_NOT_REQUIRED; + else + uac |= SamApi.USER_PASSWORD_NOT_REQUIRED; + } + + if (which != 0) + { + info.WhichFields = which; + if ((which & SamApi.USER_ALL_USERACCOUNTCONTROL) != 0) + info.UserAccountControl = uac; + + buffer = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(info, buffer, false); + + status = SamApi.SamSetInformationUser(userHandle, + USER_INFORMATION_CLASS.UserAllInformation, + buffer); + ThrowOnFailure(status); + status = SamApi.SamFreeMemory(buffer); + buffer = IntPtr.Zero; + } + + if (setFlags.HasFlag(UserProperties.UserMayChangePassword)) + SetUserMayChangePassword(userHandle, sourceUser.SID, sourceUser.UserMayChangePassword); + + if (password != null) + SetUserPassword(userHandle, password, passwordExpired); + } + finally + { + if (buffer != IntPtr.Zero) + { + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + } + } + } + + /// + /// Retrieve the User's User Account Control flags. + /// + /// + /// Handle to an open user. + /// + /// + /// A 32-bit unsigned integer containing the User Account Control + /// flags as a set of bits. + /// + private UInt32 GetUserAccountControl(IntPtr userHandle) + { + IntPtr buffer = IntPtr.Zero; + USER_LOGON_INFORMATION info; + UInt32 status; + + try + { + status = SamApi.SamQueryInformationUser(userHandle, + USER_INFORMATION_CLASS.UserLogonInformation, + out buffer); + ThrowOnFailure(status); + info = Marshal.PtrToStructure(buffer); + status = SamApi.SamFreeMemory(buffer); + buffer = IntPtr.Zero; + + return info.UserAccountControl; + } + finally + { + if (buffer != IntPtr.Zero) + status = SamApi.SamFreeMemory(buffer); + } + } + + /// + /// Retrieve the DACL from a SAM object. + /// + /// + /// A handle to the SAM object whose DACL is to be retrieved. + /// + /// + /// A object containing the DACL retrieved from + /// the SAM object. + /// + private RawAcl GetSamDacl(IntPtr objectHandle) + { + RawAcl rv = null; + IntPtr securityObject = IntPtr.Zero; + UInt32 status = 0; + + try + { + status = SamApi.SamQuerySecurityObject(objectHandle, Win32.DACL_SECURITY_INFORMATION, out securityObject); + ThrowOnFailure(status); + + SECURITY_DESCRIPTOR sd = Marshal.PtrToStructure(securityObject); + + bool daclPresent; + bool daclDefaulted; + IntPtr dacl; + bool ok = Win32.GetSecurityDescriptorDacl(securityObject, out daclPresent, out dacl, out daclDefaulted); + + if (!ok) + { + var error = Marshal.GetLastWin32Error(); + if (error == Win32.ERROR_ACCESS_DENIED) + throw new AccessDeniedException(context.target); + else + throw new Win32InternalException(error, context.target); + } + + if (daclPresent) + { + ACL acl = Marshal.PtrToStructure(dacl); + + if (acl.AclSize != 0) + { + // put the DACL into managed data + var bytes = new byte[acl.AclSize]; + + Marshal.Copy(dacl, bytes, 0, acl.AclSize); + rv = new RawAcl(bytes, 0); + } + } + } + finally + { + if (IntPtr.Zero != securityObject) + status = SamApi.SamFreeMemory(securityObject); + } + + return rv; + } + + /// + /// Set the DACL of a SAM object. + /// + /// + /// A handle to the SAM object whose DACL is to be retrieved. + /// + /// + /// A object containing the DACL to be set into + /// the SAM object. + /// + private void SetSamDacl(IntPtr objectHandle, RawAcl rawAcl) + { + IntPtr ipsd = IntPtr.Zero; + IntPtr ipDacl = IntPtr.Zero; + + try + { + bool present = false; + + // create a new security descriptor + var sd = new SECURITY_DESCRIPTOR() { Revision = 1 }; + ipsd = Marshal.AllocHGlobal(Marshal.SizeOf()); + + if (rawAcl != null && rawAcl.BinaryLength > 0) + { + Marshal.StructureToPtr(sd, ipsd, false); + + // put the DACL into unmanaged memory + var length = rawAcl.BinaryLength; + var bytes = new byte[length]; + rawAcl.GetBinaryForm(bytes, 0); + ipDacl = Marshal.AllocHGlobal(length); + + Marshal.Copy(bytes, 0, ipDacl, length); + present = true; + } + + // set the DACL into our new security descriptor + var ok = Win32.SetSecurityDescriptorDacl(ipsd, present, ipDacl, false); + if (!ok) + { + var error = Marshal.GetLastWin32Error(); + + if (error == Win32.ERROR_ACCESS_DENIED) + throw new AccessDeniedException(context.target); + else + throw new Win32InternalException(error, context.target); + } + + var status = SamApi.SamSetSecurityObject(objectHandle, Win32.DACL_SECURITY_INFORMATION, ipsd); + ThrowOnFailure(status); + } + finally + { + Marshal.FreeHGlobal(ipDacl); + Marshal.FreeHGlobal(ipsd); + } + } + + /// + /// Determine if a user account password may be changed by the user. + /// + /// + /// Handle to a SAM user object. + /// + /// + /// A object identifying the SAM + /// object's associated user. + /// + /// + /// True if the user account password may be changed by its user, + /// false otherwise. + /// + /// + /// The ability to for the user to change the user account password + /// is a permission in the object's DACL. This method walks through + /// the ACEs in the DACL, checking if the permission is granted to + /// either Everyone or the user identified by the userSid parameter. + /// + private bool GetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier userSid) + { + var rawAcl = GetSamDacl(userHandle); + + // if there is no DACL, then access is granted + if (rawAcl == null) + return true; + + foreach (var a in rawAcl) + { + var ace = a as CommonAce; + if (ace != null && ace.AceType == AceType.AccessAllowed) + { + if (ace.SecurityIdentifier == worldSid || + ace.SecurityIdentifier == userSid) + { + if ((ace.AccessMask & SamApi.USER_CHANGE_PASSWORD) != 0) + return true; + } + } + } + + return false; + } + + /// + /// Set whether a user account password may be changed by the user. + /// + /// + /// Handle to a SAM user object. + /// + /// + /// A object identifying the SAM + /// object's associated user. + /// + /// + /// A boolean indicating whether the permission is to be enabled or + /// disabled. + /// + /// + /// The ability to for the user to change the user account password + /// is a permission in the object's DACL. This method walks through + /// the ACEs in the DACL, enabling or disabling the permission on ACEs + /// associated with either Everyone or the user identified by the + /// userSid parameter. + /// + private void SetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier userSid, bool enable) + { + var changed = false; + var rawAcl = GetSamDacl(userHandle); + + if (rawAcl != null) + { + foreach (var a in rawAcl) + { + var ace = a as CommonAce; + if (ace != null && ace.AceType == AceType.AccessAllowed) + { + if (ace.SecurityIdentifier == worldSid || + ace.SecurityIdentifier == userSid) + { + if (enable) + ace.AccessMask |= SamApi.USER_CHANGE_PASSWORD; + else + ace.AccessMask &= ~SamApi.USER_CHANGE_PASSWORD; + + changed = true; + } + } + } + + if (changed) + SetSamDacl(userHandle, rawAcl); + } + } + + /// + /// Determine if a user's password has expired. + /// + /// + /// Handle to an open User. + /// + /// + /// True if the user's password has expired, false otherwise. + /// + private bool IsPasswordExpired(IntPtr userHandle) + { + IntPtr buffer = IntPtr.Zero; + USER_ALL_INFORMATION info; + UInt32 status; + + try + { + status = SamApi.SamQueryInformationUser(userHandle, + USER_INFORMATION_CLASS.UserAllInformation, + out buffer); + ThrowOnFailure(status); + info = Marshal.PtrToStructure(buffer); + status = SamApi.SamFreeMemory(buffer); + buffer = IntPtr.Zero; + + return info.PasswordExpired; + } + finally + { + if (buffer != IntPtr.Zero) + status = SamApi.SamFreeMemory(buffer); + } + } + + /// + /// Set a user's password. + /// + /// Handle to an open User. + /// A + /// object containing the new password. + /// + /// One of the + /// enumeration values indicating + /// whether the password-expired state is to be explicitly set or + /// left as is. + /// + private void SetUserPassword(IntPtr userHandle, + System.Security.SecureString password, + PasswordExpiredState passwordExpired) + { + if (password != null) + { + USER_SET_PASSWORD_INFORMATION info = new USER_SET_PASSWORD_INFORMATION(); + IntPtr buffer = IntPtr.Zero; + + try + { + bool setPwExpire = false; + + switch (passwordExpired) + { + case PasswordExpiredState.Expired: + setPwExpire = true; + break; + + case PasswordExpiredState.NotExpired: + setPwExpire = false; + break; + + case PasswordExpiredState.Unchanged: + setPwExpire = IsPasswordExpired(userHandle); + break; + } + + info.Password = new UNICODE_STRING(password.AsString()); + info.PasswordExpired = setPwExpire; + + buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); + Marshal.StructureToPtr(info, buffer, false); + + var status = SamApi.SamSetInformationUser(userHandle, + USER_INFORMATION_CLASS.UserSetPasswordInformation, + buffer); + ThrowOnFailure(status); + } + finally + { + if (buffer != IntPtr.Zero) + { + Marshal.DestroyStructure(buffer); + Marshal.FreeHGlobal(buffer); + } + } + } + } + +#region Utility Methods + /// + /// Create a + /// object from a relative ID. + /// + /// + /// Handle to the domain from which the ID was acquired. + /// + /// + /// The Relative ID value. + /// + /// + /// A SecurityIdentifier object containing the SID of the + /// object identified by the parameter. + /// + private SecurityIdentifier RidToSid(IntPtr domainHandle, uint rid) + { + IntPtr sidBytes = IntPtr.Zero; + UInt32 status = 0; + SecurityIdentifier sid = null; + + try + { + status = SamApi.SamRidToSid(domainHandle, rid, out sidBytes); + + if (status == NtStatus.STATUS_NOT_FOUND) + throw new InternalException(status, + StringUtil.Format(Strings.RidToSidFailed, rid), + ErrorCategory.ObjectNotFound); + ThrowOnFailure(status); + + sid = new SecurityIdentifier(sidBytes); + } + finally + { + if (IntPtr.Zero != sidBytes) + status = SamApi.SamFreeMemory(sidBytes); + } + + return sid; + } + + /// + /// Lookup the account identified by the specified SID. + /// + /// + /// A object identifying the account + /// to look up. + /// + /// + /// A object contains information about the + /// account, or null if no matching account was found. + /// + private AccountInfo LookupAccountInfo(SecurityIdentifier sid) + { + var sbAccountName = new StringBuilder(); + var sbDomainName = new StringBuilder(); + var accountNameLength = sbAccountName.Capacity; + var domainNameLength = sbDomainName.Capacity; + SID_NAME_USE use; + var error = Win32.NO_ERROR; + var bytes = new byte[sid.BinaryLength]; + + sid.GetBinaryForm(bytes, 0); + + if (!Win32.LookupAccountSid(null, + bytes, + sbAccountName, ref accountNameLength, + sbDomainName, ref domainNameLength, + out use)) + { + error = Marshal.GetLastWin32Error(); + + if (error == Win32.ERROR_INSUFFICIENT_BUFFER) + { + sbAccountName.EnsureCapacity(accountNameLength); + sbDomainName.EnsureCapacity((int)domainNameLength); + error = Win32.NO_ERROR; + if (!Win32.LookupAccountSid(null, + bytes, + sbAccountName, ref accountNameLength, + sbDomainName, ref domainNameLength, + out use)) + error = Marshal.GetLastWin32Error(); + } + } + + if (error == Win32.ERROR_SUCCESS) + return new AccountInfo + { + AccountName = sbAccountName.ToString(), + DomainName = sbDomainName.ToString(), + Sid = sid, + Use = use + }; + else if (error == Win32.ERROR_NONE_MAPPED) + return null; + else + throw new Win32InternalException(error, context.target); + } + + /// + /// Lookup the account identified by specified account name. + /// + /// + /// A string containing the name of the account to look up. + /// + /// + /// A object contains information about the + /// account, or null if no matching account was found. + /// + private AccountInfo LookupAccountInfo(string accountName) + { + var sbDomainName = new StringBuilder(); + var domainNameLength = (uint)sbDomainName.Capacity; + byte [] sid = null; + uint sidLength = 0; + SID_NAME_USE use; + int error = Win32.NO_ERROR; + + if (!Win32.LookupAccountName(null, + accountName, + sid, + ref sidLength, + sbDomainName, + ref domainNameLength, + out use)) + { + error = Marshal.GetLastWin32Error(); + if (error == Win32.ERROR_INSUFFICIENT_BUFFER || error == Win32.ERROR_INVALID_FLAGS) + { + sid = new byte[sidLength]; + sbDomainName.EnsureCapacity((int)domainNameLength); + error = Win32.NO_ERROR; + + if (!Win32.LookupAccountName(null, + accountName, + sid, + ref sidLength, + sbDomainName, + ref domainNameLength, + out use)) + error = Marshal.GetLastWin32Error(); + } + + } + + if (error == Win32.ERROR_SUCCESS) + { + // Bug: 7407413 : + // If accountname is in the format domain1\user1, + // then AccountName.ToString() will return domain1\domain1\user1 + // Ideally , accountname should be processed to hold only account name (without domain) + // as we are keeping the domain in 'DomainName' variable. + + int index = accountName.IndexOf("\\", StringComparison.CurrentCultureIgnoreCase); + if (index > -1) + { + accountName = accountName.Substring(index + 1); + } + + return new AccountInfo + { + AccountName = accountName, + DomainName = sbDomainName.ToString(), + Sid = new SecurityIdentifier(sid, 0), + Use = use + }; + } + else if (error == Win32.ERROR_NONE_MAPPED) + return null; + else if (error == Win32.ERROR_ACCESS_DENIED) + throw new AccessDeniedException(context.target); + else + throw new Win32InternalException(error, context.target); + } + + /// + /// Create a object from information in + /// an AccountInfo object. + /// + /// + /// An AccountInfo object containing information about the account + /// for which the LocalPrincipal object is being created. This parameter + /// may be null, in which case this method returns null. + /// + /// + /// A new LocalPrincipal object representing the account, or null if the + /// parameter is null. + /// + private LocalPrincipal MakeLocalPrincipalObject(AccountInfo info) + { + if (info == null) + return null; // this is a legitimate case + + var rv = new LocalPrincipal(info.ToString()); + rv.SID = info.Sid; + rv.PrincipalSource = GetPrincipalSource(info); + + switch (info.Use) + { + case SID_NAME_USE.SidTypeAlias: // TODO: is this the right thing to do??? + case SID_NAME_USE.SidTypeGroup: + case SID_NAME_USE.SidTypeWellKnownGroup: + rv.ObjectClass = Strings.ObjectClassGroup; + break; + + case SID_NAME_USE.SidTypeUser: + rv.ObjectClass = Strings.ObjectClassUser; + break; + + default: + rv.ObjectClass = Strings.ObjectClassOther; + break; + } + + return rv; + } + + /// + /// Indicate whether a Status code is a successful value. + /// + /// + /// One of the NTSTATUS code values indicating the error, if any. + /// + /// + /// True if the Status code represents a success, false otherwise. + /// + private static bool Succeeded(UInt32 ntStatus) + { + return NtStatus.IsSuccess(ntStatus); + } + + /// + /// Helper to throw an exception if the provided Status code + /// represents a failure. + /// + /// + /// One of the NTSTATUS code values indicating the error, if any. + /// + /// + /// A object containing information about the + /// current operation. If this parameter is null, the class's context + /// is used. + /// + private void ThrowOnFailure(UInt32 ntStatus, Context context = null) + { + if (NtStatus.IsError(ntStatus)) + { + var ex = MakeException(ntStatus, context); + + if (ex != null) + throw ex; + } + } + + /// + /// Create an appropriate exception from the specified status code. + /// + /// + /// One of the NTSTATUS code values indicating the error, if any. + /// + /// + /// A object containing information about the + /// current operation. If this parameter is null, the class's context + /// is used. + /// + /// + /// An object, or an object derived from Exception, + /// appropriate to the error. If does not + /// indicate an error, the method returns null. + /// + private Exception MakeException(UInt32 ntStatus, Context context = null) + { + if (!NtStatus.IsError(ntStatus)) + return null; + + if (context == null) + context = this.context; + + switch (ntStatus) + { + case NtStatus.STATUS_ACCESS_DENIED: + return new AccessDeniedException(context.target); + + case NtStatus.STATUS_INVALID_ACCOUNT_NAME: + return new InvalidNameException(context.ObjectName, context.target); + + case NtStatus.STATUS_USER_EXISTS: + if (context.operation == ContextOperation.New && + context.type == ContextObjectType.User) + { + return new UserExistsException(context.ObjectName, context.target); + } + else + { + return new NameInUseException(context.ObjectName, context.target); + } + + case NtStatus.STATUS_ALIAS_EXISTS: + if (context.operation == ContextOperation.New && + context.type == ContextObjectType.Group) + { + return new GroupExistsException(context.ObjectName, context.target); + } + else + { + return new NameInUseException(context.ObjectName, context.target); + } + + case NtStatus.STATUS_GROUP_EXISTS: + return new NameInUseException(context.ObjectName, context.target); + + case NtStatus.STATUS_NO_SUCH_ALIAS: + case NtStatus.STATUS_NO_SUCH_GROUP: + return new GroupNotFoundException(context.ObjectName, context.target); + + case NtStatus.STATUS_NO_SUCH_USER: + return new UserNotFoundException(context.ObjectName, context.target); + + case NtStatus.STATUS_SPECIAL_GROUP: // The group specified is a special group and cannot be operated on in the requested fashion. + // case NtStatus.STATUS_SPECIAL_ALIAS: // referred to in source for SAM api, but not in ntstatus.h!!! + + return new InvalidOperationException(StringUtil.Format(Strings.InvalidForGroup, context.ObjectName)); + + case NtStatus.STATUS_SPECIAL_USER: // The user specified is a special user and cannot be operated on in the requested fashion. + return new InvalidOperationException(StringUtil.Format(Strings.InvalidForUser, context.ObjectName)); + + case NtStatus.STATUS_NO_SUCH_MEMBER: + return new MemberNotFoundException(context.MemberName, context.ObjectName); + + case NtStatus.STATUS_MEMBER_IN_ALIAS: + case NtStatus.STATUS_MEMBER_IN_GROUP: + if (context.operation == ContextOperation.Remove && + context.type == ContextObjectType.Group) + { + return new InvalidOperationException(StringUtil.Format(Strings.GroupHasMembers, context.ObjectName)); + } + else + { + return new MemberExistsException(context.MemberName, context.ObjectName, context.target); + } + + case NtStatus.STATUS_MEMBER_NOT_IN_ALIAS: + case NtStatus.STATUS_MEMBER_NOT_IN_GROUP: + return new MemberNotFoundException(context.MemberName, context.ObjectName); + + case NtStatus.STATUS_MEMBERS_PRIMARY_GROUP: + return new InvalidOperationException(StringUtil.Format(Strings.MembersPrimaryGroup, context.ObjectName)); + + case NtStatus.STATUS_LAST_ADMIN: // Cannot delete the last administrator. + return new InvalidOperationException(Strings.LastAdmin); + + case NtStatus.STATUS_ILL_FORMED_PASSWORD: + case NtStatus.STATUS_PASSWORD_RESTRICTION: + return new InvalidPasswordException(Native.Win32.RtlNtStatusToDosError(ntStatus)); + + // TODO: do we want to handle these? + // they appear to be returned only in functions we are not calling + case NtStatus.STATUS_INVALID_SID: // member sid is corrupted + case NtStatus.STATUS_INVALID_MEMBER: // member has wrong account type + default: + return new InternalException(ntStatus, context.target); + } + } + + /// + /// Create a DateTime object from a 64-bit value from one of the SAM + /// structures. + /// + /// + /// A signed 64-bit value representing a date and time. + /// + /// + /// A nullable DateTime object representing a date and time, + /// or null if the parameter is zero. + /// + private static DateTime? DateTimeFromSam(Int64 samValue) + { + if (samValue == 0 || samValue == 0X7FFFFFFFFFFFFFFF) + return null; + + return DateTime.FromFileTime(samValue); + } + + /// + /// Determine the source of a user or group. Either local, Active Directory, + /// or Azure AD. + /// + /// + /// A object identifying the user or group. + /// + /// + /// One of the enumerations identifying the + /// source of the object. + /// + private PrincipalSource? GetPrincipalSource(SecurityIdentifier sid) + { + var bSid = new byte[sid.BinaryLength]; + + sid.GetBinaryForm(bSid, 0); + + var type = LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType; + + // Use LsaLookupUserAccountType for Windows 10 and later. + // Earlier versions of the OS will leave the property NULL because + // it is too error prone to attempt to replicate the decisions of + // LsaLookupUserAccountType. + var os = GetOperatingSystem(); + if (os.Version.Major >= 10) + { + UInt32 status = Native.Win32.LsaLookupUserAccountType(bSid, out type); + if (NtStatus.IsError(status)) + type = LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType; + + switch (type) + { + case LSA_USER_ACCOUNT_TYPE.ExternalDomainUserAccountType: + case LSA_USER_ACCOUNT_TYPE.PrimaryDomainUserAccountType: + return PrincipalSource.ActiveDirectory; + + case LSA_USER_ACCOUNT_TYPE.LocalUserAccountType: + return PrincipalSource.Local; + + case LSA_USER_ACCOUNT_TYPE.AADUserAccountType: + return PrincipalSource.AzureAD; + + // Currently, there is no value returned by LsaLookupUserAccountType + // that corresponds to LSA_USER_ACCOUNT_TYPE.MSAUserAccountType, + // but there may be in the future, so we'll account for it here. + case LSA_USER_ACCOUNT_TYPE.MSAUserAccountType: + case LSA_USER_ACCOUNT_TYPE.LocalConnectedUserAccountType: + return PrincipalSource.MicrosoftAccount; + + case LSA_USER_ACCOUNT_TYPE.InternetUserAccountType: + return sid.IsMsaAccount() + ? PrincipalSource.MicrosoftAccount + : PrincipalSource.Unknown; + + case LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType: + default: + return PrincipalSource.Unknown; + } + } + else + { + return null; + } + } + + /// + /// Determine the source of a user or group. Either local, Active Directory, + /// or Azure AD. + /// + /// + /// An object containing information about the + /// user or group. + /// + /// + /// One of the enumerations identifying the + /// source of the object. + /// + private PrincipalSource? GetPrincipalSource(AccountInfo info) + { + return GetPrincipalSource(info.Sid); + } + + /// + /// Determine the source of a user or group. Either local, Active Directory, + /// or Azure AD. + /// + /// + /// A object identifying the user or group. + /// + /// + /// One of the enumerations identifying the + /// source of the object. + /// + private PrincipalSource? GetPrincipalSource(SamRidEnumeration sre) + { + return GetPrincipalSource(RidToSid(sre.domainHandle, sre.RelativeId)); + } + +#if CORECLR + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct OSVERSIONINFOEX + { + // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) + public int OSVersionInfoSize; + public int MajorVersion; + public int MinorVersion; + public int BuildNumber; + public int PlatformId; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string CSDVersion; + public ushort ServicePackMajor; + public ushort ServicePackMinor; + public short SuiteMask; + public byte ProductType; + public byte Reserved; + } + + [DllImport(PInvokeDllNames.GetVersionExDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx); + + private static volatile OperatingSystem localOs; + + /// + /// It only contains the properties that get used in powershell. + /// + internal sealed class OperatingSystem + { + private Version _version; + private string _servicePack; + private string _versionString; + + internal OperatingSystem(Version version, string servicePack) + { + ArgumentNullException.ThrowIfNull(version); + + _version = version; + _servicePack = servicePack; + } + + /// + /// OS version. + /// + public Version Version + { + get { return _version; } + } + + /// + /// VersionString. + /// + public string VersionString + { + get + { + if (_versionString != null) + { + return _versionString; + } + + // It's always 'VER_PLATFORM_WIN32_NT' for NanoServer and IoT + const string os = "Microsoft Windows NT "; + if (string.IsNullOrEmpty(_servicePack)) + { + _versionString = os + _version.ToString(); + } + else + { + _versionString = os + _version.ToString(3) + " " + _servicePack; + } + + return _versionString; + } + } + } +#endif + + // Wraps calls to acquire the OperatingSystem version + private OperatingSystem GetOperatingSystem() + { +#if CORECLR + if (localOs == null) + { + OSVERSIONINFOEX osviex = new OSVERSIONINFOEX(); + osviex.OSVersionInfoSize = Marshal.SizeOf(osviex); + if (!GetVersionEx(ref osviex)) + { + int errorCode = Marshal.GetLastWin32Error(); + throw new Win32Exception(errorCode); + } + + Version ver = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor); + localOs = new OperatingSystem(ver, osviex.CSDVersion); + } + + return localOs; +#else + return Environment.OSVersion; +#endif + } +#endregion Utility Methods +#endregion Private Methods + +#region IDisposable Support + private bool disposedValue = false; // To detect redundant calls + + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + { + UInt32 status = 0; + + if (disposing) + { + // no managed objects need disposing. + } + + if (builtinDomainHandle != IntPtr.Zero) + { + status = SamApi.SamCloseHandle(builtinDomainHandle); + builtinDomainHandle = IntPtr.Zero; + } + + if (localDomainHandle != IntPtr.Zero) + { + status = SamApi.SamCloseHandle(localDomainHandle); + localDomainHandle = IntPtr.Zero; + } + + if (samHandle != IntPtr.Zero) + { + status = SamApi.SamCloseHandle(samHandle); + samHandle = IntPtr.Zero; + } + + if (NtStatus.IsError(status)) + { + // Do nothing to satisfy CA1806: Do not ignore method results. We want the dispose to proceed regardless of the handle close status. + } + + disposedValue = true; + } + } + + // override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. + ~Sam() + { + // Do not change this code. Put cleanup code in Dispose(bool disposing) above. + Dispose(false); + } + + // This code added to correctly implement the disposable pattern. + public void Dispose() + { + // Do not change this code. Put cleanup code in Dispose(bool disposing) above. + Dispose(true); + // uncomment the following line if the finalizer is overridden above. + GC.SuppressFinalize(this); + } +#endregion IDisposable Support + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs new file mode 100644 index 0000000000000000000000000000000000000000..c2d9bc7f95b037837dbe6619642036312f4285ca --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs @@ -0,0 +1,468 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +//using System.Management.Automation.SecurityAccountsManager.Native; + +namespace System.Management.Automation.SecurityAccountsManager.Native.NtSam +{ + #region Enums + internal enum ALIAS_INFORMATION_CLASS + { + AliasGeneralInformation = 1, + AliasNameInformation, + AliasAdminCommentInformation, + AliasReplicationInformation, + AliasExtendedInformation, + } + + internal enum GROUP_INFORMATION_CLASS + { + GroupGeneralInformation = 1, + GroupNameInformation, + GroupAttributeInformation, + GroupAdminCommentInformation, + GroupReplicationInformation + } + + internal enum USER_INFORMATION_CLASS + { + UserGeneralInformation = 1, + UserPreferencesInformation, + UserLogonInformation, + UserLogonHoursInformation, + UserAccountInformation, + UserNameInformation, + UserAccountNameInformation, + UserFullNameInformation, + UserPrimaryGroupInformation, + UserHomeInformation, + UserScriptInformation, + UserProfileInformation, + UserAdminCommentInformation, + UserWorkStationsInformation, + UserSetPasswordInformation, + UserControlInformation, + UserExpiresInformation, + UserInternal1Information, + UserInternal2Information, + UserParametersInformation, + UserAllInformation, + UserInternal3Information, + UserInternal4Information, + UserInternal5Information, + UserInternal4InformationNew, + UserInternal5InformationNew, + UserInternal6Information, + UserExtendedInformation, + UserLogonUIInformation, + } + + #endregion Enums + + #region Structures + [StructLayout(LayoutKind.Sequential)] + internal struct SR_SECURITY_DESCRIPTOR + { + public UInt32 Length; + public IntPtr SecurityDescriptor; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct LOGON_HOURS + { + public UInt16 UnitsPerWeek; + + // + // UnitsPerWeek is the number of equal length time units the week is + // divided into. This value is used to compute the length of the bit + // string in logon_hours. Must be less than or equal to + // SAM_UNITS_PER_WEEK (10080) for this release. + // + // LogonHours is a bit map of valid logon times. Each bit represents + // a unique division in a week. The largest bit map supported is 1260 + // bytes (10080 bits), which represents minutes per week. In this case + // the first bit (bit 0, byte 0) is Sunday, 00:00:00 - 00-00:59; bit 1, + // byte 0 is Sunday, 00:01:00 - 00:01:59, etc. A NULL pointer means + // DONT_CHANGE for SamSetInformationUser() calls. + // + + public IntPtr LogonHours; + } + + [StructLayout(LayoutKind.Sequential, Pack=4)] + internal struct USER_ALL_INFORMATION + { + public LARGE_INTEGER LastLogon; + public LARGE_INTEGER LastLogoff; + public LARGE_INTEGER PasswordLastSet; + public LARGE_INTEGER AccountExpires; + public LARGE_INTEGER PasswordCanChange; + public LARGE_INTEGER PasswordMustChange; + public UNICODE_STRING UserName; + public UNICODE_STRING FullName; + public UNICODE_STRING HomeDirectory; + public UNICODE_STRING HomeDirectoryDrive; + public UNICODE_STRING ScriptPath; + public UNICODE_STRING ProfilePath; + public UNICODE_STRING AdminComment; + public UNICODE_STRING WorkStations; + public UNICODE_STRING UserComment; + public UNICODE_STRING Parameters; + public UNICODE_STRING LmPassword; + public UNICODE_STRING NtPassword; + public UNICODE_STRING PrivateData; + public SR_SECURITY_DESCRIPTOR SecurityDescriptor; + public UInt32 UserId; + public UInt32 PrimaryGroupId; + public UInt32 UserAccountControl; + public UInt32 WhichFields; + public LOGON_HOURS LogonHours; + public UInt16 BadPasswordCount; + public UInt16 LogonCount; + public UInt16 CountryCode; + public UInt16 CodePage; + [MarshalAs(UnmanagedType.I1)] + public bool LmPasswordPresent; + [MarshalAs(UnmanagedType.I1)] + public bool NtPasswordPresent; + [MarshalAs(UnmanagedType.I1)] + public bool PasswordExpired; + [MarshalAs(UnmanagedType.I1)] + public bool PrivateDataSensitive; + } + + [StructLayout(LayoutKind.Sequential, Pack=4)] + internal struct USER_GENERAL_INFORMATION + { + public UNICODE_STRING UserName; + public UNICODE_STRING FullName; + public UInt32 PrimaryGroupId; + public UNICODE_STRING AdminComment; + public UNICODE_STRING UserComment; + } + + [StructLayout(LayoutKind.Sequential, Pack=4)] + internal struct USER_LOGON_INFORMATION + { + public UNICODE_STRING UserName; + public UNICODE_STRING FullName; + public UInt32 UserId; + public UInt32 PrimaryGroupId; + public UNICODE_STRING HomeDirectory; + public UNICODE_STRING HomeDirectoryDrive; + public UNICODE_STRING ScriptPath; + public UNICODE_STRING ProfilePath; + public UNICODE_STRING WorkStations; + public LARGE_INTEGER LastLogon; + public LARGE_INTEGER LastLogoff; + public LARGE_INTEGER PasswordLastSet; + public LARGE_INTEGER PasswordCanChange; + public LARGE_INTEGER PasswordMustChange; + public LOGON_HOURS LogonHours; + public UInt16 BadPasswordCount; + public UInt16 LogonCount; + public UInt32 UserAccountControl; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_ACCOUNT_NAME_INFORMATION + { + public UNICODE_STRING UserName; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_FULL_NAME_INFORMATION + { + public UNICODE_STRING FullName; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_NAME_INFORMATION + { + public UNICODE_STRING UserName; + public UNICODE_STRING FullName; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_ADMIN_COMMENT_INFORMATION + { + UNICODE_STRING AdminComment; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_EXPIRES_INFORMATION + { + // LARGE_INTEGER AccountExpires; + public Int64 AccountExpires; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_SET_PASSWORD_INFORMATION + { + public UNICODE_STRING Password; + public bool PasswordExpired; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct USER_LOGON_HOURS_INFORMATION + { + public LOGON_HOURS LogonHours; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct POLICY_PRIMARY_DOMAIN_INFO + { + public UNICODE_STRING Name; + public IntPtr Sid; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct ALIAS_GENERAL_INFORMATION + { + public UNICODE_STRING Name; + public UInt32 MemberCount; + public UNICODE_STRING AdminComment; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct ALIAS_NAME_INFORMATION + { + public UNICODE_STRING Name; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct ALIAS_ADM_COMMENT_INFORMATION + { + public UNICODE_STRING AdminComment; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SAMPR_GROUP_GENERAL_INFORMATION + { + public UNICODE_STRING Name; + public UInt32 Attributes; + public UInt32 MemberCount; + public UNICODE_STRING AdminComment; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SAMPR_GROUP_NAME_INFORMATION + { + public UNICODE_STRING Name; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SAM_RID_ENUMERATION + { + public UInt32 RelativeId; + public UNICODE_STRING Name; + } + #endregion Structures + + /// + /// Provides methods for invoking functions in the Windows + /// Security Accounts Manager (SAM) API. + /// + internal static class SamApi + { + #region Constants + // Account enumeration filters, may be combined by bitwise OR + internal const UInt32 SAM_USER_ENUMERATION_FILTER_LOCAL = 0x00000001; + internal const UInt32 SAM_USER_ENUMERATION_FILTER_INTERNET = 0x00000002; + internal const UInt32 SAM_SERVER_LOOKUP_DOMAIN = 0x0020; + + // + // Bits to be used in UserAllInformation's WhichFields field (to indicate + // which items were queried or set). + // + internal const UInt32 USER_ALL_USERNAME = 0x00000001; + internal const UInt32 USER_ALL_FULLNAME = 0x00000002; + internal const UInt32 USER_ALL_USERID = 0x00000004; + internal const UInt32 USER_ALL_PRIMARYGROUPID = 0x00000008; + internal const UInt32 USER_ALL_ADMINCOMMENT = 0x00000010; + internal const UInt32 USER_ALL_USERCOMMENT = 0x00000020; + internal const UInt32 USER_ALL_HOMEDIRECTORY = 0x00000040; + internal const UInt32 USER_ALL_HOMEDIRECTORYDRIVE = 0x00000080; + internal const UInt32 USER_ALL_SCRIPTPATH = 0x00000100; + internal const UInt32 USER_ALL_PROFILEPATH = 0x00000200; + internal const UInt32 USER_ALL_WORKSTATIONS = 0x00000400; + internal const UInt32 USER_ALL_LASTLOGON = 0x00000800; + internal const UInt32 USER_ALL_LASTLOGOFF = 0x00001000; + internal const UInt32 USER_ALL_LOGONHOURS = 0x00002000; + internal const UInt32 USER_ALL_BADPASSWORDCOUNT = 0x00004000; + internal const UInt32 USER_ALL_LOGONCOUNT = 0x00008000; + internal const UInt32 USER_ALL_PASSWORDCANCHANGE = 0x00010000; + internal const UInt32 USER_ALL_PASSWORDMUSTCHANGE = 0x00020000; + internal const UInt32 USER_ALL_PASSWORDLASTSET = 0x00040000; + internal const UInt32 USER_ALL_ACCOUNTEXPIRES = 0x00080000; + internal const UInt32 USER_ALL_USERACCOUNTCONTROL = 0x00100000; + internal const UInt32 USER_ALL_PARAMETERS = 0x00200000; // ntsubauth + internal const UInt32 USER_ALL_COUNTRYCODE = 0x00400000; + internal const UInt32 USER_ALL_CODEPAGE = 0x00800000; + internal const UInt32 USER_ALL_NTPASSWORDPRESENT = 0x01000000; // field AND boolean + internal const UInt32 USER_ALL_LMPASSWORDPRESENT = 0x02000000; // field AND boolean + internal const UInt32 USER_ALL_PRIVATEDATA = 0x04000000; // field AND boolean + internal const UInt32 USER_ALL_PASSWORDEXPIRED = 0x08000000; + internal const UInt32 USER_ALL_SECURITYDESCRIPTOR = 0x10000000; + internal const UInt32 USER_ALL_OWFPASSWORD = 0x20000000; // boolean + + internal const UInt32 USER_ALL_UNDEFINED_MASK = 0xC0000000; + + // + // Bit masks for the UserAccountControl member of the USER_ALL_INFORMATION structure + // + internal const UInt32 USER_ACCOUNT_DISABLED = 0x00000001; + internal const UInt32 USER_HOME_DIRECTORY_REQUIRED = 0x00000002; + internal const UInt32 USER_PASSWORD_NOT_REQUIRED = 0x00000004; + internal const UInt32 USER_TEMP_DUPLICATE_ACCOUNT = 0x00000008; + internal const UInt32 USER_NORMAL_ACCOUNT = 0x00000010; + internal const UInt32 USER_MNS_LOGON_ACCOUNT = 0x00000020; + internal const UInt32 USER_INTERDOMAIN_TRUST_ACCOUNT = 0x00000040; + internal const UInt32 USER_WORKSTATION_TRUST_ACCOUNT = 0x00000080; + internal const UInt32 USER_SERVER_TRUST_ACCOUNT = 0x00000100; + internal const UInt32 USER_DONT_EXPIRE_PASSWORD = 0x00000200; + internal const UInt32 USER_ACCOUNT_AUTO_LOCKED = 0x00000400; + internal const UInt32 USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x00000800; + internal const UInt32 USER_SMARTCARD_REQUIRED = 0x00001000; + internal const UInt32 USER_TRUSTED_FOR_DELEGATION = 0x00002000; + internal const UInt32 USER_NOT_DELEGATED = 0x00004000; + internal const UInt32 USER_USE_DES_KEY_ONLY = 0x00008000; + internal const UInt32 USER_DONT_REQUIRE_PREAUTH = 0x00010000; + internal const UInt32 USER_PASSWORD_EXPIRED = 0x00020000; + internal const UInt32 USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x00040000; + internal const UInt32 USER_NO_AUTH_DATA_REQUIRED = 0x00080000; + internal const UInt32 USER_PARTIAL_SECRETS_ACCOUNT = 0x00100000; + internal const UInt32 USER_USE_AES_KEYS = 0x00200000; + + // + // Access rights for user object + // + internal const UInt16 USER_CHANGE_PASSWORD = 0x0040; + #endregion Constants + + #region Sam Functions + [DllImport("samlib.dll")] + public static extern UInt32 SamConnect(ref UNICODE_STRING serverName, + out IntPtr serverHandle, + UInt32 desiredAccess, + ref OBJECT_ATTRIBUTES objectAttributes); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamRidToSid(IntPtr objectHandle, UInt32 rid, out IntPtr sid); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamCloseHandle(IntPtr serverHandle); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamFreeMemory(IntPtr buffer); + + #region Domain Functions + [DllImport("samlib.dll")] + internal static extern UInt32 SamOpenDomain(IntPtr serverHandle, + UInt32 desiredAccess, + IntPtr domainId, + out IntPtr domainHandle); + #endregion Domain Functions + + #region Alias Functions + [DllImport("samlib.dll")] + internal static extern UInt32 SamEnumerateAliasesInDomain(IntPtr domainHandle, + ref UInt32 enumerationContext, + out IntPtr buffer, + UInt32 preferredMaximumLength, + out UInt32 countReturned); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamCreateAliasInDomain(IntPtr domainHandle, + IntPtr accountName, // PUNICODE_STRING + UInt32 desiredAccess, + out IntPtr aliasHandle, + out UInt32 relativeId); // PULONG + + [DllImport("samlib.dll")] + internal static extern UInt32 SamOpenAlias(IntPtr domainHandle, + UInt32 desiredAccess, + UInt32 aliasId, + out IntPtr aliasHandle); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamQueryInformationAlias(IntPtr aliasHandle, + ALIAS_INFORMATION_CLASS aliasInformationClass, + out IntPtr buffer); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamSetInformationAlias(IntPtr aliasHandle, + ALIAS_INFORMATION_CLASS aliasInformationClass, + IntPtr buffer); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamDeleteAlias(IntPtr aliasHandle); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamAddMemberToAlias(IntPtr aliasHandle, + byte[] memberId); // PSID + + [DllImport("samlib.dll")] + internal static extern UInt32 SamRemoveMemberFromAlias(IntPtr aliasHandle, + byte[] memberId); // PSID + + [DllImport("samlib.dll")] + internal static extern UInt32 SamGetMembersInAlias(IntPtr aliasHandle, + out IntPtr memberIds, // PSID ** + out UInt32 memberCount); + #endregion Alias Functions + + #region User Functions + [DllImport("samlib.dll")] + internal static extern UInt32 SamOpenUser(IntPtr domainHandle, + UInt32 desiredAccess, + UInt32 userID, + out IntPtr userHandle); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamDeleteUser(IntPtr aliasHandle); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamEnumerateUsersInDomain(IntPtr domainHandle, + ref UInt32 enumerationContext, + UInt32 userAccountControl, + out IntPtr buffer, + UInt32 preferredMaximumLength, + out UInt32 countReturned); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamCreateUser2InDomain(IntPtr domainHandle, + ref UNICODE_STRING accountName, + Int32 accountType, + UInt32 desiredAccess, + out IntPtr userHandle, + out UInt32 grantedAccess, + out UInt32 relativeId); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamQueryInformationUser(IntPtr userHandle, + USER_INFORMATION_CLASS userInformationClass, + out IntPtr buffer); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamSetInformationUser(IntPtr userHandle, + USER_INFORMATION_CLASS userInformationClass, + IntPtr buffer); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamQuerySecurityObject(IntPtr objectHandle, + UInt32 securityInformation, + out IntPtr securityDescriptor); + + [DllImport("samlib.dll")] + internal static extern UInt32 SamSetSecurityObject(IntPtr objectHandle, + UInt32 SecurityInformation, + IntPtr SecurityDescriptor); + #endregion User Functions + #endregion Sam Functions + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs new file mode 100644 index 0000000000000000000000000000000000000000..25bbeb49329962419719d9e87f148001e44ffa3c --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Globalization; +using System.Management.Automation.SecurityAccountsManager.Native; + +namespace System.Management.Automation.SecurityAccountsManager +{ + /// + /// Contains utility functions for formatting localizable strings. + /// + internal class StringUtil + { + /// + /// Private constructor to present auto-generation of a default constructor with greater accessibility. + /// + private StringUtil() + { + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal static string Format(string str) + { + return string.Format(CultureInfo.CurrentCulture, str); + } + + internal static string Format(string fmt, string p0) + { + return string.Format(CultureInfo.CurrentCulture, fmt, p0); + } + + internal static string Format(string fmt, string p0, string p1) + { + return string.Format(CultureInfo.CurrentCulture, fmt, p0, p1); + } + + internal static string Format(string fmt, uint p0) + { + return string.Format(CultureInfo.CurrentCulture, fmt, p0); + } + + internal static string Format(string fmt, int p0) + { + return string.Format(CultureInfo.CurrentCulture, fmt, p0); + } + + internal static string FormatMessage(uint messageId, string[] args) + { + var message = new System.Text.StringBuilder(256); + UInt32 flags = Win32.FORMAT_MESSAGE_FROM_SYSTEM; + + if (args == null) + flags |= Win32.FORMAT_MESSAGE_IGNORE_INSERTS; + else + flags |= Win32.FORMAT_MESSAGE_ARGUMENT_ARRAY; + + var length = Win32.FormatMessage(flags, IntPtr.Zero, messageId, 0, message, 256, args); + + if (length > 0) + return message.ToString(); + + return null; + } + + internal static string GetSystemMessage(uint messageId) + { + return FormatMessage(messageId, null); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj new file mode 100644 index 0000000000000000000000000000000000000000..a85b06d4f907c5b99e0a32cf1653ef6e0e8480dc --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj @@ -0,0 +1,14 @@ + + + + + + PowerShell's Microsoft.PowerShell.LocalAccounts project + Microsoft.PowerShell.LocalAccounts + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx new file mode 100644 index 0000000000000000000000000000000000000000..ff1c4a1742795c99bc4179a069e4f1bf85ef1fc8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx @@ -0,0 +1,234 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Access denied. + + + Account {0} was not found. + + + Add member {0} + + + Disable local user + + + Enable local user + + + Create new local group + + + Create new local user + + + Remove local group + + + Remove member {0} + + + Remove local user + + + Rename local group to {0} + + + Rename local user to {0} + + + Modify local group + + + Modify local user + + + Group {0} already exists. + + + The group {0} still has members. + + + Group {0} was not found. + + + The operation is not allowed for group {0}. + + + The operation is not allowed for user {0}. + + + The name {0} is invalid. + + + Parameter {0} and parameter {1} may not be used together. + + + Invalid password. + + + Cannot remove the last Administrator + + + {0} is already a member of group {1}. + + + Member {0} was not found in group {1}. + + + User {0} may not be removed from its primary group. + + + The name {0} is already in use. + + + Group + + + Other + + + User + + + The password cannot be set because a password restriction is in place. + + + Principal {0} was not found. + + + RID {0} was not found. + + + An unspecified error occurred. + + + An unspecified error occurred: status = {0} + + + An unspecified error occurred: error code = {0} + + + User {0} already exists. + + + User {0} was not found. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/PowerShell-master/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj new file mode 100644 index 0000000000000000000000000000000000000000..ecc224713cc51b2404951535cdff01d208d1ed59 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -0,0 +1,55 @@ + + + + PowerShell SDK metapackage + Microsoft.PowerShell.SDK + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_RefAssemblyPath Include="%(_ReferencesFromRAR.OriginalItemSpec)%3B" Condition=" '%(_ReferencesFromRAR.NuGetPackageId)' != 'Microsoft.Management.Infrastructure' " /> + + + + + \ No newline at end of file diff --git a/PowerShell-master/src/Microsoft.PowerShell.SDK/README.md b/PowerShell-master/src/Microsoft.PowerShell.SDK/README.md new file mode 100644 index 0000000000000000000000000000000000000000..95846dfa60de5c812275c22e9cd1d249494ff3b5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.SDK/README.md @@ -0,0 +1,8 @@ +Microsoft PowerShell SDK +======================== + +This is a meta-project that serves two purposes: + +1. Group PowerShell sub projects to avoid unnecessary duplication of reference declarations. +2. Group extra .NET Core packages that PowerShell doesn't depend on directly but must provide for our users at runtime. + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj b/PowerShell-master/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj new file mode 100644 index 0000000000000000000000000000000000000000..a6dadabfed27234e96406f1bae54f04dcfa0ee2e --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj @@ -0,0 +1,20 @@ + + + + PowerShell's Microsoft.PowerShell.Security project + $(NoWarn);CS1570;CA1416 + Microsoft.PowerShell.Security + + + + + + + + + + + + + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx new file mode 100644 index 0000000000000000000000000000000000000000..d4c08f78bab4f00ebcc58e430e73d92129e141f3 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Enter password: + + + Command cannot find any of the specified files. + + + The following file could not be found: {0}. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..c45c640bbb0d0486b3d7c6984d849e7c375fee5a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx @@ -0,0 +1,189 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + X509 Certificate Provider + + + Cannot find the X509 certificate at path {0}. + + + Cannot find the X509 certificate store at path {0}. + + + Cannot find the certificate store because the specified X509 store location {0} is not valid. + + + Cannot process the path because path {0} is not a valid certificate provider path. + + + Move certificate + + + Remove certificate + + + Remove certificate and its private key. + + + Invoke Certificate Manager + + + Item: {0} Destination: {1} + + + You cannot move a certificate container. + + + You cannot move a certificate from user store to or from machine. + + + You cannot move a certificate to the same store. + + + You cannot create an item other than certificate store. + + + Creating certificate stores under CurrentUser is not supported. + + + Deleting certificate stores under CurrentUser is not supported. + + + The destination is not a valid store. + + + Item: {0} + + + The store {0} is a built-in system store and cannot be deleted. + + + You cannot remove a certificate container. + + + Private key skipped. The certificate has no private key association. + + + The operation is on user root store and UI is not allowed. + + + . The following error may be a result of user credentials required on the remote machine. See Enable-WSManCredSSP Cmdlet help on how to enable and use CredSSP for delegation with PowerShell remoting. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx new file mode 100644 index 0000000000000000000000000000000000000000..9f47134f14726d8363293d38b66b3b12305edb28 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The path '{0}' must refer to a single file system path. + + + Cannot unprotect message. The input contained no encrypted content. + + + Cannot unprotect message. The input contained no encrypted content. Specify the '{0}' parameter if you wish to output the original content when no encrypted content is detected. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx new file mode 100644 index 0000000000000000000000000000000000000000..d1bb4f0b23c2f28c6642687b9162e7181ba7400a --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of {0}. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help Set-ExecutionPolicy". + + + Contact your system administrator. + + + Cannot get execution policy. Specify only the List or Scope parameters. + + + Cannot set execution policy. Execution policies at the MachinePolicy or UserPolicy scopes must be set through Group Policy. + + + Execution Policy Change + + + The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at https://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? + + + {0} +To change the execution policy for the default (LocalMachine) scope, start PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser". + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx new file mode 100644 index 0000000000000000000000000000000000000000..af2242e5828f5e7c9769fcb5bedff001be2c8e16 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Enter secret: + + + The system cannot protect plain text input. To suppress this warning and convert the plain text to a SecureString, reissue the command specifying the Force parameter. For more information, type: get-help ConvertTo-SecureString. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..e86df1947208ee28aa490394019c0a371586b404 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This PowerShell Snap-In contains cmdlets to manage PowerShell security. + + + Microsoft Corporation + + + Security PowerShell Snap-In. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx new file mode 100644 index 0000000000000000000000000000000000000000..cbbbd5e5712242dd724b30894598873f78eae0a8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot sign code. The specified certificate is not suitable for code signing. + + + Cannot sign code. The TimeStamp server URL must be fully qualified in the form of http://<server url> or https://<server url>. + + + The Get-AuthenticodeSignature cmdlet does not support directories. Supply a path to a file and retry. + + + File {0} was not found. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx new file mode 100644 index 0000000000000000000000000000000000000000..b067e9dc988f4f016bbcf1969a71185fe3cb2bf4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cannot digitally sign file because file {0} is smaller than 4 bytes in size. Files must be at least 4 bytes in order to be digitally signed. + + + Cannot perform the operation because it is not supported on the object found in path {0}. + + + Cannot get the ACL because the necessary method, GetSecurityDescriptor, does not exist. + + + Cannot set the ACL because the method that it needs to invoke, SetSecurityDescriptor, does not exist. + + + Could not perform operation because an exception was thrown during method invoke. + + + Could not create a SACL with the specified central access policy. + + + Could not create an empty SACL. + + + Could not enable SeSecurityPrivilege. + + + Could not set central access policy. + + + ClearCentralAccessPolicy and CentralAccessPolicy parameters cannot be used at the same time. + + + Central Access Policy identifier or name is not valid. If specifying an identifier, it must begin with S-1-17. If specifying a name, the policy must be applied on the target machine. + + + PowerShell credential request + + + Enter your credentials. + + diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/AclCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..e39b296d154652d83cf79ab364f033500f28db65 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -0,0 +1,1566 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable 1634, 1691 +#pragma warning disable 56506 + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Security; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the base class from which all Security Descriptor commands + /// are derived. + /// + public abstract class SecurityDescriptorCommandsBase : PSCmdlet + { + /// + /// Gets or sets the filter property. The filter + /// property allows for provider-specific filtering of results. + /// + [Parameter] + public string Filter + { + get + { + return _filter; + } + + set + { + _filter = value; + } + } + + /// + /// Gets or sets the include property. The include property + /// specifies the items on which the command will act. + /// + [Parameter] + public string[] Include + { + get + { + return _include; + } + + set + { + _include = value; + } + } + + /// + /// Gets or sets the exclude property. The exclude property + /// specifies the items on which the command will not act. + /// + [Parameter] + public string[] Exclude + { + get + { + return _exclude; + } + + set + { + _exclude = value; + } + } + + /// + /// The context for the command that is passed to the core command providers. + /// + internal CmdletProviderContext CmdletProviderContext + { + get + { + CmdletProviderContext coreCommandContext = new(this); + + Collection includeFilter = + SessionStateUtilities.ConvertArrayToCollection(Include); + + Collection excludeFilter = + SessionStateUtilities.ConvertArrayToCollection(Exclude); + + coreCommandContext.SetFilters(includeFilter, + excludeFilter, + Filter); + + return coreCommandContext; + } + } + + #region brokered properties + + /// + /// Add brokered properties for easy access to important properties + /// of security descriptor. + /// + internal static void AddBrokeredProperties( + Collection results, + bool audit, + bool allCentralAccessPolicies) + { + foreach (PSObject result in results) + { + if (audit) + { + // Audit + result.Properties.Add + ( + new PSCodeProperty + ( + "Audit", + typeof(SecurityDescriptorCommandsBase).GetMethod("GetAudit") + ) + ); + } + // CentralAccessPolicyId retrieval does not require elevation, so we always add this property. + result.Properties.Add + ( + new PSCodeProperty + ( + "CentralAccessPolicyId", + typeof(SecurityDescriptorCommandsBase).GetMethod("GetCentralAccessPolicyId") + ) + ); +#if !CORECLR // GetAllCentralAccessPolicies and GetCentralAccessPolicyName are not supported in OneCore powershell + // because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. + if (allCentralAccessPolicies) + { + // AllCentralAccessPolicies + result.Properties.Add + ( + new PSCodeProperty + ( + "AllCentralAccessPolicies", + typeof(SecurityDescriptorCommandsBase).GetMethod("GetAllCentralAccessPolicies") + ) + ); + } + // CentralAccessPolicyName retrieval does not require elevation, so we always add this property. + result.Properties.Add + ( + new PSCodeProperty + ( + "CentralAccessPolicyName", + typeof(SecurityDescriptorCommandsBase).GetMethod("GetCentralAccessPolicyName") + ) + ); +#endif + } + } + + /// + /// Gets the Path of the provided PSObject. + /// + /// + /// The PSObject for which to obtain the path. + /// + /// + /// The path of the provided PSObject. + /// + public static string GetPath(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + else + { + // These are guaranteed to not be null, but even checking + // them for null causes a presharp warning +#pragma warning disable 56506 + + // Get path + return instance.Properties["PSPath"].Value.ToString(); +#pragma warning restore 56506 + } + } + + /// + /// Gets the Owner of the provided PSObject. + /// + /// + /// The PSObject for which to obtain the Owner. + /// + /// + /// The Owner of the provided PSObject. + /// + public static string GetOwner(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + if (instance.BaseObject is not ObjectSecurity sd) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + // Get owner + try + { + IdentityReference ir = sd.GetOwner(typeof(NTAccount)); + return ir.ToString(); + } + catch (IdentityNotMappedException) + { + // All Acl cmdlets returning SIDs will return a string + // representation of the SID in all cases where the SID + // cannot be mapped to a proper user or group name. + } + + // We are here since we cannot get IdentityReference from sd.. + // So return sddl.. + return sd.GetSecurityDescriptorSddlForm(AccessControlSections.Owner); + } + + /// + /// Gets the Group of the provided PSObject. + /// + /// + /// The PSObject for which to obtain the Group. + /// + /// + /// The Group of the provided PSObject. + /// + public static string GetGroup(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + if (instance.BaseObject is not ObjectSecurity sd) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + // Get Group + try + { + IdentityReference ir = sd.GetGroup(typeof(NTAccount)); + return ir.ToString(); + } + catch (IdentityNotMappedException) + { + // All Acl cmdlets returning SIDs will return a string + // representation of the SID in all cases where the SID + // cannot be mapped to a proper user or group name. + } + + // We are here since we cannot get IdentityReference from sd.. + // So return sddl.. + return sd.GetSecurityDescriptorSddlForm(AccessControlSections.Group); + } + /// + /// Gets the access rules of the provided PSObject. + /// + /// + /// The PSObject for which to obtain the access rules. + /// + /// + /// The access rules of the provided PSObject. + /// + public static AuthorizationRuleCollection GetAccess(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + ObjectSecurity sd = instance.BaseObject as ObjectSecurity; + if (sd == null) + { + PSTraceSource.NewArgumentException(nameof(instance)); + } + + // Get DACL + if (sd is CommonObjectSecurity cos) + { + return cos.GetAccessRules(true, true, typeof(NTAccount)); + } + else + { + DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; + Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); + return dos.GetAccessRules(true, true, typeof(NTAccount)); + } + } + + /// + /// Gets the audit rules of the provided PSObject. + /// + /// + /// The PSObject for which to obtain the audit rules. + /// + /// + /// The audit rules of the provided PSObject. + /// + public static AuthorizationRuleCollection GetAudit(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + ObjectSecurity sd = instance.BaseObject as ObjectSecurity; + if (sd == null) + { + PSTraceSource.NewArgumentException(nameof(instance)); + } + + if (sd is CommonObjectSecurity cos) + { + return cos.GetAuditRules(true, true, typeof(NTAccount)); + } + else + { + DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; + Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); + return dos.GetAuditRules(true, true, typeof(NTAccount)); + } + } + + /// + /// Gets the central access policy ID of the provided PSObject. + /// + /// + /// The PSObject for which to obtain the central access policy ID. + /// + /// + /// The central access policy ID of the provided PSObject. + /// + public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) + { + SessionState sessionState = new(); + string path = sessionState.Path.GetUnresolvedProviderPathFromPSPath( + GetPath(instance)); + IntPtr pSd = IntPtr.Zero; + + try + { + // Get the file's SACL containing the CAPID ACE. + uint rs = NativeMethods.GetNamedSecurityInfo( + path, + NativeMethods.SeObjectType.SE_FILE_OBJECT, + NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, + out IntPtr pOwner, + out IntPtr pGroup, + out IntPtr pDacl, + out IntPtr pSacl, + out pSd); + if (rs != NativeMethods.ERROR_SUCCESS) + { + throw new Win32Exception((int)rs); + } + + if (pSacl == IntPtr.Zero) + { + return null; + } + + NativeMethods.ACL sacl = Marshal.PtrToStructure(pSacl); + if (sacl.AceCount == 0) + { + return null; + } + + // Extract the first CAPID from the SACL that does not have INHERIT_ONLY_ACE flag set. + IntPtr pAce = pSacl + Marshal.SizeOf(new NativeMethods.ACL()); + for (ushort aceIdx = 0; aceIdx < sacl.AceCount; aceIdx++) + { + NativeMethods.ACE_HEADER ace = Marshal.PtrToStructure(pAce); + Dbg.Diagnostics.Assert(ace.AceType == + NativeMethods.SYSTEM_SCOPED_POLICY_ID_ACE_TYPE, + "Unexpected ACE type: " + ace.AceType.ToString(CultureInfo.CurrentCulture)); + if ((ace.AceFlags & NativeMethods.INHERIT_ONLY_ACE) == 0) + { + break; + } + + pAce += ace.AceSize; + } + + IntPtr pSid = pAce + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) - + Marshal.SizeOf(new uint()); + bool ret = NativeMethods.IsValidSid(pSid); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + return new SecurityIdentifier(pSid); + } + finally + { + NativeMethods.LocalFree(pSd); + } + } + +#if !CORECLR + /// + /// Gets the central access policy name of the provided PSObject. + /// + /// + /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. + /// + /// + /// The PSObject for which to obtain the central access policy name. + /// + /// + /// The central access policy name of the provided PSObject. + /// + public static string GetCentralAccessPolicyName(PSObject instance) + { + SecurityIdentifier capId = GetCentralAccessPolicyId(instance); + if (capId == null) + { + return null; // file does not have the scope ace + } + + int capIdSize = capId.BinaryLength; + byte[] capIdArray = new byte[capIdSize]; + capId.GetBinaryForm(capIdArray, 0); + IntPtr caps = IntPtr.Zero; + IntPtr pCapId = Marshal.AllocHGlobal(capIdSize); + + try + { + // Retrieve the CAP by CAPID. + Marshal.Copy(capIdArray, 0, pCapId, capIdSize); + IntPtr[] ppCapId = new IntPtr[1]; + ppCapId[0] = pCapId; + uint rs = NativeMethods.LsaQueryCAPs( + ppCapId, + 1, + out caps, + out uint capCount); + if (rs != NativeMethods.STATUS_SUCCESS) + { + throw new Win32Exception((int)rs); + } + + if (capCount == 0 || caps == IntPtr.Zero) + { + return null; + } + + // Get the CAP name. + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(caps); + // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. + return Marshal.PtrToStringUni(cap.Name.Buffer, cap.Name.Length / 2); + } + finally + { + Marshal.FreeHGlobal(pCapId); + uint rs = NativeMethods.LsaFreeMemory(caps); + Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, + "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); + } + } + + /// + /// Gets the names and IDs of all central access policies available on the machine. + /// + /// + /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. + /// + /// + /// The PSObject argument is ignored. + /// + /// + /// The names and IDs of all central access policies available on the machine. + /// + public static string[] GetAllCentralAccessPolicies(PSObject instance) + { + IntPtr caps = IntPtr.Zero; + + try + { + // Retrieve all CAPs. + uint rs = NativeMethods.LsaQueryCAPs( + null, + 0, + out caps, + out uint capCount); + if (rs != NativeMethods.STATUS_SUCCESS) + { + throw new Win32Exception((int)rs); + } + + Dbg.Diagnostics.Assert(capCount < 0xFFFF, + "Too many central access policies"); + if (capCount == 0 || caps == IntPtr.Zero) + { + return null; + } + + // Add CAP names and IDs to a string array. + string[] policies = new string[capCount]; + IntPtr capPtr = caps; + for (uint capIdx = 0; capIdx < capCount; capIdx++) + { + // Retrieve CAP name. + Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, + "Invalid central access policies array"); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(capPtr); + // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. + policies[capIdx] = "\"" + Marshal.PtrToStringUni( + cap.Name.Buffer, + cap.Name.Length / 2) + "\""; + + // Retrieve CAPID. + IntPtr pCapId = cap.CAPID; + Dbg.Diagnostics.Assert(pCapId != IntPtr.Zero, + "Invalid central access policies array"); + bool ret = NativeMethods.IsValidSid(pCapId); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + SecurityIdentifier sid = new SecurityIdentifier(pCapId); + policies[capIdx] += " (" + sid.ToString() + ")"; + + capPtr += Marshal.SizeOf(cap); + } + + return policies; + } + finally + { + uint rs = NativeMethods.LsaFreeMemory(caps); + Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, + "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); + } + } +#endif + + /// + /// Gets the security descriptor (in SDDL form) of the + /// provided PSObject. SDDL form is the Security Descriptor + /// Definition Language. + /// + /// + /// The PSObject for which to obtain the security descriptor. + /// + /// + /// The security descriptor of the provided PSObject, in SDDL form. + /// + public static string GetSddl(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + if (instance.BaseObject is not ObjectSecurity sd) + { + throw PSTraceSource.NewArgumentNullException(nameof(instance)); + } + + string sddl = sd.GetSecurityDescriptorSddlForm(AccessControlSections.All); + return sddl; + } + + #endregion brokered properties + + /// + /// The filter to be used to when globbing to get the item. + /// + private string _filter; + + /// + /// The glob string used to determine which items are included. + /// + private string[] _include = Array.Empty(); + + /// + /// The glob string used to determine which items are excluded. + /// + private string[] _exclude = Array.Empty(); + } + +#if !UNIX + /// + /// Defines the implementation of the 'get-acl' cmdlet. + /// This cmdlet gets the security descriptor of an item at the specified path. + /// + [Cmdlet(VerbsCommon.Get, "Acl", SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096593")] + public sealed class GetAclCommand : SecurityDescriptorCommandsBase + { + /// + /// Initializes a new instance of the GetAclCommand + /// class. Sets the default path to the current location. + /// + public GetAclCommand() + { + // Default for path is the current location + _path = new string[] { "." }; + } + #region parameters + + private string[] _path; + + /// + /// Gets or sets the path of the item for which to obtain the + /// security descriptor. Default is the current location. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + [ValidateNotNullOrEmpty] + public string[] Path + { + get + { + return _path; + } + + set + { + _path = value; + } + } + + private PSObject _inputObject; + + /// + /// InputObject Parameter + /// Gets or sets the inputObject for which to obtain the security descriptor. + /// + [Parameter(Mandatory = true, ParameterSetName = "ByInputObject")] + public PSObject InputObject + { + get + { + return _inputObject; + } + + set + { + _inputObject = value; + } + } + + /// + /// Gets or sets the literal path of the item for which to obtain the + /// security descriptor. Default is the current location. + /// + [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return _path; + } + + set + { + _path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath; + + /// + /// Gets or sets the audit flag of the command. This flag + /// determines if audit rules should also be retrieved. + /// + [Parameter] + public SwitchParameter Audit + { + get + { + return _audit; + } + + set + { + _audit = value; + } + } + + private SwitchParameter _audit; + +#if CORECLR + /// + /// Parameter '-AllCentralAccessPolicies' is not supported in OneCore powershell, + /// because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. + /// + private SwitchParameter AllCentralAccessPolicies + { + get; set; + } +#else + /// + /// Gets or sets the AllCentralAccessPolicies flag of the command. This flag + /// determines whether the information about all central access policies + /// available on the machine should be displayed. + /// + [Parameter] + public SwitchParameter AllCentralAccessPolicies + { + get + { + return allCentralAccessPolicies; + } + + set + { + allCentralAccessPolicies = value; + } + } + + private SwitchParameter allCentralAccessPolicies; +#endif + + #endregion + + /// + /// Processes records from the input pipeline. + /// For each input file, the command retrieves its + /// corresponding security descriptor. + /// + protected override void ProcessRecord() + { + AccessControlSections sections = + AccessControlSections.Owner | + AccessControlSections.Group | + AccessControlSections.Access; + if (_audit) + { + sections |= AccessControlSections.Audit; + } + + if (_inputObject != null) + { + PSMethodInfo methodInfo = _inputObject.Methods["GetSecurityDescriptor"]; + + if (methodInfo != null) + { + object customDescriptor = null; + + try + { + customDescriptor = PSObject.Base(methodInfo.Invoke()); + + if (customDescriptor is not FileSystemSecurity) + { + customDescriptor = new CommonSecurityDescriptor(false, false, customDescriptor.ToString()); + } + } + catch (Exception) + { + // Calling user code, Catch-all OK + ErrorRecord er = + SecurityUtils.CreateNotSupportedErrorRecord( + UtilsStrings.MethodInvokeFail, + "GetAcl_OperationNotSupported" + ); + + WriteError(er); + return; + } + + WriteObject(customDescriptor, true); + } + else + { + ErrorRecord er = + SecurityUtils.CreateNotSupportedErrorRecord( + UtilsStrings.GetMethodNotFound, + "GetAcl_OperationNotSupported" + ); + + WriteError(er); + } + } + else + { + foreach (string p in Path) + { + List pathsToProcess = new(); + + string currentPath = null; + try + { + if (_isLiteralPath) + { + pathsToProcess.Add(p); + } + else + { + Collection resolvedPaths = + SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext); + foreach (PathInfo pi in resolvedPaths) + { + pathsToProcess.Add(pi.Path); + } + } + + foreach (string rp in pathsToProcess) + { + currentPath = rp; + + CmdletProviderContext context = new(this.Context); + context.SuppressWildcardExpansion = true; + + if (!InvokeProvider.Item.Exists(rp, false, _isLiteralPath)) + { + ErrorRecord er = + SecurityUtils.CreatePathNotFoundErrorRecord( + rp, + "GetAcl_PathNotFound" + ); + + WriteError(er); + continue; + } + + InvokeProvider.SecurityDescriptor.Get(rp, sections, context); + + Collection sd = context.GetAccumulatedObjects(); + if (sd != null) + { + AddBrokeredProperties( + sd, + _audit, + AllCentralAccessPolicies); + WriteObject(sd, true); + } + } + } + catch (NotSupportedException) + { + ErrorRecord er = + SecurityUtils.CreateNotSupportedErrorRecord( + UtilsStrings.OperationNotSupportedOnPath, + "GetAcl_OperationNotSupported", + currentPath + ); + + WriteError(er); + } + catch (ItemNotFoundException) + { + ErrorRecord er = + SecurityUtils.CreatePathNotFoundErrorRecord( + p, + "GetAcl_PathNotFound_Exception" + ); + + WriteError(er); + continue; + } + } + } + } + } + + /// + /// Defines the implementation of the 'set-acl' cmdlet. + /// This cmdlet sets the security descriptor of an item at the specified path. + /// + [Cmdlet(VerbsCommon.Set, "Acl", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = "ByPath", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096600")] + public sealed class SetAclCommand : SecurityDescriptorCommandsBase + { + private string[] _path; + + /// + /// Gets or sets the path of the item for which to set the + /// security descriptor. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + public string[] Path + { + get + { + return _path; + } + + set + { + _path = value; + } + } + + private PSObject _inputObject; + + /// + /// InputObject Parameter + /// Gets or sets the inputObject for which to set the security descriptor. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByInputObject")] + public PSObject InputObject + { + get + { + return _inputObject; + } + + set + { + _inputObject = value; + } + } + + /// + /// Gets or sets the literal path of the item for which to set the + /// security descriptor. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return _path; + } + + set + { + _path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath; + + private object _securityDescriptor; + + /// + /// Gets or sets the security descriptor object to be + /// set on the target item(s). + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByPath")] + [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByLiteralPath")] + [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByInputObject")] + public object AclObject + { + get + { + return _securityDescriptor; + } + + set + { + _securityDescriptor = PSObject.Base(value); + } + } + +#if CORECLR + /// + /// Parameter '-CentralAccessPolicy' is not supported in OneCore powershell, + /// because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. + /// + private string CentralAccessPolicy { get; } +#else + private string centralAccessPolicy; + + /// + /// Gets or sets the central access policy to be + /// set on the target item(s). + /// + [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + public string CentralAccessPolicy + { + get + { + return centralAccessPolicy; + } + + set + { + centralAccessPolicy = value; + } + } +#endif + + private SwitchParameter _clearCentralAccessPolicy; + + /// + /// Clears the central access policy applied on the target item(s). + /// + [Parameter(Mandatory = false, ParameterSetName = "ByPath")] + [Parameter(Mandatory = false, ParameterSetName = "ByLiteralPath")] + public SwitchParameter ClearCentralAccessPolicy + { + get + { + return _clearCentralAccessPolicy; + } + + set + { + _clearCentralAccessPolicy = value; + } + } + + private SwitchParameter _passthru; + + /// + /// Gets or sets the Passthru flag for the operation. + /// If true, the security descriptor is also passed + /// down the output pipeline. + /// + [Parameter] + public SwitchParameter Passthru + { + get + { + return _passthru; + } + + set + { + _passthru = value; + } + } + + /// + /// Returns a newly allocated SACL with no ACEs in it. + /// Free the returned SACL by calling Marshal.FreeHGlobal. + /// + private static IntPtr GetEmptySacl() + { + IntPtr pSacl = IntPtr.Zero; + bool ret = true; + + try + { + // Calculate the size of the empty SACL, align to DWORD. + uint saclSize = (uint)(Marshal.SizeOf(new NativeMethods.ACL()) + + Marshal.SizeOf(new uint()) - 1) & 0xFFFFFFFC; + Dbg.Diagnostics.Assert(saclSize < 0xFFFF, + "Acl size must be less than max SD size of 0xFFFF"); + + // Allocate and initialize the SACL. + pSacl = Marshal.AllocHGlobal((int)saclSize); + ret = NativeMethods.InitializeAcl( + pSacl, + saclSize, + NativeMethods.ACL_REVISION); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + } + finally + { + if (!ret) + { + Marshal.FreeHGlobal(pSacl); + pSacl = IntPtr.Zero; + } + } + + return pSacl; + } + + /// + /// Returns a newly allocated SACL with the supplied CAPID in it. + /// Free the returned SACL by calling Marshal.FreeHGlobal. + /// + /// + /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. + /// So the parameter "-CentralAccessPolicy" is not supported on OneCore powershell, + /// and thus this method won't be hit in OneCore powershell. + /// + private IntPtr GetSaclWithCapId(string capStr) + { + IntPtr pCapId = IntPtr.Zero, pSacl = IntPtr.Zero; + IntPtr caps = IntPtr.Zero; + bool ret = true, freeCapId = true; + uint rs = NativeMethods.STATUS_SUCCESS; + + try + { + // Convert the supplied SID from string to binary form. + ret = NativeMethods.ConvertStringSidToSid(capStr, out pCapId); + if (!ret) + { + // We may have got a CAP friendly name instead of CAPID. + // Enumerate all CAPs on the system and try to find one with + // a matching friendly name. + // If we retrieve the CAPID from the LSA, the CAPID need not + // be deallocated separately (but with the entire buffer + // returned by LsaQueryCAPs). + freeCapId = false; + rs = NativeMethods.LsaQueryCAPs( + null, + 0, + out caps, + out uint capCount); + if (rs != NativeMethods.STATUS_SUCCESS) + { + throw new Win32Exception((int)rs); + } + + Dbg.Diagnostics.Assert(capCount < 0xFFFF, + "Too many central access policies"); + if (capCount == 0 || caps == IntPtr.Zero) + { + return IntPtr.Zero; + } + + // Find the supplied string among available CAP names, use the corresponding CAPID. + IntPtr capPtr = caps; + for (uint capIdx = 0; capIdx < capCount; capIdx++) + { + Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, + "Invalid central access policies array"); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(capPtr); + // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. + string capName = Marshal.PtrToStringUni( + cap.Name.Buffer, + cap.Name.Length / 2); + if (capName.Equals(capStr, StringComparison.OrdinalIgnoreCase)) + { + pCapId = cap.CAPID; + break; + } + + capPtr += Marshal.SizeOf(cap); + } + } + + if (pCapId == IntPtr.Zero) + { + Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier); + WriteError(new ErrorRecord( + e, + "SetAcl_CentralAccessPolicy", + ErrorCategory.InvalidArgument, + AclObject)); + return IntPtr.Zero; + } + + ret = NativeMethods.IsValidSid(pCapId); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + uint sidSize = NativeMethods.GetLengthSid(pCapId); + + // Calculate the size of the SACL with one CAPID ACE, align to DWORD. + uint saclSize = (uint)(Marshal.SizeOf(new NativeMethods.ACL()) + + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) + + sidSize - 1) & 0xFFFFFFFC; + Dbg.Diagnostics.Assert(saclSize < 0xFFFF, + "Acl size must be less than max SD size of 0xFFFF"); + + // Allocate and initialize the SACL. + pSacl = Marshal.AllocHGlobal((int)saclSize); + ret = NativeMethods.InitializeAcl( + pSacl, + saclSize, + NativeMethods.ACL_REVISION); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + // Add CAPID to the SACL. + rs = NativeMethods.AddScopedPolicyIDAce( + pSacl, + NativeMethods.ACL_REVISION, + NativeMethods.SUB_CONTAINERS_AND_OBJECTS_INHERIT, + 0, + pCapId); + if (rs != NativeMethods.STATUS_SUCCESS) + { + if (rs == NativeMethods.STATUS_INVALID_PARAMETER) + { + throw new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier); + } + else + { + throw new Win32Exception((int)rs); + } + } + } + finally + { + if (!ret || rs != NativeMethods.STATUS_SUCCESS) + { + Marshal.FreeHGlobal(pSacl); + pSacl = IntPtr.Zero; + } + + rs = NativeMethods.LsaFreeMemory(caps); + Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, + "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); + if (freeCapId) + { + NativeMethods.LocalFree(pCapId); + } + } + + return pSacl; + } + + /// + /// Returns the current thread or process token with the specified privilege enabled + /// and the previous state of this privilege. Free the returned token + /// by calling NativeMethods.CloseHandle. + /// + private static IntPtr GetTokenWithEnabledPrivilege( + string privilege, + NativeMethods.TOKEN_PRIVILEGE previousState) + { + IntPtr pToken = IntPtr.Zero; + bool ret = true; + + try + { + // First try to open the thread token for privilege adjustment. + ret = NativeMethods.OpenThreadToken( + NativeMethods.GetCurrentThread(), + NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES, + true, + out pToken); + + if (!ret) + { + if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NO_TOKEN) + { + // Client is not impersonating. Open the process token. + ret = NativeMethods.OpenProcessToken( + NativeMethods.GetCurrentProcess(), + NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES, + out pToken); + } + + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + } + + // Get the LUID of the specified privilege. + NativeMethods.LUID luid = new(); + ret = NativeMethods.LookupPrivilegeValue( + null, + privilege, + ref luid); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + // Enable the privilege. + NativeMethods.TOKEN_PRIVILEGE newState = new(); + newState.PrivilegeCount = 1; + newState.Privilege.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED; + newState.Privilege.Luid = luid; + uint previousSize = 0; + ret = NativeMethods.AdjustTokenPrivileges( + pToken, + false, + ref newState, + (uint)Marshal.SizeOf(previousState), + ref previousState, + ref previousSize); + if (!ret) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + } + finally + { + if (!ret) + { + NativeMethods.CloseHandle(pToken); + pToken = IntPtr.Zero; + } + } + + return pToken; + } + + /// Processes records from the input pipeline. + /// For each input file, the command sets its + /// security descriptor to the specified + /// Access Control List (ACL). + protected override void ProcessRecord() + { + ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity; + + if (_inputObject != null) + { + PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"]; + + if (methodInfo != null) + { + string sddl; + + if (aclObjectSecurity != null) + { + sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); + } + else if (_securityDescriptor is CommonSecurityDescriptor aclCommonSD) + { + sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); + } + else + { + Exception e = new ArgumentException("AclObject"); + WriteError(new ErrorRecord( + e, + "SetAcl_AclObject", + ErrorCategory.InvalidArgument, + AclObject)); + return; + } + + try + { + methodInfo.Invoke(sddl); + } + catch (Exception) + { + // Calling user code, Catch-all OK + ErrorRecord er = + SecurityUtils.CreateNotSupportedErrorRecord( + UtilsStrings.MethodInvokeFail, + "SetAcl_OperationNotSupported" + ); + + WriteError(er); + return; + } + } + else + { + ErrorRecord er = + SecurityUtils.CreateNotSupportedErrorRecord( + UtilsStrings.SetMethodNotFound, + "SetAcl_OperationNotSupported" + ); + + WriteError(er); + } + } + else + { + if (Path == null) + { + Exception e = new ArgumentException("Path"); + WriteError(new ErrorRecord( + e, + "SetAcl_Path", + ErrorCategory.InvalidArgument, + AclObject)); + return; + } + + if (aclObjectSecurity == null) + { + Exception e = new ArgumentException("AclObject"); + WriteError(new ErrorRecord( + e, + "SetAcl_AclObject", + ErrorCategory.InvalidArgument, + AclObject)); + return; + } + + if (CentralAccessPolicy != null || ClearCentralAccessPolicy) + { + if (!DownLevelHelper.IsWin8AndAbove()) + { + Exception e = new ParameterBindingException(); + WriteError(new ErrorRecord( + e, + "SetAcl_OperationNotSupported", + ErrorCategory.InvalidArgument, + null)); + return; + } + } + + if (CentralAccessPolicy != null && ClearCentralAccessPolicy) + { + Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters); + ErrorRecord er = + SecurityUtils.CreateInvalidArgumentErrorRecord( + e, + "SetAcl_OperationNotSupported" + ); + + WriteError(er); + return; + } + + IntPtr pSacl = IntPtr.Zero; + NativeMethods.TOKEN_PRIVILEGE previousState = new(); + try + { + if (CentralAccessPolicy != null) + { + pSacl = GetSaclWithCapId(CentralAccessPolicy); + if (pSacl == IntPtr.Zero) + { + SystemException e = new(UtilsStrings.GetSaclWithCapIdFail); + WriteError(new ErrorRecord(e, + "SetAcl_CentralAccessPolicy", + ErrorCategory.InvalidResult, + null)); + return; + } + } + else if (ClearCentralAccessPolicy) + { + pSacl = GetEmptySacl(); + if (pSacl == IntPtr.Zero) + { + SystemException e = new(UtilsStrings.GetEmptySaclFail); + WriteError(new ErrorRecord(e, + "SetAcl_ClearCentralAccessPolicy", + ErrorCategory.InvalidResult, + null)); + return; + } + } + + foreach (string p in Path) + { + Collection pathsToProcess = new(); + + CmdletProviderContext context = this.CmdletProviderContext; + context.PassThru = Passthru; + if (_isLiteralPath) + { + string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath( + p, out ProviderInfo Provider, out PSDriveInfo Drive); + pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState)); + context.SuppressWildcardExpansion = true; + } + else + { + pathsToProcess = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext); + } + + foreach (PathInfo pathInfo in pathsToProcess) + { + if (ShouldProcess(pathInfo.Path)) + { + try + { + InvokeProvider.SecurityDescriptor.Set(pathInfo.Path, + aclObjectSecurity, + context); + + if (CentralAccessPolicy != null || ClearCentralAccessPolicy) + { + if (!pathInfo.Provider.NameEquals(Context.ProviderNames.FileSystem)) + { + Exception e = new ArgumentException("Path"); + WriteError(new ErrorRecord( + e, + "SetAcl_Path", + ErrorCategory.InvalidArgument, + AclObject)); + continue; + } + + // Enable the security privilege required to set SCOPE_SECURITY_INFORMATION. + IntPtr pToken = GetTokenWithEnabledPrivilege("SeSecurityPrivilege", previousState); + if (pToken == IntPtr.Zero) + { + SystemException e = new(UtilsStrings.GetTokenWithEnabledPrivilegeFail); + WriteError(new ErrorRecord(e, + "SetAcl_AdjustTokenPrivileges", + ErrorCategory.InvalidResult, + null)); + return; + } + + // Set the file's CAPID. + uint rs = NativeMethods.SetNamedSecurityInfo( + pathInfo.ProviderPath, + NativeMethods.SeObjectType.SE_FILE_OBJECT, + NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, + IntPtr.Zero, + IntPtr.Zero, + IntPtr.Zero, + pSacl); + + // Restore privileges to the previous state. + if (pToken != IntPtr.Zero) + { + NativeMethods.TOKEN_PRIVILEGE newState = new(); + uint newSize = 0; + NativeMethods.AdjustTokenPrivileges( + pToken, + false, + ref previousState, + (uint)Marshal.SizeOf(newState), + ref newState, + ref newSize); + + NativeMethods.CloseHandle(pToken); + pToken = IntPtr.Zero; + } + + if (rs != NativeMethods.ERROR_SUCCESS) + { + Exception e = new Win32Exception( + (int)rs, + UtilsStrings.SetCentralAccessPolicyFail); + WriteError(new ErrorRecord(e, + "SetAcl_SetNamedSecurityInfo", + ErrorCategory.InvalidResult, + null)); + } + } + } + catch (NotSupportedException) + { + ErrorRecord er = + SecurityUtils.CreateNotSupportedErrorRecord( + UtilsStrings.OperationNotSupportedOnPath, + "SetAcl_OperationNotSupported", + pathInfo.Path + ); + + WriteError(er); + } + } + } + } + } + finally + { + Marshal.FreeHGlobal(pSacl); + } + } + } + } +#endif // !UNIX +} + +#pragma warning restore 56506 diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..4d0cad2d3e90f715174cf98fb5be780687fd51a1 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Collections.ObjectModel; +using System.IO; +using System.Management.Automation; +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the base class from which all catalog commands are derived. + /// + public abstract class CatalogCommandsBase : PSCmdlet + { + /// + /// Path of folder/file to generate or validate the catalog file. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + public string CatalogFilePath + { + get + { + return catalogFilePath; + } + + set + { + catalogFilePath = value; + } + } + + private string catalogFilePath; + + /// + /// Path of folder/file to generate or validate the catalog file. + /// + [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + public string[] Path + { + get + { + return path; + } + + set + { + path = value; + } + } + + private string[] path; + // + // name of this command + // + private readonly string commandName; + + /// + /// Initializes a new instance of the CatalogCommandsBase class, + /// using the given command name. + /// + /// + /// The name of the command. + /// + protected CatalogCommandsBase(string name) : base() + { + commandName = name; + } + + private CatalogCommandsBase() : base() { } + + /// + /// Processes records from the input pipeline. + /// For each input object, the command either generate the Catalog or + /// Validates the existing Catalog. + /// + protected override void ProcessRecord() + { + // + // this cannot happen as we have specified the Path + // property to be mandatory parameter + // + Dbg.Assert((CatalogFilePath != null) && (CatalogFilePath.Length > 0), + "CatalogCommands: Param binder did not bind catalogFilePath"); + + Collection paths = new(); + + if (Path != null) + { + foreach (string p in Path) + { + foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) + { + if (ShouldProcess("Including path " + tempPath.ProviderPath, string.Empty, string.Empty)) + { + paths.Add(tempPath.ProviderPath); + } + } + } + } + + string drive = null; + + // resolve catalog destination Path + if (!SessionState.Path.IsPSAbsolute(catalogFilePath, out drive) && !System.IO.Path.IsPathRooted(catalogFilePath)) + { + catalogFilePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(catalogFilePath); + } + + if (ShouldProcess(catalogFilePath)) + { + PerformAction(paths, catalogFilePath); + } + } + + /// + /// Performs the action i.e. Generate or Validate the Windows Catalog File. + /// + /// + /// The name of the Folder or file on which to perform the action. + /// + /// + /// Path to Catalog + /// + protected abstract void PerformAction(Collection path, string catalogFilePath); + } + + /// + /// Defines the implementation of the 'New-FileCatalog' cmdlet. + /// This cmdlet generates the catalog for File or Folder. + /// + [Cmdlet(VerbsCommon.New, "FileCatalog", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096596")] + [OutputType(typeof(FileInfo))] + public sealed class NewFileCatalogCommand : CatalogCommandsBase + { + /// + /// Initializes a new instance of the New-FileCatalog class. + /// + public NewFileCatalogCommand() : base("New-FileCatalog") { } + + /// + /// Catalog version. + /// + [Parameter] + public int CatalogVersion + { + get + { + return catalogVersion; + } + + set + { + catalogVersion = value; + } + } + + // Based on the Catalog version we will decide which hashing Algorithm to use + private int catalogVersion = 2; + + /// + /// Generate the Catalog for the Path. + /// + /// + /// File or Folder Path + /// + /// + /// Path to Catalog + /// + /// + /// True if able to Create Catalog or else False + /// + protected override void PerformAction(Collection path, string catalogFilePath) + { + if (path.Count == 0) + { + // if user has not provided the path use current directory to generate catalog + path.Add(SessionState.Path.CurrentFileSystemLocation.Path); + } + + FileInfo catalogFileInfo = new(catalogFilePath); + + // If Path points to the expected cat file make sure + // parent Directory exists other wise CryptoAPI fails to create a .cat file + if (catalogFileInfo.Extension.Equals(".cat", StringComparison.Ordinal)) + { + System.IO.Directory.CreateDirectory(catalogFileInfo.Directory.FullName); + } + else + { + // This only creates Directory if it does not exists, Append a default name + System.IO.Directory.CreateDirectory(catalogFilePath); + catalogFilePath = System.IO.Path.Combine(catalogFilePath, "catalog.cat"); + } + + FileInfo catalogFile = CatalogHelper.GenerateCatalog(this, path, catalogFilePath, catalogVersion); + + if (catalogFile != null) + { + WriteObject(catalogFile); + } + } + } + + /// + /// Defines the implementation of the 'Test-FileCatalog' cmdlet. + /// This cmdlet validates the Integrity of catalog. + /// + [Cmdlet(VerbsDiagnostic.Test, "FileCatalog", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", + HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096921")] + [OutputType(typeof(CatalogValidationStatus))] + [OutputType(typeof(CatalogInformation))] + public sealed class TestFileCatalogCommand : CatalogCommandsBase + { + /// + /// Initializes a new instance of the New-FileCatalog class. + /// + public TestFileCatalogCommand() : base("Test-FileCatalog") { } + + /// + /// + [Parameter] + public SwitchParameter Detailed + { + get { return detailed; } + + set { detailed = value; } + } + + private bool detailed = false; + + /// + /// Patterns used to exclude files from DiskPaths and Catalog. + /// + [Parameter] + public string[] FilesToSkip + { + get + { + return filesToSkip; + } + + set + { + filesToSkip = value; + this.excludedPatterns = new WildcardPattern[filesToSkip.Length]; + for (int i = 0; i < filesToSkip.Length; i++) + { + this.excludedPatterns[i] = WildcardPattern.Get(filesToSkip[i], WildcardOptions.IgnoreCase); + } + } + } + + private string[] filesToSkip = null; + internal WildcardPattern[] excludedPatterns = null; + + /// + /// Validate the Integrity of given Catalog. + /// + /// + /// File or Folder Path + /// + /// + /// Path to Catalog + /// + /// + /// True if able to Validate the Catalog and its not tampered or else False + /// + protected override void PerformAction(Collection path, string catalogFilePath) + { + if (path.Count == 0) + { + // if user has not provided the path use the path of catalog file itself. + path.Add(new FileInfo(catalogFilePath).Directory.FullName); + } + + CatalogInformation catalogInfo = CatalogHelper.ValidateCatalog(this, path, catalogFilePath, excludedPatterns); + + if (detailed) + { + WriteObject(catalogInfo); + } + else + { + WriteObject(catalogInfo.Status); + } + } + } +} + +#endif diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..e3a386ee507fb0aa36d35b3bd347107b15e82fd8 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; +using System.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the get-pfxcertificate cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "PfxCertificate", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096918")] + [OutputType(typeof(X509Certificate2))] + public sealed class GetPfxCertificateCommand : PSCmdlet + { + /// + /// Gets or sets the path of the item for which to obtain the + /// certificate. + /// + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "ByPath")] + public string[] FilePath + { + get + { + return _path; + } + + set + { + _path = value; + } + } + + private string[] _path; + + /// + /// Gets or sets the literal path of the item for which to obtain the + /// certificate. + /// + [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return _path; + } + + set + { + _path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// Gets or sets the password for unlocking the certificate. + /// + [Parameter(Mandatory = false)] + public SecureString Password { get; set; } + + /// + /// Do not prompt for password if not given. + /// + [Parameter(Mandatory = false)] + public SwitchParameter NoPromptForPassword { get; set; } + + // + // list of files that were not found + // + private readonly List _filesNotFound = new(); + + /// + /// Initializes a new instance of the GetPfxCertificateCommand + /// class. + /// + public GetPfxCertificateCommand() : base() + { + } + + /// + /// Processes records from the input pipeline. + /// For each input file, the command retrieves its + /// corresponding certificate. + /// + 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 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) + { + _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( + e, + "GetPfxCertificateUnknownCryptoError", + ErrorCategory.NotSpecified, + targetObject: 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 static X509Certificate2 GetCertFromPfxFile(string path, SecureString password) + { + // No overload found in X509CertificateLoader that takes SecureString + #pragma warning disable SYSLIB0057 + var cert = new X509Certificate2(path, password, X509KeyStorageFlags.DefaultKeySet); + return cert; + #pragma warning restore SYSLIB0057 + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..37c687a7770e717cbab40f4e50b86618177f4663 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -0,0 +1,3565 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Management.Automation.Provider; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.XPath; + +using Dbg = System.Management.Automation; +using DWORD = System.UInt32; +using Runspaces = System.Management.Automation.Runspaces; +using SMASecurity = System.Management.Automation.Security; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the Certificate Provider dynamic parameters. + /// We only support one dynamic parameter for Win 7 and earlier: + /// CodeSigningCert + /// If provided, we only return certificates valid for signing code or + /// scripts. + /// + internal sealed class CertificateProviderDynamicParameters + { + /// + /// Gets or sets a switch that controls whether we only return + /// code signing certs. + /// + [Parameter] + public SwitchParameter CodeSigningCert + { + get { return _codeSigningCert; } + + set { _codeSigningCert = value; } + } + + private SwitchParameter _codeSigningCert = new(); + + /// + /// Gets or sets a filter that controls whether we only return + /// data encipherment certs. + /// + [Parameter] + public SwitchParameter DocumentEncryptionCert + { + get; + set; + } + + /// + /// Gets or sets a filter that controls whether we only return + /// server authentication certs. + /// + [Parameter] + public SwitchParameter SSLServerAuthentication + { + get; + set; + } + + /// + /// Gets or sets a filter by DNSName. + /// Expected content is a single DNS Name that may start and/or end + /// with '*': "contoso.com" or "*toso.c*". + /// All WildcardPattern class features supported. + /// + [Parameter] + public string DnsName + { + get; + set; + } + + /// + /// Gets or sets a filter by EKU. + /// Expected content is one or more OID strings: + /// "1.3.6.1.5.5.7.3.1", "*Server*", etc. + /// For a cert to match, it must be valid for all listed OIDs. + /// All WildcardPattern class features supported. + /// + [Parameter] + public string[] Eku + { + get; + set; + } + + /// + /// Gets or sets a filter by the number of valid days. + /// Expected content is a non-negative integer. + /// "0" matches all certs that have already expired. + /// "1" matches all certs that are currently valid and will expire + /// by next day (local time). + /// + [Parameter] + [ValidateRange(ValidateRangeKind.NonNegative)] + public int ExpiringInDays + { + get; + set; + } = -1; + } + + /// + /// Defines the type of DNS string + /// The structure contains punycode name and unicode name. + /// + [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] + public readonly struct DnsNameRepresentation + { + /// + /// Punycode version of DNS name. + /// + private readonly string _punycodeName; + + /// + /// Unicode version of DNS name. + /// + private readonly string _unicodeName; + + /// + /// Ambiguous constructor of a DnsNameRepresentation. + /// + public DnsNameRepresentation(string inputDnsName) + { + _punycodeName = inputDnsName; + _unicodeName = inputDnsName; + } + + /// + /// Specific constructor of a DnsNameRepresentation. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")] + public DnsNameRepresentation( + string inputPunycodeName, + string inputUnicodeName) + { + _punycodeName = inputPunycodeName; + _unicodeName = inputUnicodeName; + } + + /// + /// Value comparison. + /// + public bool Equals(DnsNameRepresentation dnsName) + { + bool match = false; + + if (_unicodeName != null && dnsName._unicodeName != null) + { + if (string.Equals( + _unicodeName, + dnsName._unicodeName, + StringComparison.OrdinalIgnoreCase)) + { + match = true; + } + } + else if (_unicodeName == null && dnsName._unicodeName == null) + { + match = true; + } + + return match; + } + + /// + /// Get property of Punycode. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")] + public string Punycode + { + get + { + return _punycodeName; + } + } + + /// + /// Get property of Unicode. + /// + public string Unicode + { + get + { + return _unicodeName; + } + } + + /// + /// Get display string. + /// + public override string ToString() + { + // Use case sensitive comparison here. + // We don't ever expect to see the punycode and unicode strings + // to differ only by upper/lower case. If they do, that's really + // a code bug, and the effect is to just display both strings. + + return string.Equals(_punycodeName, _unicodeName, StringComparison.Ordinal) + ? _punycodeName + : _unicodeName + " (" + _punycodeName + ")"; + } + } + + /// + /// Defines the Certificate Provider remove-item dynamic parameters. + /// + /// Currently, we only support one dynamic parameter: DeleteKey + /// If provided, we will delete the private key when we remove a certificate. + /// + internal sealed class ProviderRemoveItemDynamicParameters + { + /// + /// Switch that controls whether we should delete private key + /// when remove a certificate. + /// + [Parameter] + public SwitchParameter DeleteKey + { + get + { + { + return _deleteKey; + } + } + + set + { + { + _deleteKey = value; + } + } + } + + private SwitchParameter _deleteKey = new(); + } + + /// + /// Defines the safe handle class for native cert store handles, + /// HCERTSTORE. + /// + internal sealed class CertificateStoreHandle : SafeHandle + { + public CertificateStoreHandle() : base(IntPtr.Zero, true) + { + return; + } + + public override bool IsInvalid + { + get { return handle == IntPtr.Zero; } + } + + protected override bool ReleaseHandle() + { + bool fResult = false; + + if (handle != IntPtr.Zero) + { + fResult = SMASecurity.NativeMethods.CertCloseStore(handle, 0); + handle = IntPtr.Zero; + } + + return fResult; + } + + public IntPtr Handle + { + get { return handle; } + + set { handle = value; } + } + } + + /// + /// Defines the Certificate Provider store handle class. + /// + internal sealed class X509NativeStore + { + // #region tracer + + /// + /// Initializes a new instance of the X509NativeStore class. + /// + public X509NativeStore(X509StoreLocation StoreLocation, string StoreName) + { + _storeLocation = StoreLocation; + _storeName = StoreName; + } + + public void Open(bool includeArchivedCerts) + { + if (_storeHandle != null && _archivedCerts != includeArchivedCerts) + { + _storeHandle = null; // release the old handle + } + + if (_storeHandle == null) + { + _valid = false; + _open = false; + + SMASecurity.NativeMethods.CertOpenStoreFlags StoreFlags = + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_STORE_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_CONTEXT_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG; + + if (includeArchivedCerts) + { + StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG; + } + + switch (_storeLocation.Location) + { + case StoreLocation.LocalMachine: + StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + break; + + case StoreLocation.CurrentUser: + StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + break; + + default: + // ThrowItemNotFound(storeLocation.ToString(), CertificateProviderItem.StoreLocation); + break; + } + + IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore( + SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + IntPtr.Zero, // hCryptProv + StoreFlags, + _storeName); + if (hCertStore == IntPtr.Zero) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + + _storeHandle = new CertificateStoreHandle(); + _storeHandle.Handle = hCertStore; + + // we only do CertControlStore for stores other than UserDS + if (!string.Equals( + _storeName, + "UserDS", + StringComparison.OrdinalIgnoreCase)) + { + if (!SMASecurity.NativeMethods.CertControlStore( + _storeHandle.Handle, + 0, + SMASecurity.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC, + IntPtr.Zero)) + { + _storeHandle = null; + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + } + + _valid = true; + _open = true; + _archivedCerts = includeArchivedCerts; + } + } + + public IntPtr GetFirstCert() + { + return GetNextCert(IntPtr.Zero); + } + + public IntPtr GetNextCert(IntPtr certContext) + { + if (!_open) + { + throw Marshal.GetExceptionForHR( + SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND); + } + + if (Valid) + { + certContext = SMASecurity.NativeMethods.CertEnumCertificatesInStore( + _storeHandle.Handle, + certContext); + } + else + { + certContext = IntPtr.Zero; + } + + return certContext; + } + + public IntPtr GetCertByName(string Name) + { + IntPtr certContext = IntPtr.Zero; + + if (!_open) + { + throw Marshal.GetExceptionForHR( + SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND); + } + + if (Valid) + { + if (DownLevelHelper.HashLookupSupported()) + { + certContext = SMASecurity.NativeMethods.CertFindCertificateInStore( + _storeHandle.Handle, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + 0, // dwFindFlags + SMASecurity.NativeMethods.CertFindType.CERT_FIND_HASH_STR, + Name, + IntPtr.Zero); // pPrevCertContext + } + else + { + // + // the pre-Win8 CAPI2 code does not provide an easy way + // to directly access a specific certificate. + // We have to iterate through all certs to find + // what we want. + // + + while (true) + { + certContext = GetNextCert(certContext); + if (certContext == IntPtr.Zero) + { + break; + } + + X509Certificate2 cert = new(certContext); + if (string.Equals( + cert.Thumbprint, + Name, + StringComparison.OrdinalIgnoreCase)) + { + break; + } + } + } + } + + return certContext; + } + + public void FreeCert(IntPtr certContext) + { + SMASecurity.NativeMethods.CertFreeCertificateContext(certContext); + } + + /// + /// Native IntPtr store handle. + /// + public IntPtr StoreHandle + { + get + { + return _storeHandle.Handle; + } + } + + /// + /// X509StoreLocation store location. + /// + public X509StoreLocation Location + { + get + { + return _storeLocation; + } + } + + /// + /// String store name. + /// + public string StoreName + { + get + { + return _storeName; + } + } + + /// + /// True if a real store is open. + /// + public bool Valid + { + get + { + return _valid; + } + } + + private bool _archivedCerts = false; + private readonly X509StoreLocation _storeLocation = null; + private readonly string _storeName = null; + private CertificateStoreHandle _storeHandle = null; + private bool _valid = false; + private bool _open = false; + } + + /// + /// Defines the types of items + /// supported by the certificate provider. + /// + internal enum CertificateProviderItem + { + /// + /// An unknown item. + /// + Unknown, + + /// + /// An X509 Certificate. + /// + Certificate, + + /// + /// A certificate store location. + /// For example, cert:\CurrentUser. + /// + Store, + + /// + /// A certificate store. + /// For example, cert:\CurrentUser\My. + /// + StoreLocation + } + + /// + /// Defines the implementation of a Certificate Store Provider. This provider + /// allows for stateless namespace navigation of the computer's certificate + /// store. + /// + [CmdletProvider("Certificate", ProviderCapabilities.ShouldProcess)] + [OutputType(typeof(string), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)] + [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)] + [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PopLocation)] + [OutputType(typeof(Microsoft.PowerShell.Commands.X509StoreLocation), typeof(X509Certificate2), ProviderCmdlet = ProviderCmdlet.GetItem)] + [OutputType(typeof(X509Store), typeof(X509Certificate2), ProviderCmdlet = ProviderCmdlet.GetChildItem)] + public sealed class CertificateProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp + { + #region tracer + + /// + /// Tracer for certificate provider. + /// + [TraceSource("CertificateProvider", + "The core command provider for certificates")] + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CertificateProvider", + "The core command provider for certificates"); + + #endregion tracer + + /// + /// Indicate if we already have attempted to load the PKI module. + /// + private bool _hasAttemptedToLoadPkiModule = false; + + /// + /// Lock that guards access to the following static members + /// -- storeLocations + /// -- pathCache. + /// + private static readonly object s_staticLock = new(); + + /// + /// List of store locations. They do not change once initialized. + /// + /// Synchronized on staticLock. + /// + private static List s_storeLocations = null; + + /// + /// Cache that stores paths and their associated objects. + /// + /// key is full path to store-location/store/certificate + /// value is X509StoreLocation/X509NativeStore/X509Certificate2 object + /// + /// Synchronized on staticLock. + /// + private static Hashtable s_pathCache = null; + + /// + /// We allow either / or \ to be the path separator. + /// + private static readonly char[] s_pathSeparators = new char[] { '/', '\\' }; + + /// + /// Regex pattern that defines a valid cert path. + /// + private const string certPathPattern = @"^\\((?CurrentUser|LocalMachine)(\\(?[a-zA-Z]+)(\\(?[0-9a-f]{40}))?)?)?$"; + + /// + /// Cache the store handle to avoid repeated CertOpenStore calls. + /// + private static X509NativeStore s_storeCache = null; + + /// + /// On demand create the Regex to avoid a hit to startup perf. + /// + /// + /// Note, its OK that staticLock is being used here because only + /// IsValidPath is calling this static property so we shouldn't + /// have any deadlocks due to other locked static members calling + /// this property. + /// + private static Regex s_certPathRegex = null; + + private static Regex CertPathRegex + { + get + { + lock (s_staticLock) + { + if (s_certPathRegex == null) + { + const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; + s_certPathRegex = new Regex(certPathPattern, options); + } + } + + return s_certPathRegex; + } + } + + /// + /// Initializes a new instance of the CertificateProvider class. + /// This initializes the default certificate store locations. + /// + public CertificateProvider() + { + // + // initialize storeLocations list and also update the cache + // + lock (s_staticLock) + { + if (s_storeLocations == null) + { + s_pathCache = new Hashtable(StringComparer.OrdinalIgnoreCase); + s_storeLocations = + new List(); + + // + // create and cache CurrentUser store-location + // + X509StoreLocation user = new(StoreLocation.CurrentUser); + s_storeLocations.Add(user); + AddItemToCache(nameof(StoreLocation.CurrentUser), + user); + + // + // create and cache LocalMachine store-location + // + X509StoreLocation machine = new(StoreLocation.LocalMachine); + s_storeLocations.Add(machine); + AddItemToCache(nameof(StoreLocation.LocalMachine), + machine); + + AddItemToCache(string.Empty, s_storeLocations); + } + } + } + + /// + /// Removes an item at the specified path. + /// + /// + /// The path of the item to remove. + /// + /// + /// Recursively remove. + /// + /// + /// Nothing. + /// + /// + /// path is null or empty. + /// destination is null or empty. + /// + protected override void RemoveItem( + string path, + bool recurse) + { + path = NormalizePath(path); + bool isContainer = false; + bool fDeleteKey = false; + + object outObj = GetItemAtPath(path, false, out isContainer); + string[] pathElements = GetPathElements(path); + + bool fUserContext = string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase); + + // isContainer = true means not a valid certificate + + // if source store is user root store and UI is not allowed + // we raise invalid operation + if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero && fUserContext && + string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) + { + string message = CertificateProviderStrings.UINotAllowed; + const string errorId = "UINotAllowed"; + ThrowInvalidOperation(errorId, message); + } + + if (DynamicParameters != null && DynamicParameters is ProviderRemoveItemDynamicParameters dp) + { + if (dp.DeleteKey) + { + fDeleteKey = true; + } + } + + if (isContainer) + { + if (pathElements.Length == 2) // is a store + { + // not support user context + if (fUserContext) + { + string message = CertificateProviderStrings.CannotDeleteUserStore; + const string errorId = "CannotDeleteUserStore"; + ThrowInvalidOperation(errorId, message); + } + + RemoveCertStore(pathElements[1], fDeleteKey, path); + return; + } + else // other container than a store + { + string message = CertificateProviderStrings.CannotRemoveContainer; + const string errorId = "CannotRemoveContainer"; + ThrowInvalidOperation(errorId, message); + } + } + else // certificate + { + // do remove + X509Certificate2 certificate = outObj as X509Certificate2; + RemoveCertItem(certificate, fDeleteKey, !fUserContext, path); + return; + } + } + + /// + /// Gets the dynamic parameters for remove-item on the Certificate + /// Provider. We currently only support one dynamic parameter, + /// "DeleteKey," that delete private key when we delete a certificate. + /// + /// + /// If the path was specified on the command line, this is the path + /// to the item for which to get the dynamic parameters. + /// + /// + /// Ignored. + /// + /// + /// An object that has properties and fields decorated with + /// parsing attributes similar to a cmdlet class. + /// + protected override object RemoveItemDynamicParameters(string path, bool recurse) + { + return new ProviderRemoveItemDynamicParameters(); + } + + /// + /// Moves an item at the specified path to the given destination. + /// + /// + /// The path of the item to move. + /// + /// + /// The path of the destination. + /// + /// + /// Nothing. Moved items are written to the context's pipeline. + /// + /// + /// path is null or empty. + /// destination is null or empty. + /// + protected override void MoveItem( + string path, + string destination) + { + // normalize path + path = NormalizePath(path); + destination = NormalizePath(destination); + + // get elements from the path + string[] pathElements = GetPathElements(path); + string[] destElements = GetPathElements(destination); + + bool isContainer = false; + object cert = GetItemAtPath(path, false, out isContainer); + + // + // isContainer = true; means an invalid path + // + if (isContainer) + { + string message = CertificateProviderStrings.CannotMoveContainer; + const string errorId = "CannotMoveContainer"; + ThrowInvalidOperation(errorId, message); + } + + if (destElements.Length != 2) // not a store + { + // if the destination leads to the same thumbprint + if (destElements.Length == 3 && + (string.Equals(pathElements[2], destElements[2], StringComparison.OrdinalIgnoreCase))) + { + // in this case we think of destination path as valid + // and strip the thumbprint part + destination = Path.GetDirectoryName(destination); + } + else + { + string message = CertificateProviderStrings.InvalidDestStore; + const string errorId = "InvalidDestStore"; + ThrowInvalidOperation(errorId, message); + } + } + + // the second element is store location + // we do not allow cross context move + // we do not allow the destination store is the same as source + + if (!string.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase)) + { + string message = CertificateProviderStrings.CannotMoveCrossContext; + const string errorId = "CannotMoveCrossContext"; + ThrowInvalidOperation(errorId, message); + } + + if (string.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase)) + { + string message = CertificateProviderStrings.CannotMoveToSameStore; + const string errorId = "CannotMoveToSameStore"; + ThrowInvalidOperation(errorId, message); + } + + // if source or destination store is user root store and UI is not allowed + // we raise invalid operation + if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero) + { + if ((string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) && + string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) || + (string.Equals(destElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) && + string.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))) + { + string message = CertificateProviderStrings.UINotAllowed; + const string errorId = "UINotAllowed"; + ThrowInvalidOperation(errorId, message); + } + } + + if (cert != null) // we get cert + { + // get destination store + bool isDestContainer = false; + object store = GetItemAtPath(destination, false, out isDestContainer); + + X509Certificate2 certificate = cert as X509Certificate2; + + if (store is X509NativeStore certstore) + { + certstore.Open(true); + + string action = CertificateProviderStrings.Action_Move; + string resource = string.Format( + CultureInfo.CurrentCulture, + CertificateProviderStrings.MoveItemTemplate, + path, + destination); + if (ShouldProcess(resource, action)) + { + DoMove(destination, certificate, certstore, path); + } + } + } + else + { + ThrowItemNotFound(path, CertificateProviderItem.Certificate); + } + } + + /// + /// Creates a certificate store with the given path. + /// + /// + /// New-Item doesn't go through the method "ItemExists". But for the + /// CertificateProvider, New-Item can create an X509Store and return + /// it, and the user can access the certificates within the store via its + /// property "Certificates". We want the extra new properties of the + /// X509Certificate2 objects to be shown to the user, so we also need + /// to import the PKI module in this method, if we haven't tried it yet. + /// + /// + /// The path of the certificate store to create. + /// + /// + /// Ignored. + /// Only support store. + /// + /// + /// Ignored + /// + /// + /// Nothing. The new certificate store object is + /// written to the context's pipeline. + /// + /// + /// path is null or empty. + /// + protected override void NewItem( + string path, + string type, + object value) + { + if (!_hasAttemptedToLoadPkiModule) + { + // Attempt to load the PKI module if we haven't tried yet + AttemptToImportPkiModule(); + } + + path = NormalizePath(path); + + // get the elements from the path + string[] pathElements = GetPathElements(path); + + // only support creating store + if (pathElements.Length != 2) + { + string message = CertificateProviderStrings.CannotCreateItem; + const string errorId = "CannotCreateItem"; + ThrowInvalidOperation(errorId, message); + } + + bool fUserContext = string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase); + + // not support user context + if (fUserContext) + { + string message = CertificateProviderStrings.CannotCreateUserStore; + const string errorId = "CannotCreateUserStore"; + ThrowInvalidOperation(errorId, message); + } + + const SMASecurity.NativeMethods.CertOpenStoreFlags StoreFlags = + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + + // Create new store + IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore( + SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + IntPtr.Zero, // hCryptProv + StoreFlags, + pathElements[1]); + if (hCertStore == IntPtr.Zero) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + else // free native store handle + { + bool fResult = false; + fResult = SMASecurity.NativeMethods.CertCloseStore(hCertStore, 0); + } + + X509Store outStore = new(pathElements[1], StoreLocation.LocalMachine); + WriteItemObject(outStore, path, true); + } + + #region DriveCmdletProvider overrides + + /// + /// Initializes the cert: drive. + /// + /// + /// A collection that contains the PSDriveInfo object + /// that represents the cert: drive. + /// + protected override Collection InitializeDefaultDrives() + { + string providerDescription = CertificateProviderStrings.CertProvidername; + + PSDriveInfo drive = new( + name: "Cert", + provider: ProviderInfo, + root: @"\", + providerDescription, + credential: null); + + Collection drives = new(); + drives.Add(drive); + + return drives; + } + + /// + /// Determines if the item at the given path is a store-location + /// or store with items in it. + /// + /// + /// The full path to the item. + /// + /// + /// True if the path refers to a store location, or store that contains + /// certificates. False otherwise. + /// + /// + /// Path is null + /// + /// + /// This exception can be thrown if any cryptographic error occurs. + /// It is not possible to know exactly what went wrong. + /// This is because of the way CryptographicException is designed. + /// Some example reasons include: + /// -- certificate is invalid + /// -- certificate has no private key + /// -- certificate password mismatch + /// + protected override bool HasChildItems(string path) + { + bool result = false; + + Utils.CheckArgForNull(path, "path"); + + path = NormalizePath(path); + + if (path.Length == 0) + { + return true; + } + + bool isContainer = false; + + object item = GetItemAtPath(path, false, out isContainer); + + if ((item != null) && isContainer) + { + if (item is X509StoreLocation storeLocation) + { + result = storeLocation.StoreNames.Count > 0; + } + else if (item is X509NativeStore store) + { + store.Open(IncludeArchivedCerts()); + IntPtr certContext = store.GetFirstCert(); + if (certContext != IntPtr.Zero) + { + store.FreeCert(certContext); + result = true; + } + } + } + + return result; + } + + /// + /// Determines if the specified path is syntactically and semantically valid. + /// An example path looks like this: + /// cert:\CurrentUser\My\5F98EBBFE735CDDAE00E33E0FD69050EF9220254. + /// + /// + /// The path of the item to check. + /// + /// + /// True if the path is valid, false otherwise. + /// + protected override bool IsValidPath(string path) + { + path = NormalizePath(path); + path = EnsureDriveIsRooted(path); + + bool isCertPath = CertPathRegex.Match(path).Success; + + return isCertPath; + } + + /// + /// Determines if the store location, store, or certificate exists + /// at the specified path. + /// + /// + /// The method ItemExists will be hit by all built-in cmdlets that interact + /// with the CertificateProvider except for the New-Item. They are: + /// Get-ChildItem + /// Set-Location + /// Push-Location + /// Pop-Location + /// Move-Item + /// Invoke-Item + /// Get-Item + /// Remove-Item + /// So we import the PKI module in this method if we haven't tried yet. + /// + /// + /// The path of the item to check. + /// + /// + /// True if a the store location, store, or certificate exists + /// at the specified path. False otherwise. + /// + /// + /// Path is null + /// + /// + /// This exception can be thrown if any cryptographic error occurs. + /// It is not possible to know exactly what went wrong. + /// This is because of the way CryptographicException is designed. + /// Possible reasons: + /// -- certificate is invalid + /// -- certificate has no private key + /// -- certificate password mismatch + /// -- etc + /// + protected override bool ItemExists(string path) + { + if (!_hasAttemptedToLoadPkiModule) + { + // Attempt to load the PKI module if we haven't tried yet + AttemptToImportPkiModule(); + } + + Utils.CheckArgForNull(path, "path"); + bool result = false; + bool isContainer = false; + object item = null; + + path = NormalizePath(path); + + if (path.Length == 0) + { + result = true; + } + else + { + // + // We fetch the item to see if it exists. This is + // because the managed cert infrastructure does not + // provide a way to test for existence. + // + try + { + item = GetItemAtPath(path, true, out isContainer); + } + catch (ProviderInvocationException e) + { + // + // if the item is not found, we get ProviderInvocationException + // with inner exception set to CertificateProviderItemNotFoundException + // If the inner exception is not of that type + // then we need to rethrow + // + if (e.InnerException is not CertificateProviderItemNotFoundException) + { + throw; + } + } + + result = (bool)item; + } + + s_tracer.WriteLine("result = {0}", result); + return result; + } + + /// + /// Gets the store location, store, or certificate + /// at the specified path. + /// + /// + /// The path of the item to retrieve. + /// + /// + /// Path is null + /// + /// + /// This exception can be thrown if any cryptographic error occurs. + /// It is not possible to know exactly what went wrong. + /// This is because of the way CryptographicException is designed. + /// Possible reasons: + /// -- certificate is invalid + /// -- certificate has no private key + /// -- certificate password mismatch + /// -- etc + /// + protected override void GetItem(string path) + { + bool isContainer = false; + + path = NormalizePath(path); + object item = GetItemAtPath(path, false, out isContainer); + CertificateFilterInfo filter = GetFilter(); + + if (item != null) + { + if (!isContainer) // certificate + { + // If the filter is null, output the certificate we got. + if (filter == null) + { + WriteItemObject(item, path, isContainer); + } + else + { + // The filter is non null. If the certificate + // satisfies the filter, output it. Otherwise, don't. + X509Certificate2 cert = item as X509Certificate2; + Dbg.Diagnostics.Assert(cert != null, "item should be a certificate"); + + if (MatchesFilter(cert, filter)) + { + WriteItemObject(item, path, isContainer); + } + } + } + else // container + { + // The item is a container. If the filter is non null, we don't output it. + if (filter != null) + { + return; + } + + if (item is X509StoreLocation storeLocation) // store location + { + WriteItemObject(item, path, isContainer); + } + else if (item is X509NativeStore store) // store + { + // create X509Store + X509Store outStore = new(store.StoreName, store.Location.Location); + WriteItemObject(outStore, path, isContainer); + } + } + } + } + + /// + /// Gets the parent of the given path. + /// + /// + /// The path of which to get the parent. + /// + /// + /// The root of the drive. + /// + /// + /// The parent of the given path. + /// + protected override string GetParentPath(string path, string root) + { + string parentPath = base.GetParentPath(path, root); + + return parentPath; + } + + /// + /// Gets the name of the leaf element of the specified path. + /// + /// + /// The fully qualified path to the item. + /// + /// + /// The leaf element of the specified path. + /// + protected override string GetChildName(string path) + { + // Path for root is empty string + if (path != null && path.Length == 0) + { + return path; + } + else + { + return MyGetChildName(path); + } + } + + /// + /// We want to import the PKI module explicitly because a type for X509Certificate + /// is defined in the PKI module that add new properties to the X509Certificate2 + /// objects. We want to show those new properties to the user without requiring + /// someone to force the loading of this module. + /// + private void AttemptToImportPkiModule() + { + const string moduleName = "pki"; + + if (Runspaces.Runspace.DefaultRunspace == null) + { + // + // Requires default runspace. Only import the module. + // when a default runspace is available. + // + + return; + } + + CommandInfo commandInfo = + new CmdletInfo( + "Import-Module", + typeof(Microsoft.PowerShell.Commands.ImportModuleCommand)); + Runspaces.Command importModuleCommand = new(commandInfo); + + s_tracer.WriteLine("Attempting to load module: {0}", moduleName); + + try + { + System.Management.Automation.PowerShell ps = null; + ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace) + .AddCommand(importModuleCommand) + .AddParameter("Name", moduleName) + .AddParameter("Scope", StringLiterals.Global) + .AddParameter("ErrorAction", ActionPreference.Ignore) + .AddParameter("WarningAction", ActionPreference.Ignore) + .AddParameter("InformationAction", ActionPreference.Ignore) + .AddParameter("Verbose", false) + .AddParameter("Debug", false); + ps.Invoke(); + } + catch (Exception) + { + } + + _hasAttemptedToLoadPkiModule = true; + } + + private static string MyGetChildName(string path) + { + // Verify the parameters + + if (string.IsNullOrEmpty(path)) + { + throw PSTraceSource.NewArgumentException(nameof(path)); + } + + // Normalize the path + path = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); + + // Trim trailing back slashes + path = path.TrimEnd(StringLiterals.DefaultPathSeparator); + string result = null; + + int separatorIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator); + + // Since there was no path separator return the entire path + if (separatorIndex == -1) + { + result = path; + } + else + { + result = path.Substring(separatorIndex + 1); + } + + return result; + } + /// + /// Invokes the certificate management UI (certmgr.msc) + /// for any path. + /// + /// + /// Ignored. + /// + protected override void InvokeDefaultAction(string path) + { + path = NormalizePath(path); + string action = CertificateProviderStrings.Action_Invoke; + const string certmgr = "certmgr.msc"; + string certPath = System.IO.Path.Combine( + System.Environment.ExpandEnvironmentVariables("%windir%"), "system32"); + + if (ShouldProcess(path, action)) + { + System.Diagnostics.Process.Start(System.IO.Path.Combine(certPath, certmgr)); + } + } + + private static string EnsureDriveIsRooted(string path) + { + string result = path; + + // Find the drive separator + int index = path.IndexOf(':'); + + if (index != -1) + { + // if the drive separator is the end of the path, add + // the root path separator back + if (index + 1 == path.Length) + { + result = path + StringLiterals.DefaultPathSeparator; + } + } + else if ((path.Length == 0) || (path[0] != StringLiterals.DefaultPathSeparator)) + { + result = StringLiterals.DefaultPathSeparator + path; + } + + s_tracer.WriteLine("result = {0}", result); + return result; + } + + private static ErrorRecord CreateErrorRecord(string path, + CertificateProviderItem itemType) + { + Exception e = null; + string message = null; + + // + // first, find the resource-id so that we can display + // correct message + // + switch (itemType) + { + case CertificateProviderItem.Certificate: + message = CertificateProviderStrings.CertificateNotFound; + break; + + case CertificateProviderItem.Store: + message = CertificateProviderStrings.CertificateStoreNotFound; + break; + + case CertificateProviderItem.StoreLocation: + message = CertificateProviderStrings.CertificateStoreLocationNotFound; + break; + + default: + message = CertificateProviderStrings.InvalidPath; + break; + } + + message = string.Format( + System.Globalization.CultureInfo.CurrentCulture, + message, path); + ErrorDetails ed = new(message); + + // + // create appropriate exception type + // + switch (itemType) + { + case CertificateProviderItem.Certificate: + e = new CertificateNotFoundException(message); + break; + + case CertificateProviderItem.Store: + e = new CertificateStoreNotFoundException(message); + break; + + case CertificateProviderItem.StoreLocation: + e = new CertificateStoreLocationNotFoundException(message); + break; + + default: + e = new ArgumentException(message); + break; + } + + ErrorRecord er = new( + e, + "CertProviderItemNotFound", + ErrorCategory.ObjectNotFound, + targetObject: null); + + er.ErrorDetails = ed; + + return er; + } + + private void ThrowErrorRemoting(int stat) + { + if (this.Host.Name.Equals("ServerRemoteHost", StringComparison.OrdinalIgnoreCase)) + { + Exception e = new System.ComponentModel.Win32Exception(stat); + string error = e.Message; + string message = CertificateProviderStrings.RemoteErrorMessage; + error += message; + + Exception e2 = new(error); + ThrowTerminatingError( + new ErrorRecord( + e2, + "RemotingFailure", + ErrorCategory.NotSpecified, + null)); + } + else + { + throw new System.ComponentModel.Win32Exception(stat); + } + } + + private void ThrowInvalidOperation(string errorId, string message) + { + ErrorRecord errorRecord = new( + new InvalidOperationException(message), + errorId, + ErrorCategory.InvalidOperation, + targetObject: null); + errorRecord.ErrorDetails = new ErrorDetails(message); + ThrowTerminatingError(errorRecord); + + return; + } + + private void ThrowItemNotFound(string path, + CertificateProviderItem itemType) + { + ErrorRecord er = CreateErrorRecord(path, itemType); + + ThrowTerminatingError(er); + } + + private static string NormalizePath(string path) + { + if (path.Length > 0) + { + char lastChar = path[path.Length - 1]; + + if ((lastChar == '/') || (lastChar == '\\')) + { + path = path.Substring(0, path.Length - 1); + } + + string[] elts = GetPathElements(path); + + path = string.Join('\\', elts); + } + + return path; + } + + private static string[] GetPathElements(string path) + { + string[] allElts = path.Split(s_pathSeparators); + string[] result = null; + + Stack elts = new(); + + foreach (string e in allElts) + { + if ((e == ".") || (e == string.Empty)) + { + continue; + } + else if (e == "..") + { + if (elts.Count > 0) + { + elts.Pop(); + } + } + else + { + elts.Push(e); + } + } + + result = elts.ToArray(); + Array.Reverse(result); + + return result; + } + + /// + /// Delete private key. + /// + /// Key prov info. + /// No return. + [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptSetProperty(System.IntPtr,System.String,System.Void*,System.Int32,System.Int32)")] + [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptFreeObject(System.IntPtr)")] + private void DoDeleteKey(IntPtr pProvInfo) + { + IntPtr hProv = IntPtr.Zero; + SMASecurity.NativeMethods.CRYPT_KEY_PROV_INFO keyProvInfo = + Marshal.PtrToStructure(pProvInfo); + + IntPtr hWnd = DetectUIHelper.GetOwnerWindow(Host); + + if (keyProvInfo.dwProvType != 0) // legacy + { + if (hWnd != IntPtr.Zero) + { + if (SMASecurity.NativeMethods.CryptAcquireContext( + ref hProv, + keyProvInfo.pwszContainerName, + keyProvInfo.pwszProvName, + (int)keyProvInfo.dwProvType, + (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_VERIFYCONTEXT)) + { + unsafe + { + void* pWnd = hWnd.ToPointer(); + SMASecurity.NativeMethods.CryptSetProvParam( + hProv, + SMASecurity.NativeMethods.ProviderParam.PP_CLIENT_HWND, + &pWnd, + 0); + SMASecurity.NativeMethods.CryptReleaseContext(hProv, 0); + } + } + } + + if (!SMASecurity.NativeMethods.CryptAcquireContext( + ref hProv, + keyProvInfo.pwszContainerName, + keyProvInfo.pwszProvName, + (int)keyProvInfo.dwProvType, + keyProvInfo.dwFlags | (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_DELETEKEYSET | + (hWnd == IntPtr.Zero ? (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT : 0))) + { + ThrowErrorRemoting(Marshal.GetLastWin32Error()); + } + } + else // cng key + { + uint cngKeyFlag = 0; + int result = 0; + + IntPtr hCNGProv = IntPtr.Zero; + IntPtr hCNGKey = IntPtr.Zero; + + if ((keyProvInfo.dwFlags & (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_MACHINE_KEYSET) != 0) + { + cngKeyFlag = (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_MACHINE_KEY_FLAG; + } + + if (hWnd == IntPtr.Zero || + (keyProvInfo.dwFlags & (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT) != 0) + { + cngKeyFlag |= (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG; + } + + int stat = 0; + try + { + stat = SMASecurity.NativeMethods.NCryptOpenStorageProvider( + ref hCNGProv, + keyProvInfo.pwszProvName, + 0); + if (stat != 0) + { + ThrowErrorRemoting(stat); + } + + stat = SMASecurity.NativeMethods.NCryptOpenKey( + hCNGProv, + ref hCNGKey, + keyProvInfo.pwszContainerName, + keyProvInfo.dwKeySpec, + cngKeyFlag); + if (stat != 0) + { + ThrowErrorRemoting(stat); + } + + if ((cngKeyFlag & (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG) != 0) + { + unsafe + { + void* pWnd = hWnd.ToPointer(); + SMASecurity.NativeMethods.NCryptSetProperty( + hCNGProv, + SMASecurity.NativeMethods.NCRYPT_WINDOW_HANDLE_PROPERTY, + &pWnd, + sizeof(void*), + 0); // dwFlags + } + } + + stat = SMASecurity.NativeMethods.NCryptDeleteKey(hCNGKey, 0); + if (stat != 0) + { + ThrowErrorRemoting(stat); + } + + hCNGKey = IntPtr.Zero; + } + finally + { + if (hCNGProv != IntPtr.Zero) + result = SMASecurity.NativeMethods.NCryptFreeObject(hCNGProv); + + if (hCNGKey != IntPtr.Zero) + result = SMASecurity.NativeMethods.NCryptFreeObject(hCNGKey); + } + } + } + + /// + /// Delete the cert store; if -DeleteKey is specified, we also delete + /// the associated private key. + /// + /// The store name. + /// Boolean to specify whether or not to delete private key. + /// Source path. + /// No return. + private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath) + { + // if recurse is true, remove every cert in the store + IntPtr localName = SMASecurity.NativeMethods.CryptFindLocalizedName(storeName); + string[] pathElements = GetPathElements(sourcePath); + if (localName == IntPtr.Zero)//not find, we can remove + { + X509NativeStore store = null; + + // + // first open the store + // + store = GetStore(sourcePath, false, pathElements); + store.Open(IncludeArchivedCerts()); + + // + // enumerate over each cert and remove it + // + IntPtr certContext = store.GetFirstCert(); + while (certContext != IntPtr.Zero) + { + X509Certificate2 cert = new(certContext); + string certPath = sourcePath + cert.Thumbprint; + RemoveCertItem(cert, fDeleteKey, true, certPath); + + certContext = store.GetNextCert(certContext); + } + // remove the cert store + const SMASecurity.NativeMethods.CertOpenStoreFlags StoreFlags = + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_DELETE_FLAG | + SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + + // delete store + IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore( + SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + IntPtr.Zero, // hCryptProv + StoreFlags, + storeName); + } + else + { + string message = string.Format( + CultureInfo.CurrentCulture, + CertificateProviderStrings.RemoveStoreTemplate, + storeName); + const string errorId = "CannotRemoveSystemStore"; + ThrowInvalidOperation(errorId, message); + } + } + /// + /// Delete the a single cert from the store; if -DeleteKey is specified, we also delete + /// the associated private key. + /// + /// An X509Certificate2 object. + /// Boolean to specify whether or not to delete private key. + /// Machine context or user. + /// Source path. + /// No return. + private void RemoveCertItem(X509Certificate2 cert, bool fDeleteKey, bool fMachine, string sourcePath) + { + if (cert != null) + { + string action = null; + if (fDeleteKey) + { + action = CertificateProviderStrings.Action_RemoveAndDeleteKey; + } + else + { + action = CertificateProviderStrings.Action_Remove; + } + + string resource = string.Format( + CultureInfo.CurrentCulture, + CertificateProviderStrings.RemoveItemTemplate, + sourcePath); + + if (ShouldProcess(resource, action)) + { + DoRemove(cert, fDeleteKey, fMachine, sourcePath); + } + } + } + + /// + /// Delete the cert from the store; if -DeleteKey is specified, we also delete + /// the associated private key. + /// + /// An X509Certificate2 object. + /// Boolean to specify whether or not to delete private key. + /// Machine context or user. + /// Source path. + /// No return. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")] + private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, string sourcePath) + { + // get CERT_KEY_PROV_INFO_PROP_ID + int provSize = 0; + IntPtr pProvInfo = IntPtr.Zero; + bool fHasPrivateKey = false; + + try + { + if (fDeleteKey) + { + // it is fine if below call fails + if (SMASecurity.NativeMethods.CertGetCertificateContextProperty( + cert.Handle, + SMASecurity.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, + IntPtr.Zero, + ref provSize)) + { + pProvInfo = Marshal.AllocHGlobal((int)provSize); + + if (SMASecurity.NativeMethods.CertGetCertificateContextProperty( + cert.Handle, + SMASecurity.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, + pProvInfo, + ref provSize)) + { + fHasPrivateKey = true; + } + } + + if (!fHasPrivateKey) + { + // raise a verbose message + // we should not use WriteWarning here + string verboseNoPrivatekey = CertificateProviderStrings.VerboseNoPrivateKey; + WriteVerbose(verboseNoPrivatekey); + } + } + + // do remove certificate + // should not use the original handle + + if (!SMASecurity.NativeMethods.CertDeleteCertificateFromStore( + SMASecurity.NativeMethods.CertDuplicateCertificateContext(cert.Handle))) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + + // commit the change to physical store + if (sourcePath.Contains("UserDS")) + { + SMASecurity.NativeMethods.CERT_CONTEXT context = + Marshal.PtrToStructure(cert.Handle); + + CommitUserDS(context.hCertStore); + } + + // TODO: Log Cert Delete + + // delete private key + if (fDeleteKey && fHasPrivateKey) + { + DoDeleteKey(pProvInfo); + } + } + finally + { + if (pProvInfo != IntPtr.Zero) + Marshal.FreeHGlobal(pProvInfo); + } + } + + /// + /// Commit store for UserDS store. + /// + /// An IntPtr for store handle. + /// No return. + private static void CommitUserDS(IntPtr storeHandle) + { + if (!SMASecurity.NativeMethods.CertControlStore( + storeHandle, + 0, + SMASecurity.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_COMMIT, + IntPtr.Zero)) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + } + + /// + /// Delete the cert from the original store and add to the destination store. + /// + /// Destination path. + /// An X509Certificate2. + /// An X509NativeStore. + /// Source path. + /// No return. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")] + private void DoMove(string destination, X509Certificate2 cert, X509NativeStore store, string sourcePath) + { + IntPtr dupCert = IntPtr.Zero; // should not free this + IntPtr outCert = IntPtr.Zero; + + // duplicate cert first + dupCert = SMASecurity.NativeMethods.CertDuplicateCertificateContext(cert.Handle); + + if (dupCert == IntPtr.Zero) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + else + { + if (!SMASecurity.NativeMethods.CertAddCertificateContextToStore( + store.StoreHandle, + cert.Handle, + (uint)SMASecurity.NativeMethods.AddCertificateContext.CERT_STORE_ADD_ALWAYS, + ref outCert)) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + + if (!SMASecurity.NativeMethods.CertDeleteCertificateFromStore(dupCert)) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + + // TODO: log cert move + } + + // commit the change to physical store + if (destination.Contains("UserDS")) + { + CommitUserDS(store.StoreHandle); + } + + if (sourcePath.Contains("UserDS")) + { + SMASecurity.NativeMethods.CERT_CONTEXT context = Marshal.PtrToStructure(cert.Handle); + + CommitUserDS(context.hCertStore); + } + + // get the output object + X509Certificate2 outObj = new(outCert); + string certName = GetCertName(outObj); + string certPath = MakePath(destination, certName); + WriteItemObject((object)outObj, certPath, false); + } + + /// + /// Fetches the store-location/store/certificate at the + /// specified path. + /// + /// Path to the item. + /// True if this is to only for an ItemExists call. Returns True / False. + /// Set to true if item exists and is a container. + /// Item at the path. + private object GetItemAtPath(string path, bool test, out bool isContainer) + { + Utils.CheckArgForNull(path, "path"); + + object item = null; + string[] pathElements = GetPathElements(path); + + // + // certs have a fixed depth hierarchy. + // + // pathElements.Length == 0 ==> List + // pathElements.Length == 1 ==> X509StoreLocation + // pathElements.Length == 2 ==> X509NativeStore + // pathElements.Length == 3 ==> X509Certificate2 + // + // Thus lengths 1 & 2 are container items. + // + isContainer = pathElements.Length <= 2; + + X509NativeStore store = null; + + // + // handle invalid path depth + // + if (pathElements.Length > 3) + { + if (test) + { + return false; + } + else + { + ThrowItemNotFound(path, CertificateProviderItem.Certificate); + } + } + + // + // if path cache already has the item, return it + // + item = GetCachedItem(path); + + if (item == null) + { + switch (pathElements.Length) + { + case 1: + // if this is a single element path and if we + // did not find in path-cache, the path + // must be wrong. This is because we initialize + // the only possible two store locations in ctor + if (test) + { + isContainer = false; + return false; + } + else + { + ThrowItemNotFound(path, CertificateProviderItem.StoreLocation); + } + + break; + + case 2: + // + // items at paths of depth 2 are stores. + // + + // + // GetStore() handles store-not-found case. If Test is true, + // Item is True / False and we can return it. + // + store = GetStore(path, test, pathElements); + item = store; + + break; + + case 3: + // + // items at paths of depth 3 are certificates. + // + string storePath = GetParentPath(path, string.Empty); + string[] storePathElements = GetPathElements(storePath); + + // + // first get the store + // + + store = GetStore(storePath, false, storePathElements); + + // + // store must be opened to get access to the + // certificates within it. + // + + store.Open(IncludeArchivedCerts()); + + IntPtr certContext = store.GetCertByName(pathElements[2]); + if (certContext == IntPtr.Zero) + { + if (test) + { + return false; + } + else + { + ThrowItemNotFound(path, CertificateProviderItem.Certificate); + } + } + + // Return true / false rather than the certificate + if (test) + { + item = true; + } + else + { + item = new X509Certificate2(certContext); + } + + store.FreeCert(certContext); + + break; + + default: + // already handled by ThrowItemNotFound() + // at the beginning. + break; + } + } + + if ((item != null) && test) + { + item = true; + } + + return item; + } + + /// + /// Gets the child items of a given store, or location. + /// + /// + /// The full path of the store or location to enumerate. + /// + /// + /// If true, recursively enumerates the child items as well. + /// + /// + /// Path is null or empty. + /// + /// + /// This exception can be thrown if any cryptographic error occurs. + /// It is not possible to know exactly what went wrong. + /// This is because of the way CryptographicException is designed. + /// Possible reasons: + /// -- certificate is invalid + /// -- certificate has no private key + /// -- certificate password mismatch + /// -- etc + /// + protected override void GetChildItems(string path, bool recurse) + { + path = NormalizePath(path); + + GetChildItemsOrNames(path, recurse, ReturnContainers.ReturnAllContainers, false, GetFilter()); + } + + /// + /// Gets the child names of a given store, or location. + /// + /// + /// The full path of the store or location to enumerate. + /// + /// + /// Determines if all containers should be returned or only those containers that match the + /// filter(s). + /// + /// + /// Path is null or empty. + /// + /// + /// This exception can be thrown if any cryptographic error occurs. + /// It is not possible to know exactly what went wrong. + /// This is because of the way CryptographicException is designed. + /// Possible reasons: + /// -- certificate is invalid + /// -- certificate has no private key + /// -- certificate password mismatch + /// -- etc + /// + protected override void GetChildNames( + string path, + ReturnContainers returnContainers) + { + path = NormalizePath(path); + GetChildItemsOrNames(path, false, returnContainers, true, GetFilter()); + } + + /// + /// Determines if the item at the specified path is a store + /// or location. + /// + /// + /// True if the item at the specified path is a store or location. + /// False otherwise. + /// + /// + /// Path is null or empty. + /// + /// + /// This exception can be thrown if any cryptographic error occurs. + /// It is not possible to know exactly what went wrong. + /// This is because of the way CryptographicException is designed. + /// Possible reasons: + /// -- certificate is invalid + /// -- certificate has no private key + /// -- certificate password mismatch + /// -- etc + /// + protected override bool IsItemContainer(string path) + { + path = NormalizePath(path); + Utils.CheckArgForNull(path, "path"); + bool isContainer = false; + + if (path.Length == 0) + { + // + // root path is always container + // + isContainer = true; + } + else + { + // + // We fetch the item to see if it is a container. This is + // because the managed cert infrastructure does not + // provide a way to test for existence. + // + GetItemAtPath(path, true, out isContainer); + } + + s_tracer.WriteLine("result = {0}", isContainer); + return isContainer; + } + + /// + /// Gets the dynamic parameters for get-item on the Certificate + /// Provider. We currently support the following dynamic parameters: + /// "CodeSigning," that returns only certificates good for signing + /// code or scripts. + /// + /// + /// If the path was specified on the command line, this is the path + /// to the item for which to get the dynamic parameters. + /// + /// + /// An object that has properties and fields decorated with + /// parsing attributes similar to a cmdlet class. + /// + protected override object GetItemDynamicParameters(string path) + { + return new CertificateProviderDynamicParameters(); + } + + /// + /// Gets the dynamic parameters for get-childitem on the Certificate + /// Provider. We currently only support one dynamic parameter, + /// "CodeSigning," that returns only certificates good for signing + /// code or scripts. + /// + /// + /// If the path was specified on the command line, this is the path + /// to the item for which to get the dynamic parameters. + /// + /// + /// Ignored. + /// + /// + /// An object that has properties and fields decorated with + /// parsing attributes similar to a cmdlet class. + /// + protected override object GetChildItemsDynamicParameters(string path, bool recurse) + { + return new CertificateProviderDynamicParameters(); + } + + #endregion DriveCmdletProvider overrides + + #region private members + + /// + /// Helper function to get store-location/store/cert at + /// the specified path. + /// + /// Path to the item. + /// Whether we need to recursively find all. + /// + /// Determines if all containers should be returned or only those containers that match the + /// filter(s). + /// + /// Whether we only need the names. + /// Filter info. + /// Does not return a value. + private void GetChildItemsOrNames( + string path, + bool recurse, + ReturnContainers returnContainers, + bool returnNames, + CertificateFilterInfo filter) + { + object thingToReturn = null; + string childPath = null; + + bool returnAllContainers = returnContainers == ReturnContainers.ReturnAllContainers; + + Utils.CheckArgForNull(path, "path"); + + // + // children at the root path are store locations + // + if (path.Length == 0) + { + foreach (X509StoreLocation l in s_storeLocations) + { + thingToReturn = returnNames ? + (object)l.LocationName : (object)l; + + // 'returnNames' is true only when called from + // GetChildNames(), in which case 'recurse' will always be + // false. When the -Path parameter needs to be globbed, + // the potential location names should be returned by + // calling this method from GetChildNames. + + // The original code didn't have a "|| returnNames" clause. + // Suppose the user types: + // dir cert:\curr* -CodeSigningCert -recurse + // We need to do path globbing here to resolve wild cards. + // Since -CodeSigningCert is present, 'filter' is not null. + // Since this method is called from GetChildNames() when + // doing the path globbing, 'returnNames' is true and + // 'recurse' is false. + // In the original code, nothing was returned by + // WriteItemObject(), so the path globbing fails and the + // above dir command would not display the certificates + // as expected. + + // Another case is: + // dir cert:\ -CodeSigningCert -Recurse + // -Recurse is present, so we need to call + // DoManualGetChildItems, and inside DoManualGetChildItems, + // this method will be called to get the names. + // The original code had the same problem for this case. + + // With the "|| returnNames" clause, we test if this method + // is called from the GetChildNames(). When this method is + // called from GetChildNames(), 'recurse' will always be + // false. Then we should return the names whether 'filter' + // is null or not. + + if (filter == null || returnNames) + { + WriteItemObject(thingToReturn, l.LocationName, true); + } + + childPath = l.LocationName; + if (recurse) + { + GetChildItemsOrNames( + childPath, + recurse, + returnContainers, + returnNames, + filter); + } + } + } + else + { + string[] pathElements = GetPathElements(path); + + // + // children at depth 1 are stores + // + if (pathElements.Length == 1) + { + GetStoresOrNames(pathElements[0], + recurse, + returnNames, + filter); + } + // + // children at depth 2 are certificates + // + else if (pathElements.Length == 2) + { + GetCertificatesOrNames(path, + pathElements, + returnNames, + filter); + } + else + { + ThrowItemNotFound(path, CertificateProviderItem.Certificate); + } + } + } + + /// + /// Get the name of the specified certificate. + /// + /// + /// Cert name . + /// we use Thumbprint as the name + private static string GetCertName(X509Certificate2 cert) + { + return cert.Thumbprint; + } + + /// + /// Get cert objects or their name at the specified path. + /// + /// Path to cert. + /// Path elements. + /// Whether we should return only the names (instead of objects). + /// Filter info. + /// Does not return a value. + private void GetCertificatesOrNames(string path, + string[] pathElements, + bool returnNames, + CertificateFilterInfo filter) + { + object thingToReturn = null; + string certPath = null; + X509NativeStore store = null; + + // + // first open the store + // + + store = GetStore(path, false, pathElements); + store.Open(IncludeArchivedCerts()); + + // + // enumerate over each cert and return it (or its name) + // + IntPtr certContext = store.GetFirstCert(); + + while (certContext != IntPtr.Zero) + { + X509Certificate2 cert = new(certContext); + + if (MatchesFilter(cert, filter)) + { + string certName = GetCertName(cert); + certPath = MakePath(path, certName); + + if (returnNames) + { + thingToReturn = (object)certName; + } + else + { + PSObject myPsObj = new(cert); + thingToReturn = (object)myPsObj; + } + + WriteItemObject(thingToReturn, certPath, false); + } + + certContext = store.GetNextCert(certContext); + } + } + + /// + /// Get X509StoreLocation object at path. + /// + /// + /// X509StoreLocation object. + private X509StoreLocation GetStoreLocation(string path) + { + // + // we store the only two possible store-location + // objects during ctor. + // + X509StoreLocation location = + GetCachedItem(path) as X509StoreLocation; + + if (location == null) + { + ThrowItemNotFound(path, CertificateProviderItem.StoreLocation); + } + + return location; + } + + /// + /// Get the X509NativeStore object at path. + /// + /// Path to store. + /// True if this should be a test for path existence. Returns True or False. + /// Path elements. + /// X509NativeStore object. + private X509NativeStore GetStore(string path, bool test, string[] pathElements) + { + X509StoreLocation location = GetStoreLocation(pathElements[0]); + X509NativeStore store = GetStore(path, pathElements[1], location); + + if (store == null) + { + if (test) + { + return null; + } + else + { + ThrowItemNotFound(path, CertificateProviderItem.Store); + } + } + + return store; + } + + /// + /// Gets the X509NativeStore at the specified path. + /// Adds to cache if not already there. + /// + /// Path to the store. + /// Name of store (path leaf element). + /// Location of store (CurrentUser or LocalMachine). + /// X509NativeStore object. + private X509NativeStore GetStore(string storePath, + string storeName, + X509StoreLocation storeLocation) + { + if (!storeLocation.StoreNames.ContainsKey(storeName)) + { + ThrowItemNotFound(storePath, CertificateProviderItem.Store); + } + + if (s_storeCache != null) + { + if (s_storeCache.Location != storeLocation || + !string.Equals( + s_storeCache.StoreName, + storeName, + StringComparison.OrdinalIgnoreCase)) + { + s_storeCache = null; + } + } + + s_storeCache ??= new X509NativeStore(storeLocation, storeName); + + return s_storeCache; + } + + /// + /// Gets X509NativeStore objects or their name at the specified path. + /// + /// Path to the store. + /// Recursively return all items if true. + /// + /// Filter info. + /// Does not return a value. + private void GetStoresOrNames( + string path, + bool recurse, + bool returnNames, + CertificateFilterInfo filter) + { + object thingToReturn = null; + + X509StoreLocation location = GetStoreLocation(path); + + string storePath = null; + + // + // enumerate over each store + // + foreach (string name in location.StoreNames.Keys) + { + storePath = MakePath(path, name); + if (returnNames) + { + thingToReturn = name; + } + else + { + X509NativeStore store = GetStore(storePath, name, location); + X509Store ManagedStore = new(store.StoreName, store.Location.Location); + thingToReturn = ManagedStore; + } + + // 'returnNames' is true only when called from + // GetChildNames(), in which case 'recurse' will always be + // false. When the -Path parameter needs to be globbed, + // the potential store names should be returned by + // calling this method from GetChildNames. + + // The original code didn't have a "|| returnNames" clause. + // Suppose the user types: + // dir cert:\CurrentUser\Tru* -CodeSigningCert -recurse + // We need to do path globbing here to resolve wild cards. + // Since -CodeSigningCert is present, 'filter' is not null. + // Since this method is called from GetChildNames() when + // doing the path globbing, 'returnNames' is true and + // 'recurse' is false. + // In the original code, nothing was returned by + // WriteItemObject(), so the path globbing fails and the + // above dir command would not display the certificates + // as expected. + + // Another case is: + // dir cert:\CurrentUser -CodeSigningCert -Recurse + // -Recurse is present, so we need to call + // DoManualGetChildItems, and inside DoManualGetChildItems, + // this method will be called to get the names. + // The original code had the same problem for this case. + + // With the "|| returnNames" clause, we test if this method + // is called from the GetChildNames(). When this method is + // called from GetChildNames(), 'recurse' will always be + // false. Then we should return the names whether 'filter' + // is null or not. + + if (filter == null || returnNames) + { + WriteItemObject(thingToReturn, name, true); + } + + // + // if recurse is true, get cert objects (or names) as well + // + if (recurse) + { + string[] pathElements = GetPathElements(storePath); + GetCertificatesOrNames( + storePath, + pathElements, + returnNames, + filter); + } + } + } + + private CertificateFilterInfo GetFilter() + { + CertificateFilterInfo filter = null; + + if (DynamicParameters != null && DynamicParameters is CertificateProviderDynamicParameters dp) + { + if (dp.CodeSigningCert) + { + filter = new CertificateFilterInfo(); + filter.Purpose = CertificatePurpose.CodeSigning; + } + + if (dp.DocumentEncryptionCert) + { + filter ??= new CertificateFilterInfo(); + filter.Purpose = CertificatePurpose.DocumentEncryption; + } + + if (dp.DnsName != null) + { + filter ??= new CertificateFilterInfo(); + filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase); + } + + if (dp.Eku != null) + { + filter ??= new CertificateFilterInfo(); + filter.Eku = new List(); + foreach (var pattern in dp.Eku) + { + filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase)); + } + } + + if (dp.ExpiringInDays >= 0) + { + filter ??= new CertificateFilterInfo(); + filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays); + } + + if (dp.SSLServerAuthentication) + { + filter ??= new CertificateFilterInfo(); + filter.SSLServerAuthentication = true; + } + } + + return filter; + } + + private bool IncludeArchivedCerts() + { + bool includeArchivedCerts = false; + + if (Force) + { + includeArchivedCerts = true; + } + + return includeArchivedCerts; + } + + private static bool MatchesFilter(X509Certificate2 cert, CertificateFilterInfo filter) + { + // No filter means, match everything + if (filter == null) + { + return true; + } + + if (filter.Expiring > DateTime.MinValue && !SecuritySupport.CertExpiresByTime(cert, filter.Expiring)) + { + return false; + } + + if (filter.DnsName != null && !CertContainsName(cert, filter.DnsName)) + { + return false; + } + + if (filter.Eku != null && !CertContainsEku(cert, filter.Eku)) + { + return false; + } + + if (filter.SSLServerAuthentication && !CertIsSSLServerAuthentication(cert)) + { + return false; + } + + switch (filter.Purpose) + { + case CertificatePurpose.CodeSigning: + return SecuritySupport.CertIsGoodForSigning(cert); + + case CertificatePurpose.DocumentEncryption: + return SecuritySupport.CertIsGoodForEncryption(cert); + + case CertificatePurpose.NotSpecified: + case CertificatePurpose.All: + return true; + + default: + break; + } + + return false; + } + + /// + /// Check if the specified certificate has the name in DNS name list. + /// + /// Certificate object. + /// Wildcard pattern for DNS name to search. + /// True on success, false otherwise. + internal static bool CertContainsName(X509Certificate2 cert, WildcardPattern pattern) + { + List list = (new DnsNameProperty(cert)).DnsNameList; + foreach (DnsNameRepresentation dnsName in list) + { + if (pattern.IsMatch(dnsName.Unicode)) + { + return true; + } + } + + return false; + } + + /// + /// Check if the specified certificate is a server authentication certificate. + /// + /// Certificate object. + /// True on success, false otherwise. + internal static bool CertIsSSLServerAuthentication(X509Certificate2 cert) + { + X509ExtensionCollection extentionList = cert.Extensions; + foreach (var extension in extentionList) + { + if (extension is X509EnhancedKeyUsageExtension eku) + { + foreach (Oid usage in eku.EnhancedKeyUsages) + { + if (usage.Value.Equals(CertificateFilterInfo.OID_PKIX_KP_SERVER_AUTH, StringComparison.Ordinal)) + { + return true; + } + } + } + } + + return false; + } + + /// + /// Check if the specified certificate contains EKU matching all of these patterns. + /// + /// Certificate object. + /// EKU patterns. + /// True on success, false otherwise. + internal static bool CertContainsEku(X509Certificate2 cert, List ekuPatterns) + { + X509ExtensionCollection extensionList = cert.Extensions; + foreach (var extension in extensionList) + { + if (extension is X509EnhancedKeyUsageExtension eku) + { + OidCollection enhancedKeyUsages = eku.EnhancedKeyUsages; + foreach (WildcardPattern ekuPattern in ekuPatterns) + { + const bool patternPassed = false; + foreach (var usage in enhancedKeyUsages) + { + if (ekuPattern.IsMatch(usage.Value) || ekuPattern.IsMatch(usage.FriendlyName)) + { + return true; + } + } + + if (!patternPassed) + { + return false; + } + } + + return true; + } + } + + return false; + } + + private static object GetCachedItem(string path) + { + object item = null; + + lock (s_staticLock) + { + if (s_pathCache.ContainsKey(path)) + { + item = s_pathCache[path]; + Dbg.Diagnostics.Assert(item != null, "GetCachedItem"); + } + } + + return item; + } + + private static void AddItemToCache(string path, object item) + { + lock (s_staticLock) + { + if ((item != null) && (!s_pathCache.ContainsKey(path))) + { + s_pathCache.Add(path, item); + } + } + } + + #endregion private members + + #region ICmdletProviderSupportsHelp Members + + /// + /// Get provider-specific help. + /// + /// + /// Name of help item or cmdlet for which user has requested help + /// + /// + /// Path to the current location or path to the location of the property that the user needs + /// help about. + /// + /// + /// Provider specific MAML help content string + /// + string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) + { + // + // Get the ver and noun from helpItemName + // + string verb = null; + string noun = null; + try + { + if (!string.IsNullOrEmpty(helpItemName)) + { + CmdletInfo.SplitCmdletName(helpItemName, out verb, out noun); + } + else + { + return string.Empty; + } + + if (string.IsNullOrEmpty(verb) || string.IsNullOrEmpty(noun)) + { + return string.Empty; + } + + // + // Load the help file from the current UI culture subfolder of the module's root folder + // + XmlDocument document = new(); + + CultureInfo currentUICulture = CultureInfo.CurrentUICulture; + + string fullHelpPath = Path.Combine( + this.ProviderInfo.ApplicationBase, + currentUICulture.ToString(), + this.ProviderInfo.HelpFile); + XmlReaderSettings settings = new(); + settings.XmlResolver = null; + using (XmlReader reader = XmlReader.Create(fullHelpPath, settings)) + { + document.Load(reader); + } + + // Add "msh" and "command" namespaces from the MAML schema + XmlNamespaceManager nsMgr = new(document.NameTable); + nsMgr.AddNamespace("msh", HelpCommentsParser.mshURI); + nsMgr.AddNamespace("command", HelpCommentsParser.commandURI); + + // Compose XPath query to select the appropriate node based on the cmdlet + string xpathQuery = string.Format( + CultureInfo.InvariantCulture, + HelpCommentsParser.ProviderHelpCommandXPath, + string.Empty, + verb, + noun); + + // Execute the XPath query and return its MAML snippet + XmlNode result = document.SelectSingleNode(xpathQuery, nsMgr); + if (result != null) + { + return result.OuterXml; + } + } + catch (XmlException) + { + return string.Empty; + } + catch (PathTooLongException) + { + return string.Empty; + } + catch (IOException) + { + return string.Empty; + } + catch (UnauthorizedAccessException) + { + return string.Empty; + } + catch (NotSupportedException) + { + return string.Empty; + } + catch (SecurityException) + { + return string.Empty; + } + catch (XPathException) + { + return string.Empty; + } + + return string.Empty; + } + + #endregion + } + + /// + /// Defines a class to represent a store location in the certificate + /// provider. The two possible store locations are CurrentUser and + /// LocalMachine. + /// + public sealed class X509StoreLocation + { + /// + /// Gets the location, as a string. + /// + public string LocationName + { + get + { + return _location.ToString(); + } + } + + /// + /// Gets the location as a + /// + /// + public StoreLocation Location + { + get + { + return _location; + } + + set + { + _location = value; + } + } + + private StoreLocation _location = StoreLocation.CurrentUser; + + /// + /// Gets the list of stores at this location. + /// + public Hashtable StoreNames + { + get + { + Hashtable storeNames; + // always try to get new names + storeNames = new Hashtable(StringComparer.OrdinalIgnoreCase); + + // since there is no managed support to obtain store names, + // we use pinvoke to get it ourselves. + List names = Crypt32Helpers.GetStoreNamesAtLocation(_location); + foreach (string name in names) + { + storeNames.Add(name, true); + } + + return storeNames; + } + } + + /// + /// Initializes a new instance of the X509StoreLocation class. + /// + public X509StoreLocation(StoreLocation location) + { + Location = location; + } + } + + /// + /// Defines the type of EKU string + /// The structure contains friendly name and EKU oid. + /// + [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] + public readonly struct EnhancedKeyUsageRepresentation + { + /// + /// Localized friendly name of EKU. + /// + private readonly string _friendlyName; + + /// + /// OID of EKU. + /// + private readonly string _oid; + + /// + /// Constructor of an EnhancedKeyUsageRepresentation. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oid")] + + public EnhancedKeyUsageRepresentation(string inputFriendlyName, string inputOid) + { + _friendlyName = inputFriendlyName; + _oid = inputOid; + } + + /// + /// Value comparison. + /// + public bool Equals(EnhancedKeyUsageRepresentation keyUsage) + { + bool match = false; + + if (_oid != null && keyUsage._oid != null) + { + // OID strings only contain numbers and periods + + if (string.Equals(_oid, keyUsage._oid, StringComparison.Ordinal)) + { + match = true; + } + } + else if (_oid == null && keyUsage._oid == null) + { + match = true; + } + + return match; + } + + /// + /// Get property of friendlyName. + /// + public string FriendlyName + { + get + { + return _friendlyName; + } + } + + /// + /// Get property of oid. + /// + public string ObjectId + { + get + { + return _oid; + } + } + + /// + /// Get display string. + /// + public override string ToString() + { + return string.IsNullOrEmpty(_friendlyName) ? + _oid : + _friendlyName + " (" + _oid + ")"; + } + } + + /// + /// Class for SendAsTrustedIssuer. + /// + [SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors")] + public sealed class SendAsTrustedIssuerProperty + { + /// + /// Get property of SendAsTrustedIssuer. + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] + public static bool ReadSendAsTrustedIssuerProperty(X509Certificate2 cert) + { + bool fHasProperty = false; + if (DownLevelHelper.TrustedIssuerSupported()) + { + int propSize = 0; + // try to get the property + // it is fine if fail for not there + if (SMASecurity.NativeMethods.CertGetCertificateContextProperty( + cert.Handle, + SMASecurity.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, + IntPtr.Zero, + ref propSize)) + { + // we have the property + fHasProperty = true; + } + else + { + // if fail + int error = Marshal.GetLastWin32Error(); + if (error != SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND) + { + throw new System.ComponentModel.Win32Exception(error); + } + } + } + + return fHasProperty; + } + + /// + /// Set property of SendAsTrustedIssuer. + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] + public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, string certPath, bool addProperty) + { + if (DownLevelHelper.TrustedIssuerSupported()) + { + IntPtr propertyPtr = IntPtr.Zero; + SMASecurity.NativeMethods.CRYPT_DATA_BLOB dataBlob = new(); + dataBlob.cbData = 0; + dataBlob.pbData = IntPtr.Zero; + X509Certificate certFromStore = null; + + try + { + if (certPath != null) + { + // try to open the store and get the cert out + // in case the store handle is already released + string[] pathElements = GetPathElements(certPath); + + // certpath is in the format: Microsoft.Powershell.Security\ + // Certificate::CurrentUser(LocalMachine)\my\HashID + // obtained pathElements[0] is Microsoft.Powershell.Security + // obtained pathElements[1] is Certificate::CurrentUser + // obtained pathElements[2] is MY + // obtained pathElements[3] is HashID + + bool fUserContext = string.Equals(pathElements[1], "Certificate::CurrentUser", StringComparison.OrdinalIgnoreCase); + + X509StoreLocation storeLocation = + new(fUserContext ? StoreLocation.CurrentUser : StoreLocation.LocalMachine); + + // get certificate from the store pathElements[2] + X509NativeStore store = null; + + store = new X509NativeStore(storeLocation, pathElements[2]); + store.Open(true); // including archival flag + + IntPtr certContext = store.GetCertByName(pathElements[3]); + + if (certContext != IntPtr.Zero) + { + certFromStore = new X509Certificate2(certContext); + store.FreeCert(certContext); + } + } + + if (addProperty) // should add the property + { + propertyPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dataBlob)); + Marshal.StructureToPtr(dataBlob, propertyPtr, false); + } + + // set property + if (!SMASecurity.NativeMethods.CertSetCertificateContextProperty( + certFromStore != null ? certFromStore.Handle : cert.Handle, + SMASecurity.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, + 0, + propertyPtr)) + { + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + } + } + finally + { + if (propertyPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(propertyPtr); + } + } + } + else + { + Marshal.ThrowExceptionForHR(SMASecurity.NativeMethods.NTE_NOT_SUPPORTED); + } + } + + private static readonly char[] s_separators = new char[] { '/', '\\' }; + + private static string[] GetPathElements(string path) + { + string[] allElts = path.Split(s_separators); + string[] result = null; + + Stack elts = new(); + + foreach (string e in allElts) + { + if ((e == ".") || (e == string.Empty)) + { + continue; + } + else if (e == "..") + { + if (elts.Count > 0) + { + elts.Pop(); + } + } + else + { + elts.Push(e); + } + } + + result = elts.ToArray(); + Array.Reverse(result); + + return result; + } + } + /// + /// Class for ekulist. + /// + public sealed class EnhancedKeyUsageProperty + { + private readonly List _ekuList = new(); + + /// + /// Get property of EKUList. + /// + public List EnhancedKeyUsageList + { + get + { + return _ekuList; + } + } + + /// + /// Constructor for EnhancedKeyUsageProperty. + /// + public EnhancedKeyUsageProperty(X509Certificate2 cert) + { + foreach (X509Extension extension in cert.Extensions) + { + // Filter to the OID for EKU + if (extension.Oid.Value == "2.5.29.37" && extension is X509EnhancedKeyUsageExtension ext) + { + OidCollection oids = ext.EnhancedKeyUsages; + foreach (Oid oid in oids) + { + EnhancedKeyUsageRepresentation ekuString = new(oid.FriendlyName, oid.Value); + _ekuList.Add(ekuString); + } + } + } + } + } + + /// + /// Class for DNSNameList. + /// + public sealed class DnsNameProperty + { + private readonly List _dnsList = new(); + private readonly IdnMapping idnMapping = new(); + + private const string distinguishedNamePrefix = "CN="; + + /// + /// Get property of DnsNameList. + /// + public List DnsNameList => _dnsList; + + private DnsNameRepresentation GetDnsNameRepresentation(string dnsName) + { + string unicodeName; + + try + { + unicodeName = idnMapping.GetUnicode(dnsName); + } + catch (ArgumentException) + { + // The name is not valid Punycode, assume it's valid ASCII. + unicodeName = dnsName; + } + + return new DnsNameRepresentation(dnsName, unicodeName); + } + + /// + /// Constructor for DnsNameProperty. + /// + public DnsNameProperty(X509Certificate2 cert) + { + _dnsList = new List(); + + // extract DNS name from subject distinguish name + // if it exists and does not contain a comma + // a comma, indicates it is not a DNS name + if (cert.Subject.StartsWith(distinguishedNamePrefix, StringComparison.OrdinalIgnoreCase) && + !cert.Subject.Contains(',')) + { + string parsedSubjectDistinguishedDnsName = cert.Subject.Substring(distinguishedNamePrefix.Length); + DnsNameRepresentation dnsName = GetDnsNameRepresentation(parsedSubjectDistinguishedDnsName); + _dnsList.Add(dnsName); + } + + // Extract DNS names from SAN extensions + foreach (X509Extension extension in cert.Extensions) + { + if (extension is X509SubjectAlternativeNameExtension sanExtension) + { + foreach (string dnsNameEntry in sanExtension.EnumerateDnsNames()) + { + DnsNameRepresentation dnsName = GetDnsNameRepresentation(dnsNameEntry); + + // Only add the name if it is not the same as an existing name. + if (!_dnsList.Contains(dnsName)) + { + _dnsList.Add(dnsName); + } + } + } + } + } + } + + /// + /// Downlevel helper function to determine if the OS is WIN8 and above. + /// + internal static class DownLevelHelper + { + private static bool s_isWin8Set = false; + private static bool s_isWin8 = false; + + internal static bool IsWin8AndAbove() + { + if (!s_isWin8Set) + { + System.OperatingSystem osInfo = System.Environment.OSVersion; + PlatformID platform = osInfo.Platform; + Version version = osInfo.Version; + + if (platform.Equals(PlatformID.Win32NT) && + ((version.Major > 6) || + (version.Major == 6 && version.Minor >= 2))) + { + s_isWin8 = true; + } + + s_isWin8Set = true; + } + + return s_isWin8; + } + + internal static bool TrustedIssuerSupported() + { + return IsWin8AndAbove(); + } + + internal static bool HashLookupSupported() + { + return IsWin8AndAbove(); + } + } + + /// + /// Check in UI is allowed. + /// + internal static class DetectUIHelper + { +#if CORECLR + internal static IntPtr GetOwnerWindow(PSHost host) + { + return IntPtr.Zero; + } +#else + private static IntPtr hWnd = IntPtr.Zero; + private static bool firstRun = true; + + internal static IntPtr GetOwnerWindow(PSHost host) + { + if (firstRun) + { + firstRun = false; + + if (IsUIAllowed(host)) + { + hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + + if (hWnd == IntPtr.Zero) + { + hWnd = SMASecurity.NativeMethods.GetConsoleWindow(); + } + + if (hWnd == IntPtr.Zero) + { + hWnd = SMASecurity.NativeMethods.GetDesktopWindow(); + } + } + } + + return hWnd; + } + + private static bool IsUIAllowed(PSHost host) + { + if (host.Name.Equals("ServerRemoteHost", StringComparison.OrdinalIgnoreCase)) + return false; + + uint SessionId; + if (!SMASecurity.NativeMethods.ProcessIdToSessionId((uint)Environment.ProcessId, out SessionId)) + return false; + + if (SessionId == 0) + return false; + + if (!Environment.UserInteractive) + return false; + + string[] args = Environment.GetCommandLineArgs(); + + bool fRet = true; + foreach (string arg in args) + { + const string NonInteractiveParamName = "-noninteractive"; + if (arg.Length >= 4 && NonInteractiveParamName.StartsWith(arg, StringComparison.OrdinalIgnoreCase)) + { + fRet = false; + break; + } + } + + return fRet; + } +#endif + } + + /// + /// Container for helper functions that use pinvoke into crypt32.dll. + /// + internal static class Crypt32Helpers + { + /// + /// Lock that guards access to the following static members + /// -- storeNames. + /// + private static readonly object s_staticLock = new(); + + internal static readonly List storeNames = new(); + + /// + /// Get a list of store names at the specified location. + /// + internal static List GetStoreNamesAtLocation(StoreLocation location) + { + SMASecurity.NativeMethods.CertStoreFlags locationFlag = + SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + + switch (location) + { + case StoreLocation.CurrentUser: + locationFlag = SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + break; + + case StoreLocation.LocalMachine: + locationFlag = SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + break; + + default: + Diagnostics.Assert(false, "GetStoreNamesAtLocation: invalid location value"); + break; + } + + SMASecurity.NativeMethods.CertEnumSystemStoreCallBackProto callBack = new(CertEnumSystemStoreCallBack); + + // Return a new list to avoid synchronization issues. + + List names = new(); + lock (s_staticLock) + { + storeNames.Clear(); + + SMASecurity.NativeMethods.CertEnumSystemStore(locationFlag, IntPtr.Zero, + IntPtr.Zero, callBack); + foreach (string name in storeNames) + { + names.Add(name); + } + } + + return names; + } + + /// + /// Call back function used by CertEnumSystemStore + /// + /// Currently, there is no managed support for enumerating store + /// names on a machine. We use the win32 function CertEnumSystemStore() + /// to get a list of stores for a given context. + /// + /// Each time this callback is called, we add the passed store name + /// to the list of stores. + /// + internal static bool CertEnumSystemStoreCallBack(string storeName, + DWORD dwFlagsNotUsed, + IntPtr notUsed1, + IntPtr notUsed2, + IntPtr notUsed3) + { + storeNames.Add(storeName); + return true; + } + } +} +#endif // !UNIX diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CmsCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..5e8e6d19b46a738f1c069c42b5b45fa9d6759ec2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -0,0 +1,602 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Management.Automation; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the 'Protect-CmsMessage' cmdlet. + /// + /// This cmdlet generates a new encrypted CMS message given the + /// recipient and content supplied. + /// + [Cmdlet(VerbsSecurity.Protect, "CmsMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096826", DefaultParameterSetName = "ByContent")] + [OutputType(typeof(string))] + public sealed class ProtectCmsMessageCommand : PSCmdlet + { + /// + /// Gets or sets the recipient of the CMS Message. + /// + [Parameter(Position = 0, Mandatory = true)] + public CmsMessageRecipient[] To + { + get; set; + } + + /// + /// Gets or sets the content of the CMS Message. + /// + [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByContent")] + [AllowNull] + [AllowEmptyString] + public PSObject Content + { + get; + set; + } + + private readonly PSDataCollection _inputObjects = new(); + + /// + /// Gets or sets the content of the CMS Message by path. + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByPath")] + public string Path + { + get; + set; + } + + /// + /// Gets or sets the content of the CMS Message by literal path. + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByLiteralPath")] + public string LiteralPath + { + get; + set; + } + + private string _resolvedPath = null; + + /// + /// Emits the protected message to a file path. + /// + [Parameter(Position = 2)] + public string OutFile + { + get; + set; + } + + private string _resolvedOutFile = null; + + /// + /// Validate / convert arguments. + /// + protected override void BeginProcessing() + { + // Validate Path + if (!string.IsNullOrEmpty(Path)) + { + ProviderInfo provider = null; + Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out provider); + + // Ensure the path is a single path from the file system provider + if ((resolvedPaths.Count > 1) || + (!string.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase))) + { + ErrorRecord error = new( + new ArgumentException( + string.Format( + CultureInfo.InvariantCulture, + CmsCommands.FilePathMustBeFileSystemPath, + Path)), + "FilePathMustBeFileSystemPath", + ErrorCategory.ObjectNotFound, + provider); + ThrowTerminatingError(error); + } + + _resolvedPath = resolvedPaths[0]; + } + + if (!string.IsNullOrEmpty(LiteralPath)) + { + // Validate that the path exists + SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true); + _resolvedPath = LiteralPath; + } + + // Validate OutFile + if (!string.IsNullOrEmpty(OutFile)) + { + _resolvedOutFile = GetUnresolvedProviderPathFromPSPath(OutFile); + } + } + + /// + /// Processes records from the input pipeline. + /// For each input object, the command encrypts + /// and exports the object. + /// + protected override void ProcessRecord() + { + if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + _inputObjects.Add(Content); + } + } + + /// + /// Encrypts and outputs the message. + /// + protected override void EndProcessing() + { + byte[] contentBytes = null; + + if (_inputObjects.Count > 0) + { + StringBuilder outputString = new(); + + Collection output = System.Management.Automation.PowerShell.Create() + .AddCommand("Microsoft.PowerShell.Utility\\Out-String") + .AddParameter("Stream") + .Invoke(_inputObjects); + + foreach (PSObject outputObject in output) + { + if (outputString.Length > 0) + { + outputString.AppendLine(); + } + + outputString.Append(outputObject); + } + + contentBytes = System.Text.Encoding.UTF8.GetBytes(outputString.ToString()); + } + else + { + contentBytes = System.IO.File.ReadAllBytes(_resolvedPath); + } + + ErrorRecord terminatingError = null; + string encodedContent = CmsUtils.Encrypt(contentBytes, To, this.SessionState, out terminatingError); + + if (terminatingError != null) + { + ThrowTerminatingError(terminatingError); + } + + if (string.IsNullOrEmpty(_resolvedOutFile)) + { + WriteObject(encodedContent); + } + else + { + System.IO.File.WriteAllText(_resolvedOutFile, encodedContent); + } + } + } + + /// + /// Defines the implementation of the 'Get-CmsMessage' cmdlet. + /// + /// This cmdlet retrieves information about an encrypted CMS + /// message. + /// + [Cmdlet(VerbsCommon.Get, "CmsMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096598")] + [OutputType(typeof(EnvelopedCms))] + public sealed class GetCmsMessageCommand : PSCmdlet + { + /// + /// Gets or sets the content of the CMS Message. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByContent")] + [AllowNull] + [AllowEmptyString] + public string Content + { + get; + set; + } + + private readonly StringBuilder _contentBuffer = new(); + + /// + /// Gets or sets the CMS Message by path. + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByPath")] + public string Path + { + get; + set; + } + + /// + /// Gets or sets the CMS Message by literal path. + /// + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByLiteralPath")] + public string LiteralPath + { + get; + set; + } + + private string _resolvedPath = null; + + /// + /// Validate / convert arguments. + /// + protected override void BeginProcessing() + { + // Validate Path + if (!string.IsNullOrEmpty(Path)) + { + ProviderInfo provider = null; + Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out provider); + + // Ensure the path is a single path from the file system provider + if ((resolvedPaths.Count > 1) || + (!string.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase))) + { + ErrorRecord error = new( + new ArgumentException( + string.Format( + CultureInfo.InvariantCulture, + CmsCommands.FilePathMustBeFileSystemPath, + Path)), + "FilePathMustBeFileSystemPath", + ErrorCategory.ObjectNotFound, + provider); + ThrowTerminatingError(error); + } + + _resolvedPath = resolvedPaths[0]; + } + + if (!string.IsNullOrEmpty(LiteralPath)) + { + // Validate that the path exists + SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true); + _resolvedPath = LiteralPath; + } + } + + /// + /// Processes records from the input pipeline. + /// For each input object, the command gets the information + /// about the protected message and exports the object. + /// + protected override void ProcessRecord() + { + if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + if (_contentBuffer.Length > 0) + { + _contentBuffer.Append(System.Environment.NewLine); + } + + _contentBuffer.Append(Content); + } + } + + /// + /// Gets the CMS Message object. + /// + protected override void EndProcessing() + { + string actualContent = null; + + // Read in the content + if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + actualContent = _contentBuffer.ToString(); + } + else + { + actualContent = System.IO.File.ReadAllText(_resolvedPath); + } + + // Extract out the bytes and Base64 decode them + byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out int _, out int _); + if (contentBytes == null) + { + ErrorRecord error = new( + new ArgumentException(CmsCommands.InputContainedNoEncryptedContent), + "InputContainedNoEncryptedContent", ErrorCategory.ObjectNotFound, null); + ThrowTerminatingError(error); + } + + EnvelopedCms cms = new(); + cms.Decode(contentBytes); + + PSObject result = new(cms); + List recipients = new(); + foreach (RecipientInfo recipient in cms.RecipientInfos) + { + recipients.Add(recipient.RecipientIdentifier.Value); + } + + result.Properties.Add( + new PSNoteProperty("Recipients", recipients)); + result.Properties.Add( + new PSNoteProperty("Content", actualContent)); + + WriteObject(result); + } + } + + /// + /// Defines the implementation of the 'Unprotect-CmsMessage' cmdlet. + /// + /// This cmdlet retrieves the clear text content of an encrypted CMS + /// message. + /// + [Cmdlet(VerbsSecurity.Unprotect, "CmsMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096701", DefaultParameterSetName = "ByWinEvent")] + [OutputType(typeof(string))] + public sealed class UnprotectCmsMessageCommand : PSCmdlet + { + /// + /// Gets or sets the content of the CMS Message. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] + [AllowNull] + [AllowEmptyString] + public string Content + { + get; + set; + } + + private readonly StringBuilder _contentBuffer = new(); + + /// + /// Gets or sets the Windows Event Log Message with contents to be decrypted. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByWinEvent")] + [PSTypeName("System.Diagnostics.Eventing.Reader.EventLogRecord")] + public PSObject EventLogRecord + { + get; + set; + } + + /// + /// Gets or sets the CMS Message by path. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "ByPath")] + public string Path + { + get; + set; + } + + /// + /// Gets or sets the CMS Message by literal path. + /// + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "ByLiteralPath")] + public string LiteralPath + { + get; + set; + } + + private string _resolvedPath = null; + + /// + /// Determines whether to include the decrypted content in its original context, + /// rather than just output the decrypted content itself. + /// + [Parameter] + public SwitchParameter IncludeContext + { + get; + set; + } + + /// + /// Gets or sets the recipient of the CMS Message. + /// + [Parameter(Position = 1)] + public CmsMessageRecipient[] To + { + get; + set; + } + + /// + /// Validate / convert arguments. + /// + protected override void BeginProcessing() + { + // Validate Path + if (!string.IsNullOrEmpty(Path)) + { + ProviderInfo provider = null; + Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out provider); + + // Ensure the path is a single path from the file system provider + if ((resolvedPaths.Count > 1) || + (!string.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase))) + { + ErrorRecord error = new( + new ArgumentException( + string.Format( + CultureInfo.InvariantCulture, + CmsCommands.FilePathMustBeFileSystemPath, + Path)), + "FilePathMustBeFileSystemPath", + ErrorCategory.ObjectNotFound, + provider); + ThrowTerminatingError(error); + } + + _resolvedPath = resolvedPaths[0]; + } + + if (!string.IsNullOrEmpty(LiteralPath)) + { + // Validate that the path exists + SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true); + _resolvedPath = LiteralPath; + } + } + + /// + /// Processes records from the input pipeline. + /// For each input object, the command gets the information + /// about the protected message and exports the object. + /// + protected override void ProcessRecord() + { + // If we're process by content, collect it. + if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + if (_contentBuffer.Length > 0) + { + _contentBuffer.Append(System.Environment.NewLine); + } + + _contentBuffer.Append(Content); + } + + // If we're processing event log records, decrypt those inline. + if (string.Equals("ByWinEvent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + string actualContent = EventLogRecord.Properties["Message"].Value.ToString(); + string decrypted = Decrypt(actualContent); + + if (!IncludeContext) + { + WriteObject(decrypted); + } + else + { + EventLogRecord.Properties["Message"].Value = decrypted; + WriteObject(EventLogRecord); + } + } + } + + /// + /// Processes records from the input pipeline. + /// For each input object, the command gets the information + /// about the protected message and exports the object. + /// + protected override void EndProcessing() + { + if (string.Equals("ByWinEvent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + string actualContent = null; + + // Read in the content + if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) + { + actualContent = _contentBuffer.ToString(); + } + else + { + actualContent = System.IO.File.ReadAllText(_resolvedPath); + } + + string decrypted = Decrypt(actualContent); + WriteObject(decrypted); + } + + private string Decrypt(string actualContent) + { + // Extract out the bytes and Base64 decode them + int startIndex, endIndex; + byte[] messageBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex); + if ((messageBytes == null) && (!IncludeContext)) + { + ErrorRecord error = new( + new ArgumentException( + string.Format( + CultureInfo.InvariantCulture, + CmsCommands.InputContainedNoEncryptedContentIncludeContext, + "-IncludeContext")), + "InputContainedNoEncryptedContentIncludeContext", + ErrorCategory.ObjectNotFound, + targetObject: null); + ThrowTerminatingError(error); + } + + // Capture the pre and post context, if there was any + string preContext = null; + string postContext = null; + if (IncludeContext) + { + if (startIndex > -1) + { + preContext = actualContent.Substring(0, startIndex); + } + + if (endIndex > -1) + { + postContext = actualContent.Substring(endIndex); + } + } + + EnvelopedCms cms = new(); + X509Certificate2Collection certificates = new(); + + if ((To != null) && (To.Length > 0)) + { + ErrorRecord error = null; + + foreach (CmsMessageRecipient recipient in To) + { + recipient.Resolve(this.SessionState, ResolutionPurpose.Decryption, out error); + if (error != null) + { + ThrowTerminatingError(error); + return null; + } + + foreach (X509Certificate2 certificate in recipient.Certificates) + { + certificates.Add(certificate); + } + } + } + + string resultString = actualContent; + if (messageBytes != null) + { + cms.Decode(messageBytes); + cms.Decrypt(certificates); + + resultString = System.Text.Encoding.UTF8.GetString(cms.ContentInfo.Content); + } + + if (IncludeContext) + { + if (preContext != null) + { + resultString = preContext + resultString; + } + + if (postContext != null) + { + resultString += postContext; + } + } + + return resultString; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..cc354ee15315db2e662353d90a893c51d42abd1b --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the 'get-credential' cmdlet. + /// The get-credential Cmdlet establishes a credential object called a + /// PSCredential, by pairing a given username with + /// a prompted password. That credential object can then be used for other + /// operations involving security. + /// + [Cmdlet(VerbsCommon.Get, "Credential", DefaultParameterSetName = GetCredentialCommand.credentialSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096824")] + [OutputType(typeof(PSCredential), ParameterSetName = new string[] { GetCredentialCommand.credentialSet, GetCredentialCommand.messageSet })] + public sealed class GetCredentialCommand : PSCmdlet + { + /// + /// The Credential parameter set name. + /// + private const string credentialSet = "CredentialSet"; + + /// + /// The Message parameter set name. + /// + private const string messageSet = "MessageSet"; + + /// + /// Gets or sets the underlying PSCredential of + /// the instance. + /// + [Parameter(Position = 0, ParameterSetName = credentialSet)] + [ValidateNotNull] + [Credential] + public PSCredential Credential { get; set; } + + /// + /// Gets and sets the user supplied message providing description about which script/function is + /// requesting the PSCredential from the user. + /// + [Parameter(Mandatory = false, ParameterSetName = messageSet)] + [ValidateNotNullOrEmpty] + public string Message + { + get { return _message; } + + set { _message = value; } + } + + private string _message = UtilsStrings.PromptForCredential_DefaultMessage; + + /// + /// Gets and sets the user supplied username to be used while creating the PSCredential. + /// + [Parameter(Position = 0, Mandatory = false, ParameterSetName = messageSet)] + [ValidateNotNullOrEmpty] + public string UserName + { + get { return _userName; } + + set { _userName = value; } + } + + private string _userName = null; + + /// + /// Gets and sets the title on the window prompt. + /// + [Parameter(Mandatory = false, ParameterSetName = messageSet)] + [ValidateNotNullOrEmpty] + public string Title + { + get { return _title; } + + set { _title = value; } + } + + private string _title = UtilsStrings.PromptForCredential_DefaultCaption; + + /// + /// Initializes a new instance of the GetCredentialCommand + /// class. + /// + public GetCredentialCommand() : base() + { + } + + /// + /// The command outputs the stored PSCredential. + /// + protected override void BeginProcessing() + { + if (Credential != null) + { + WriteObject(Credential); + return; + } + + try + { + Credential = this.Host.UI.PromptForCredential(_title, _message, _userName, string.Empty); + } + catch (ArgumentException exception) + { + ErrorRecord errorRecord = new( + exception, + "CouldNotPromptForCredential", + ErrorCategory.InvalidOperation, + targetObject: null); + WriteError(errorRecord); + } + + if (Credential != null) + { + WriteObject(Credential); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..dc526425c74b9160af5fdb353c8bd301c29d1790 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#region Using directives + +using System; +// System.Management.Automation is the namespace which contains the types and +// methods pertaining to the Microsoft Command Shell +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Management.Automation.Tracing; +#endregion + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the implementation of the 'Get-ExecutionPolicy' cmdlet. + /// This cmdlet gets the effective execution policy of the shell. + /// + /// In priority-order (highest priority first,) these come from: + /// - Machine-wide Group Policy + /// - Current-user Group Policy + /// - Current session preference + /// - Current user machine preference + /// - Local machine preference. + /// + [Cmdlet(VerbsCommon.Get, "ExecutionPolicy", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096594")] + [OutputType(typeof(ExecutionPolicy))] + public class GetExecutionPolicyCommand : PSCmdlet + { + /// + /// Gets or sets the scope of the execution policy. + /// + [Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true)] + public ExecutionPolicyScope Scope + { + get { return _executionPolicyScope; } + + set { _executionPolicyScope = value; _scopeSpecified = true; } + } + + private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine; + private bool _scopeSpecified = false; + + /// + /// Gets or sets the List parameter, which lists all scopes and their execution + /// policies. + /// + [Parameter(Mandatory = false)] + public SwitchParameter List + { + get { return _list; } + + set { _list = value; } + } + + private bool _list; + + /// + /// Outputs the execution policy. + /// + protected override void BeginProcessing() + { + if (_list && _scopeSpecified) + { + string message = ExecutionPolicyCommands.ListAndScopeSpecified; + + ErrorRecord errorRecord = new( + new InvalidOperationException(), + "ListAndScopeSpecified", + ErrorCategory.InvalidOperation, + targetObject: null); + + errorRecord.ErrorDetails = new ErrorDetails(message); + ThrowTerminatingError(errorRecord); + + return; + } + + string shellId = base.Context.ShellID; + + if (_list) + { + foreach (ExecutionPolicyScope scope in SecuritySupport.ExecutionPolicyScopePreferences) + { + PSObject outputObject = new(); + + ExecutionPolicy policy = SecuritySupport.GetExecutionPolicy(shellId, scope); + PSNoteProperty inputNote = new("Scope", scope); + outputObject.Properties.Add(inputNote); + inputNote = new PSNoteProperty( + "ExecutionPolicy", policy); + outputObject.Properties.Add(inputNote); + + WriteObject(outputObject); + } + } + else if (_scopeSpecified) + { + WriteObject(SecuritySupport.GetExecutionPolicy(shellId, _executionPolicyScope)); + } + else + { + WriteObject(SecuritySupport.GetExecutionPolicy(shellId)); + } + } + } + + /// + /// Defines the implementation of the 'Set-ExecutionPolicy' cmdlet. + /// This cmdlet sets the local preference for the execution policy of the + /// shell. + /// + /// The execution policy may be overridden by settings in Group Policy. + /// If the Group Policy setting overrides the desired behaviour, the Cmdlet + /// generates a terminating error. + /// + [Cmdlet(VerbsCommon.Set, "ExecutionPolicy", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096612")] + public class SetExecutionPolicyCommand : PSCmdlet + { + /// + /// Gets or sets the execution policy that the user requests. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + public ExecutionPolicy ExecutionPolicy + { + get { return _executionPolicy; } + + set { _executionPolicy = value; } + } + + private ExecutionPolicy _executionPolicy; + + /// + /// Gets or sets the scope of the execution policy. + /// + [Parameter(Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true)] + public ExecutionPolicyScope Scope + { + get { return _executionPolicyScope; } + + set { _executionPolicyScope = value; } + } + + private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine; + + /// + /// Specifies whether to force the execution policy change. + /// + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private SwitchParameter _force; + + /// + /// Sets the execution policy (validation). + /// + protected override void BeginProcessing() + { + // Verify they've specified a valid scope + if ((_executionPolicyScope == ExecutionPolicyScope.UserPolicy) || + (_executionPolicyScope == ExecutionPolicyScope.MachinePolicy)) + { + string message = ExecutionPolicyCommands.CantSetGroupPolicy; + + ErrorRecord errorRecord = new( + new InvalidOperationException(), + "CantSetGroupPolicy", + ErrorCategory.InvalidOperation, + targetObject: null); + + errorRecord.ErrorDetails = new ErrorDetails(message); + ThrowTerminatingError(errorRecord); + + return; + } + } + + /// + /// Set the desired execution policy. + /// + protected override void ProcessRecord() + { + string shellId = base.Context.ShellID; + string executionPolicy = SecuritySupport.GetExecutionPolicy(ExecutionPolicy); + + if (ShouldProcessPolicyChange(executionPolicy)) + { + try + { + SecuritySupport.SetExecutionPolicy(_executionPolicyScope, ExecutionPolicy, shellId); + } + catch (UnauthorizedAccessException exception) + { + OnAccessDeniedError(exception); + } + catch (System.Security.SecurityException exception) + { + OnAccessDeniedError(exception); + } + + // Ensure it is now the effective execution policy + if (ExecutionPolicy != ExecutionPolicy.Undefined) + { + string effectiveExecutionPolicy = SecuritySupport.GetExecutionPolicy(shellId).ToString(); + if (!string.Equals(effectiveExecutionPolicy, executionPolicy, StringComparison.OrdinalIgnoreCase)) + { + string message = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, effectiveExecutionPolicy); + string recommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction; + + ErrorRecord errorRecord = new( + new System.Security.SecurityException(), + "ExecutionPolicyOverride", + ErrorCategory.PermissionDenied, + targetObject: null); + + errorRecord.ErrorDetails = new ErrorDetails(message); + errorRecord.ErrorDetails.RecommendedAction = recommendedAction; + ThrowTerminatingError(errorRecord); + } + } + + PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(Context, MyInvocation), + EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null); + } + } + + // Determine if we should process this policy change +#if CORECLR // Seems that we cannot find if the cmdlet is executed interactive or through a script on CoreCLR + private bool ShouldProcessPolicyChange(string localPreference) + { + return ShouldProcess(localPreference); + } +#else + private bool ShouldProcessPolicyChange(string localPreference) + { + if (ShouldProcess(localPreference)) + { + // See if we're being invoked directly at the + // command line. In that case, give a warning. + if (!Force) + { + // We don't give this warning if we're in a script, or + // if we don't have a window handle + // (i.e.: PowerShell -command Set-ExecutionPolicy Unrestricted) + if (IsProcessInteractive()) + { + string query = ExecutionPolicyCommands.SetExecutionPolicyQuery; + string caption = ExecutionPolicyCommands.SetExecutionPolicyCaption; + + try + { + bool yesToAllNoToAllDefault = false; + if (!ShouldContinue(query, caption, true, ref yesToAllNoToAllDefault, ref yesToAllNoToAllDefault)) + { + return false; + } + } + catch (InvalidOperationException) + { + // Host is non-interactive. This should + // return false, but must return true due + // to backward compatibility. + return true; + } + catch (System.Management.Automation.Host.HostException) + { + // Host doesn't implement ShouldContinue. This should + // return false, but must return true due + // to backward compatibility. + return true; + } + } + } + + return true; + } + + return false; + } + + private bool IsProcessInteractive() + { + // CommandOrigin != Runspace means it is in a script + if (MyInvocation.CommandOrigin != CommandOrigin.Runspace) + return false; + + // If we don't own the window handle, we've been invoked + // from another process that just calls "PowerShell -Command" + if (System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle == IntPtr.Zero) + return false; + + // If the window has been idle for less than a second, + // they're probably still calling "PowerShell -Command" + // but from Start-Process, or the StartProcess API + try + { + System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); + TimeSpan timeSinceStart = DateTime.Now - currentProcess.StartTime; + TimeSpan idleTime = timeSinceStart - currentProcess.TotalProcessorTime; + + if (idleTime.TotalSeconds > 1) + return true; + } + catch (System.ComponentModel.Win32Exception) + { + // Don't have access to the properties + return false; + } + + return false; + } +#endif + + // Throw terminating error when the access to the registry is denied + private void OnAccessDeniedError(Exception exception) + { + string message = StringUtil.Format(ExecutionPolicyCommands.SetExecutionPolicyAccessDeniedError, exception.Message); + ErrorRecord errorRecord = new( + exception, + exception.GetType().FullName, + ErrorCategory.PermissionDenied, + targetObject: null); + + errorRecord.ErrorDetails = new ErrorDetails(message); + ThrowTerminatingError(errorRecord); + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..29179a7046d99f9a7a785c48aa4d6322bf5ce2bd --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -0,0 +1,389 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; + +using Dbg = System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the base class from which all SecureString commands + /// are derived. + /// + public abstract class SecureStringCommandBase : PSCmdlet + { + private SecureString _ss; + + /// + /// Gets or sets the secure string to be used by the get- and set- + /// commands. + /// + protected SecureString SecureStringData + { + get { return _ss; } + + set { _ss = value; } + } + + // + // name of this command + // + private readonly string _commandName; + + /// + /// Initializes a new instance of the SecureStringCommandBase + /// class. + /// + /// + /// The command name deriving from this class + /// + protected SecureStringCommandBase(string name) : base() + { + _commandName = name; + } + + private SecureStringCommandBase() : base() { } + } + + /// + /// Defines the base class from which all SecureString import and + /// export commands are derived. + /// + public abstract class ConvertFromToSecureStringCommandBase : SecureStringCommandBase + { + /// + /// Initializes a new instance of the ConvertFromToSecureStringCommandBase + /// class. + /// + protected ConvertFromToSecureStringCommandBase(string name) : base(name) { } + + private SecureString _secureKey = null; + private byte[] _key; + + /// + /// Gets or sets the SecureString version of the encryption + /// key used by the SecureString cmdlets. + /// + [Parameter(Position = 1, ParameterSetName = "Secure")] + public SecureString SecureKey + { + get + { + return _secureKey; + } + + set + { + _secureKey = value; + } + } + + /// + /// Gets or sets the byte version of the encryption + /// key used by the SecureString cmdlets. + /// + [Parameter(ParameterSetName = "Open")] + public byte[] Key + { + get + { + return _key; + } + + set + { + _key = value; + } + } + } + + /// + /// Defines the implementation of the 'ConvertFrom-SecureString' cmdlet. + /// This cmdlet exports a new SecureString -- one that represents + /// text that should be kept confidential. The text is encrypted + /// for privacy when being used, and deleted from computer memory + /// when no longer needed. When no key is specified, the command + /// uses the DPAPI to encrypt the string. When a key is specified, the + /// command uses the AES algorithm to encrypt the string. + /// + [Cmdlet(VerbsData.ConvertFrom, "SecureString", DefaultParameterSetName = "Secure", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096497")] + [OutputType(typeof(string))] + public sealed class ConvertFromSecureStringCommand : ConvertFromToSecureStringCommandBase + { + /// + /// Initializes a new instance of the ExportSecureStringCommand class. + /// + public ConvertFromSecureStringCommand() : base("ConvertFrom-SecureString") { } + + /// + /// Gets or sets the secure string to be exported. + /// + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] + public SecureString SecureString + { + get + { + return SecureStringData; + } + + set + { + SecureStringData = value; + } + } + + /// + /// Gets or sets a switch to get the secure string as plain text. + /// + [Parameter(ParameterSetName = "AsPlainText")] + public SwitchParameter AsPlainText { get; set; } + + /// + /// Processes records from the input pipeline. + /// For each input object, the command encrypts + /// and exports the object. + /// + protected override void ProcessRecord() + { + string exportedString = null; + EncryptionResult encryptionResult = null; + + const string argumentName = "SecureString"; + Utils.CheckSecureStringArg(SecureStringData, argumentName); + if (SecureStringData.Length == 0) + { + throw PSTraceSource.NewArgumentException(argumentName); + } + + if (SecureKey != null) + { + Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified"); + encryptionResult = SecureStringHelper.Encrypt(SecureString, SecureKey); + } + else if (Key != null) + { + encryptionResult = SecureStringHelper.Encrypt(SecureString, Key); + } + else if (AsPlainText) + { + IntPtr valuePtr = IntPtr.Zero; + try + { + valuePtr = Marshal.SecureStringToGlobalAllocUnicode(SecureString); + exportedString = Marshal.PtrToStringUni(valuePtr); + } + finally + { + Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); + } + } + else + { + exportedString = SecureStringHelper.Protect(SecureString); + } + + if (encryptionResult != null) + { + // The formatted string is Algorithm Version, + // Initialization Vector, Encrypted Data + string dataPackage = string.Format( + System.Globalization.CultureInfo.InvariantCulture, + "{0}|{1}|{2}", + 2, + encryptionResult.IV, + encryptionResult.EncryptedData); + + // encode the package, and output it. + // We also include a recognizable prefix so that + // we can use the old decryption mechanism if we + // don't see it. While the old decryption + // generated invalid data for the first bit of the + // SecureString, it at least didn't generate an + // exception. + byte[] outputBytes = System.Text.Encoding.Unicode.GetBytes(dataPackage); + string encodedString = Convert.ToBase64String(outputBytes); + WriteObject(SecureStringHelper.SecureStringExportHeader + encodedString); + } + else if (exportedString != null) + { + WriteObject(exportedString); + } + } + } + + /// + /// Defines the implementation of the 'ConvertTo-SecureString' cmdlet. + /// This cmdlet imports a new SecureString from encrypted data -- + /// one that represents text that should be kept confidential. + /// The text is encrypted for privacy when being used, and deleted + /// from computer memory when no longer needed. When no key is + /// specified, the command uses the DPAPI to decrypt the data. + /// When a key is specified, the command uses the AES algorithm + /// to decrypt the data. + /// + [Cmdlet(VerbsData.ConvertTo, "SecureString", DefaultParameterSetName = "Secure", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096916")] + [OutputType(typeof(SecureString))] + public sealed class ConvertToSecureStringCommand : ConvertFromToSecureStringCommandBase + { + /// + /// Initializes a new instance of the ImportSecureStringCommand class. + /// + public ConvertToSecureStringCommand() : base("ConvertTo-SecureString") { } + + /// + /// Gets or sets the unsecured string to be imported. + /// + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] + public string String + { + get + { + return _s; + } + + set + { + _s = value; + } + } + + private string _s; + + /// + /// Gets or sets the flag that marks the unsecured string as a plain + /// text string. + /// + [Parameter(Position = 1, ParameterSetName = "PlainText")] + public SwitchParameter AsPlainText + { + get + { + return _asPlainText; + } + + set + { + _asPlainText = value; + } + } + + private bool _asPlainText; + + /// + /// Gets or sets the flag that will force the import of a plaintext + /// unsecured string. + /// + [Parameter(Position = 2, ParameterSetName = "PlainText")] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// Processes records from the input pipeline. + /// For each input object, the command decrypts the data, + /// then exports a new SecureString created from the object. + /// + protected override void ProcessRecord() + { + SecureString importedString = null; + + Utils.CheckArgForNullOrEmpty(_s, "String"); + + try + { + string encryptedContent = String; + byte[] iv = null; + + // If this is a V2 package + if (String.StartsWith(SecureStringHelper.SecureStringExportHeader, StringComparison.OrdinalIgnoreCase)) + { + try + { + // Trim out the header, and retrieve the + // rest of the string + string remainingData = this.String.Substring( + SecureStringHelper.SecureStringExportHeader.Length, + String.Length - SecureStringHelper.SecureStringExportHeader.Length); + + // Unpack it from Base64, get the string + // representation, then parse it into its components. + byte[] inputBytes = Convert.FromBase64String(remainingData); + string dataPackage = System.Text.Encoding.Unicode.GetString(inputBytes); + string[] dataElements = dataPackage.Split('|'); + + if (dataElements.Length == 3) + { + encryptedContent = dataElements[2]; + iv = Convert.FromBase64String(dataElements[1]); + } + } + catch (FormatException) + { + // Will be raised if we can't convert the + // input from a Base64 string. This means + // it's not really a V2 package. + encryptedContent = String; + iv = null; + } + } + + if (SecureKey != null) + { + Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified"); + importedString = SecureStringHelper.Decrypt(encryptedContent, SecureKey, iv); + } + else if (Key != null) + { + importedString = SecureStringHelper.Decrypt(encryptedContent, Key, iv); + } + else if (!AsPlainText) + { + importedString = SecureStringHelper.Unprotect(String); + } + else + { + importedString = SecureStringHelper.FromPlainTextString(String); + } + } + catch (ArgumentException e) + { + ErrorRecord er = + SecurityUtils.CreateInvalidArgumentErrorRecord( + e, + "ImportSecureString_InvalidArgument" + ); + WriteError(er); + } + catch (CryptographicException e) + { + ErrorRecord er = + SecurityUtils.CreateInvalidArgumentErrorRecord( + e, + "ImportSecureString_InvalidArgument_CryptographicError" + ); + WriteError(er); + } + + if (importedString != null) + { + WriteObject(importedString); + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..53a662ca4f9b56ab32aa964aef12c609115b9670 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -0,0 +1,623 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Internal; +using System.Security.Cryptography.X509Certificates; + +using Dbg = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the base class from which all signature commands + /// are derived. + /// + public abstract class SignatureCommandsBase : PSCmdlet + { + /// + /// Gets or sets the path to the file for which to get or set the + /// digital signature. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + public string[] FilePath + { + get + { + return _path; + } + + set + { + _path = value; + } + } + + private string[] _path; + + /// + /// Gets or sets the literal path to the file for which to get or set the + /// digital signature. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] + [Alias("PSPath", "LP")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] LiteralPath + { + get + { + return _path; + } + + set + { + _path = value; + _isLiteralPath = true; + } + } + + private bool _isLiteralPath = false; + + /// + /// Gets or sets the digital signature to be written to + /// the output pipeline. + /// + protected Signature Signature + { + get { return _signature; } + + set { _signature = value; } + } + + private Signature _signature; + + /// + /// Gets or sets the file type of the byte array containing the content with + /// digital signature. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] SourcePathOrExtension + { + get + { + return _sourcePathOrExtension; + } + + set + { + _sourcePathOrExtension = value; + } + } + + private string[] _sourcePathOrExtension; + + /// + /// File contents as a byte array. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public byte[] Content + { + get + { + return _content; + } + + set + { + _content = value; + } + } + + private byte[] _content; + + // + // name of this command + // + private readonly string _commandName; + + /// + /// Initializes a new instance of the SignatureCommandsBase class, + /// using the given command name. + /// + /// + /// The name of the command. + /// + protected SignatureCommandsBase(string name) : base() + { + _commandName = name; + } + + // + // hide default ctor + // + private SignatureCommandsBase() : base() { } + + /// + /// 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. + /// + 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 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); + } + } + } + } + + /// + /// Performs the action (ie: get signature, or set signature) + /// on the specified file. + /// + /// + /// The name of the file on which to perform the action. + /// + protected abstract Signature PerformAction(string filePath); + + /// + /// Performs the action (ie: get signature, or set signature) + /// on the specified contents. + /// + /// + /// The filename used for type if content is specified. + /// + /// + /// The file contents on which to perform the action. + /// + protected abstract Signature PerformAction(string fileName, byte[] content); + } + + /// + /// Defines the implementation of the 'get-AuthenticodeSignature' cmdlet. + /// This cmdlet extracts the digital signature from the given file. + /// + [Cmdlet(VerbsCommon.Get, "AuthenticodeSignature", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096823")] + [OutputType(typeof(Signature))] + public sealed class GetAuthenticodeSignatureCommand : SignatureCommandsBase + { + /// + /// Initializes a new instance of the GetSignatureCommand class. + /// + public GetAuthenticodeSignatureCommand() : base("Get-AuthenticodeSignature") { } + + /// + /// Gets the signature from the specified file. + /// + /// + /// The name of the file on which to perform the action. + /// + /// + /// The signature on the specified file. + /// + protected override Signature PerformAction(string filePath) + { + return SignatureHelper.GetSignature(filePath, null); + } + + /// + /// Gets the signature from the specified file contents. + /// + /// The file type associated with the contents. + /// + /// The contents of the file on which to perform the action. + /// + /// + /// The signature on the specified file contents. + /// + protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) + { + return SignatureHelper.GetSignature(sourcePathOrExtension, content); + } + } + + /// + /// Defines the implementation of the 'set-AuthenticodeSignature' cmdlet. + /// This cmdlet sets the digital signature on a given file. + /// + [Cmdlet(VerbsCommon.Set, "AuthenticodeSignature", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096919")] + [OutputType(typeof(Signature))] + public sealed class SetAuthenticodeSignatureCommand : SignatureCommandsBase + { + /// + /// Initializes a new instance of the SetAuthenticodeSignatureCommand class. + /// + public SetAuthenticodeSignatureCommand() : base("set-AuthenticodeSignature") { } + + /// + /// Gets or sets the certificate with which to sign the + /// file. + /// + [Parameter(Position = 1, Mandatory = true)] + public X509Certificate2 Certificate + { + get + { + return _certificate; + } + + set + { + _certificate = value; + } + } + + private X509Certificate2 _certificate; + + /// + /// Gets or sets the additional certificates to + /// include in the digital signature. + /// Use 'signer' to include only the signer's certificate. + /// Use 'notroot' to include all certificates in the certificate + /// chain, except for the root authority. + /// Use 'all' to include all certificates in the certificate chain. + /// + /// Defaults to 'notroot'. + /// + [Parameter(Mandatory = false)] + [ValidateSet("signer", "notroot", "all")] + public string IncludeChain + { + get + { + return _includeChain; + } + + set + { + _includeChain = value; + } + } + + private string _includeChain = "notroot"; + + /// + /// Gets or sets the Url of the time stamping server. + /// The time stamping server certifies the exact time + /// that the certificate was added to the file. + /// + [Parameter(Mandatory = false)] + public string TimestampServer + { + get + { + return _timestampServer; + } + + set + { + value ??= string.Empty; + + _timestampServer = value; + } + } + + private string _timestampServer = string.Empty; + + /// + /// Gets or sets the hash algorithm used for signing. + /// This string value must represent the name of a Cryptographic Algorithm + /// Identifier supported by Windows. + /// + [Parameter(Mandatory = false)] + public string HashAlgorithm + { + get + { + return _hashAlgorithm; + } + + set + { + _hashAlgorithm = value; + } + } + + private string _hashAlgorithm = "SHA256"; + + /// + /// Property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force + { + get + { + return _force; + } + + set + { + _force = value; + } + } + + private bool _force; + + /// + /// Sets the digital signature on the specified file. + /// + /// + /// The name of the file on which to perform the action. + /// + /// + /// The signature on the specified file. + /// + protected override Signature PerformAction(string filePath) + { + SigningOption option = GetSigningOption(IncludeChain); + + if (Certificate == null) + { + throw PSTraceSource.NewArgumentNullException("certificate"); + } + + // + // if the cert is not good for signing, we cannot + // process any more files. Exit the command. + // + if (!SecuritySupport.CertIsGoodForSigning(Certificate)) + { + Exception e = PSTraceSource.NewArgumentException( + "certificate", + SignatureCommands.CertNotGoodForSigning); + + throw e; + } + + if (!ShouldProcess(filePath)) + return null; + + FileInfo readOnlyFileInfo = null; + try + { + if (this.Force) + { + try + { + // remove readonly attributes on the file + FileInfo fInfo = new(filePath); + if (fInfo != null) + { + // Save some disk write time by checking whether file is readonly.. + if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + // remember to reset the read-only attribute later + readOnlyFileInfo = fInfo; + // Make sure the file is not read only + fInfo.Attributes &= ~(FileAttributes.ReadOnly); + } + } + } + // These are the known exceptions for File.Load and StreamWriter.ctor + catch (ArgumentException e) + { + ErrorRecord er = new( + e, + "ForceArgumentException", + ErrorCategory.WriteError, + filePath); + WriteError(er); + return null; + } + catch (IOException e) + { + ErrorRecord er = new( + e, + "ForceIOException", + ErrorCategory.WriteError, + filePath); + WriteError(er); + return null; + } + catch (UnauthorizedAccessException e) + { + ErrorRecord er = new( + e, + "ForceUnauthorizedAccessException", + ErrorCategory.PermissionDenied, + filePath); + WriteError(er); + return null; + } + catch (NotSupportedException e) + { + ErrorRecord er = new( + e, + "ForceNotSupportedException", + ErrorCategory.WriteError, + filePath); + WriteError(er); + return null; + } + catch (System.Security.SecurityException e) + { + ErrorRecord er = new( + e, + "ForceSecurityException", + ErrorCategory.PermissionDenied, + filePath); + WriteError(er); + return null; + } + } + + // + // ProcessRecord() code in base class has already + // ascertained that filePath really represents an existing + // file. Thus we can safely call GetFileSize() below. + // + + if (SecurityUtils.GetFileSize(filePath) < 4) + { + // Note that the message param comes first + string message = string.Format( + System.Globalization.CultureInfo.CurrentCulture, + UtilsStrings.FileSmallerThan4Bytes, filePath); + + PSArgumentException e = new(message, nameof(filePath)); + ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( + e, + "SignatureCommandsBaseFileSmallerThan4Bytes" + ); + + WriteError(er); + + return null; + } + + return SignatureHelper.SignFile(option, + filePath, + Certificate, + TimestampServer, + _hashAlgorithm); + } + finally + { + // reset the read-only attribute + if (readOnlyFileInfo != null) + { + readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + } + } + } + + /// + /// Not implemented. + /// + protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) + { + throw new NotImplementedException(); + } + + private struct SigningOptionInfo + { + internal SigningOption option; + internal string optionName; + + internal SigningOptionInfo(SigningOption o, string n) + { + option = o; + optionName = n; + } + } + + /// + /// Association between SigningOption.* values and the + /// corresponding string names. + /// + private static readonly SigningOptionInfo[] s_sigOptionInfo = + { + new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"), + new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"), + new SigningOptionInfo(SigningOption.AddFullCertificateChain, "all") + }; + + /// + /// Get SigningOption value corresponding to a string name. + /// + /// Name of option. + /// SigningOption. + private static SigningOption GetSigningOption(string optionName) + { + foreach (SigningOptionInfo si in s_sigOptionInfo) + { + if (string.Equals(optionName, si.optionName, + StringComparison.OrdinalIgnoreCase)) + { + return si.option; + } + } + + return SigningOption.AddFullCertificateChainExceptRoot; + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/Utils.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/Utils.cs new file mode 100644 index 0000000000000000000000000000000000000000..702b44a85182f4fef032f10880f8465e2a1f6cb5 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/Utils.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; +using System.Security; + +namespace Microsoft.PowerShell +{ + internal static class SecurityUtils + { + /// + /// Gets the size of a file. + /// + /// Path to file. + /// File size. + internal static long GetFileSize(string filePath) + { + long size = 0; + + using (FileStream fs = new(filePath, FileMode.Open)) + { + size = fs.Length; + } + + return size; + } + + /// + /// Present a prompt for a SecureString data. + /// + /// Ref to host ui interface. + /// Prompt text. + /// user input as secure string. + internal static SecureString PromptForSecureString(PSHostUserInterface hostUI, + string prompt) + { + SecureString ss = null; + + hostUI.Write(prompt); + ss = hostUI.ReadLineAsSecureString(); + hostUI.WriteLine(string.Empty); + + return ss; + } + + /// + /// + /// Resource string. + /// Error identifier. + /// Replacement params for resource string formatting. + /// + internal static + ErrorRecord CreateFileNotFoundErrorRecord(string resourceStr, + string errorId, + params object[] args) + { + string message = + StringUtil.Format( + resourceStr, + args + ); + + FileNotFoundException e = new(message); + + ErrorRecord er = new( + e, + errorId, + ErrorCategory.ObjectNotFound, + targetObject: null); + + return er; + } + + /// + /// + /// Path that was not found. + /// Error identifier. + /// ErrorRecord instance. + internal static + ErrorRecord CreatePathNotFoundErrorRecord(string path, + string errorId) + { + ItemNotFoundException e = new(path, "PathNotFound", SessionStateStrings.PathNotFound); + + ErrorRecord er = new( + e, + errorId, + ErrorCategory.ObjectNotFound, + targetObject: null); + + return er; + } + + /// + /// Create an error record for 'operation not supported' condition. + /// + /// Resource string. + /// Error identifier. + /// Replacement params for resource string formatting. + /// + internal static + ErrorRecord CreateNotSupportedErrorRecord(string resourceStr, + string errorId, + params object[] args) + { + string message = StringUtil.Format(resourceStr, args); + + NotSupportedException e = new(message); + + ErrorRecord er = new( + e, + errorId, + ErrorCategory.NotImplemented, + targetObject: null); + + return er; + } + + /// + /// Create an error record for 'operation not supported' condition. + /// + /// Exception to include in ErrorRecord. + /// Error identifier. + /// + internal static + ErrorRecord CreateInvalidArgumentErrorRecord(Exception e, + string errorId) + { + ErrorRecord er = new( + e, + errorId, + ErrorCategory.InvalidArgument, + targetObject: null); + + return er; + } + + /// + /// Convert the specified provider path to a provider path + /// and make sure that all of the following is true: + /// -- it represents a FileSystem path + /// -- it points to a file + /// -- the file exists. + /// + /// Cmdlet instance. + /// Provider path. + /// + /// filesystem path if all conditions are true, + /// null otherwise + /// + internal static string GetFilePathOfExistingFile(PSCmdlet cmdlet, + string path) + { + string resolvedProviderPath = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); + if (File.Exists(resolvedProviderPath)) + { + return resolvedProviderPath; + } + else + { + return null; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs new file mode 100644 index 0000000000000000000000000000000000000000..6d602d2d99fc93e7a3a4859643b7f61bf78f38a9 --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs @@ -0,0 +1,304 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if !UNIX + +using System; +using System.Runtime.Serialization; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Defines the base class for exceptions thrown by the + /// certificate provider when the specified item cannot be located. + /// + public class CertificateProviderItemNotFoundException : SystemException + { + /// + /// Initializes a new instance of the CertificateProviderItemNotFoundException + /// class with the default message. + /// + public CertificateProviderItemNotFoundException() : base() + { + } + + /// + /// Initializes a new instance of the CertificateProviderItemNotFoundException + /// class with the specified message. + /// + /// + /// The message to be included in the exception. + /// + public CertificateProviderItemNotFoundException(string message) : base(message) + { + } + + /// + /// Initializes a new instance of the CertificateProviderItemNotFoundException + /// class with the specified message, and inner exception. + /// + /// + /// The message to be included in the exception. + /// + /// + /// The inner exception to be included in the exception. + /// + public CertificateProviderItemNotFoundException(string message, + Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the CertificateProviderItemNotFoundException + /// class with the specified serialization information, and context. + /// + /// + /// The serialization information. + /// + /// + /// The streaming context. + /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CertificateProviderItemNotFoundException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + + /// + /// Initializes a new instance of the CertificateProviderItemNotFoundException + /// class with the specified inner exception. + /// + /// + /// The inner exception to be included in the exception. + /// + internal CertificateProviderItemNotFoundException(Exception innerException) + : base(innerException.Message, innerException) + { + } + } + + /// + /// Defines the exception thrown by the certificate provider + /// when the specified X509 certificate cannot be located. + /// + public class CertificateNotFoundException + : CertificateProviderItemNotFoundException + { + /// + /// Initializes a new instance of the CertificateNotFoundException + /// class with the default message. + /// + public CertificateNotFoundException() + : base() + { + } + + /// + /// Initializes a new instance of the CertificateNotFoundException + /// class with the specified message. + /// + /// + /// The message to be included in the exception. + /// + public CertificateNotFoundException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the CertificateNotFoundException + /// class with the specified message, and inner exception. + /// + /// + /// The message to be included in the exception. + /// + /// + /// The inner exception to be included in the exception. + /// + public CertificateNotFoundException(string message, + Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the CertificateNotFoundException + /// class with the specified serialization information, and context. + /// + /// + /// The serialization information. + /// + /// + /// The streaming context. + /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CertificateNotFoundException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + + /// + /// Initializes a new instance of the CertificateNotFoundException + /// class with the specified inner exception. + /// + /// + /// The inner exception to be included in the exception. + /// + internal CertificateNotFoundException(Exception innerException) + : base(innerException.Message, innerException) + { + } + } + + /// + /// Defines the exception thrown by the certificate provider + /// when the specified X509 store cannot be located. + /// + public class CertificateStoreNotFoundException + : CertificateProviderItemNotFoundException + { + /// + /// Initializes a new instance of the CertificateStoreNotFoundException + /// class with the default message. + /// + public CertificateStoreNotFoundException() + : base() + { + } + + /// + /// Initializes a new instance of the CertificateStoreNotFoundException + /// class with the specified serialization information, and context. + /// + /// + /// The serialization information. + /// + /// + /// The streaming context. + /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CertificateStoreNotFoundException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + + /// + /// Initializes a new instance of the CertificateStoreNotFoundException + /// class with the specified message. + /// + /// + /// The message to be included in the exception. + /// + public CertificateStoreNotFoundException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the CertificateStoreNotFoundException + /// class with the specified message, and inner exception. + /// + /// + /// The message to be included in the exception. + /// + /// + /// The inner exception to be included in the exception. + /// + public CertificateStoreNotFoundException(string message, + Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the CertificateStoreNotFoundException + /// class with the specified inner exception. + /// + /// + /// The inner exception to be included in the exception. + /// + internal CertificateStoreNotFoundException(Exception innerException) + : base(innerException.Message, innerException) + { + } + } + + /// + /// Defines the exception thrown by the certificate provider + /// when the specified X509 store location cannot be located. + /// + public class CertificateStoreLocationNotFoundException + : CertificateProviderItemNotFoundException + { + /// + /// Initializes a new instance of the CertificateStoreLocationNotFoundException + /// class with the default message. + /// + public CertificateStoreLocationNotFoundException() + : base() + { + } + + /// + /// Initializes a new instance of the CertificateStoreLocationNotFoundException + /// class with the specified serialization information, and context. + /// + /// + /// The serialization information. + /// + /// + /// The streaming context. + /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CertificateStoreLocationNotFoundException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + + /// + /// Initializes a new instance of the CertificateStoreLocationNotFoundException + /// class with the specified message. + /// + /// + /// The message to be included in the exception. + /// + public CertificateStoreLocationNotFoundException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the CertificateStoreLocationNotFoundException + /// class with the specified message, and inner exception. + /// + /// + /// The message to be included in the exception. + /// + /// + /// The inner exception to be included in the exception. + /// + public CertificateStoreLocationNotFoundException(string message, + Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the CertificateStoreLocationNotFoundException + /// class with the specified inner exception. + /// + /// + /// The inner exception to be included in the exception. + /// + internal CertificateStoreLocationNotFoundException(Exception innerException) + : base(innerException.Message, innerException) + { + } + } +} +#endif // !UNIX diff --git a/PowerShell-master/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/PowerShell-master/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs new file mode 100644 index 0000000000000000000000000000000000000000..e92502e391121c10869597e78c1191e822677baa --- /dev/null +++ b/PowerShell-master/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Configuration.Install; +using System.IO; +using System.Management.Automation; +using System.Reflection; + +using Microsoft.Win32; + +namespace Microsoft.PowerShell +{ + /// + /// PSSecurityPSSnapIn is a class for facilitating registry + /// of necessary information for PowerShell security PSSnapin. + /// + [RunInstaller(true)] + public sealed class PSSecurityPSSnapIn : PSSnapIn + { + /// + /// Create an instance of this class. + /// + public PSSecurityPSSnapIn() + : base() + { + } + + /// + /// Get name of this PSSnapin. + /// + public override string Name + { + get + { + return RegistryStrings.SecurityMshSnapinName; + } + } + + /// + /// Get the default vendor string for this PSSnapin. + /// + public override string Vendor + { + get + { + return "Microsoft"; + } + } + + /// + /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. + /// + public override string VendorResource + { + get + { + return "SecurityMshSnapInResources,Vendor"; + } + } + + /// + /// Get the default description string for this PSSnapin. + /// + public override string Description + { + get + { + return "This PSSnapIn contains cmdlets to manage MSH security."; + } + } + + /// + /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. + /// + public override string DescriptionResource + { + get + { + return "SecurityMshSnapInResources,Description"; + } + } + } +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/ConfigProvider.cs b/PowerShell-master/src/Microsoft.WSMan.Management/ConfigProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..55141379faa59898794a8fa43c721e030134387a --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -0,0 +1,6577 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Runtime.InteropServices; +using System.Security; +using System.ServiceProcess; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.XPath; + +namespace Microsoft.WSMan.Management +{ + /// + /// WsMan Provider. + /// + [CmdletProvider(WSManStringLiterals.ProviderName, ProviderCapabilities.Credentials)] + public sealed class WSManConfigProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp + { + // Plugin Name Storage + private PSObject objPluginNames = null; + + private ServiceController winrmServiceController; + + /// + /// Determines if Set-Item user input type validation is required or not. + /// It is True by default, Clear-Item will set it to false so that it can + /// pass Empty string as value for Set-Item. + /// + private bool clearItemIsCalled = false; + + private WSManHelper helper = new WSManHelper(); + + /// + /// Object contains the cache of the enumerate results for the cmdlet to execute. + /// + private readonly Dictionary enumerateMapping = new Dictionary(); + + /// + /// Mapping of ResourceURI with the XML returned by the Get call. + /// + private readonly Dictionary getMapping = new Dictionary(); + + #region ICmdletProviderSupportsHelp Members + + /// + /// This implements Get-Help for config provider custom path. + /// When user calls "Get-Help new-item" in our config provider path, this function will get called. + /// + /// + /// + /// + string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) + { + // Get the leaf node from the path for which help is requested. + int ChildIndex = path.LastIndexOf('\\'); + if (ChildIndex == -1) + { + // Means we are at host level, where no new-item is supported. Return empty string. + return string.Empty; + } + + string child = path.Substring(ChildIndex + 1); + + // We only return help for the below set of 5 commands, not for any other case. + switch (helpItemName) + { + case "New-Item": + case "Get-Item": + case "Set-Item": + case "Clear-Item": + case "Remove-Item": + break; + default: + return string.Empty; + } + + // Load the help file from the current UI culture subfolder of the module's root folder + XmlDocument document = new XmlDocument(); + CultureInfo culture = Host.CurrentUICulture; + string providerBase = this.ProviderInfo.PSSnapIn != null ? this.ProviderInfo.PSSnapIn.ApplicationBase : this.ProviderInfo.Module.ModuleBase; // "\windows\system32\WindowsPowerShell\v1.0" + string helpFile = null; + + do + { + string muiDirectory = Path.Combine(providerBase, culture.Name); + if (Directory.Exists(muiDirectory)) + { + string supposedHelpFile = Path.Combine(muiDirectory, this.ProviderInfo.HelpFile); + if (File.Exists(supposedHelpFile)) + { + helpFile = supposedHelpFile; + break; + } + } + + culture = culture.Parent; + } while (culture != culture.Parent); + + if (helpFile == null) + { + // Can't find help file. Return empty string + return string.Empty; + } + + try + { + XmlReaderSettings readerSettings = new XmlReaderSettings(); + readerSettings.XmlResolver = null; + using (XmlReader reader = XmlReader.Create(helpFile, readerSettings)) + { + document.Load(reader); + } + } + catch (XmlException) + { + return string.Empty; + } + catch (PathTooLongException) + { + return string.Empty; + } + catch (IOException) + { + return string.Empty; + } + catch (UnauthorizedAccessException) + { + return string.Empty; + } + catch (NotSupportedException) + { + return string.Empty; + } + catch (SecurityException) + { + return string.Empty; + } + + // Add the "msh" and "command" namespaces from the MAML schema + XmlNamespaceManager nsMgr = new XmlNamespaceManager(document.NameTable); + // XPath 1.0 associates empty prefix with "null" namespace; must use non-empty prefix for default namespace. + // This will not work: nsMgr.AddNamespace(string.Empty, "http://msh"); + nsMgr.AddNamespace("msh", "http://msh"); + nsMgr.AddNamespace("command", "http://schemas.microsoft.com/maml/dev/command/2004/10"); + + // Split the help item name into verb and noun + string verb = helpItemName.Split('-')[0]; + string noun = helpItemName.Substring(helpItemName.IndexOf('-') + 1); + + // Compose XPath query to select the appropriate node based on the verb, noun and id + string xpathQuery = "/msh:helpItems/msh:providerHelp/msh:CmdletHelpPaths/msh:CmdletHelpPath[@id='" + child + "' or @ID='" + child + "']/command:command/command:details[command:verb='" + verb + "' and command:noun='" + noun + "']"; + + // Execute the XPath query and if the command was found, return its MAML snippet + XmlNode result = null; + try + { + result = document.SelectSingleNode(xpathQuery, nsMgr); + } + catch (XPathException) + { + return string.Empty; + } + + if (result != null) + { + return result.ParentNode.OuterXml; + } + + return string.Empty; + } + + #endregion + + #region DriveCmdletProvider + /// + /// + /// + /// + protected override PSDriveInfo NewDrive(PSDriveInfo drive) + { + if (drive == null) + { + return null; + } + + if (!string.IsNullOrEmpty(drive.Root)) + { + AssertError(helper.GetResourceMsgFromResourcetext("NewDriveRootDoesNotExist"), false); + return null; + } + + return drive; + } + + /// + /// Adds the required drive. + /// + /// + protected override Collection InitializeDefaultDrives() + { + Collection drives = new Collection(); + drives.Add(new PSDriveInfo(WSManStringLiterals.rootpath, ProviderInfo, string.Empty, + helper.GetResourceMsgFromResourcetext("ConfigStorage"), null)); + return drives; + } + + /// + /// Removes the required drive. + /// + /// + protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) + { + WSManHelper.ReleaseSessions(); + return drive; + } + + #endregion + + #region ItemCmdletProvider + + /// + /// Get a Child Name. This method is called from MakePath method. + /// This Method helps in getting the correct case of particular element in the provider path. + /// XML is case sensitive but Powershell is not. + /// + /// + /// + protected override string GetChildName(string path) + { + string result = string.Empty; + int separatorIndex = path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator); + string hostname = string.Empty; + if (separatorIndex == -1) + { + result = path; + hostname = path; + } + else + { + result = path.Substring(separatorIndex + 1); + hostname = GetHostName(path); + } + + return GetCorrectCaseOfName(result, hostname, path); + } + + /// + /// This method is provided by the Provider infrastructure. This method is called in all actions done + /// by the provider to get the resolved path. Internally Resolve-Path is called. + /// Since Root is empty for WsMan Provider the default path generated by Makepath is not correct. + /// So we have made the tweaks in this method to return the correct resolved path. + /// + /// + /// + /// + protected override string MakePath(string parent, string child) + { + if (child.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + child = child.Remove(child.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + // For Listeners only ... should remove Listener from listener\listener but not from listener_[Hashcode] + if (parent.Equals(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase) && child.StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { + if (!child.StartsWith(parent + "_", StringComparison.OrdinalIgnoreCase)) + { + child = child.Remove(0, parent.Length); + } + } + + string path = string.Empty; + string ChildName = string.Empty; + string CorrectCaseChildName = string.Empty; + if (parent.Length != 0) + { + path = parent + WSManStringLiterals.DefaultPathSeparator + child; + } + else + { + path = child; + } + + if (path.Length != 0) + { + ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + CorrectCaseChildName = GetChildName(path); + } + + if (ChildName.Equals(CorrectCaseChildName, StringComparison.OrdinalIgnoreCase)) + { + if (child.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + child = child.Substring(0, child.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + child = child + WSManStringLiterals.DefaultPathSeparator + CorrectCaseChildName; + } + else + { + child = CorrectCaseChildName; + } + } + + string basepath = base.MakePath(parent, child); + return GetCorrectCaseOfPath(basepath); + } + + /// + /// Checks whether the path is Valid. + /// eg. winrm/config/client. + /// + /// + /// + protected override bool IsValidPath(string path) + { + bool result = false; + result = CheckValidContainerOrPath(path); + return result; + } + + /// + /// Check whether an Item Exist in the winrm configuration. + /// + /// + /// + protected override bool ItemExists(string path) + { + bool result = false; + result = CheckValidContainerOrPath(path); + return result; + } + + /// + /// Checks whether the given path has got child items. + /// e.g: This is called by Provider infrastructure when we do a Remove-Item and prompts user + /// if child items are present. + /// + /// + /// + protected override bool HasChildItems(string path) + { + string childname = string.Empty; + string strPathCheck = string.Empty; + + if (path.Length == 0 && string.IsNullOrEmpty(childname)) + { + return true; + } + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + // Get the ChildName + childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + } + + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + if (SessionObjCache.ContainsKey(path)) + { + return true; + } + + // Get the wsman host name to find the session object + string host = GetHostName(path); + + // Chks the WinRM Service + if (IsPathLocalMachine(host)) + { + if (!IsWSManServiceRunning()) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(Force); + } + } + + string WsManURI = NormalizePath(path, host); + + lock (WSManHelper.AutoSession) + { + // Gets the session object from the cache. + object sessionobj; + SessionObjCache.TryGetValue(host, out sessionobj); + + /* + WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Child Items. + + * 1. Branch in to Listeners (winrm/config/listener) + * 2. Branch in to CertMapping (winrm/config/service/certmapping) + * 3. Branch in to Plugin (winrm/config/plugin) - Plugin is subdivided in Resources,Security & InitParams + * 4. Rest all the branches like Client, Shell(WinRS) ,Service + + */ + + // 1. Listener Checks + strPathCheck = host + WSManStringLiterals.DefaultPathSeparator; + if (WsManURI.Contains(WSManStringLiterals.containerListener)) + { + XmlDocument xmlListeners = EnumerateResourceValue(sessionobj, WsManURI); + if (xmlListeners != null) + { + Hashtable KeyCache, ListenerObjCache; + ProcessListenerObjects(xmlListeners, out ListenerObjCache, out KeyCache); + if (ListenerObjCache.Count > 0) + { + return true; + } + } + } + // 2. Client Certificate Checks + else if (WsManURI.Contains(WSManStringLiterals.containerCertMapping)) + { + XmlDocument xmlCertificates = EnumerateResourceValue(sessionobj, WsManURI); + Hashtable KeyCache, CertificatesObjCache; + if (xmlCertificates == null) + { + return true; + } + + ProcessCertMappingObjects(xmlCertificates, out CertificatesObjCache, out KeyCache); + if (CertificatesObjCache.Count > 0) + { + return true; + } + } + // 3. Plugin and its internal structure Checks + else if (WsManURI.Contains(WSManStringLiterals.containerPlugin)) + { + strPathCheck += WSManStringLiterals.containerPlugin; + // Check for Plugin path + XmlDocument xmlPlugins = FindResourceValue(sessionobj, WsManURI, null); + string currentpluginname = string.Empty; + int PluginCount = GetPluginNames(xmlPlugins, out objPluginNames, out currentpluginname, path); + if (path.Equals(strPathCheck)) + { + if (PluginCount > 0) + { + return true; + } + else + { + return false; + } + } + + strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator + currentpluginname; + if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) + { + if (objPluginNames != null) + { + if (objPluginNames.Properties.Match(currentpluginname).Count > 0) + { + return true; + } + else + { + return false; + } + } + } + + string filter = WsManURI + "?Name=" + currentpluginname; + XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); + ArrayList arrSecurities = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurities); + ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML); + strPathCheck += WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + if (arrResources != null && arrResources.Count > 0) + { + return true; + } + } + + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + if (arrInitParams != null && arrInitParams.Count > 0) + { + return true; + } + } + + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + { + XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters); + if (nodeListForQuotas.Count > 0) + { + XmlNode pluginQuotas = nodeListForQuotas[0]; + return pluginQuotas.Attributes.Count > 0; + } + + return false; + } + + if (arrResources != null) + { + foreach (PSObject objresource in arrResources) + { + string sResourceDirName = objresource.Properties["ResourceDir"].Value.ToString(); + if (path.Contains(sResourceDirName)) + { + strPathCheck = strPathCheck + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathCheck + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity)) + { + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + if (arrSecurities != null && arrSecurities.Count > 0) + { + return true; + } + } + + strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_")) + { + if (arrSecurities == null) + { + return false; + } + + foreach (PSObject security in arrSecurities) + { + string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); + if (path.EndsWith(sSecurity, StringComparison.OrdinalIgnoreCase)) + return true; + } + } + } + } + } + } + } + else + // 4. All Other Item Checks + { + string getXml = this.GetResourceValueInXml(sessionobj, WsManURI, null); + XmlDocument xmlResourceValues = new XmlDocument(); + xmlResourceValues.LoadXml(getXml.ToLowerInvariant()); + XmlNodeList nodes = SearchXml(xmlResourceValues, childname, WsManURI, path, host); + if (nodes != null) + { + return IsItemContainer(nodes); + } + } + + return false; + } + } + + /// + /// This cmdlet is used to get a particular item. + /// cd wsman:\localhost\client> Get-Item .\Auth. + /// + /// + [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] + protected override void GetItem(string path) + { + string childname = string.Empty; + + if (path.Length == 0 && string.IsNullOrEmpty(childname)) + { + WriteItemObject(GetItemPSObjectWithTypeName(WSManStringLiterals.rootpath, WSManStringLiterals.ContainerChildValue, null, null, null, WsManElementObjectTypes.WSManConfigElement), WSManStringLiterals.rootpath, true); + return; + } + + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + // Get the ChildName + childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + } + else + { + childname = path; + } + + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + if (childname.Equals(path, StringComparison.OrdinalIgnoreCase)) + { + if (SessionObjCache.ContainsKey(childname)) + { + WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, null, "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement), WSManStringLiterals.rootpath + WSManStringLiterals.DefaultPathSeparator + childname, true); + } + + return; + } + + path = path.Substring(0, path.LastIndexOf(childname, StringComparison.OrdinalIgnoreCase)); + + // Get the wsman host name to find the session object + string host = GetHostName(path); + string uri = NormalizePath(path, host); + + lock (WSManHelper.AutoSession) + { + // Gets the session object from the cache. + object sessionobj; + SessionObjCache.TryGetValue(host, out sessionobj); + + XmlDocument xmlResource = FindResourceValue(sessionobj, uri, null); + if (xmlResource == null) + { + return; + } + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + string strPathChk = host + WSManStringLiterals.DefaultPathSeparator; + + if (path.Contains(strPathChk + WSManStringLiterals.containerListener)) + { + GetItemListenerOrCertMapping(path, xmlResource, WSManStringLiterals.containerListener, childname, host); + } + else if (path.Contains(strPathChk + WSManStringLiterals.containerClientCertificate)) + { + GetItemListenerOrCertMapping(path, xmlResource, WSManStringLiterals.containerClientCertificate, childname, host); + } + else if (path.Contains(strPathChk + WSManStringLiterals.containerPlugin)) + { + string currentpluginname = string.Empty; + GetPluginNames(xmlResource, out objPluginNames, out currentpluginname, path); + + if (path.EndsWith(strPathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + try + { + WriteItemObject(GetItemPSObjectWithTypeName(objPluginNames.Properties[childname].Name, objPluginNames.Properties[childname].Value.ToString(), null, new string[] { "Name=" + objPluginNames.Properties[childname].Name }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true); + } + catch (PSArgumentNullException) { return; } + catch (NullReferenceException) { return; } + } + else + { + strPathChk = strPathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; + string filter = uri + "?Name=" + currentpluginname; + XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); + if (CurrentPluginXML == null) + { + return; + } + + PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML, true); + ArrayList arrSecurity = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); + ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML); + try + { + if (path.Contains(strPathChk + currentpluginname)) + { + if (path.EndsWith(strPathChk + currentpluginname, StringComparison.OrdinalIgnoreCase)) + { + if (!objPluginlevel.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + WriteItemObject(GetItemPSObjectWithTypeName(objPluginlevel.Properties[childname].Name, objPluginlevel.Properties[childname].TypeNameOfValue, objPluginlevel.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + objPluginlevel.Properties[childname].Name, false); + } + else + { + WriteItemObject(GetItemPSObjectWithTypeName(objPluginlevel.Properties[childname].Name, objPluginlevel.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + objPluginlevel.Properties[childname].Name, true); + } + } + + strPathChk = strPathChk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerResources)) + { + if (arrResources == null) + { + return; + } + + if (path.EndsWith(strPathChk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + foreach (PSObject p in arrResources) + { + if (p.Properties["ResourceDir"].Value.ToString().Equals(childname)) + { + WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, new string[] { "ResourceURI=" + p.Properties["ResourceUri"].Value.ToString() }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true); + } + } + + return; + } + + strPathChk = strPathChk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length); + string sResourceDirName = string.Empty; + if (Sepindex == -1) + { + sResourceDirName = path.Substring(strPathChk.Length); + } + else + { + sResourceDirName = path.Substring(strPathChk.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length) - (strPathChk.Length)); + } + + if (path.Contains(strPathChk + sResourceDirName)) + { + if (path.EndsWith(strPathChk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + foreach (PSObject p in arrResources) + { + if (sResourceDirName.Equals(p.Properties["ResourceDir"].Value.ToString(), StringComparison.OrdinalIgnoreCase)) + { + p.Properties.Remove("ResourceDir"); + if (p.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, true); + } + else + { + WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false); + } + + break; + } + } + + return; + } + + strPathChk = strPathChk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity)) + { + if (arrSecurity == null) + { + return; + } + + foreach (PSObject p in arrSecurity) + { + if (path.EndsWith(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + WriteItemObject(GetItemPSObjectWithTypeName(p.Properties["SecurityDIR"].Value.ToString(), WSManStringLiterals.ContainerChildValue, null, new string[] { "Uri=" + p.Properties["Uri"].Value.ToString() }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties["SecurityDIR"].Value.ToString(), true); + } + else + { + string sSecurityDirName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1, path.Length - (path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1)); + if (sSecurityDirName.Equals(p.Properties["SecurityDIR"].Value.ToString())) + { + p.Properties.Remove("SecurityDIR"); + WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false); + break; + } + } + } + + return; + } + } + } + else if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentpluginname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + if (arrInitParams != null) + { + foreach (PSObject p in arrInitParams) + { + if (p.Properties.Match(childname, PSMemberTypes.NoteProperty).Count > 0) + WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, "InitParams", WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false); + } + } + } + else if (path.EndsWith(WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + { + // Get the Quotas element from the config XML. + XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters); + if (nodeListForQuotas.Count > 0) + { + XmlNode pluginQuotas = nodeListForQuotas[0]; + foreach (XmlAttribute attrOfQuotas in pluginQuotas.Attributes) + { + if (childname.Equals(attrOfQuotas.Name, StringComparison.OrdinalIgnoreCase)) + { + PSObject objectToAdd = + GetItemPSObjectWithTypeName( + attrOfQuotas.Name, + attrOfQuotas.Value.GetType().ToString(), + attrOfQuotas.Value, + null, + null, + WsManElementObjectTypes.WSManConfigLeafElement); + + string pathToAdd = + string.Format( + CultureInfo.InvariantCulture, + "{0}{1}{2}", + path, + WSManStringLiterals.DefaultPathSeparator, + attrOfQuotas.Name); + + WriteItemObject(objectToAdd, pathToAdd, false); + break; + } + } + } + } + } + } + catch (PSArgumentNullException) { return; } + catch (NullReferenceException) { return; } + } + } + else + { + try + { + PSObject mshObject = null; + if (!uri.Equals(WinrmRootName[0], StringComparison.OrdinalIgnoreCase)) + { + foreach (XmlNode innerResourceNodes in xmlResource.ChildNodes) + { + mshObject = ConvertToPSObject(innerResourceNodes); + } + } + else + { + mshObject = BuildHostLevelPSObjectArrayList(sessionobj, uri, false); + } + + if (mshObject != null) + { + if (mshObject.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + WriteItemObject(GetItemPSObjectWithTypeName(mshObject.Properties[childname].Name, mshObject.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + mshObject.Properties[childname].Name, true); + } + else + { + WriteItemObject( + GetItemPSObjectWithTypeName( + mshObject.Properties[childname].Name, + mshObject.Properties[childname].TypeNameOfValue, + mshObject.Properties[childname].Value, + null, null, + WsManElementObjectTypes.WSManConfigLeafElement, + mshObject), + path + WSManStringLiterals.DefaultPathSeparator + mshObject.Properties[childname].Name, + false); + } + } + } + catch (PSArgumentNullException) { return; /*Leaving this known exception for no value found. Not Throwing error.*/} + catch (NullReferenceException) { return; /*Leaving this known exception for no value found. Not Throwing error.*/} + } + } + } + + /// + /// This cmdlet is used to set the value of a particular item. + /// cd wsman:\localhost\client> Set-Item .\TrustedHosts -value "*" + /// This has one dynamic parameter. It is used with TrustedHost only. + /// The parameter is -Concatenate. + /// + /// + /// + [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] + protected override void SetItem(string path, object value) + { + if (value == null) + { + throw new ArgumentException(helper.GetResourceMsgFromResourcetext("value")); + } + + string ChildName = string.Empty; + + if (path.Length == 0 && string.IsNullOrEmpty(ChildName)) + { + AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + return; + } + + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + // Get the ChildName + ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + } + else + { + ChildName = path; + } + + if (ChildName.Equals(path, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + return; + } + + if (!this.clearItemIsCalled) + { + value = this.ValidateAndGetUserObject(ChildName, value); + + // The value will be Null only if the object provided by User is not of accepted type. + // As of now, this can only happen in case of RunAsUserName and RunAsPassword + if (value == null) + { + return; + } + } + else + { + // If validation is not required, that means Clear-Item cmdlet is called. + // Clear-Item is not allowed on RunAsPassword, Admin should call Clear-Item RunAsUser + // if he intends to disable RunAs on the Plugin. + if (string.Equals(ChildName, WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("ClearItemOnRunAsPassword"), false); + return; + } + } + + string whatIfMessage = string.Format(CultureInfo.CurrentUICulture, helper.GetResourceMsgFromResourcetext("SetItemWhatIfAndConfirmText"), path, value); + if (!ShouldProcess(whatIfMessage, string.Empty, string.Empty)) + { + return; + } + + path = path.Substring(0, path.LastIndexOf(ChildName, StringComparison.OrdinalIgnoreCase)); + + // Get the wsman host name to find the session object + string host = GetHostName(path); + string uri = NormalizePath(path, host); + + // Chk for Winrm Service + if (IsPathLocalMachine(host)) + { + if (!IsWSManServiceRunning()) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(this.Force); + } + } + + bool settingPickedUpDynamically = false; + + lock (WSManHelper.AutoSession) + { + // Gets the session object from the cache. + object sessionobj; + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + SessionObjCache.TryGetValue(host, out sessionobj); + + List warningMessage = new List(); + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + string strPathChk = host + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerListener)) + { + SetItemListenerOrClientCertificate(sessionobj, uri, PKeyListener, ChildName, value, path, WSManStringLiterals.containerListener, host); + } + else if (path.Contains(strPathChk + WSManStringLiterals.containerClientCertificate)) + { + SetItemListenerOrClientCertificate(sessionobj, uri, PKeyCertMapping, ChildName, value, path, WSManStringLiterals.containerClientCertificate, host); + } + else if (path.Contains(strPathChk + WSManStringLiterals.containerPlugin)) + { + if (path.EndsWith(strPathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + } + + try + { + XmlDocument xmlPlugins = FindResourceValue(sessionobj, uri, null); + string currentpluginname = string.Empty; + GetPluginNames(xmlPlugins, out objPluginNames, out currentpluginname, path); + if (string.IsNullOrEmpty(currentpluginname)) + { + if (!this.clearItemIsCalled) + { + // Don't need an error if ClearItem is called. + AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + } + + return; + } + + string filter = uri + "?Name=" + currentpluginname; + + CurrentConfigurations pluginConfiguration = new CurrentConfigurations((IWSManSession)sessionobj); + + string pluginXML = this.GetResourceValueInXml((IWSManSession)sessionobj, filter, null); + pluginConfiguration.RefreshCurrentConfiguration(pluginXML); + + XmlDocument CurrentPluginXML = pluginConfiguration.RootDocument; + + ArrayList arrSecurity = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); + ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML); + + try + { + // Remove XML:LANG attribute if present. + // If not present ignore the exception. + pluginConfiguration.RemoveOneConfiguration("./attribute::xml:lang"); + } + catch (ArgumentException) + { } + + strPathChk = strPathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathChk + currentpluginname, StringComparison.OrdinalIgnoreCase)) + { + if (WSManStringLiterals.ConfigRunAsUserName.Equals(ChildName, StringComparison.OrdinalIgnoreCase) && value is PSCredential runAsCredentials) + { + // UserName + value = runAsCredentials.UserName; + + pluginConfiguration.UpdateOneConfiguration( + ".", + WSManStringLiterals.ConfigRunAsPasswordName, + GetStringFromSecureString(runAsCredentials.Password)); + } + + if (WSManStringLiterals.ConfigRunAsPasswordName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrEmpty( + pluginConfiguration.GetOneConfiguration( + string.Format( + CultureInfo.InvariantCulture, + "./attribute::{0}", + WSManStringLiterals.ConfigRunAsUserName)))) + { + // User Cannot set RunAsPassword if, RunAsUser is not present. + AssertError(helper.GetResourceMsgFromResourcetext("SetItemOnRunAsPasswordNoRunAsUser"), false); + } + + value = GetStringFromSecureString(value); + } + + pluginConfiguration.UpdateOneConfiguration(".", ChildName, value.ToString()); + } + + strPathChk = strPathChk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerResources)) + { + if (path.EndsWith(strPathChk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + return; + } + + strPathChk = strPathChk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length); + string sResourceDirName = string.Empty; + if (Sepindex == -1) + { + sResourceDirName = path.Substring(strPathChk.Length); + } + else + { + sResourceDirName = path.Substring(strPathChk.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length) - (strPathChk.Length)); + } + + if (path.Contains(strPathChk + sResourceDirName)) + { + if (path.EndsWith(strPathChk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + if (arrResources == null) + { + return; + } + + if (ChildName.Equals(WSManStringLiterals.ConfigResourceUriName, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("NoChangeValue"), false); + return; + } + + foreach (PSObject p in arrResources) + { + if (sResourceDirName.Equals(p.Properties["ResourceDir"].Value.ToString(), StringComparison.OrdinalIgnoreCase)) + { + string xpathToUse = string.Format( + CultureInfo.InvariantCulture, + "{0}:{1}/{0}:{2}[attribute::{3}='{4}']", + CurrentConfigurations.DefaultNameSpacePrefix, + WSManStringLiterals.containerResources, + WSManStringLiterals.containerSingleResource, + WSManStringLiterals.ConfigResourceUriName, + p.Properties[WSManStringLiterals.ConfigResourceUriName].Value.ToString()); + + if (!p.Properties[ChildName].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + // Allow Set-Item on non-container values only. + pluginConfiguration.UpdateOneConfiguration(xpathToUse, ChildName, value.ToString()); + } + else + { + AssertError(helper.GetResourceMsgFromResourcetext("NoChangeValue"), false); + } + } + } + } + + strPathChk = strPathChk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity)) + { + if (path.EndsWith(strPathChk + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("NoChangeValue"), false); + return; + } + + if (arrSecurity == null) + { + return; + } + + if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity + "_")) + { + // Any setting inside security for plugin is picked up by service dynamically + settingPickedUpDynamically = true; + + foreach (PSObject p in arrSecurity) + { + string sSecurityDirName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1, path.Length - (path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1)); + if (sSecurityDirName.Equals(p.Properties["SecurityDIR"].Value.ToString(), StringComparison.OrdinalIgnoreCase)) + { + if (!Force) + { + string query = helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityQuery"); + query = string.Format(CultureInfo.CurrentCulture, query, currentpluginname); + if (!ShouldContinue(query, helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityCaption"))) + { + return; + } + } + + // NameSpace:Resources/NameSpace:Resource[@ResourceUri={''}]/NameSpace:Security[@Uri='{2}'] + string xpathToUse = string.Format( + CultureInfo.InvariantCulture, + "{0}:{1}/{0}:{2}[@{6}='{7}']/{0}:{3}[@{4}='{5}']", + CurrentConfigurations.DefaultNameSpacePrefix, + WSManStringLiterals.containerResources, + WSManStringLiterals.containerSingleResource, + WSManStringLiterals.containerSecurity, + WSManStringLiterals.ConfigSecurityUri, + p.Properties[WSManStringLiterals.ConfigSecurityUri].Value.ToString(), + WSManStringLiterals.ConfigResourceUriName, + p.Properties["ParentResourceUri"].Value.ToString()); + + pluginConfiguration.UpdateOneConfiguration(xpathToUse, ChildName, value.ToString()); + } + } + } + } + } + } + else if (path.EndsWith(strPathChk + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + foreach (PSObject p in arrInitParams) + { + if (p.Properties[ChildName] != null) + { + string xpathToUse = string.Format( + CultureInfo.InvariantCulture, + "{0}:{1}/{0}:{2}[@{3}='{4}']", + CurrentConfigurations.DefaultNameSpacePrefix, + WSManStringLiterals.containerInitParameters, + WSManStringLiterals.ConfigInitializeParameterTag, + WSManStringLiterals.ConfigInitializeParameterName, + p.Properties[ChildName].Name); + + pluginConfiguration.UpdateOneConfiguration(xpathToUse, WSManStringLiterals.ConfigInitializeParameterValue, value.ToString()); + + break; + } + } + } + else if (path.EndsWith(strPathChk + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + { + string xpathToUse = string.Format( + CultureInfo.InvariantCulture, + "{0}:{1}", + CurrentConfigurations.DefaultNameSpacePrefix, + WSManStringLiterals.containerQuotasParameters); + + pluginConfiguration.UpdateOneConfiguration(xpathToUse, ChildName, value.ToString()); + + if (ppqWarningConfigurations.Contains(ChildName.ToLowerInvariant())) + { + string adjustedChileName = ChildName; + + if (ChildName.Equals("IdleTimeoutms", StringComparison.OrdinalIgnoreCase)) + { + adjustedChileName = "IdleTimeout"; + } + + string pathForGlobalQuota = + string.Format( + CultureInfo.InvariantCulture, + @"{0}:\{1}\{2}\{3}", + WSManStringLiterals.rootpath, + host, + WSManStringLiterals.containerShell, + adjustedChileName); + + warningMessage.Add(string.Format(helper.GetResourceMsgFromResourcetext("SetItemWarnigForPPQ"), pathForGlobalQuota)); + } + } + + SessionObjCache.TryGetValue(host, out sessionobj); + string resourceUri = string.Format( + CultureInfo.InvariantCulture, + "{0}?Name={1}", + uri, + currentpluginname); + + try + { + pluginConfiguration.PutConfigurationOnServer(resourceUri); + + // Show Win RM service restart warning only when the changed setting is not picked up dynamically + if (!settingPickedUpDynamically) + { + if (IsPathLocalMachine(host)) + { + warningMessage.Add(helper.GetResourceMsgFromResourcetext("SetItemServiceRestartWarning")); + } + else + { + warningMessage.Add(string.Format(helper.GetResourceMsgFromResourcetext("SetItemServiceRestartWarningRemote"), host)); + } + } + } + finally + { + if (!string.IsNullOrEmpty(pluginConfiguration.ServerSession.Error)) + { + AssertError(pluginConfiguration.ServerSession.Error, true); + } + } + } + catch (PSArgumentException) + { + AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + return; + } + catch (PSArgumentNullException) + { + AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + return; + } + catch (NullReferenceException) + { + AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + return; + } + } + else + { + try + { + Hashtable cmdlinevalue = new Hashtable(); + if (ChildName.Equals("TrustedHosts", StringComparison.OrdinalIgnoreCase) || ChildName.Equals("RootSDDL", StringComparison.OrdinalIgnoreCase)) + { + if (value.GetType().FullName.Equals("System.String")) + { + if (!Force) + { + string query = string.Empty; + string caption = helper.GetResourceMsgFromResourcetext("SetItemGeneralSecurityCaption"); + if (ChildName.Equals("TrustedHosts", StringComparison.OrdinalIgnoreCase)) + { + query = helper.GetResourceMsgFromResourcetext("SetItemTrustedHostsWarningQuery"); + } + else if (ChildName.Equals("RootSDDL", StringComparison.OrdinalIgnoreCase)) + { + query = helper.GetResourceMsgFromResourcetext("SetItemRootSDDLWarningQuery"); + } + + if (!ShouldContinue(query, caption)) + { + return; + } + } + + if (DynamicParameters is WSManProviderSetItemDynamicParameters dynParams) + { + if (dynParams.Concatenate) + { + if (!string.IsNullOrEmpty(value.ToString())) + { + // ',' is used as the delimiter in WSMan for TrustedHosts. + value = SplitAndUpdateStringUsingDelimiter(sessionobj, uri, ChildName, value.ToString(), ","); + } + } + } + + cmdlinevalue.Add(ChildName, value); + } + else + { + AssertError(helper.GetResourceMsgFromResourcetext("TrustedHostValueTypeError"), false); + } + } + else + { + cmdlinevalue.Add(ChildName, value); + + if (globalWarningUris.Contains(uri) && globalWarningConfigurations.Contains(ChildName.ToLowerInvariant())) + { + warningMessage.Add(string.Format(helper.GetResourceMsgFromResourcetext("SetItemWarningForGlobalQuota"), value)); + } + } + + PutResourceValue(sessionobj, uri, cmdlinevalue, host); + } + catch (COMException e) + { + AssertError(e.Message, false); + return; + } + } + + foreach (string warnings in warningMessage) + { + WriteWarning(warnings); + } + } + } + + /// + /// This command is used to clear the value of a item. + /// + /// + protected override void ClearItem(string path) + { + this.clearItemIsCalled = true; + SetItem(path, string.Empty); + this.clearItemIsCalled = false; + } + + /// + /// This is method which create the dynamic or runtime parameter for set-item. + /// + /// + /// + /// + protected override object SetItemDynamicParameters(string path, object value) + { + if (path.Length != 0) + { + string hostname = GetHostName(path); + if (path.EndsWith(hostname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerClient, StringComparison.OrdinalIgnoreCase)) + { + // To have Tab completion. + return new WSManProviderSetItemDynamicParameters(); + } + else if (path.EndsWith(hostname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerClient + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerTrustedHosts, StringComparison.OrdinalIgnoreCase)) + { + // To Support Concatenate parameter for trustedhosts. + return new WSManProviderSetItemDynamicParameters(); + } + } + + return null; + } + + #endregion + + #region ContainerCmdletProvider + /// + /// Gets the Child items. dir functionality + /// wsman:\localhost\client> dir. + /// + /// + /// + protected override void GetChildItems(string path, bool recurse) + { + GetChildItemsOrNames(path, ProviderMethods.GetChildItems, recurse); + } + + /// + /// This method gives the names of child items. this is used for Tab completion. + /// + /// + /// + protected override void GetChildNames(string path, ReturnContainers returnContainers) + { + GetChildItemsOrNames(path, ProviderMethods.GetChildNames, false); + } + #endregion + + #region NavigationalCmdletProvider + + /// + /// Checks whether the specified path is a container path. + /// + /// + /// + protected override bool IsItemContainer(string path) + { + string childname = string.Empty; + string strPathCheck = string.Empty; + + if (path.Length == 0 && string.IsNullOrEmpty(childname)) + { + return true; + } + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + // Get the ChildName + childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + } + + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + if (SessionObjCache.ContainsKey(path)) + { + return true; + } + + // Get the wsman host name to find the session object + string host = GetHostName(path); + if (string.IsNullOrEmpty(host)) + { + return false; + } + + string WsManURI = NormalizePath(path, host); + + lock (WSManHelper.AutoSession) + { + // Gets the session object from the cache. + object sessionobj; + SessionObjCache.TryGetValue(host, out sessionobj); + + /* + WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Container + + * 1. Branch in to Listeners (winrm/config/listener) + * 2. Branch in to CertMapping (winrm/config/service/certmapping) + * 3. Branch in to Plugin (winrm/config/plugin) - Plugin is subdivided in Resources,Security & InitParams + * 4. Rest all the branches like Client, Shell(WinRS) ,Service + + */ + + // 1. Listener Checks + strPathCheck = host + WSManStringLiterals.DefaultPathSeparator; + if (WsManURI.Contains(WSManStringLiterals.containerListener)) + { + strPathCheck += WSManStringLiterals.containerListener; + if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + XmlDocument xmlListeners = EnumerateResourceValue(sessionobj, WsManURI); + + if (xmlListeners != null) + { + Hashtable KeyCache, ListenerObjCache; + ProcessListenerObjects(xmlListeners, out ListenerObjCache, out KeyCache); + if (KeyCache.Contains(childname)) + { + return true; + } + } + } + // 2. Client Certificate Checks + else if (WsManURI.Contains(WSManStringLiterals.containerCertMapping)) + { + strPathCheck += WSManStringLiterals.containerClientCertificate; + if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + XmlDocument xmlCertificates = EnumerateResourceValue(sessionobj, WsManURI); + if (xmlCertificates != null) + { + Hashtable KeyCache, CertificatesObjCache; + ProcessCertMappingObjects(xmlCertificates, out CertificatesObjCache, out KeyCache); + if (KeyCache.Contains(childname)) + { + return true; + } + } + } + // 3. Plugin and its internal structure Checks + else if (WsManURI.Contains(WSManStringLiterals.containerPlugin)) + { + strPathCheck += WSManStringLiterals.containerPlugin; + // Check for Plugin path + if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + strPathCheck += WSManStringLiterals.DefaultPathSeparator; + XmlDocument xmlPlugins = FindResourceValue(sessionobj, WsManURI, null); + + string currentpluginname = string.Empty; + GetPluginNames(xmlPlugins, out objPluginNames, out currentpluginname, path); + strPathCheck += currentpluginname; + if (path.EndsWith(currentpluginname, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + string filter = WsManURI + "?Name=" + currentpluginname; + XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); + ArrayList arrSecurities = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurities); + if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + strPathCheck += WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (arrResources == null || arrResources.Count == 0) + { + return false; + } + + foreach (PSObject objresource in arrResources) + { + string sResourceDirName = objresource.Properties["ResourceDir"].Value.ToString(); + if (path.Contains(sResourceDirName)) + { + strPathCheck = strPathCheck + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathCheck + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity)) + { + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_")) + { + if (arrSecurities == null) + { + return false; + } + + foreach (PSObject security in arrSecurities) + { + string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); + if (path.EndsWith(sSecurity, StringComparison.OrdinalIgnoreCase)) + return true; + } + } + } + } + } + } + else + // 4. All Other Item Checks + { + string getXml = this.GetResourceValueInXml(sessionobj, WsManURI, null); + XmlDocument xmlResourceValues = new XmlDocument(); + xmlResourceValues.LoadXml(getXml.ToLowerInvariant()); + XmlNodeList nodes = SearchXml(xmlResourceValues, childname, WsManURI, path, host); + bool result = IsItemContainer(nodes); + return result; + } + + return false; + } + } + + /// + /// Removes a particular item. + /// + /// + /// + protected override void RemoveItem(string path, bool recurse) + { + bool throwerror = true; + if (path.Length == 0) + { + AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); + return; + } + + string ChildName = string.Empty; + + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + // Get the ChildName + ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + } + else + { + ChildName = path; + } + + if (ChildName.Equals(path, StringComparison.OrdinalIgnoreCase)) + { + if (ChildName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false); + } + + helper.RemoveFromDictionary(ChildName); + return; + } + + path = path.Substring(0, path.LastIndexOf(ChildName, StringComparison.OrdinalIgnoreCase)); + + // Get the wsman host name to find the session object + string host = GetHostName(path); + string uri = NormalizePath(path, host); + + // Chk for Winrm Service + if (IsPathLocalMachine(host)) + { + if (!IsWSManServiceRunning()) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(this.Force); + } + } + + lock (WSManHelper.AutoSession) + { + // Gets the session object from the cache. + object sessionobj; + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + SessionObjCache.TryGetValue(host, out sessionobj); + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + string inputStr = string.Empty; + string strPathCheck = string.Empty; + strPathCheck = host + WSManStringLiterals.DefaultPathSeparator; + + if (path.Contains(strPathCheck + WSManStringLiterals.containerPlugin))//(path.Contains(@"\plugin")) + { + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + // Deletes all the Plugin when user is in WsMan:\Localhost\Plugin. + string pluginUri = uri + "?Name=" + ChildName; + DeleteResourceValue(sessionobj, pluginUri, null, recurse); + return; + } + + strPathCheck += WSManStringLiterals.containerPlugin; + int pos = 0; string pName = null; + + pos = path.LastIndexOf(strPathCheck + WSManStringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase) + strPathCheck.Length + 1; + int pindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, pos); + if (pindex != -1) + { + pName = path.Substring(pos, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, pos) - pos); + } + else + { + pName = path.Substring(pos); + } + + string filter1 = uri + "?Name=" + pName; + XmlDocument pxml = GetResourceValue(sessionobj, filter1, null); + + PSObject ps = ProcessPluginConfigurationLevel(pxml); + ArrayList SecurityArray = null; + ArrayList ResourceArray = ProcessPluginResourceLevel(pxml, out SecurityArray); + ArrayList InitParamArray = ProcessPluginInitParamLevel(pxml); + + strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator + pName + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathCheck + WSManStringLiterals.containerResources)) + { + // Remove-Item is called for one of the resources. + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + throwerror = false; + ResourceArray = RemoveItemfromResourceArray(ResourceArray, ChildName, string.Empty, "ResourceDir"); + } + + if (throwerror) + { + strPathCheck = strPathCheck + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathCheck.Length); + string sResourceDirName = string.Empty; + if (Sepindex == -1) + { + sResourceDirName = path.Substring(strPathCheck.Length); + } + else + { + sResourceDirName = path.Substring(strPathCheck.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathCheck.Length) - (strPathCheck.Length)); + } + + strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + throwerror = false; + SecurityArray = RemoveItemfromResourceArray(SecurityArray, ChildName, string.Empty, "SecurityDIR"); + } + } + } + else if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + // Remove-Item is called for one of the initialization Parameters. + throwerror = false; + InitParamArray = RemoveItemfromResourceArray(InitParamArray, ChildName, "InitParams", string.Empty); + } + + if (throwerror) + { + AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); + return; + } + + inputStr = ConstructPluginXml(ps, uri, host, "Set", ResourceArray, SecurityArray, InitParamArray); + try + { + ((IWSManSession)sessionobj).Put(uri + "?Name=" + pName, inputStr, 0); + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + else if (path.EndsWith(strPathCheck + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + throwerror = false; + RemoveListenerOrCertMapping(sessionobj, uri, ChildName, PKeyListener, true); + } + else if (path.EndsWith(strPathCheck + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + throwerror = false; + RemoveListenerOrCertMapping(sessionobj, uri, ChildName, PKeyCertMapping, false); + } + + if (throwerror) + { + AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); + return; + } + } + } + + /// + /// This method creates a new item of listener,clientcertificate etc. + /// + /// + /// + /// + protected override void NewItem(string path, string itemTypeName, object newItemValue) + { + string inputStr = string.Empty; + object sessionobj; + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + return; + } + + if (path.Length == 0 || !path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + NewItemCreateComputerConnection(path); + return; + } + + // Get the wsman host name to find the session object + string host = GetHostName(path); + + if (string.IsNullOrEmpty(host)) + { + throw new ArgumentException(helper.GetResourceMsgFromResourcetext("InvalidPath")); + } + + // Chk for Winrm Service + if (IsPathLocalMachine(host)) + { + if (!IsWSManServiceRunning()) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(this.Force); + } + } + + string uri = NormalizePath(path, host); + + lock (WSManHelper.AutoSession) + { + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + SessionObjCache.TryGetValue(host, out sessionobj); + + string strPathChk = host + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerPlugin))//(path.Contains(@"\plugin")) + { + NewItemPluginOrPluginChild(sessionobj, path, host, uri); + } + else if (path.EndsWith(strPathChk + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + WSManProvidersListenerParameters niParams = DynamicParameters as WSManProvidersListenerParameters; + Hashtable listenerparams = new Hashtable(); + listenerparams.Add("Address", niParams.Address); + listenerparams.Add("Transport", niParams.Transport); + listenerparams.Add("Enabled", niParams.Enabled); + if (niParams.HostName != null) + { + listenerparams.Add("Hostname", niParams.HostName); + } + + if (niParams.URLPrefix != null) + { + listenerparams.Add("URLPrefix", niParams.URLPrefix); + } + + if (niParams.IsPortSpecified) + { + listenerparams.Add("Port", niParams.Port); + } + + if (niParams.CertificateThumbPrint != null) + { + listenerparams.Add("CertificateThumbPrint", niParams.CertificateThumbPrint); + } + + NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, listenerparams, WSManStringLiterals.containerListener, helper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerQuery"), helper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerCaption")); + } + else if (path.EndsWith(strPathChk + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + WSManProviderClientCertificateParameters dynParams = DynamicParameters as WSManProviderClientCertificateParameters; + SessionObjCache.TryGetValue(host, out sessionobj); + Hashtable Certparams = new Hashtable(); + Certparams.Add("Issuer", dynParams.Issuer); + Certparams.Add("Subject", dynParams.Subject); + Certparams.Add("Uri", dynParams.URI); + if (this.Credential.UserName != null) + { + System.Net.NetworkCredential nwCredentials = this.Credential.GetNetworkCredential(); + Certparams.Add("UserName", nwCredentials.UserName); + Certparams.Add("Password", nwCredentials.Password); + } + + Certparams.Add("Enabled", dynParams.Enabled); + NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, Certparams, WSManStringLiterals.containerClientCertificate, helper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertQuery"), helper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertCaption")); + } + else + { + AssertError(helper.GetResourceMsgFromResourcetext("NewItemNotSupported"), false); + return; + } + } + } + + /// + /// Dynamic parameter used by New-Item. According to different path. This method return the + /// required dynamic parameters. + /// + /// + /// + /// + /// + protected override object NewItemDynamicParameters(string path, string itemTypeName, object newItemValue) + { + if (path.Length == 0) + { + return new WSManProviderNewItemComputerParameters(); + } + + string hostname = GetHostName(path); + string strpathchk = hostname + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strpathchk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + return new WSManProviderNewItemPluginParameters(); + } + + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + return new WSManProviderInitializeParameters(); + } + + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + return new WSManProviderNewItemResourceParameters(); + } + + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + return new WSManProviderNewItemSecurityParameters(); + } + + if (path.EndsWith(strpathchk + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + return new WSManProvidersListenerParameters(); + } + + if (path.EndsWith(strpathchk + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + return new WSManProviderClientCertificateParameters(); + } + + return null; + } + + #endregion + + #region Private + + /// + /// This method creates the connection to new machine in wsman provider. + /// This is called from New-Item. + /// + /// + private void NewItemCreateComputerConnection(string Name) + { + helper = new WSManHelper(this); + string parametersetName = "ComputerName"; + if (DynamicParameters is WSManProviderNewItemComputerParameters dynParams) + { + if (dynParams.ConnectionURI != null) + { + parametersetName = "URI"; + } + + helper.CreateWsManConnection(parametersetName, dynParams.ConnectionURI, dynParams.Port, Name, dynParams.ApplicationName, dynParams.UseSSL, dynParams.Authentication, dynParams.SessionOption, this.Credential, dynParams.CertificateThumbprint); + if (dynParams.ConnectionURI != null) + { + string[] constrsplit = dynParams.ConnectionURI.OriginalString.Split(":" + dynParams.Port + "/" + dynParams.ApplicationName, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + Name = constrsplit1[1].Trim(); + } + + WriteItemObject(GetItemPSObjectWithTypeName(Name, WSManStringLiterals.ContainerChildValue, null, null, "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement), WSManStringLiterals.rootpath + WSManStringLiterals.DefaultPathSeparator + Name, true); + } + else + { + dynParams = new WSManProviderNewItemComputerParameters(); + helper.CreateWsManConnection(parametersetName, dynParams.ConnectionURI, dynParams.Port, Name, dynParams.ApplicationName, dynParams.UseSSL, dynParams.Authentication, dynParams.SessionOption, this.Credential, dynParams.CertificateThumbprint); + WriteItemObject(GetItemPSObjectWithTypeName(Name, WSManStringLiterals.ContainerChildValue, null, null, "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement), WSManStringLiterals.rootpath + WSManStringLiterals.DefaultPathSeparator + Name, true); + } + } + + /// + /// This method creates the Listener or ClientCertificate in wsman provider. + /// This is called from New-Item. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void NewItemContainerListenerOrCertMapping(object sessionobj, string path, string uri, string host, Hashtable InputParams, string ContainerListenerOrCertMapping, string ShouldContinueQuery, string ShouldContinueCaption) + { + if (!Force) + { + if (!ShouldContinue(ShouldContinueQuery, ShouldContinueCaption)) + { + return; + } + } + + string inputstr = GetInputStringForCreate(uri, InputParams, host); + CreateResourceValue(sessionobj, uri, inputstr, InputParams); + XmlDocument xmlResource = GetResourceValue(sessionobj, uri, InputParams); + Hashtable CCache = null; + Hashtable kCache = null; + if (ContainerListenerOrCertMapping.Equals(WSManStringLiterals.containerClientCertificate)) + { + ProcessCertMappingObjects(xmlResource, out CCache, out kCache); + } + else if (ContainerListenerOrCertMapping.Equals(WSManStringLiterals.containerListener)) + { + ProcessListenerObjects(xmlResource, out CCache, out kCache); + } + + if (CCache != null && CCache.Count > 0) + { + foreach (DictionaryEntry resource in CCache) + { + WriteItemObject(GetItemPSObjectWithTypeName(resource.Key.ToString(), WSManStringLiterals.ContainerChildValue, null, (string[])kCache[resource.Key], string.Empty, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + resource.Key.ToString(), true); + } + } + } + + /// + /// This method creates the Plugin and its child items in wsman provider. + /// This is called from New-Item. + /// + /// + /// + /// + /// + private void NewItemPluginOrPluginChild(object sessionobj, string path, string host, string uri) + { + PSObject mshObj = new PSObject(); + string PluginName = string.Empty; + string inputStr = string.Empty; + + string strPathChk = host + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin; + if (!path.Equals(strPathChk)) + { + int separatorindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length + 1); + if (separatorindex == -1) + { + PluginName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + } + // to create a new plugin + if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) + { + if (DynamicParameters is WSManProviderNewItemPluginParameters niParams) + { + if (string.IsNullOrEmpty(niParams.File)) + { + mshObj.Properties.Add(new PSNoteProperty("Name", niParams.Plugin)); + mshObj.Properties.Add(new PSNoteProperty("Filename", niParams.FileName)); + mshObj.Properties.Add(new PSNoteProperty("Resource", niParams.Resource)); + mshObj.Properties.Add(new PSNoteProperty("SDKVersion", niParams.SDKVersion)); + mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); + + if (niParams.RunAsCredential != null) + { + mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigRunAsUserName, niParams.RunAsCredential.UserName)); + mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigRunAsPasswordName, niParams.RunAsCredential.Password)); + } + + if (niParams.AutoRestart) + { + mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigAutoRestart, niParams.AutoRestart)); + } + + if (niParams.ProcessIdleTimeoutSec.HasValue) + { + mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigProcessIdleTimeoutSec, niParams.ProcessIdleTimeoutSec.Value)); + } + + if (niParams.UseSharedProcess) + { + mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigUseSharedProcess, niParams.UseSharedProcess)); + } + + if (niParams.XMLRenderingType != null) + { + mshObj.Properties.Add(new PSNoteProperty("XmlRenderingType", niParams.XMLRenderingType)); + } + else + { + mshObj.Properties.Add(new PSNoteProperty("XmlRenderingType", "Text")); + } + + inputStr = ConstructPluginXml(mshObj, uri, host, "New", null, null, null); + PluginName = niParams.Plugin; + } + else + { + inputStr = ReadFile(niParams.File); + } + } + else + { + ErrorRecord er = new ErrorRecord(new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewItemNotSupported")), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + string filter = uri + "?Name=" + PluginName; + CreateResourceValue(sessionobj, filter, inputStr, null); + WriteItemObject(GetItemPSObjectWithTypeName(PluginName, WSManStringLiterals.ContainerChildValue, null, new string[] { "Name=" + PluginName }, string.Empty, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + PluginName, true); + } + else + {// to create an internal item of as plugin + string pName = string.Empty; + string NewItem = string.Empty; + string[] Keys = null; + + int pos = path.LastIndexOf(strPathChk + WSManStringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase) + strPathChk.Length + 1; + int pindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, pos); + if (pindex != -1) + { + pName = path.Substring(pos, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, pos) - pos); + } + else + { + pName = path.Substring(pos); + } + + string filter = uri + "?Name=" + pName; + XmlDocument pxml = GetResourceValue(sessionobj, filter, null); + + ArrayList SecurityArray = null; + PSObject ps = ProcessPluginConfigurationLevel(pxml); + ArrayList ResourceArray = ProcessPluginResourceLevel(pxml, out SecurityArray); + ArrayList InitParamArray = ProcessPluginInitParamLevel(pxml); + + strPathChk = strPathChk + WSManStringLiterals.DefaultPathSeparator + pName + WSManStringLiterals.DefaultPathSeparator; + if (path.Contains(strPathChk + WSManStringLiterals.containerResources)) + { + strPathChk += WSManStringLiterals.containerResources; + if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) + { + if (DynamicParameters is WSManProviderNewItemResourceParameters niParams) + { + mshObj.Properties.Add(new PSNoteProperty("Resource", niParams.ResourceUri)); + mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); + + inputStr = ConstructResourceXml(mshObj, null, null); + XmlDocument xdoc = new XmlDocument(); + xdoc.LoadXml(inputStr); + + ArrayList arrList = null; + ArrayList NewResource = ProcessPluginResourceLevel(xdoc, out arrList); + + NewItem = ((PSObject)NewResource[0]).Properties["ResourceDir"].Value.ToString(); + Keys = new string[] { "Uri=" + ((PSObject)NewResource[0]).Properties["ResourceURI"].Value.ToString() }; + + if (ResourceArray != null) + { + ResourceArray.Add(NewResource[0]); + } + else + { + ResourceArray = NewResource; + } + } + } + + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length); + string sResourceDirName = string.Empty; + if (Sepindex != -1) + { + sResourceDirName = path.Substring(strPathChk.Length + 1, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length + 1) - (strPathChk.Length + 1)); + } + + strPathChk = strPathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName; + + if (path.EndsWith(strPathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + if (!Force) + { + string query = helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityQuery"); + query = string.Format(CultureInfo.CurrentCulture, query, pName); + if (!ShouldContinue(query, helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityCaption"))) + { + return; + } + } + // Construct the Uri from Resource_XXXX resource dir. + PSObject resourceDirProperties = GetItemValue(strPathChk); + if ((resourceDirProperties == null) || (resourceDirProperties.Properties["ResourceUri"] == null)) + { + string message = helper.FormatResourceMsgFromResourcetext("ResourceURIMissingInResourceDir", + "ResourceUri", strPathChk); + AssertError(message, false); + return; // AssertError is going to throw - return silences some static analysis tools + } + + WSManProviderNewItemSecurityParameters niParams = DynamicParameters as WSManProviderNewItemSecurityParameters; + mshObj.Properties.Add(new PSNoteProperty("Uri", resourceDirProperties.Properties["ResourceUri"].Value)); + mshObj.Properties.Add(new PSNoteProperty("Sddl", niParams.Sddl)); + + inputStr = ConstructSecurityXml(mshObj, null, string.Empty); + XmlDocument xdoc = new XmlDocument(); + xdoc.LoadXml(inputStr); + + ArrayList newSecurity = new ArrayList(); + newSecurity = ProcessPluginSecurityLevel(newSecurity, xdoc, sResourceDirName, resourceDirProperties.Properties["ResourceUri"].Value.ToString()); + + NewItem = ((PSObject)newSecurity[0]).Properties["SecurityDIR"].Value.ToString(); + Keys = new string[] { "Uri=" + ((PSObject)newSecurity[0]).Properties["Uri"].Value.ToString() }; + + if (SecurityArray != null) + { + SecurityArray.Add(newSecurity[0]); + } + else + { + SecurityArray = newSecurity; + } + } + } + + if (path.EndsWith(strPathChk + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + WSManProviderInitializeParameters niParams = DynamicParameters as WSManProviderInitializeParameters; + mshObj.Properties.Add(new PSNoteProperty(niParams.ParamName, niParams.ParamValue)); + inputStr = ConstructInitParamsXml(mshObj, null); + XmlDocument xdoc = new XmlDocument(); + xdoc.LoadXml(inputStr); + ArrayList newInitParam = ProcessPluginInitParamLevel(xdoc); + NewItem = niParams.ParamName; + if (InitParamArray != null) + { + InitParamArray.Add(newInitParam[0]); + } + else + { + InitParamArray = ProcessPluginInitParamLevel(xdoc); + } + } + + inputStr = ConstructPluginXml(ps, uri, host, "Set", ResourceArray, SecurityArray, InitParamArray); + try + { + ((IWSManSession)sessionobj).Put(uri + "?" + "Name=" + pName, inputStr, 0); + if (path.EndsWith(strPathChk + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + WriteItemObject(GetItemPSObjectWithTypeName(mshObj.Properties[NewItem].Name, mshObj.Properties[NewItem].TypeNameOfValue, mshObj.Properties[NewItem].Value, null, "InitParams", WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + mshObj.Properties[NewItem].Name, false); + } + else + { + WriteItemObject(GetItemPSObjectWithTypeName(NewItem, WSManStringLiterals.ContainerChildValue, null, Keys, string.Empty, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + NewItem, true); + } + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + } + + /// + /// Returns the object to be written to the console. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfElement, object Value, string[] keys, string ExtendedTypeName, WsManElementObjectTypes WSManElementObjectType, PSObject input = null) + { + PSObject mshObject = null; + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigElement)) + { + WSManConfigElement element = new WSManConfigElement(Name, TypeNameOfElement); + mshObject = new PSObject(element); + } + + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigContainerElement)) + { + WSManConfigContainerElement element = new WSManConfigContainerElement(Name, TypeNameOfElement, keys); + mshObject = new PSObject(element); + } + + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigLeafElement)) + { + object source = null; + + if (input != null) + { + string sourceProp = Name + WSManStringLiterals.HiddenSuffixForSourceOfValue; + if (input.Properties[sourceProp] != null) + { + source = input.Properties[sourceProp].Value; + } + } + + WSManConfigLeafElement element = new WSManConfigLeafElement(Name, Value, TypeNameOfElement, source); + mshObject = new PSObject(element); + } + + if (!string.IsNullOrEmpty(ExtendedTypeName)) + { + StringBuilder types = new StringBuilder(string.Empty); + if (mshObject != null) + { + types.Append(mshObject.ImmediateBaseObject.GetType().FullName); + types.Append('#'); + types.Append(ExtendedTypeName); + mshObject.TypeNames.Insert(0, types.ToString()); + } + } + + return mshObject; + } + + /// + /// Called from setitem. This set the value in Listener and Client Certificate container. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void SetItemListenerOrClientCertificate(object sessionObj, string ResourceURI, string[] PrimaryKeys, string childName, object value, string path, string parent, string host) + { + Hashtable objcache = null; + Hashtable Keyscache = null; + XmlDocument xmlResource = EnumerateResourceValue(sessionObj, ResourceURI); + + if (xmlResource == null) + { + AssertError(helper.GetResourceMsgFromResourcetext("InvalidPath"), false); + } + + if (ResourceURI.EndsWith(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + ProcessListenerObjects(xmlResource, out objcache, out Keyscache); + } + else if (ResourceURI.EndsWith(WSManStringLiterals.containerCertMapping, StringComparison.OrdinalIgnoreCase)) + { + ProcessCertMappingObjects(xmlResource, out objcache, out Keyscache); + } + + if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + parent, StringComparison.OrdinalIgnoreCase)) + { + AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + } + else + { + if (!Force) + { + if (!ShouldContinue(helper.GetResourceMsgFromResourcetext("SetItemShouldContinueQuery"), helper.GetResourceMsgFromResourcetext("SetItemShouldContinueCaption"))) + { + return; + } + } + + string item = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + try + { + Hashtable cmdlinevalue = new Hashtable(); + cmdlinevalue.Add(childName, value); + foreach (string key in PrimaryKeys) + { + cmdlinevalue.Add(key, ((PSObject)objcache[item]).Properties[key].Value); + } + + PutResourceValue(sessionObj, ResourceURI, cmdlinevalue, host); + } + catch (COMException e) + { + ErrorRecord er = new ErrorRecord(e, "COMException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + } + + /// + /// Get the input string for create. + /// + /// + /// + /// + /// + private static string GetInputStringForCreate(string ResourceURI, Hashtable value, string host) + { + string putstr = string.Empty; + string nilns = string.Empty; + StringBuilder sbvalues = new StringBuilder(); + + if (value.Count > 0) + { + foreach (string key in value.Keys) + { + if (!IsPKey(key, ResourceURI)) + { + sbvalues.Append("'); + sbvalues.Append(EscapeValuesForXML(((Hashtable)value)[key].ToString())); + sbvalues.Append("'); + } + } + } + + string root = GetRootNodeName(ResourceURI); + putstr = "" + sbvalues.ToString() + ""; + return putstr; + } + + /// + /// Reads the file. used by New-Item for Plugin creation from file. + /// + /// + /// + private string ReadFile(string path) + { + string putstr = string.Empty; + try + { + string filePath = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); + putstr = File.ReadAllText(filePath, System.Text.Encoding.UTF8); + } + // known exceptions + catch (ArgumentNullException e) + { + ErrorRecord er = new ErrorRecord(e, "ArgumentNullException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (UnauthorizedAccessException e) + { + ErrorRecord er = new ErrorRecord(e, "UnauthorizedAccessException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (NotSupportedException e) + { + ErrorRecord er = new ErrorRecord(e, "NotSupportedException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (FileNotFoundException e) + { + ErrorRecord er = new ErrorRecord(e, "FileNotFoundException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (DirectoryNotFoundException e) + { + ErrorRecord er = new ErrorRecord(e, "DirectoryNotFoundException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (System.Security.SecurityException e) + { + ErrorRecord er = new ErrorRecord(e, "SecurityException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + + return putstr; + } + + /// + /// Get the host name or the machine to which connected. + /// This is used by most of the methods like GetItem,GetChildItem, NewItem, SetItem,RemoveItem etc... + /// + /// + /// + private string GetHostName(string path) + { + string sHostname = path; + try + { + // HostName is always followed by root name + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + sHostname = path.Substring(0, path.IndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + if (!SessionObjCache.ContainsKey(sHostname)) + sHostname = null; + } + catch (ArgumentNullException e) + { + ErrorRecord er = new ErrorRecord(e, "ArgumentNullException", ErrorCategory.InvalidArgument, null); + WriteError(er); + } + + return sHostname; + } + + private static string GetRootNodeName(string ResourceURI) + { + string tempuri = string.Empty; + if (ResourceURI.Contains('?')) + { + ResourceURI = ResourceURI.Split('?').GetValue(0).ToString(); + } + + const string PTRN_URI_LAST = "([a-z_][-a-z0-9._]*)$"; + Regex objregex = new Regex(PTRN_URI_LAST, RegexOptions.IgnoreCase); + MatchCollection regexmatch = objregex.Matches(ResourceURI); + if (regexmatch.Count > 0) + { + tempuri = regexmatch[0].Value; + } + + return tempuri; + } + + private static string EscapeValuesForXML(string value) + { + StringBuilder esc_str = new StringBuilder(); + for (int i = 0; i <= value.Length - 1; i++) + { + switch (value[i]) + { + case '&': + { + esc_str.Append("&"); + break; + } + case '<': + { + esc_str.Append("<"); + break; + } + case '>': + { + esc_str.Append(">"); + break; + } + case '\"': + { + esc_str.Append("""); + break; + } + case '\'': + { + esc_str.Append("'"); + break; + } + default: + { + esc_str.Append(value[i]); + break; + } + } + } + + return esc_str.ToString(); + } + + private static bool IsItemContainer(XmlNodeList nodes) + { + bool result = false; + if (nodes.Count != 0) + { + if (nodes[0].ChildNodes.Count != 0) + { + if (!nodes[0].FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + { + result = true; + } + } + } + + return result; + } + + private XmlNodeList SearchXml(XmlDocument resourcexmldocument, string searchitem, string ResourceURI, string path, string host) + { + XmlNodeList nodes = null; + try + { + string xpathString = string.Empty; + if (ResourceURI.EndsWith(WSManStringLiterals.containerWinrs, StringComparison.OrdinalIgnoreCase)) + { + if (path.Equals(host + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerShell, StringComparison.OrdinalIgnoreCase)) + { + searchitem = WSManStringLiterals.containerWinrs.ToLowerInvariant(); + } + } + + if (ResourceURI.EndsWith("Config", StringComparison.OrdinalIgnoreCase) || !ResourceURI.EndsWith(searchitem, StringComparison.OrdinalIgnoreCase)) + { + xpathString = @"/*/*[local-name()=""" + searchitem.ToLowerInvariant() + @"""]"; + } + else + { + xpathString = @"/*[local-name()=""" + searchitem.ToLowerInvariant() + @"""]"; + } + + nodes = resourcexmldocument.SelectNodes(xpathString); + } + catch (System.Xml.XPath.XPathException ex) + { + ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidArgument, null); + WriteError(er); + } + + return nodes; + } + + #region "WsMan linking Operations" + /// + /// To put a resource value. Wsman put operation. + /// + /// + /// + /// + /// + private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable value, string host) + { + XmlDocument inputxml = null; + try + { + inputxml = GetResourceValue(sessionobj, ResourceURI, value); + if (inputxml != null) + { + bool Itemfound = false; + XmlNamespaceManager nsmgr = new XmlNamespaceManager(inputxml.NameTable); + string uri_schema = SetSchemaPath(ResourceURI); + nsmgr.AddNamespace("cfg", uri_schema); + string xpath = SetXPathString(ResourceURI); + XmlNodeList nodelist = inputxml.SelectNodes(xpath, nsmgr); + if (nodelist != null && nodelist.Count == 1) + { + XmlNode node = (XmlNode)nodelist.Item(0); + if (node.HasChildNodes) + { + for (int i = 0; i < node.ChildNodes.Count; i++) + { + if ((node.ChildNodes[i].ChildNodes.Count == 0) || node.ChildNodes[i].FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + { + foreach (string key in value.Keys) + { + // to make sure we dont set values at inner level. + // for eg: when set-item at winrm/config we dont take input at below level + if (!IsPKey(key, ResourceURI)) + { + if (node.ChildNodes[i].LocalName.Equals(key, StringComparison.OrdinalIgnoreCase)) + { + node.ChildNodes[i].InnerText = value[key].ToString(); + Itemfound = true; + } + } + } + } + } + + if (Itemfound) + { + ResourceURI = GetURIWithFilter(ResourceURI, value); + ((IWSManSession)sessionobj).Put(ResourceURI, node.OuterXml, 0); + } + else + { + AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + return; + } + } + } + } + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + + private string GetResourceValueInXml(object sessionobj, string ResourceURI, Hashtable cmdlinevalues) + { + try + { + ResourceURI = GetURIWithFilter(ResourceURI, cmdlinevalues); + + string returnValue = string.Empty; + + if (!this.getMapping.TryGetValue(ResourceURI, out returnValue)) + { + returnValue = ((IWSManSession)sessionobj).Get(ResourceURI, 0); + this.getMapping.Add(ResourceURI, returnValue); + } + + return returnValue; + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + + /// + /// WSMan Get operation. + /// + /// + /// + /// + /// + private XmlDocument GetResourceValue(object sessionobj, string ResourceURI, Hashtable cmdlinevalues) + { + XmlDocument xmlResource = null; + + string strValueXml = this.GetResourceValueInXml(sessionobj, ResourceURI, cmdlinevalues); + xmlResource = new XmlDocument(); + xmlResource.LoadXml(strValueXml); + + return xmlResource; + } + + /// + /// WsMan Enumerate operation. + /// + /// + /// + /// + private XmlDocument EnumerateResourceValue(object sessionobj, string ResourceURI) + { + XmlDocument xmlEnumResources = null; + + if (!this.enumerateMapping.TryGetValue(ResourceURI, out xmlEnumResources)) + { + try + { + object value = ((IWSManSession)sessionobj).Enumerate(ResourceURI, string.Empty, string.Empty, 0); + string strXmlValue = string.Empty; + + while (!((IWSManEnumerator)value).AtEndOfStream) + { + strXmlValue += ((IWSManEnumerator)value).ReadItem(); + } + + Marshal.ReleaseComObject(value); + + if (!string.IsNullOrEmpty(strXmlValue)) + { + xmlEnumResources = new XmlDocument(); + strXmlValue = "" + strXmlValue + ""; + xmlEnumResources.LoadXml(strXmlValue); + this.enumerateMapping.Add(ResourceURI, xmlEnumResources); + } + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + + return xmlEnumResources; + } + + /// + /// WsMan Delete Operation. + /// + /// + /// + /// + /// + private void DeleteResourceValue(object sessionobj, string ResourceURI, Hashtable cmdlinevalues, bool recurse) + { + try + { + // Support only for Listener,plugin and ClientCertificate. + if (ResourceURI.Contains(WSManStringLiterals.containerPlugin) || ResourceURI.Contains(WSManStringLiterals.containerListener) || ResourceURI.Contains(WSManStringLiterals.containerCertMapping)) + { + if (cmdlinevalues != null) + { + ResourceURI = GetURIWithFilter(ResourceURI, cmdlinevalues); + } + + ((IWSManSession)sessionobj).Delete(ResourceURI, 0); + } + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + + /// + /// WsMan Create Operation. + /// + /// + /// + /// + /// + private void CreateResourceValue(object sessionobj, string ResourceURI, string resource, Hashtable cmdlinevalues) + { + try + { + if (ResourceURI.Contains(WSManStringLiterals.containerListener) || ResourceURI.Contains(WSManStringLiterals.containerPlugin) || ResourceURI.Contains(WSManStringLiterals.containerCertMapping)) + { + ResourceURI = GetURIWithFilter(ResourceURI, cmdlinevalues); + ((IWSManSession)sessionobj).Create(ResourceURI, resource, 0); + } + } + finally + { + if (!string.IsNullOrEmpty(((IWSManSession)sessionobj).Error)) + { + AssertError(((IWSManSession)sessionobj).Error, true); + } + } + } + + /// + /// To find a resource value. Both Get and Enumerate works here. + /// + /// + /// + /// + /// + private XmlDocument FindResourceValue(object sessionobj, string ResourceURI, Hashtable cmdlinevalues) + { + XmlDocument outval = null; + if (ResourceURI.Contains(WSManStringLiterals.containerListener) || ResourceURI.Contains(WSManStringLiterals.containerPlugin) || ResourceURI.Contains(WSManStringLiterals.containerCertMapping)) + { + if (cmdlinevalues == null || cmdlinevalues.Count == 0) + { + outval = EnumerateResourceValue(sessionobj, ResourceURI); + } + else + { + outval = GetResourceValue(sessionobj, ResourceURI, cmdlinevalues); + } + } + else + { + outval = GetResourceValue(sessionobj, ResourceURI, cmdlinevalues); + } + + return outval; + } + + /// + /// Checks whether a value is present in Wsman config. + /// + /// + /// + /// + /// + /// + /// + private bool ContainResourceValue(object sessionobj, string ResourceURI, string childname, string path, string host) + { + bool result = false; + string valuexml = string.Empty; + try + { + if (ResourceURI.Contains(WSManStringLiterals.containerListener) || ResourceURI.Contains(WSManStringLiterals.containerPlugin) || ResourceURI.Contains(WSManStringLiterals.containerCertMapping)) + { + object value = ((IWSManSession)sessionobj).Enumerate(ResourceURI, string.Empty, string.Empty, 0); + + while (!((IWSManEnumerator)value).AtEndOfStream) + { + valuexml += ((IWSManEnumerator)value).ReadItem(); + } + + if ((valuexml != string.Empty) && !(string.IsNullOrEmpty(valuexml))) + { + valuexml = "" + valuexml + ""; + } + + Marshal.ReleaseComObject(value); + } + else + { + valuexml = this.GetResourceValueInXml(((IWSManSession)sessionobj), ResourceURI, null); + } + + if (string.IsNullOrEmpty(valuexml)) + { + return false; + } + + XmlDocument xmlResourceValues = new XmlDocument(); + xmlResourceValues.LoadXml(valuexml.ToLowerInvariant()); + XmlNodeList nodes = SearchXml(xmlResourceValues, childname, ResourceURI, path, host); + if (nodes.Count > 0) + { + result = true; + } + } + catch (COMException) { result = false; } + + return result; + } + + #endregion "WsMan linking Operations" + + private static string GetURIWithFilter(string uri, Hashtable cmdlinevalues) + { + StringBuilder sburi = new StringBuilder(uri); + if (cmdlinevalues != null) + { + if (uri.Contains("Config/Listener")) + { + sburi.Append('?'); + sburi.Append(GetFilterString(cmdlinevalues, PKeyListener)); + } + else if (uri.Contains("Config/Service/certmapping")) + { + sburi.Append('?'); + sburi.Append(GetFilterString(cmdlinevalues, PKeyCertMapping)); + } + else if (uri.Contains("Config/Plugin")) + { + sburi.Append('?'); + sburi.Append(GetFilterString(cmdlinevalues, PKeyPlugin)); + } + } + + return sburi.ToString(); + } + + private static string GetFilterString(Hashtable cmdlinevalues, string[] pkey) + { + StringBuilder filter = new StringBuilder(); + foreach (string key in pkey) + { + if (cmdlinevalues.Contains(key)) + { + filter.Append(key); + filter.Append('='); + filter.Append(cmdlinevalues[key].ToString()); + filter.Append('+'); + } + } + + if (filter.ToString().EndsWith('+')) + filter.Remove(filter.ToString().Length - 1, 1); + return filter.ToString(); + } + + private static bool IsPKey(string value, string ResourceURI) + { + bool result = false; + if (ResourceURI.Contains(WSManStringLiterals.containerListener)) + { + result = CheckPkeysArray(null, value, PKeyListener); + } + else if (ResourceURI.Contains(WSManStringLiterals.containerPlugin)) + { + result = CheckPkeysArray(null, value, PKeyPlugin); + } + else if (ResourceURI.Contains(WSManStringLiterals.containerCertMapping)) + { + result = CheckPkeysArray(null, value, PKeyCertMapping); + } + + return result; + } + + private static bool CheckPkeysArray(Hashtable values, string value, string[] pkeys) + { + bool result = false; + if (values != null) + foreach (string key in pkeys) + { + if (values.Contains(key)) + { + result = true; + } + } + else if (!string.IsNullOrEmpty(value)) + { + foreach (string key in pkeys) + { + if (key.Equals(value, StringComparison.OrdinalIgnoreCase)) + { + result = true; + break; + } + } + } + + return result; + } + + private void WritePSObjectPropertyNames(PSObject psobject, string path) + { + foreach (PSPropertyInfo prop in psobject.Properties) + { + if (!prop.Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + WriteItemObject(prop.Name, path + WSManStringLiterals.DefaultPathSeparator + prop.Name, true); + } + else + { + WriteItemObject(prop.Name, path + WSManStringLiterals.DefaultPathSeparator + prop.Name, false); + } + } + } + + /// + /// Used to Write WSMan objects to the output console. Used by GetChildItem, GetItem and NewItem. + /// + /// + /// + /// + /// + /// + /// + private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, string path, string[] keys, string ExtendedTypeName, WsManElementObjectTypes WSManElementObjectType, bool recurse) + { + PSObject mshObject = null; + Collection directory = new Collection(); + foreach (PSPropertyInfo prop in psobject.Properties) + { + if (prop.Name.EndsWith(WSManStringLiterals.HiddenSuffixForSourceOfValue)) + { + continue; + } + + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigElement)) + { + WSManConfigElement element = new WSManConfigElement(prop.Name, prop.Value.ToString()); + mshObject = new PSObject(element); + } + + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigContainerElement)) + { + WSManConfigContainerElement element = new WSManConfigContainerElement(prop.Name, prop.Value.ToString(), keys); + mshObject = new PSObject(element); + } + + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigLeafElement)) + { + string sourceProp = prop.Name + WSManStringLiterals.HiddenSuffixForSourceOfValue; + object source = null; + if (psobject.Properties[sourceProp] != null) + { + source = psobject.Properties[sourceProp].Value; + } + + WSManConfigLeafElement element = null; + if (!prop.Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + element = new WSManConfigLeafElement(prop.Name, prop.Value, prop.TypeNameOfValue, source); + } + else + { + element = new WSManConfigLeafElement(prop.Name, null, prop.Value.ToString()); + } + + if (element != null) + { + mshObject = new PSObject(element); + } + } + + if (!string.IsNullOrEmpty(ExtendedTypeName)) + { + StringBuilder types = new StringBuilder(string.Empty); + if (mshObject != null) + { + types.Append(mshObject.ImmediateBaseObject.GetType().FullName); + types.Append('#'); + types.Append(ExtendedTypeName); + mshObject.TypeNames.Insert(0, types.ToString()); + } + } + + if (!prop.Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) + { + // This path is used by WriteItemObject to construct PSPath. + // PSPath is a provider qualified path and we dont need to specify + // provider root in this path..So I am trying to eliminate provider root + // in this case. + string pathToUse = WSManStringLiterals.rootpath.Equals(path, StringComparison.OrdinalIgnoreCase) ? + prop.Name : + (path + WSManStringLiterals.DefaultPathSeparator + prop.Name); + WriteItemObject(mshObject, pathToUse, false); + } + else + { + // This path is used by WriteItemObject to construct PSPath. + // PSPath is a provider qualified path and we dont need to specify + // provider root in this path..So I am trying to eliminate provider root + // in this case. + string pathToUse = WSManStringLiterals.rootpath.Equals(path, StringComparison.OrdinalIgnoreCase) ? + prop.Name : + (path + WSManStringLiterals.DefaultPathSeparator + prop.Name); + WriteItemObject(mshObject, pathToUse, true); + if (recurse) + { + directory.Add(prop.Name); + } + } + } + + if (recurse) + { + foreach (string dir in directory) + { + GetChildItemsRecurse(path, dir, ProviderMethods.GetChildItems, recurse); + } + } + } + + private string SplitAndUpdateStringUsingDelimiter(object sessionobj, string uri, string childname, string value, string Delimiter) + { + XmlDocument xmlResource = GetResourceValue(sessionobj, uri, null); + PSObject mshObject = null; + foreach (XmlNode innerResourceNodes in xmlResource.ChildNodes) + { + mshObject = ConvertToPSObject(innerResourceNodes); + } + + string existingvalue = string.Empty; + try + { + if (mshObject != null) + { + existingvalue = mshObject.Properties[childname].Value.ToString(); + } + + if (!string.IsNullOrEmpty(existingvalue)) + { + string[] existingsplitvalues = existingvalue.Split(Delimiter, StringSplitOptions.None); + string[] newvalues = value.Split(Delimiter, StringSplitOptions.None); + foreach (string val in newvalues) + { + if (Array.IndexOf(existingsplitvalues, val) == -1) + { + existingvalue += Delimiter + val; + } + } + } + else + { + existingvalue = value; + } + } + catch (PSArgumentException) + { + } + + return existingvalue; + } + + /// + /// For Host Level or WsMan level + /// WsMan\Localhost:\> + /// WsMan:\> + /// + /// + /// + /// + /// + private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string uri, bool IsWsManLevel) + { + PSObject mshobject = new PSObject(); + if (IsWsManLevel) + { + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + foreach (string key in SessionObjCache.Keys) + { + mshobject.Properties.Add(new PSNoteProperty(key, WSManStringLiterals.ContainerChildValue)); + } + } + else + { + if (objSessionObject != null) + { + XmlDocument ConfigXml = GetResourceValue(objSessionObject, uri, null); + // Moving in to + foreach (XmlNode node in ConfigXml.ChildNodes) + { + foreach (XmlNode node1 in node.ChildNodes) + { + // Getting Top Element in + if ((node1.ChildNodes.Count == 0) || node1.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + { + mshobject.Properties.Add(new PSNoteProperty(node1.LocalName, node1.InnerText)); + } + } + } + } + // Getting the Fixed root nodes. + foreach (string root in WinRmRootConfigs) + { + mshobject.Properties.Add(new PSNoteProperty(root, WSManStringLiterals.ContainerChildValue)); + } + } + + return mshobject; + } + + /// + /// Converts XmlNodes ChildNodes to Properties of PSObject. + /// + /// + /// + private static PSObject ConvertToPSObject(XmlNode xmlnode) + { + PSObject mshObject = new PSObject(); + foreach (XmlNode node in xmlnode.ChildNodes) + { + // If node contains 0 child-nodes, it is empty node, if it's name = "#text" then it's a simple node. + if ((node.ChildNodes.Count == 0) || node.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + { + XmlAttribute attrSource = null; + foreach (XmlAttribute attr in node.Attributes) + { + if (attr.LocalName.Equals("Source", StringComparison.OrdinalIgnoreCase)) + { + attrSource = attr; + break; + } + } + + mshObject.Properties.Add(new PSNoteProperty(node.LocalName, node.InnerText)); + + if (attrSource != null) + { + string propName = node.LocalName + WSManStringLiterals.HiddenSuffixForSourceOfValue; + mshObject.Properties.Remove(propName); + mshObject.Properties.Add(new PSNoteProperty(propName, attrSource.Value)); + } + } + else + { + mshObject.Properties.Add(new PSNoteProperty(node.LocalName, WSManStringLiterals.ContainerChildValue)); + } + } + + return mshObject; + } + + private static string SetXPathString(string uri) + { + string parent = uri.Substring(uri.LastIndexOf(WSManStringLiterals.WinrmPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase) + 1); + if (parent.Equals(WSManStringLiterals.containerWinrs, StringComparison.OrdinalIgnoreCase)) + { + parent = WSManStringLiterals.containerWinrs; + } + else if (parent.Equals(WSManStringLiterals.containerAuth, StringComparison.OrdinalIgnoreCase)) + { + parent = WSManStringLiterals.containerAuth; + } + else if (parent.Equals("certmapping", StringComparison.OrdinalIgnoreCase)) + { + parent = "CertMapping"; + } + else if (parent.Equals(WSManStringLiterals.containerService, StringComparison.OrdinalIgnoreCase)) + { + parent = WSManStringLiterals.containerService; + } + else if (parent.Equals(WSManStringLiterals.containerDefaultPorts, StringComparison.OrdinalIgnoreCase)) + { + parent = WSManStringLiterals.containerDefaultPorts; + } + else if (parent.Equals(WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + parent = WSManStringLiterals.containerPlugin; + } + + parent = "/cfg:" + parent; + return parent; + } + + private static string SetSchemaPath(string uri) + { + string schemapath = string.Empty; + uri = uri.Remove(0, WinrmRootName[0].Length); + if (uri.Contains(WSManStringLiterals.containerPlugin)) + { + schemapath = WSManStringLiterals.WsMan_Schema + "/plugin"; + } + else if (uri.Contains(WSManStringLiterals.containerClientCertificate)) + { + uri = uri.Replace(WSManStringLiterals.containerClientCertificate, "/service/certmapping"); + schemapath = WSManStringLiterals.WsMan_Schema + uri.ToLowerInvariant(); + } + else + { + schemapath = WSManStringLiterals.WsMan_Schema + uri.ToLowerInvariant(); + } + + return schemapath; + } + + /// + /// Get the Uri for the operation from a path. + /// + /// + /// + /// + private static string NormalizePath(string path, string host) + { + string uri = string.Empty; + if (path.StartsWith(host, StringComparison.OrdinalIgnoreCase)) + { + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + path = path.TrimEnd(WSManStringLiterals.DefaultPathSeparator); + + if (path.Equals(host, StringComparison.OrdinalIgnoreCase)) + { + uri = WinrmRootName[0]; + return uri; + } + + uri = path.Substring(host.Length); + uri = uri.Replace(WSManStringLiterals.DefaultPathSeparator, WSManStringLiterals.WinrmPathSeparator); + string host_prefix = host + WSManStringLiterals.DefaultPathSeparator; + if (path.StartsWith(host_prefix + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerCertMapping; + } + else if (path.StartsWith(host_prefix + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerPlugin; + } + else if (path.StartsWith(host_prefix + WSManStringLiterals.containerShell, StringComparison.OrdinalIgnoreCase)) + { + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerWinrs; + } + else if (path.StartsWith(host_prefix + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerListener; + } + else + { + if (!(path.Equals(host_prefix + WSManStringLiterals.containerService, StringComparison.OrdinalIgnoreCase) + || path.Equals(host_prefix + WSManStringLiterals.containerClient, StringComparison.OrdinalIgnoreCase) || path.EndsWith(WSManStringLiterals.containerDefaultPorts, StringComparison.OrdinalIgnoreCase) + || path.EndsWith(WSManStringLiterals.containerAuth, StringComparison.OrdinalIgnoreCase))) + { + int index = uri.LastIndexOf(WSManStringLiterals.WinrmPathSeparator); + if (index != -1) + { + uri = uri.Remove(index); + } + } + + uri = WinrmRootName[0] + uri; + } + + return uri; + } + + return uri; + } + + /// + /// Given wsman config path, gets the value of the leaf present. + /// If path is not valid or not present throws an exception. + /// + /// Currently this supports only retrieving Resource_XXXX dir contents. + /// if you need support at other levels implement them. + /// Example resource dir: WSMan:\localhost\Plugin\someplugin\Resources\Resource_XXXXXXX. + /// + /// + /// + /// A PSObject representing the contents of the path if successful, + /// Otherwise null. + /// + /// + /// 1. path is null or empty. + /// + /// + /// 1. should be of form + /// WSMan:\localhost\Plugin\someplugin\Resources\Resource_XXXXXXX + /// Other paths are not supported currently. If you want you can + /// add them later. + /// + private PSObject GetItemValue(string path) + { + ArgumentException.ThrowIfNullOrEmpty(path); + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + // Get the wsman host name to find the session object + string host = GetHostName(path); + if (string.IsNullOrEmpty(host)) + { + throw new InvalidOperationException("InvalidPath"); + } + + // Chks the WinRM Service + if (IsPathLocalMachine(host) && (!IsWSManServiceRunning())) + { + AssertError("WinRMServiceError", false); + } + + lock (WSManHelper.AutoSession) + { + object sessionobj; + // gets the sessionobject + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + SessionObjCache.TryGetValue(host, out sessionobj); + + // Normalize to the required uri + string uri = NormalizePath(path, host); + + string strPathchk = host + WSManStringLiterals.DefaultPathSeparator; + + if (path.EndsWith(host, StringComparison.OrdinalIgnoreCase)) + { + PSObject result = BuildHostLevelPSObjectArrayList(sessionobj, uri, false); + return result; + } + + // Get the XML for the resource path we are looking for. + XmlDocument outxml = FindResourceValue(sessionobj, uri, null); + if (outxml == null || !outxml.HasChildNodes) + { + return null; + } + + if (path.Contains(strPathchk + WSManStringLiterals.containerListener)) + { + // Implement the necessary functionality here when needed. + throw new NotSupportedException(); + } + else if (path.Contains(strPathchk + WSManStringLiterals.containerClientCertificate)) + { + // Implement the necessary functionality here when needed. + throw new NotSupportedException(); + } + else if (path.Contains(strPathchk + WSManStringLiterals.containerPlugin)) + { + string currentpluginname = string.Empty; + GetPluginNames(outxml, out objPluginNames, out currentpluginname, path); + if (path.EndsWith(strPathchk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + return objPluginNames; + } + else + { + // Currently this supports only retrieving Resource_XXXX dir contents. + // if you need support at other levels implement them. + // Example resource dir: WSMan:\localhost\Plugin\someplugin\Resources\Resource_67830040 + string filter = uri + "?Name=" + currentpluginname; + XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); + if (CurrentPluginXML == null) + { + return null; + } + + PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML); + ArrayList arrSecurity = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); + ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML); + strPathchk = strPathchk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; + strPathchk = strPathchk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; + + // We support only retrieving Resource_XXX dir properties only. + // other directory support can be added as needed. + if (arrResources == null) + { + return null; + } + + strPathchk = strPathchk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathchk.Length); + string sResourceDirName = string.Empty; + if (Sepindex == -1) + { + sResourceDirName = path.Substring(strPathchk.Length); + } + else + { + sResourceDirName = path.Substring(strPathchk.Length, + path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathchk.Length) - (strPathchk.Length)); + } + + if (path.EndsWith(strPathchk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + foreach (PSObject p in arrResources) + { + if (sResourceDirName.Equals(p.Properties["ResourceDir"].Value.ToString())) + { + p.Properties.Remove("ResourceDir"); + return p; + } + } + } + } + } + } + + return null; + } + + private string GetCorrectCaseOfPath(string path) + { + if (!path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + return GetChildName(path); + } + + string[] splitpath = path.Split(WSManStringLiterals.DefaultPathSeparator); + StringBuilder sbPath = new StringBuilder(); + bool first = true; + StringBuilder tempPath = new StringBuilder(); + foreach (string strpath in splitpath) + { + if (first) + { + first = false; + tempPath.Append(GetChildName(strpath)); + sbPath.Append(tempPath); + } + else + { + tempPath.Append(WSManStringLiterals.DefaultPathSeparator); + tempPath.Append(strpath); + sbPath.Append(WSManStringLiterals.DefaultPathSeparator); + sbPath.Append(GetChildName(tempPath.ToString())); + } + } + + return sbPath.ToString(); + } + + private string GetCorrectCaseOfName(string ChildName, string hostname, string path) + { + string result = ChildName; + if (ChildName != null) + { + if (!ChildName.Contains('_')) + { + if (ChildName.Equals(WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerQuotasParameters; + else if (ChildName.Equals(WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerPlugin; + else if (ChildName.Equals(WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerResources; + else if (ChildName.Equals(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerSecurity; + else if (ChildName.Equals(WSManStringLiterals.containerService, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerService; + else if (ChildName.Equals(WSManStringLiterals.containerShell, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerShell; + else if (ChildName.Equals(WSManStringLiterals.containerTrustedHosts, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerTrustedHosts; + else if (ChildName.Equals(WSManStringLiterals.containerAuth, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerAuth; + else if (ChildName.Equals(WSManStringLiterals.containerClient, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerClient; + else if (ChildName.Equals(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerClientCertificate; + else if (ChildName.Equals(WSManStringLiterals.containerDefaultPorts, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerDefaultPorts; + else if (ChildName.Equals(WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerInitParameters; + else if (ChildName.Equals(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + result = WSManStringLiterals.containerListener; + else + { + if (!string.IsNullOrEmpty(hostname)) + { + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + if (ChildName.Equals(hostname, StringComparison.OrdinalIgnoreCase)) + { + foreach (string key in SessionObjCache.Keys) + if (ChildName.Equals(key, StringComparison.OrdinalIgnoreCase)) + result = key; + } + else if (path.Contains(hostname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin)) + { + if (IsPathLocalMachine(hostname)) + { + if (!IsWSManServiceRunning()) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(this.Force); + } + } + + string uri = NormalizePath(path, hostname); + + lock (WSManHelper.AutoSession) + { + object sessionobj; + SessionObjCache.TryGetValue(hostname, out sessionobj); + XmlDocument outxml = FindResourceValue(sessionobj, uri, null); + if (outxml != null) + { + string currentPluginName = string.Empty; + GetPluginNames(outxml, out objPluginNames, out currentPluginName, path); + if (path.EndsWith(hostname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentPluginName, StringComparison.OrdinalIgnoreCase)) + { + result = currentPluginName; + } + } + } + } + } + } + } + else + { + if (ChildName.StartsWith(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + result = string.Concat(WSManStringLiterals.containerListener, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); + if (ChildName.StartsWith(WSManStringLiterals.containerSingleResource, StringComparison.OrdinalIgnoreCase)) + result = string.Concat(WSManStringLiterals.containerSingleResource, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); + if (ChildName.StartsWith(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + result = string.Concat(WSManStringLiterals.containerSecurity, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); + if (ChildName.StartsWith(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + result = string.Concat(WSManStringLiterals.containerClientCertificate, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); + } + } + + return result; + } + + private static ArrayList RemoveItemfromResourceArray(ArrayList resourceArray, string ChildName, string type, string property) + { + if (resourceArray != null) + { + bool itemfound = false; + int index = 0; + foreach (PSObject obj in resourceArray) + { + if (type.Equals("InitParams")) + { + if (obj.Properties.Match(ChildName).Count > 0) + { + itemfound = true; + break; + } + } + else + { + if (obj.Properties[property].Value.ToString().Equals(ChildName, StringComparison.OrdinalIgnoreCase)) + { + itemfound = true; + break; + } + } + + index++; + } + + if (itemfound) + resourceArray.RemoveAt(index); + } + + return resourceArray; + } + + /// + /// Get Child Items of Listener and Client Certificate. Used by Getchilditem or getchildname. + /// + /// + /// + /// + /// + /// + /// + private void GetChildItemOrNamesForListenerOrCertMapping(XmlDocument xmlResource, string ListenerOrCerMapping, string path, string host, ProviderMethods methodname, bool recurse) + { + Hashtable Objcache, Keyscache; + string PathEnd = string.Empty; + if (ListenerOrCerMapping.Equals(WSManStringLiterals.containerClientCertificate)) + { + ProcessCertMappingObjects(xmlResource, out Objcache, out Keyscache); + } + else if (ListenerOrCerMapping.Equals(WSManStringLiterals.containerListener)) + { + ProcessListenerObjects(xmlResource, out Objcache, out Keyscache); + } + else + { return; } + + if (Objcache == null || Keyscache == null) + { + return; + } + + if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + ListenerOrCerMapping, StringComparison.OrdinalIgnoreCase)) + { + foreach (string key in Keyscache.Keys) + { + switch (methodname) + { + // Get the items at Config level + case ProviderMethods.GetChildItems: + PSObject obj = new PSObject(); + obj.Properties.Add(new PSNoteProperty(key, WSManStringLiterals.ContainerChildValue)); + WritePSObjectPropertiesAsWSManElementObjects(obj, path, (string[])Keyscache[key], null, WsManElementObjectTypes.WSManConfigContainerElement, recurse); + // WriteItemObject(new WSManConfigContainerElement(key, WSManStringLiterals.ContainerChildValue, (string[])Keyscache[key]), path, true); + break; + // Get the names of container at config level + case ProviderMethods.GetChildNames: + WriteItemObject(key, path, true); + break; + } + } + + return; + } + else + { + string item = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + if (methodname.Equals(ProviderMethods.GetChildItems)) + { + WritePSObjectPropertiesAsWSManElementObjects((PSObject)Objcache[item], path, null, null, WsManElementObjectTypes.WSManConfigLeafElement, recurse); + } + else if (methodname.Equals(ProviderMethods.GetChildNames)) + { + foreach (PSPropertyInfo prop in ((PSObject)Objcache[item]).Properties) + { + WriteItemObject(prop.Name, path + WSManStringLiterals.DefaultPathSeparator + prop.Name, false); + } + } + + return; + } + } + + /// + /// Get a Listener or ClientCertificate Item. Used by GEt-Item. + /// + /// + /// + /// + /// + /// + private void GetItemListenerOrCertMapping(string path, XmlDocument xmlResource, string ContainerListenerOrClientCert, string childname, string host) + { + Hashtable Objcache, Keyscache; + if (ContainerListenerOrClientCert.Equals(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + ProcessListenerObjects(xmlResource, out Objcache, out Keyscache); + } + else if (ContainerListenerOrClientCert.Equals(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + ProcessCertMappingObjects(xmlResource, out Objcache, out Keyscache); + } + else + { return; } + + if (Objcache == null || Keyscache == null) + { + return; + } + + if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + ContainerListenerOrClientCert, StringComparison.OrdinalIgnoreCase)) + { + if (Objcache.ContainsKey(childname)) + WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, (string[])Keyscache[childname], null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true); + } + else + { + string item = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + try + { + WriteItemObject(GetItemPSObjectWithTypeName(((PSObject)Objcache[item]).Properties[childname].Name, ((PSObject)Objcache[item]).Properties[childname].TypeNameOfValue, ((PSObject)Objcache[item]).Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + childname, false); + } + catch (PSArgumentException) { return; } + } + } + + /// + /// Removes a Listener or ClientCertificate object. Used by Remove-Item cmdlets. + /// + /// + /// + /// + /// + /// + private void RemoveListenerOrCertMapping(object sessionobj, string WsManUri, string childname, string[] primarykeys, bool IsListener) + { + XmlDocument xmlresources = EnumerateResourceValue(sessionobj, WsManUri); + + if (xmlresources != null) + { + Hashtable KeysCache, ResourcesCache; + if (!IsListener) + { + ProcessCertMappingObjects(xmlresources, out ResourcesCache, out KeysCache); + } + else + { + ProcessListenerObjects(xmlresources, out ResourcesCache, out KeysCache); + } + + if (KeysCache.Contains(childname)) + { + PSObject objResource = (PSObject)ResourcesCache[childname]; + Hashtable SelectorParams = new Hashtable(); + foreach (string pKey in primarykeys) + { + SelectorParams.Add(pKey, objResource.Properties[pKey].Value); + } + + DeleteResourceValue(sessionobj, WsManUri, SelectorParams, false); + } + } + } + + /// + /// Used By ItemExists, HasChildItem,IsValidPath, IsItemContainer. + /// + /// + /// + private bool CheckValidContainerOrPath(string path) + { + if (path.Length == 0) + { + return true; + } + // if endswith '\', removes it. + + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + + string ChildName = string.Empty; + string strpathChk = string.Empty; + + if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) + { + ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); + } + else + { + ChildName = path; + } + + // Get the wsman host name to find the session object + string host = GetHostName(path); + + if (string.IsNullOrEmpty(host)) + { + return false; + } + + // Chks the WinRM Service + if (IsPathLocalMachine(host)) + { + if (!IsWSManServiceRunning()) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(Force); + } + } + + // Get URI to pass to WsMan Automation API + string uri = NormalizePath(path, host); + + if (string.IsNullOrEmpty(uri)) + { + return false; + } + + lock (WSManHelper.AutoSession) + { + object sessionobj = null; + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + SessionObjCache.TryGetValue(host, out sessionobj); + + strpathChk = host + WSManStringLiterals.DefaultPathSeparator; + // Check for host path + if (path.Equals(host, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (path.StartsWith(strpathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + // Check for Plugin path + if (path.Equals(strpathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + XmlDocument outxml = FindResourceValue(sessionobj, uri, null); + string currentpluginname = string.Empty; + GetPluginNames(outxml, out objPluginNames, out currentpluginname, path); + if (string.IsNullOrEmpty(currentpluginname)) + { + return false; + } + + string filter = uri + "?Name=" + currentpluginname; + XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); + PSObject mshPluginLvl = ProcessPluginConfigurationLevel(CurrentPluginXML); + ArrayList arrSecurities = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurities); + ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML); + strpathChk = strpathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentpluginname; + if (path.Equals(strpathChk, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + if (path.Equals(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (arrResources != null) + { + strpathChk = strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources; + foreach (PSObject objresource in arrResources) + { + string sResourceDirName = objresource.Properties["ResourceDir"].Value.ToString(); + if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + if (path.Equals(strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + else + { + if (objresource.Properties.Match(ChildName).Count > 0) + { + return true; + } + } + + if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + if (path.Equals(strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + strpathChk = strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; + if (arrSecurities == null) + { + return false; + } + + foreach (PSObject security in arrSecurities) + { + string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); + + if (path.Equals(strpathChk + sSecurity, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + else + { + if (security.Properties.Match(ChildName).Count > 0) + { + return true; + } + } + } + } + } + } + } + } + else if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + if (path.Equals(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + else + { + if (arrInitParams != null) + { + foreach (PSObject obj in arrInitParams) + { + if (obj.Properties.Match(ChildName).Count > 0) + { + return true; + } + } + } + } + } + else + { + if (mshPluginLvl.Properties.Match(ChildName).Count > 0) + { + return true; + } + } + } + else if (path.StartsWith(strpathChk + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) + { + return ItemExistListenerOrClientCertificate(sessionobj, uri, path, WSManStringLiterals.containerListener, host); + } + else if (path.StartsWith(strpathChk + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + return ItemExistListenerOrClientCertificate(sessionobj, uri, path, WSManStringLiterals.containerClientCertificate, host); + } + else + { + return (ContainResourceValue(sessionobj, uri, ChildName, path, host)); + } + + return false; + } + } + + private bool ItemExistListenerOrClientCertificate(object sessionobj, string ResourceURI, string path, string parentListenerOrCert, string host) + { + XmlDocument outxml = EnumerateResourceValue(sessionobj, ResourceURI); + if (path.Equals(host + WSManStringLiterals.DefaultPathSeparator + parentListenerOrCert, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (outxml == null) + { + return false; + } + + Hashtable KeysCache = null, objcache = null; + if (parentListenerOrCert.Equals(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) + { + ProcessCertMappingObjects(outxml, out objcache, out KeysCache); + } + else + { + ProcessListenerObjects(outxml, out objcache, out KeysCache); + } + + string PathChecked = host + WSManStringLiterals.DefaultPathSeparator + parentListenerOrCert; + int pos = PathChecked.Length + 1; + string RemainingPath = path.Substring(pos); + string CurrentNode = null; + pos = RemainingPath.IndexOf(WSManStringLiterals.DefaultPathSeparator); + if (pos == -1) + { + CurrentNode = RemainingPath; + } + else + { + CurrentNode = RemainingPath.Substring(0, pos); + } + + if (!objcache.Contains(CurrentNode)) + { + return false; + } + + if (pos == -1) + { + // means the path was only till the CurrentNode. Nothing ahead + return true; + } + + // Get the object cache from the listener object + PSObject obj = (PSObject)objcache[CurrentNode]; + + CurrentNode = RemainingPath.Substring(pos + 1); + if (CurrentNode.Contains(WSManStringLiterals.DefaultPathSeparator)) + { + // No more directories allowed after listeners objects + return false; + } + + if (obj.Properties.Match(CurrentNode).Count > 0) + { + return true; + } + + return false; + } + + /// + /// For the recurse operation of Get-ChildItems. + /// + /// + /// + /// + /// + private void GetChildItemsRecurse(string path, string childname, ProviderMethods methodname, bool recurse) + { + if (path.Equals(WSManStringLiterals.rootpath)) + { + path = childname; + } + else + { + path = path + WSManStringLiterals.DefaultPathSeparator + childname; + } + + if (HasChildItems(path)) + { + GetChildItemsOrNames(path, ProviderMethods.GetChildItems, recurse); + } + } + + /// + /// Get the child items or Names. Used by GetChildItems and GetChildNames. + /// + /// + /// + /// + [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] + private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool recurse) + { + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); + if (path.Length == 0) + { + switch (methodname) + { + case ProviderMethods.GetChildItems: + PSObject obj = BuildHostLevelPSObjectArrayList(null, string.Empty, true); + WritePSObjectPropertiesAsWSManElementObjects(obj, WSManStringLiterals.rootpath, null, + "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement, recurse); + break; + case ProviderMethods.GetChildNames: + foreach (string hostname in SessionObjCache.Keys) + { + WriteItemObject(hostname, WSManStringLiterals.rootpath, true); + } + + break; + } + + return; + } + + // if endswith '\', removes it. + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) + { + path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); + } + + // Get the wsman host name to find the session object + string host = GetHostName(path); + if (string.IsNullOrEmpty(host)) + { + throw new InvalidOperationException("InvalidPath"); + } + + // Checks the WinRM Service + if (IsPathLocalMachine(host)) + { + if (!IsWSManServiceRunning()) + { + if (methodname.Equals(ProviderMethods.GetChildItems)) + { + WSManHelper.ThrowIfNotAdministrator(); + StartWSManService(Force); + } + else if (methodname.Equals(ProviderMethods.GetChildNames)) + { + AssertError("WinRMServiceError", false); + } + } + } + + lock (WSManHelper.AutoSession) + { + object sessionobj; + // gets the sessionobject + SessionObjCache.TryGetValue(host, out sessionobj); + + // Normalize to the required uri + string uri = NormalizePath(path, host); + + string strPathchk = host + WSManStringLiterals.DefaultPathSeparator; + + if (path.EndsWith(host, StringComparison.OrdinalIgnoreCase)) + { + PSObject obj = BuildHostLevelPSObjectArrayList(sessionobj, uri, false); + switch (methodname) + { + // Get the items at Config level + case ProviderMethods.GetChildItems: + WritePSObjectPropertiesAsWSManElementObjects(obj, path, null, null, WsManElementObjectTypes.WSManConfigLeafElement, recurse); + break; + // Get the names of container at config level + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(obj, path); + break; + } + + return; + } + + XmlDocument outxml = FindResourceValue(sessionobj, uri, null); + if (outxml == null || !outxml.HasChildNodes) + { + return; + } + + if (path.Contains(strPathchk + WSManStringLiterals.containerListener)) + { + GetChildItemOrNamesForListenerOrCertMapping(outxml, WSManStringLiterals.containerListener, path, host, methodname, recurse); + } + else if (path.Contains(strPathchk + WSManStringLiterals.containerClientCertificate)) + { + GetChildItemOrNamesForListenerOrCertMapping(outxml, WSManStringLiterals.containerClientCertificate, path, host, methodname, recurse); + } + else if (path.Contains(strPathchk + WSManStringLiterals.containerPlugin)) + { + string currentpluginname = string.Empty; + GetPluginNames(outxml, out objPluginNames, out currentpluginname, path); + if (path.EndsWith(strPathchk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) + { + switch (methodname) + { + // Get the items at Plugin level + case ProviderMethods.GetChildItems: + foreach (PSPropertyInfo p in objPluginNames.Properties) + { + PSObject obj = new PSObject(); + obj.Properties.Add(new PSNoteProperty(p.Name, p.Value)); + WritePSObjectPropertiesAsWSManElementObjects(obj, path, new string[] { "Name=" + p.Name }, null, WsManElementObjectTypes.WSManConfigContainerElement, recurse); + // WriteItemObject(new PSObject(new WSManConfigContainerElement(p.Name, p.Value.ToString(), new string[] { "Name=" + p.Name })), path + WSManStringLiterals.DefaultPathSeparator + p.Name, true); + } + + break; + // Get the names of container at Plugin level + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(objPluginNames, path); + break; + } + + return; + } + else + { + string filter = uri + "?Name=" + currentpluginname; + XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); + if (CurrentPluginXML == null) + { + return; + } + + PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML, true); + ArrayList arrSecurity = null; + ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); + ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML); + strPathchk = strPathchk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathchk + currentpluginname, StringComparison.OrdinalIgnoreCase)) + { + switch (methodname) + { + // Get the items at Plugin level + case ProviderMethods.GetChildItems: + WritePSObjectPropertiesAsWSManElementObjects(objPluginlevel, path, null, null, WsManElementObjectTypes.WSManConfigLeafElement, recurse); + break; + // Get the names of container at Plugin level + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(objPluginlevel, path); + break; + } + + return; + } + else if (path.EndsWith(WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + { + // Get the Quotas element from the config XML. + XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters); + if (nodeListForQuotas.Count > 0) + { + XmlNode pluginQuotas = nodeListForQuotas[0]; + foreach (XmlAttribute attrOfQuotas in pluginQuotas.Attributes) + { + string pathToAdd = + string.Format( + CultureInfo.InvariantCulture, + "{0}{1}{2}", + path, + WSManStringLiterals.DefaultPathSeparator, + attrOfQuotas.Name); + if (methodname == ProviderMethods.GetChildNames) + { + WriteItemObject(attrOfQuotas.Name, pathToAdd, false); + } + else + { + PSObject objectToAdd = + GetItemPSObjectWithTypeName( + attrOfQuotas.Name, + attrOfQuotas.Value.GetType().ToString(), + attrOfQuotas.Value, + null, + null, + WsManElementObjectTypes.WSManConfigLeafElement); + + WriteItemObject(objectToAdd, pathToAdd, false); + } + } + } + } + else if (path.Contains(strPathchk + currentpluginname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources)) + { + strPathchk = strPathchk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathchk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) + { + if (arrResources != null) + { + foreach (PSObject p in arrResources) + { + switch (methodname) + { + // Get the items at Plugin level + case ProviderMethods.GetChildItems: + string[] key = new string[] { "Uri" + WSManStringLiterals.Equalto + p.Properties["ResourceURI"].Value.ToString() }; + PSObject obj = new PSObject(); + obj.Properties.Add(new PSNoteProperty(p.Properties["ResourceDir"].Value.ToString(), WSManStringLiterals.ContainerChildValue)); + WritePSObjectPropertiesAsWSManElementObjects(obj, path, key, null, WsManElementObjectTypes.WSManConfigContainerElement, recurse); + + // WriteItemObject(new WSManConfigContainerElement(p.Properties["ResourceDir"].Value.ToString(), WSManStringLiterals.ContainerChildValue, key), path + WSManStringLiterals.DefaultPathSeparator + p.Properties["ResourceDir"].Value.ToString(), true); + break; + case ProviderMethods.GetChildNames: + WriteItemObject(p.Properties["ResourceDir"].Value.ToString(), path, true); + break; + } + } + + return; + } + } + + strPathchk = strPathchk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathchk.Length); + string sResourceDirName = string.Empty; + if (Sepindex == -1) + { + sResourceDirName = path.Substring(strPathchk.Length); + } + else + { + sResourceDirName = path.Substring(strPathchk.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathchk.Length) - (strPathchk.Length)); + } + + if (arrResources == null) + { + return; + } + + if (path.Contains(strPathchk + sResourceDirName)) + { + if (path.EndsWith(strPathchk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) + { + foreach (PSObject p in arrResources) + { + if (sResourceDirName.Equals(p.Properties["ResourceDir"].Value.ToString())) + { + p.Properties.Remove("ResourceDir"); + switch (methodname) + { + // Get the items at Initparams level + case ProviderMethods.GetChildItems: + WritePSObjectPropertiesAsWSManElementObjects(p, path, null, null, WsManElementObjectTypes.WSManConfigLeafElement, recurse); + break; + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(p, path); + break; + } + } + } + + return; + } + + strPathchk = strPathchk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; + if (path.EndsWith(strPathchk + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase) || path.Contains(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity + "_")) + { + if (arrSecurity != null) + { + foreach (PSObject objsecurity in arrSecurity) + { + if (sResourceDirName.Equals(objsecurity.Properties["ResourceDir"].Value.ToString(), StringComparison.OrdinalIgnoreCase)) + { + if (path.EndsWith(strPathchk + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) + { + objsecurity.Properties.Remove("ResourceDir"); + switch (methodname) + { + // Get the items at Security level + case ProviderMethods.GetChildItems: + string key = "Uri" + WSManStringLiterals.Equalto + objsecurity.Properties["Uri"].Value.ToString(); + PSObject obj = new PSObject(); + obj.Properties.Add(new PSNoteProperty(objsecurity.Properties["SecurityDIR"].Value.ToString(), WSManStringLiterals.ContainerChildValue)); + WritePSObjectPropertiesAsWSManElementObjects(obj, path, new string[] { key }, null, WsManElementObjectTypes.WSManConfigContainerElement, recurse); + // WriteItemObject(new WSManConfigContainerElement(objsecurity.Properties["SecurityDIR"].Value.ToString(), WSManStringLiterals.ContainerChildValue, new string[] { key }), path + WSManStringLiterals.DefaultPathSeparator + objsecurity.Properties["SecurityDIR"].Value.ToString(), true); + + break; + case ProviderMethods.GetChildNames: + WriteItemObject(objsecurity.Properties["SecurityDIR"].Value.ToString(), path, true); + break; + } + } + else + { + string sSecurityDirName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1, path.Length - (path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1)); + if (sSecurityDirName.Equals(objsecurity.Properties["SecurityDIR"].Value.ToString(), StringComparison.OrdinalIgnoreCase)) + { + objsecurity.Properties.Remove("ResourceDir"); + objsecurity.Properties.Remove("SecurityDIR"); + switch (methodname) + { + // Get the items at Security level + case ProviderMethods.GetChildItems: + WritePSObjectPropertiesAsWSManElementObjects(objsecurity, path, null, null, WsManElementObjectTypes.WSManConfigLeafElement, recurse); + break; + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(objsecurity, path); + break; + } + } + } + } + } + } + } + } + } + else if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentpluginname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) + { + if (arrInitParams == null) + { + return; + } + + foreach (PSObject p in arrInitParams) + { + switch (methodname) + { + // Get the items at Initparams level + case ProviderMethods.GetChildItems: + WritePSObjectPropertiesAsWSManElementObjects(p, path, null, "InitParams", WsManElementObjectTypes.WSManConfigLeafElement, recurse); + break; + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(p, path); + break; + } + } + } + } + } + else + { + if ((path.EndsWith(WSManStringLiterals.containerService, StringComparison.OrdinalIgnoreCase) || path.EndsWith(WSManStringLiterals.containerTrustedHosts, StringComparison.OrdinalIgnoreCase) + || path.EndsWith(WSManStringLiterals.containerClient, StringComparison.OrdinalIgnoreCase) || path.EndsWith(WSManStringLiterals.containerDefaultPorts, StringComparison.OrdinalIgnoreCase) + || path.EndsWith(WSManStringLiterals.containerAuth, StringComparison.OrdinalIgnoreCase) || path.EndsWith(WSManStringLiterals.containerShell, StringComparison.OrdinalIgnoreCase))) + { + foreach (XmlNode node in outxml.ChildNodes) + { + PSObject mshObject = ConvertToPSObject(node); + switch (methodname) + { + case ProviderMethods.GetChildItems: + WritePSObjectPropertiesAsWSManElementObjects(mshObject, path, null, null, WsManElementObjectTypes.WSManConfigLeafElement, recurse); + break; + case ProviderMethods.GetChildNames: + WritePSObjectPropertyNames(mshObject, path); + break; + } + } + } + } + } + } + + /// + /// Get the Plugin names from the WsMan Config file. + /// + /// + /// + /// + /// + /// + private static int GetPluginNames(XmlDocument xmlPlugins, out PSObject PluginNames, out string CurrentPluginName, string path) + { + PluginNames = new PSObject(); + CurrentPluginName = string.Empty; + + // If the execution is reached this point ... that means the path should for plugins directory (..\Plugins...). + if (!path.Contains(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin)) + { + return 0; + } + + // The path will be something like \Plugin\\... + string[] splitPath = path.Split(WSManStringLiterals.DefaultPathSeparator); + + XmlNodeList pluginNodeList = xmlPlugins.GetElementsByTagName("PlugInConfiguration"); + + foreach (XmlElement e in pluginNodeList) + { + for (int i = 0; i <= e.Attributes.Count - 1; i++) + { + if (e.Attributes[i].LocalName.Equals("Name")) + { + PluginNames.Properties.Add(new PSNoteProperty(e.Attributes[i].Value, WSManStringLiterals.ContainerChildValue)); + + // If the path contains \plugin and splitLength is greater than 3 then splitLength[2] will be plugin Name. + if (splitPath.Length >= 3 && splitPath[2].Equals(e.Attributes[i].Value, StringComparison.OrdinalIgnoreCase)) + { + CurrentPluginName = e.Attributes[i].Value; + } + } + } + } + + return pluginNodeList.Count; + } + + /// + /// All Error are thrown using this method. + /// + /// + /// + private void AssertError(string ErrorMessage, bool IsWSManError) + { + if (IsWSManError) + { + XmlDocument ErrorDoc = new XmlDocument(); + ErrorDoc.LoadXml(ErrorMessage); + XmlNodeList errornodelist = ErrorDoc.GetElementsByTagName("f:Message"); + foreach (XmlNode node in errornodelist) + { + InvalidOperationException ex = new InvalidOperationException(node.InnerText); + ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + } + else + { + InvalidOperationException ex = new InvalidOperationException(ErrorMessage); + ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, null); + ThrowTerminatingError(er); + } + } + + /// + /// Checks whether WsMan Service is running. + /// + /// + private bool IsWSManServiceRunning() + { + if (winrmServiceController == null) + { + winrmServiceController = new ServiceController("WinRM"); + } + else + { + winrmServiceController.Refresh(); + } + + return (winrmServiceController.Status.Equals(ServiceControllerStatus.Running)); + } + + /// + /// Starts the WsMan service. + /// + /// + private void StartWSManService(bool force) + { + try + { + string startserviceScript = string.Format(CultureInfo.InvariantCulture, WSManStringLiterals.StartWinrmServiceSBFormat); + ScriptBlock startserviceSb = ScriptBlock.Create(startserviceScript); + Collection result = startserviceSb.Invoke(force, helper.GetResourceMsgFromResourcetext("WSManServiceStartCaption"), helper.GetResourceMsgFromResourcetext("WSManServiceStartQuery")); + if (!(bool)result[0].ImmediateBaseObject) + { + AssertError(helper.GetResourceMsgFromResourcetext("WinRMServiceError"), false); + } + } + catch (CmdletInvocationException) + { + // Eating cmdlet invocation exception. The exception is thrown when No is given. + } + } + + /// + /// Checks whether localmachine or not. If this returns true only we start the service. + /// + /// + /// + private static bool IsPathLocalMachine(string host) + { + bool hostfound = false; + // Check is Localhost + if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) + { + hostfound = true; + } + + // Check is TestMac + if (!hostfound) + { + if (host.Equals(System.Net.Dns.GetHostName(), StringComparison.OrdinalIgnoreCase)) + { + hostfound = true; + } + } + + // Check is TestMac.redmond.microsoft.corp.com + if (!hostfound) + { + System.Net.IPHostEntry hostentry = System.Net.Dns.GetHostEntry("localhost"); + if (host.Equals(hostentry.HostName, StringComparison.OrdinalIgnoreCase)) + { + hostfound = true; + } + + // Check is 127.0.0.1 or ::1 + if (!hostfound) + { + foreach (System.Net.IPAddress ipaddress in hostentry.AddressList) + { + if (ipaddress.ToString().Equals(host, StringComparison.OrdinalIgnoreCase)) + { + hostfound = true; + } + } + } + } + + // check if any IPAddress. + if (!hostfound) + { + foreach (System.Net.IPAddress ipaddress in System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())) + { + if (ipaddress.ToString().Equals(host, StringComparison.OrdinalIgnoreCase)) + { + hostfound = true; + } + } + } + + return hostfound; + } + + #region Plugin private functions + + private static void GenerateObjectNameAndKeys(Hashtable InputAttributes, string ResourceURI, string ContainerItem, out string ItemName, out string[] keys) + { + StringBuilder sbHashKey = new StringBuilder(); + string keysColumns = string.Empty; + foreach (DictionaryEntry attribute in InputAttributes) + { + if (IsPKey(attribute.Key.ToString(), ResourceURI)) + { + sbHashKey.Append(attribute.Key.ToString()); + sbHashKey.Append(WSManStringLiterals.Equalto); + sbHashKey.Append(attribute.Value.ToString()); + keysColumns = keysColumns + attribute.Key.ToString() + WSManStringLiterals.Equalto + attribute.Value.ToString() + "|"; + } + else + { + if (ContainerItem.Equals("Listener", StringComparison.OrdinalIgnoreCase) + && attribute.Key.ToString().Equals("Port", StringComparison.OrdinalIgnoreCase)) + { + // we add the Port number when generating the name in order + // be distinguish compatibility listeners which might have the same + // real key (address and port) as a real listener + sbHashKey.Append(attribute.Key.ToString()); + sbHashKey.Append(WSManStringLiterals.Equalto); + sbHashKey.Append(attribute.Value.ToString()); + } + } + } + + keysColumns = keysColumns.Substring(0, keysColumns.LastIndexOf('|')); + ItemName = ContainerItem + "_" + Math.Abs(sbHashKey.ToString().GetHashCode()); + keys = keysColumns.Split('|'); + } + + private static void ProcessCertMappingObjects(XmlDocument xmlCerts, out Hashtable Certcache, out Hashtable Keyscache) + { + Hashtable lCache = new Hashtable(); + Hashtable kCache = new Hashtable(); + XmlNodeList xmlnodesCerts = xmlCerts.GetElementsByTagName("cfg:" + "CertMapping"); + if (xmlnodesCerts == null) + { + Certcache = null; + Keyscache = null; + return; + } + + foreach (XmlNode node in xmlnodesCerts) + { + Hashtable InputAttributes = new Hashtable(); + PSObject objCerts = new PSObject(); + string[] keys = null; + string ItemName = string.Empty; + foreach (XmlNode childnode in node.ChildNodes) + { + // if (childnode.LocalName.Equals("URI")) + // { + + // // sbCerts.Append(childnode.LocalName); + // // sbCerts.Append(WSManStringLiterals.Equalto); + // // sbCerts.Append(childnode.InnerText); + // // keys[0] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; + // } + // else if (childnode.LocalName.Equals("Subject")) + // { + // // sbCerts.Append(childnode.LocalName); + // // sbCerts.Append(WSManStringLiterals.Equalto); + // // sbCerts.Append(childnode.InnerText); + // // keys[1] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; + // } + // else if (childnode.LocalName.Equals("Issuer")) + // { + // // sbCerts.Append(childnode.LocalName); + // // sbCerts.Append(WSManStringLiterals.Equalto); + // // sbCerts.Append(childnode.InnerText); + // // keys[2] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; + // } + + InputAttributes.Add(childnode.LocalName, childnode.InnerText); + objCerts.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); + } + + GenerateObjectNameAndKeys(InputAttributes, WSManStringLiterals.containerCertMapping, WSManStringLiterals.containerClientCertificate, out ItemName, out keys); + // lCache.Add(WSManStringLiterals.containerClientCertificate + "_" + Math.Abs(sbCerts.ToString().GetHashCode()), objCerts); + lCache.Add(ItemName, objCerts); + kCache.Add(ItemName, keys); + // kCache.Add(WSManStringLiterals.containerClientCertificate + "_" + Math.Abs(sbCerts.ToString().GetHashCode()), keys); + } + + Certcache = lCache; + Keyscache = kCache; + } + + private static void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable listenercache, out Hashtable Keyscache) + { + Hashtable lCache = new Hashtable(); + Hashtable kCache = new Hashtable(); + XmlNodeList xmlnodesListeners = xmlListeners.GetElementsByTagName("cfg:" + WSManStringLiterals.containerListener); + if (xmlnodesListeners == null) + { + listenercache = null; + Keyscache = null; + return; + } + + foreach (XmlNode node in xmlnodesListeners) + { + Hashtable InputAttributes = new Hashtable(); + PSObject objListener = new PSObject(); + string[] Keys = null; + string ItemName = string.Empty; + foreach (XmlNode childnode in node.ChildNodes) + { + // if (childnode.LocalName.Equals("Address")) + // { + // sbListener.Append(childnode.LocalName); + // sbListener.Append(WSManStringLiterals.Equalto); + // sbListener.Append(childnode.InnerText); + // Keys[0] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; + // objListener.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); + // } + // else if (childnode.LocalName.Equals("Transport")) + // { + // sbListener.Append(childnode.LocalName); + // sbListener.Append(WSManStringLiterals.Equalto); + // sbListener.Append(childnode.InnerText); + // Keys[1] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; + // objListener.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); + // } + + if (childnode.LocalName.Equals("ListeningOn")) + { + string ListeningOnItem = childnode.LocalName + "_" + Math.Abs(childnode.InnerText.GetHashCode()); + objListener.Properties.Add(new PSNoteProperty(ListeningOnItem, childnode.InnerText)); + InputAttributes.Add(ListeningOnItem, childnode.InnerText); + } + else + { + InputAttributes.Add(childnode.LocalName, childnode.InnerText); + objListener.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); + } + } + + GenerateObjectNameAndKeys(InputAttributes, WSManStringLiterals.containerListener, WSManStringLiterals.containerListener, out ItemName, out Keys); + // lCache.Add(WSManStringLiterals.containerListener + "_" + Math.Abs(sbListener.ToString().GetHashCode()), objListener); + lCache.Add(ItemName, objListener); + kCache.Add(ItemName, Keys); + // kCache.Add(WSManStringLiterals.containerListener + "_" + Math.Abs(sbListener.ToString().GetHashCode()), Keys); + } + + listenercache = lCache; + Keyscache = kCache; + } + + private static PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRunasPasswordAsSecureString = false) + { + PSObject objConfiglvl = null; + + if (xmldoc != null) + { + XmlNodeList nodelistPlugin = xmldoc.GetElementsByTagName("PlugInConfiguration"); + if (nodelistPlugin.Count > 0) + { + objConfiglvl = new PSObject(); + XmlAttributeCollection attributecol = nodelistPlugin.Item(0).Attributes; + + XmlNode runAsUserNode = attributecol.GetNamedItem(WSManStringLiterals.ConfigRunAsUserName); + bool runAsUserPresent = runAsUserNode != null && !string.IsNullOrEmpty(runAsUserNode.Value); + + for (int i = 0; i <= attributecol.Count - 1; i++) + { + if (string.Equals(attributecol[i].LocalName, WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase) + && runAsUserPresent + && setRunasPasswordAsSecureString) + { + objConfiglvl.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, new SecureString())); + } + else + { + objConfiglvl.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); + } + } + } + // Containers in Plugin Level Configs + if (objConfiglvl != null) + { + objConfiglvl.Properties.Add(new PSNoteProperty("InitializationParameters", WSManStringLiterals.ContainerChildValue)); + objConfiglvl.Properties.Add(new PSNoteProperty("Resources", WSManStringLiterals.ContainerChildValue)); + objConfiglvl.Properties.Add(new PSNoteProperty(WSManStringLiterals.containerQuotasParameters, WSManStringLiterals.ContainerChildValue)); + } + } + + return objConfiglvl; + } + + private static ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList arrSecurity) + { + ArrayList Resources = null; + ArrayList nSecurity = null; + if (xmldoc != null) + { + XmlNodeList xmlpluginResource = xmldoc.GetElementsByTagName("Resource"); + if (xmlpluginResource.Count > 0) + { + Resources = new ArrayList(); + nSecurity = new ArrayList(); + foreach (XmlElement xe in xmlpluginResource) + { + PSObject objResource = new PSObject(); + string strUniqueResourceId = string.Empty; + XmlAttributeCollection attributecol = xe.Attributes; + bool ExactMatchFound = false; + bool SupportsOptionsFound = false; + string resourceUri = string.Empty; + + for (int i = 0; i <= attributecol.Count - 1; i++) + { + if (attributecol[i].LocalName.Equals("ResourceUri", StringComparison.OrdinalIgnoreCase)) + { + resourceUri = attributecol[i].Value; + strUniqueResourceId = "Resource_" + Convert.ToString(Math.Abs(attributecol[i].Value.GetHashCode()), CultureInfo.InvariantCulture); + objResource.Properties.Add(new PSNoteProperty("ResourceDir", strUniqueResourceId)); + } + + if (attributecol[i].LocalName.Equals("ExactMatch", StringComparison.OrdinalIgnoreCase)) + { + objResource.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); + ExactMatchFound = true; + continue; + } + + if (attributecol[i].LocalName.Equals("SupportsOptions", StringComparison.OrdinalIgnoreCase)) + { + objResource.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); + SupportsOptionsFound = true; + continue; + } + + objResource.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); + } + + if (!ExactMatchFound) + { + objResource.Properties.Add(new PSNoteProperty("ExactMatch", false)); + } + + if (!SupportsOptionsFound) + { + objResource.Properties.Add(new PSNoteProperty("SupportsOptions", false)); + } + + // Processing capabilities + + XmlDocument xmlCapabilities = new XmlDocument(); + xmlCapabilities.LoadXml("" + xe.InnerXml + ""); + XmlNodeList nodeCapabilities = xmlCapabilities.GetElementsByTagName("Capability"); + object[] enumcapability = null; + if (nodeCapabilities.Count > 0) + { + enumcapability = new object[nodeCapabilities.Count]; + for (int i = 0; i < nodeCapabilities.Count; i++) + { + enumcapability.SetValue(nodeCapabilities[i].Attributes["Type"].Value, i); + } + } + + objResource.Properties.Add(new PSNoteProperty("Capability", enumcapability)); + objResource.Properties.Add(new PSNoteProperty(WSManStringLiterals.containerSecurity, WSManStringLiterals.ContainerChildValue)); + + // Process Security in Resources. We add the resource Unique ID in to each security to + // identify in the Provider methods. + nSecurity = ProcessPluginSecurityLevel(nSecurity, xmlCapabilities, strUniqueResourceId, resourceUri); + Resources.Add(objResource); + } + } + } + + arrSecurity = nSecurity; + return Resources; + } + + private static ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) + { + ArrayList InitParamLvl = null; + if (xmldoc != null) + { + XmlNodeList nodelistInitParam = xmldoc.GetElementsByTagName("Param"); + if (nodelistInitParam.Count > 0) + { + InitParamLvl = new ArrayList(); + foreach (XmlElement xe in nodelistInitParam) + { + PSObject objInitParam = new PSObject(); + XmlAttributeCollection attributecol = xe.Attributes; + string Name = string.Empty; + string Value = string.Empty; + for (int i = 0; i <= attributecol.Count - 1; i++) + { + if (attributecol[i].LocalName.Equals("Name", StringComparison.OrdinalIgnoreCase)) + { + Name = attributecol[i].Value; + } + + if (attributecol[i].LocalName.Equals("Value", StringComparison.OrdinalIgnoreCase)) + { + string ValueAsXML = attributecol[i].Value; + Value = SecurityElement.Escape(ValueAsXML); + } + } + + objInitParam.Properties.Add(new PSNoteProperty(Name, Value)); + InitParamLvl.Add(objInitParam); + } + } + } + + return InitParamLvl; + } + + private static ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument xmlSecurity, string UniqueResourceID, string ParentResourceUri) + { + // ArrayList SecurityLvl = null; + if (xmlSecurity != null) + { + XmlNodeList nodelistSecurity = xmlSecurity.GetElementsByTagName(WSManStringLiterals.containerSecurity); + if (nodelistSecurity.Count > 0) + { + // SecurityLvl = new ArrayList(); + foreach (XmlElement xe in nodelistSecurity) + { + bool ExactMatchFound = false; + PSObject objSecurity = new PSObject(); + XmlAttributeCollection attributecol = xe.Attributes; + + for (int i = 0; i <= attributecol.Count - 1; i++) + { + if (attributecol[i].LocalName.Equals("Uri", StringComparison.OrdinalIgnoreCase)) + { + objSecurity.Properties.Add(new PSNoteProperty("SecurityDIR", "Security_" + Math.Abs(UniqueResourceID.GetHashCode()))); + } + + if (attributecol[i].LocalName.Equals("ExactMatch", StringComparison.OrdinalIgnoreCase)) + { + objSecurity.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); + ExactMatchFound = true; + continue; + } + + objSecurity.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); + } + + if (!ExactMatchFound) + { + objSecurity.Properties.Add(new PSNoteProperty("ExactMatch", false)); + } + + objSecurity.Properties.Add(new PSNoteProperty("ResourceDir", UniqueResourceID)); + objSecurity.Properties.Add(new PSNoteProperty("ParentResourceUri", ParentResourceUri)); + + arrSecurity.Add(objSecurity); + } + } + } + + return arrSecurity; + } + + /// + /// This method constructs the Configuration XML from the PSObject. + /// For RunAsPassword, if the value is not of type SecureString or the value is not present + /// then an Empty string is added as value. The caller of this method MUST make sure that + /// the RunAsPassword (if updated) is of type SecureString. + /// + /// PSObject, from which XML will be produced. + /// Resource URI for the XML. + /// Name of the Host. + /// Type of Operation. + /// List of Resources. + /// List of Securities + /// List of initialization parameters. + /// An Configuration XML, ready to send to server. + private static string ConstructPluginXml(PSObject objinputparam, string ResourceURI, string host, string Operation, ArrayList resources, ArrayList securities, ArrayList initParams) + { + StringBuilder sbvalues = new StringBuilder(); + sbvalues.Append(" + sbvalues.Append(WSManStringLiterals.GreaterThan); + if (Operation.Equals("New")) + { + if (objinputparam != null) + sbvalues.Append(ConstructResourceXml(objinputparam, null, null)); + else + sbvalues.Append(ConstructResourceXml(null, resources, null)); + } + else if (Operation.Equals("Set")) + { + if (initParams != null) + sbvalues.Append(ConstructInitParamsXml(null, initParams)); + if (resources != null) + sbvalues.Append(ConstructResourceXml(null, resources, securities)); + } + + sbvalues.Append(""); + return sbvalues.ToString(); + } + + /// + /// PS wraps most of the parameters to Item cmdlets in PSObject. These values are passed as 'Object'. + /// This method unwraps the PSObjects and returns the base object as the required Type for the given + /// configuration name as follows: + /// RunAsUser - PSCredential + /// RunAsPassword - SecureString + /// If the object provided by user is not of required type the method return Null. + /// If the object is not PSObject, the method returns the 'value'. + /// + /// Name of the configuration setting. + /// Object provided by User. + /// Object of the required type or Null. + private object ValidateAndGetUserObject(string configurationName, object value) + { + PSObject basePsObject = value as PSObject; + PSCredential psCredential = null; + if (basePsObject == null) + { + psCredential = value as PSCredential; + } + + if (configurationName.Equals(WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase)) + { + if (basePsObject != null && basePsObject.BaseObject is SecureString) + { + return basePsObject.BaseObject as SecureString; + } + else + { + string error = string.Format( + helper.GetResourceMsgFromResourcetext("InvalidValueType"), + WSManStringLiterals.ConfigRunAsPasswordName, + typeof(SecureString).FullName); + + AssertError(error, false); + return null; + } + } + else if (configurationName.Equals(WSManStringLiterals.ConfigRunAsUserName, StringComparison.OrdinalIgnoreCase)) + { + if (basePsObject != null && basePsObject.BaseObject is PSCredential) + { + return basePsObject.BaseObject as PSCredential; + } + else if (psCredential != null) + { + return psCredential; + } + else + { + string error = string.Format( + helper.GetResourceMsgFromResourcetext("InvalidValueType"), + WSManStringLiterals.ConfigRunAsUserName, + typeof(PSCredential).FullName); + + AssertError(error, false); + return null; + } + } + + return value; + } + + /// + /// Appends the plain text value of a SecureString variable to the StringBuilder. + /// if the propertyValue provided is not SecureString appends empty string. + /// + /// Value to append. + private static string GetStringFromSecureString(object propertyValue) + { + string passwordValueToAdd = string.Empty; + + if (propertyValue is SecureString value) + { + IntPtr ptr = Marshal.SecureStringToBSTR(value); + passwordValueToAdd = Marshal.PtrToStringAuto(ptr); + Marshal.ZeroFreeBSTR(ptr); + } + + return passwordValueToAdd; + } + + private static string ConstructResourceXml(PSObject objinputparams, ArrayList resources, ArrayList securities) + { + StringBuilder sbvalues = new StringBuilder(string.Empty); + if (objinputparams == null && resources == null) + { + return sbvalues.ToString(); + } + + object[] capability = null; + sbvalues.Append(""); + if (objinputparams != null) + { + sbvalues.Append(""); + } + else + { + foreach (PSObject p in resources) + { + sbvalues.Append(""); + } + } + + sbvalues.Append(""); + return sbvalues.ToString(); + } + + private static string ConstructSecurityXml(PSObject objinputparams, ArrayList securities, string strResourceIdentity) + { + // + StringBuilder sbvalues = new StringBuilder(string.Empty); + if (objinputparams == null && securities == null) + { + return sbvalues.ToString(); + } + + if (objinputparams != null) + { + AddSecurityProperties(objinputparams.Properties, sbvalues); + } + else + { + foreach (PSObject p in securities) + { + if (p.Properties["ResourceDir"].Value.ToString().Equals(strResourceIdentity)) + { + AddSecurityProperties(p.Properties, sbvalues); + } + } + } + + return sbvalues.ToString(); + } + + private static void AddSecurityProperties( + PSMemberInfoCollection properties, + StringBuilder sbValues) + { + sbValues.Append(""); + } + + private static string ConstructInitParamsXml(PSObject objinputparams, ArrayList initparams) + { + // + // + // + StringBuilder sbvalues = new StringBuilder(string.Empty); + if (objinputparams == null && initparams == null) + { + return sbvalues.ToString(); + } + + sbvalues.Append(""); + if (objinputparams != null) + { + foreach (PSPropertyInfo prop in objinputparams.Properties) + { + sbvalues.Append(""); + return sbvalues.ToString(); + } + + private static string ConstructCapabilityXml(object[] capabilities) + { + StringBuilder sbvalues = new StringBuilder(string.Empty); + foreach (object cap in capabilities) + { + sbvalues.Append(""); + } + + return sbvalues.ToString(); + } + + private static bool IsValueOfParamList(string name, string[] paramcontainer) + { + bool result = false; + foreach (string value in paramcontainer) + { + if (value.Equals(name, StringComparison.OrdinalIgnoreCase)) + { + result = true; + break; + } + } + + return result; + } + + #endregion Plugin private functions + + private enum ProviderMethods + { + GetChildItems, + GetChildNames + } + + private enum WsManElementObjectTypes + { + WSManConfigElement, + WSManConfigContainerElement, + WSManConfigLeafElement + } + + #region def + private static readonly string[] WinrmRootName = new string[] { "winrm/Config" }; + + private static readonly string[] WinRmRootConfigs = new string[] { + "Client", + "Service", + "Shell", + "Listener", + "Plugin", + "ClientCertificate" +}; + + // Defining Primarykeys for resource uri's + private static readonly string[] PKeyListener = new string[] { "Address", "Transport" }; + private static readonly string[] PKeyPlugin = new string[] { "Name" }; + private static readonly string[] PKeyCertMapping = new string[] { "Issuer", "Subject", "Uri" }; + + /// + /// In PPQ display warnings for these configurations. + /// + private static readonly List ppqWarningConfigurations = new List + { + "idletimeoutms", + "maxprocessespershell", + "maxmemorypershellmb", + "maxshellsperuser", + "maxconcurrentusers" + }; + + /// + /// Display warning for these configurations. + /// + private static readonly List globalWarningConfigurations = new List + { + "maxconcurrentoperationsperuser", + "idletimeout", + "maxprocessespershell", + "maxmemorypershellmb", + "maxshellsperuser", + "maxconcurrentusers" + }; + + /// + /// Display warning for these URIs. + /// + private static readonly List globalWarningUris = + new List { + WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerWinrs, + WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerService}; + + #endregion def + + #endregion private + } + + #region "Dynamic Parameter Classes" + + #region "New-Item Dynamic Parameters" + + /// + /// Computer dynamic parameters. This is similar to connect-wsman parameters. + /// Available path wsman:\> + /// + public class WSManProviderNewItemComputerParameters + { + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hash table and is used to pass a set of switches to the + /// service to modify or refine the nature of the request. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("OS")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable OptionSet + { + get { return optionset; } + + set { optionset = value; } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Authentication". + /// This parameter takes a set of authentication methods the user can select + /// from. The available method are an enum called Authentication in the + /// System.Management.Automation.Runspaces namespace. The available options + /// should be as follows: + /// - Default : Use the default authentication (ad defined by the underlying + /// protocol) for establishing a remote connection. + /// - Negotiate + /// - Kerberos + /// - Basic: Use basic authentication for establishing a remote connection. + /// -CredSSP: Use CredSSP authentication for establishing a remote connection + /// which will enable the user to perform credential delegation. (i.e. second + /// hop) + /// + [Parameter] + [ValidateNotNullOrEmpty] + public AuthenticationMechanism Authentication + { + get { return authentication; } + + set { authentication = value; } + } + + private AuthenticationMechanism authentication = AuthenticationMechanism.Default; + + /// + /// Specifies the certificate thumbprint to be used to impersonate the user on the + /// remote machine. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string CertificateThumbprint + { + get { return thumbPrint; } + + set { thumbPrint = value; } + } + + private string thumbPrint = null; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. This hashtable can + /// be created using New-WSManSessionOption. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("SO")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public SessionOption SessionOption + { + get { return sessionoption; } + + set { sessionoption = value; } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "nameSet")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = "wsman"; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Parameter(ParameterSetName = "nameSet")] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "nameSet")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and ApplicationName of the new + /// runspace. The format of this string is: + /// transport://server:port/ApplicationName. + /// + [Parameter(ParameterSetName = "pathSet", Mandatory = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ConnectionURI + { + get { return connectionuri; } + + set { connectionuri = value; } + } + + private Uri connectionuri; + } + + /// + /// Plugin Dynamic parameter. There are 2 parameter sets. + /// Path - WSMan:\Localhost\Plugin> + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Plugin")] + public class WSManProviderNewItemPluginParameters + { + /// + /// Parameter Plugin. + /// + [Parameter(Mandatory = true, ParameterSetName = "pathSet")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Plugin")] + [ValidateNotNullOrEmpty] + public string Plugin + { + get { return _plugin; } + + set { _plugin = value; } + } + + private string _plugin; + + /// + /// Parameter FileName. + /// + [Parameter(Mandatory = true, ParameterSetName = "pathSet")] + [ValidateNotNullOrEmpty] + public string FileName + { + get { return _filename; } + + set { _filename = value; } + } + + private string _filename; + + /// + /// Parameter SDKVersion. + /// + [Parameter(Mandatory = true, ParameterSetName = "pathSet")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SDK")] + [ValidateNotNullOrEmpty] + public string SDKVersion + { + get { return _sdkversion; } + + set { _sdkversion = value; } + } + + private string _sdkversion; + + /// + /// Parameter Resource. + /// + [Parameter(Mandatory = true, ParameterSetName = "pathSet")] + [ValidateNotNullOrEmpty] + public System.Uri Resource + { + get { return _resourceuri; } + + set { _resourceuri = value; } + } + + private System.Uri _resourceuri; + + /// + /// Parameter Capability. + /// + [Parameter(Mandatory = true, ParameterSetName = "pathSet")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [ValidateNotNullOrEmpty] + public object[] Capability + { + get { return _capability; } + + set { _capability = value; } + } + + private object[] _capability; + + /// + /// Parameter XMLRenderingType. + /// + [Parameter(Mandatory = true, ParameterSetName = "pathSet")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "XML")] + [ValidateNotNullOrEmpty] + public string XMLRenderingType + { + get { return _xmlRenderingtype; } + + set { _xmlRenderingtype = value; } + } + + private string _xmlRenderingtype; + + /// + /// Parameter File. + /// + [Parameter(Mandatory = true, ParameterSetName = "nameSet")] + [ValidateNotNullOrEmpty] + public string File + { + get { return _file; } + + set { _file = value; } + } + + private string _file; + + /// + /// Parameter for RunAs credentials for a Plugin. + /// + [ValidateNotNull] + [Parameter] + public PSCredential RunAsCredential + { + get { return this.runAsCredentials; } + + set { this.runAsCredentials = value; } + } + + private PSCredential runAsCredentials; + + /// + /// Parameter for Plugin Host Process configuration (Shared or Separate). + /// + [Parameter] + public SwitchParameter UseSharedProcess + { + get { return this.sharedHost; } + + set { this.sharedHost = value; } + } + + private bool sharedHost; + + /// + /// Parameter for Auto Restart configuration for Plugin. + /// + [Parameter] + public SwitchParameter AutoRestart + { + get { return this.autoRestart; } + + set { this.autoRestart = value; } + } + + private bool autoRestart; + + /// + /// Parameter for Idle timeout for HostProcess. + /// + [Parameter] + public uint? ProcessIdleTimeoutSec + { + get + { + return this.processIdleTimeoutSeconds; + } + + set + { + this.processIdleTimeoutSeconds = value; + } + } + + private uint? processIdleTimeoutSeconds; + } + + /// + /// Initparameters dynamic parameters + /// Path - wsman:\localhost\plugin\[specified plugin]\Initializationparameters> + /// + public class WSManProviderInitializeParameters + { + /// + /// Parameter ParamName. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")] + [Parameter(Mandatory = true, Position = 0)] + [ValidateNotNullOrEmpty] + public string ParamName + { + get { return _paramname; } + + set { _paramname = value; } + } + + private string _paramname; + + /// + /// Parameter ParamValue. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")] + [Parameter(Mandatory = true, Position = 1)] + [ValidateNotNullOrEmpty] + public string ParamValue + { + get { return _paramvalue; } + + set { _paramvalue = value; } + } + + private string _paramvalue; + } + + /// + /// Dynamic parameter for Resource Item. + /// Path - WsMAn:\localhost\Plugin\[Specified Plugin]\Resources> + /// + public class WSManProviderNewItemResourceParameters + { + /// + /// Parameter ResourceUri. + /// + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public System.Uri ResourceUri + { + get { return _resourceuri; } + + set { _resourceuri = value; } + } + + private System.Uri _resourceuri; + + /// + /// Parameter Capability. + /// + [Parameter(Mandatory = true)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [ValidateNotNullOrEmpty] + public object[] Capability + { + get { return _capability; } + + set { _capability = value; } + } + + private object[] _capability; + } + + /// + /// Security Dynamic Parameters + /// Path - WsMan:\Localhost\Plugin\[Specified Plugin]\Resources\[Specified Resource]\Security> + /// + public class WSManProviderNewItemSecurityParameters + { + /// + /// Parameter Sddl. + /// + [Parameter(Mandatory = true)] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sddl")] + public string Sddl + { + get { return _sddl; } + + set { _sddl = value; } + } + + private string _sddl; + } + + #region "ClientCertificate Dynamic Parameters" + /// + /// Client Certificate Dynamic Parameters + /// Path - WsMan:\Localhost\ClientCertificate. + /// + public class WSManProviderClientCertificateParameters + { + /// + /// Parameter Issuer. + /// + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Issuer + { + get + { + return _issuer; + } + + set + { + _issuer = value; + } + } + + private string _issuer; + + /// + /// Parameter Subject. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string Subject + { + get + { + return _subject; + } + + set + { + _subject = value; + } + } + + private string _subject = "*"; + + /// + /// Parameter URI. + /// + [Parameter] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [ValidateNotNullOrEmpty] + public System.Uri URI + { + get + { + return _uri; + } + + set + { + _uri = value; + } + } + + private System.Uri _uri = new Uri("*", UriKind.RelativeOrAbsolute); + + /// + /// Parameter Enabled. + /// + [Parameter] + public bool Enabled + { + get + { + return _enabled; + } + + set + { + _enabled = value; + } + } + + private bool _enabled = true; + } + + #endregion + + #region Listener Dynamic Parameters + + /// + /// Listener Dynamic parameters + /// Path - WsMan:\Localhost\Listener> + /// + public class WSManProvidersListenerParameters + { + /// + /// Parameter Address. + /// + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Address + { + get + { + return _address; + } + + set + { + _address = value; + } + } + + private string _address; + + /// + /// Parameter Transport. + /// + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Transport + { + get + { + return _transport; + } + + set + { + _transport = value; + } + } + + private string _transport = "http"; + + /// + /// Parameter Port. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public int Port + { + get + { + return _port; + } + + set + { + _port = value; + _IsPortSpecified = true; + } + } + + private int _port = 0; + + /// + /// Parameter HostName. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public string HostName + { + get + { + return _hostName; + } + + set + { + _hostName = value; + } + } + + private string _hostName; + + /// + /// Parameter Enabled. + /// + [Parameter] + public bool Enabled + { + get + { + return _enabled; + } + + set + { + _enabled = value; + } + } + + private bool _enabled = true; + + /// + /// Parameter URLPrefix. + /// + [Parameter] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URL")] + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + [ValidateNotNullOrEmpty] + public string URLPrefix + { + get + { + return _urlprefix; + } + + set + { + _urlprefix = value; + } + } + + private string _urlprefix = "wsman"; + + /// + /// Parameter CertificateThumbPrint. + /// + [Parameter] + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "ThumbPrint")] + [ValidateNotNullOrEmpty] + public string CertificateThumbPrint + { + get + { + return _certificatethumbprint; + } + + set + { + _certificatethumbprint = value; + } + } + + private string _certificatethumbprint; + + /// + /// Variable IsPortSpecified. + /// + public bool IsPortSpecified + { + get + { + return _IsPortSpecified; + } + + set + { + _IsPortSpecified = value; + } + } + + private bool _IsPortSpecified = false; + } + + #endregion + + #endregion + + #region SetItemDynamicParameters + + /// + /// Set-Item Dynamic parameters + /// Path - WsMan:\Localhost\Client> Set-Item .\TrustedHosts. + /// + public class WSManProviderSetItemDynamicParameters + { + /// + /// Parameter Concatenate. + /// + [Parameter] + public SwitchParameter Concatenate + { + get { return _concatenate; } + + set { _concatenate = value; } + } + + private SwitchParameter _concatenate = false; + } + + #endregion SetItemDynamicParameters + + #endregion + + #region "String Literals" + + internal static class WSManStringLiterals + { + // constants + + /// + /// The default path separator used by the base implementation of the providers. + /// + internal const char DefaultPathSeparator = '\\'; + + /// + /// The alternate path separator used by the base implementation of the providers. + /// + internal const char AlternatePathSeparator = '/'; + /// + /// Double Quotes used while constructing XML. + /// + internal const char EnclosingDoubleQuotes = '\"'; + /// + /// Equalto Used while constructing XML. + /// + internal const char Equalto = '='; + /// + /// For XML Construction. + /// + internal const char GreaterThan = '>'; + /// + /// XML Closing Tag. + /// + internal const string XmlClosingTag = "/>"; + /// + /// White space used while constructing XML. + /// + internal const char SingleWhiteSpace = ' '; + + /// + /// Root node of WsMan. + /// + internal const string ProviderName = "WSMan"; + + /// + /// + internal const string WsMan_Schema = "http://schemas.microsoft.com/wbem/wsman/1/config"; + /// + /// + internal const string NS_XSI = "xmlns:xsi=" + "\"http://www.w3.org/2001/XMLSchema-instance\""; + /// + /// + internal const string ATTR_NIL = "xsi:nil=" + "\"true\""; + /// + /// + internal const string ATTR_NIL_NAME = "xsi:nil"; + /// + /// + internal const char WinrmPathSeparator = '/'; + /// + /// + internal const string rootpath = "WSMan"; + + /// + /// + internal const string ContainerChildValue = "Container"; + + #region WsMan Containers + + /// + /// Plugin Container. + /// + internal const string containerPlugin = "Plugin"; + /// + /// Client Container. + /// + internal const string containerClient = "Client"; + /// + /// Shell Container. + /// + internal const string containerShell = "Shell"; + /// + /// ClientCertificate Container. + /// + internal const string containerClientCertificate = "ClientCertificate"; + /// + /// Listener Container. + /// + internal const string containerListener = "Listener"; + /// + /// Service Container. + /// + internal const string containerService = "Service"; + /// + /// Auth Container - Under Client,Service. + /// + internal const string containerAuth = "Auth"; + /// + /// DefaultPorts Container - Under Client,Service. + /// + internal const string containerDefaultPorts = "DefaultPorts"; + /// + /// TrustedHosts Container - Under Client,Service. + /// + internal const string containerTrustedHosts = "TrustedHosts"; + /// + /// Security Container - Under Plugin. + /// + internal const string containerSecurity = "Security"; + /// + /// Resources Container - Under Plugin. + /// + internal const string containerResources = "Resources"; + + /// + /// Resource in Resources Container - Under Plugin. + /// + internal const string containerSingleResource = "Resource"; + /// + /// InitParameters Container - Under Plugin. + /// + internal const string containerInitParameters = "InitializationParameters"; + + /// + /// Quotas Container - Under Plugin. + /// + internal const string containerQuotasParameters = "Quotas"; + + /// + /// Winrs Container - Exposed as Shell. + /// + internal const string containerWinrs = "Winrs"; + + /// + /// Certmapping Container - Exposed as ClientCertificate in the provider. + /// + internal const string containerCertMapping = "Service/certmapping"; + + /// + /// Possible Values in Plugin Top Level XML. + /// + internal static readonly string[] NewItemPluginConfigParams = + new string[] { + "Name", + "Filename", + "SDKVersion", + "XmlRenderingType", + "Enabled", + "Architecture", + WSManStringLiterals.ConfigRunAsPasswordName, + WSManStringLiterals.ConfigRunAsUserName, + WSManStringLiterals.ConfigAutoRestart, + WSManStringLiterals.ConfigProcessIdleTimeoutSec, + WSManStringLiterals.ConfigUseSharedProcess, + }; + + /// Possible Values in Plugin Top Resources XML + internal static readonly string[] NewItemResourceParams = new string[] { "Resource", "ResourceUri", "Capability", "ExactMatch", "SupportsOptions" }; + + /// Possible Values in Plugin Top Init Param XML + internal static readonly string[] NewItemInitParamsParams = new string[] { "Name", "Value" }; + + /// Possible Values in Plugin Top Security XML + internal static readonly string[] NewItemSecurityParams = new string[] { "Uri", "Sddl", "ExactMatch" }; + + #endregion WsMan Containers + + #region WSMAN Config Names + /// + /// Name of the configuration which represents RunAs Password. + /// + internal const string ConfigRunAsPasswordName = "RunAsPassword"; + + /// + /// Name of the configuration which represents RunAs Name. + /// + internal const string ConfigRunAsUserName = "RunAsUser"; + + /// + /// Name of the configuration which represents if HostProcess is shared or separate. + /// + internal const string ConfigUseSharedProcess = "UseSharedProcess"; + + /// + /// Name of the configuration which represents if AutoRestart is enabled or not. + /// + internal const string ConfigAutoRestart = "AutoRestart"; + + /// + /// Name of the configuration which represents the Host Idle Timeout in seconds. + /// + internal const string ConfigProcessIdleTimeoutSec = "ProcessIdleTimeoutSec"; + + /// + /// Name of the configuration which represents the Resource URI for a Resource. + /// + internal const string ConfigResourceUriName = "ResourceUri"; + + /// + /// Name of the tag which represents a initialization parameter. + /// + internal const string ConfigInitializeParameterTag = "Param"; + + /// + /// Name of the tag which represents Name of the parameter. + /// + internal const string ConfigInitializeParameterName = "Name"; + + /// + /// Name of the tag which represents Value of the parameter. + /// + internal const string ConfigInitializeParameterValue = "Value"; + + /// + /// Name of the tag which represents a Security URI. + /// + internal const string ConfigSecurityUri = "Uri"; + + /// + /// Name of the tag which represents a Security URI. + /// + internal const string HiddenSuffixForSourceOfValue = "___Source"; + + #endregion + + /// + /// This is used to start the service. return a bool value. if false we throw error. + /// + public const string StartWinrmServiceSBFormat = @" +function Start-WSManServiceD15A7957836142a18627D7E1D342DD82 +{{ +[CmdletBinding()] +param( + [Parameter()] + [bool] + $Force, + + [Parameter()] + [string] + $captionForStart, + + [Parameter()] + [string] + $queryForStart) + + begin + {{ + if ($force -or $pscmdlet.ShouldContinue($queryForStart, $captionForStart)) + {{ + Restart-Service WinRM -Force -Confirm:$false + return $true + }} + + return $false + }} #end of Begin block +}} +$_ | Start-WSManServiceD15A7957836142a18627D7E1D342DD82 -force $args[0] -captionForStart $args[1] -queryForStart $args[2] +"; + } + + #endregion "String Literals" + + #region "WsMan Output Objects" + + /// + /// Base Output object. + /// + public class WSManConfigElement + { + internal WSManConfigElement() + { + } + + internal WSManConfigElement(string name, string typenameofelement) + { + _name = name; + _typenameofelement = typenameofelement; + } + + /// + /// Variable Name. + /// + public string Name + { + get { return _name; } + + set { _name = value; } + } + + private string _name; + + /// + /// Variable TypeNameOfElement. + /// + public string TypeNameOfElement + { + get { return _typenameofelement; } + + set { _typenameofelement = value; } + } + + private string _typenameofelement; + + /// + /// Gets or Sets the type if the object. + /// + public string Type + { + get { return _typenameofelement; } + + set { _typenameofelement = value; } + } + } + /// + /// Leaf Element. + /// + public class WSManConfigLeafElement : WSManConfigElement + { + internal WSManConfigLeafElement() + { + } + + internal WSManConfigLeafElement(string Name, object Value, string TypeNameOfElement, object SourceOfValue = null) + { + _value = Value; + _SourceOfValue = SourceOfValue; + base.Name = Name; + base.Type = TypeNameOfElement; + } + + /// + /// Variable Value. + /// + public object SourceOfValue + { + get { return _SourceOfValue; } + + set { _SourceOfValue = value; } + } + + private object _SourceOfValue; + + /// + /// Variable Value. + /// + public object Value + { + get { return _value; } + + set { _value = value; } + } + + private object _value; + } + /// + /// Container Element. + /// + public class WSManConfigContainerElement : WSManConfigElement + { + internal WSManConfigContainerElement(string Name, string TypeNameOfElement, string[] keys) + { + _keys = keys; + base.Name = Name; + base.Type = TypeNameOfElement; + } + + /// + /// Variable Keys. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] Keys + { + get { return _keys; } + + set { _keys = value; } + } + + private string[] _keys; + } + + #endregion "WsMan Output Objects" +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/CredSSP.cs b/PowerShell-master/src/Microsoft.WSMan.Management/CredSSP.cs new file mode 100644 index 0000000000000000000000000000000000000000..a8457ab5bc293a4e5ee01b741dce05d6acc13987 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/CredSSP.cs @@ -0,0 +1,927 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using System.Threading; +using System.Xml; + +using Microsoft.Win32; + +using Dbg = System.Management.Automation; + +namespace Microsoft.WSMan.Management +{ + #region WSManCredSSP cmdlet base + + /// + /// Base class used *-WSManCredSSP cmdlets (Enable-WSManCredSSP, Disable-WSManCredSSP) + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] + public class WSManCredSSPCommandBase : PSCmdlet + { + #region Protected / Internal Data + + internal const string Server = "Server"; + internal const string Client = "Client"; + + #endregion + + #region Parameters + + /// + /// Role can either "Client" or "Server". + /// + [Parameter(Mandatory = true, Position = 0)] + [ValidateSet(Client, Server)] + public string Role + { + get { return role; } + + set { role = value; } + } + + private string role; + #endregion + + #region Utilities + + /// + /// + /// + /// Returns a session object upon successful creation..otherwise + /// writes an error using WriteError and returns null. + /// + internal IWSManSession CreateWSManSession() + { + IWSManEx wsmanObject = (IWSManEx)new WSManClass(); + IWSManSession m_SessionObj = null; + + try + { + m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); + return m_SessionObj; + } + catch (COMException ex) + { + ErrorRecord er = new ErrorRecord(ex, "COMException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + + return null; + } + + #endregion + } + + #endregion + + #region DisableWsManCredSsp + + /// + /// Disables CredSSP authentication on the client. CredSSP authentication + /// enables an application to delegate the user's credentials from the client to + /// the server, hence allowing the user to perform management operations that + /// access a second hop. + /// + [Cmdlet(VerbsLifecycle.Disable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096628")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] + public class DisableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable + { + #region private + + // The application name MUST be "wsman" as wsman got approval from security + // folks who suggested to register the SPN with name "wsman". + private const string applicationname = "wsman"; + + private void DisableClientSideSettings() + { + WSManHelper helper = new WSManHelper(this); + IWSManSession m_SessionObj = CreateWSManSession(); + if (m_SessionObj == null) + { + return; + } + + try + { + string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); + XmlDocument resultopxml = new XmlDocument(); + resultopxml.LoadXml(result); + XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); + nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp); + XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); + if (xNode is null) + { + InvalidOperationException ex = new InvalidOperationException(); + ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + string inputXml = @"false"; + + m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0); + + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + { + this.DeleteUserDelegateSettings(); + } + else + { + ThreadStart start = new ThreadStart(this.DeleteUserDelegateSettings); + Thread thread = new Thread(start); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + } + + if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname)) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null); + } + } + catch (System.Xml.XPath.XPathException ex) + { + ErrorRecord er = new ErrorRecord(ex, "XpathException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + finally + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + helper.AssertError(m_SessionObj.Error, true, null); + } + + if (m_SessionObj != null) + Dispose(m_SessionObj); + } + } + + private void DisableServerSideSettings() + { + WSManHelper helper = new WSManHelper(this); + IWSManSession m_SessionObj = CreateWSManSession(); + if (m_SessionObj == null) + { + return; + } + + try + { + string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); + XmlDocument resultopxml = new XmlDocument(); + resultopxml.LoadXml(result); + + XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); + nsmgr.AddNamespace("cfg", helper.Service_CredSSP_XMLNmsp); + XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); + if (xNode is null) + { + InvalidOperationException ex = new InvalidOperationException(); + ErrorRecord er = new ErrorRecord(ex, + helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), + ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + string inputXml = string.Format( + CultureInfo.InvariantCulture, + @"false", + helper.Service_CredSSP_XMLNmsp); + + m_SessionObj.Put(helper.Service_CredSSP_Uri, inputXml, 0); + } + finally + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + helper.AssertError(m_SessionObj.Error, true, null); + } + + if (m_SessionObj != null) + { + Dispose(m_SessionObj); + } + } + } + + private void DeleteUserDelegateSettings() + { + System.IntPtr KeyHandle = System.IntPtr.Zero; + IGroupPolicyObject GPO = (IGroupPolicyObject)new GPClass(); + GPO.OpenLocalMachineGPO(1); + KeyHandle = GPO.GetRegistryKey(2); + RegistryKey rootKey = Registry.CurrentUser; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); + foreach (string keyname in GPOKey.GetSubKeyNames()) + { + if (keyname.EndsWith("Machine", StringComparison.OrdinalIgnoreCase)) + { + string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows"; + DeleteDelegateSettings(applicationname, Registry.CurrentUser, key, GPO); + } + } + + KeyHandle = System.IntPtr.Zero; + } + + private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, string Registry_Path, IGroupPolicyObject GPO) + { + WSManHelper helper = new WSManHelper(this); + RegistryKey rKey; + int i = 0; + bool otherkeys = false; + try + { + string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; + RegistryKey Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true); + if (Allow_Fresh_Credential_Key != null) + { + string[] valuenames = Allow_Fresh_Credential_Key.GetValueNames(); + if (valuenames.Length > 0) + { + Collection KeyCollection = new Collection(); + foreach (string value in valuenames) + { + object keyvalue = Allow_Fresh_Credential_Key.GetValue(value); + if (keyvalue != null) + { + if (!keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) + { + KeyCollection.Add(keyvalue.ToString()); + otherkeys = true; + } + } + + Allow_Fresh_Credential_Key.DeleteValue(value); + } + + foreach (string keyvalue in KeyCollection) + { + Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), keyvalue, RegistryValueKind.String); + i++; + } + } + } + + if (!otherkeys) + { + rKey = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true); + if (rKey != null) + { + object regval1 = rKey.GetValue(helper.Key_Allow_Fresh_Credentials); + if (regval1 != null) + { + rKey.DeleteValue(helper.Key_Allow_Fresh_Credentials, false); + } + + object regval2 = rKey.GetValue(helper.Key_Concatenate_Defaults_AllowFresh); + if (regval2 != null) + { + rKey.DeleteValue(helper.Key_Concatenate_Defaults_AllowFresh, false); + } + + if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) != null) + { + rKey.DeleteSubKeyTree(helper.Key_Allow_Fresh_Credentials); + } + } + } + + GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("6AD20875-336C-4e22-968F-C709ACB15814")); + } + catch (InvalidOperationException ex) + { + ErrorRecord er = new ErrorRecord(ex, "InvalidOperation", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (ArgumentException ex) + { + ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidArgument, null); + WriteError(er); + } + catch (SecurityException ex) + { + ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.SecurityError, null); + WriteError(er); + } + catch (UnauthorizedAccessException ex) + { + ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.SecurityError, null); + WriteError(er); + } + } + #endregion private + /// + /// Begin processing method. + /// + protected override void BeginProcessing() + { + // If not running elevated, then throw an "elevation required" error message. + WSManHelper.ThrowIfNotAdministrator(); + + if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) + { + DisableClientSideSettings(); + } + + if (Role.Equals(Server, StringComparison.OrdinalIgnoreCase)) + { + DisableServerSideSettings(); + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + } + #endregion DisableWsManCredSSP + + #region EnableCredSSP + /// + /// Enables CredSSP authentication on the client. CredSSP authentication enables + /// an application to delegate the user's credentials from the client to the + /// server, hence allowing the user to perform management operations that access + /// a second hop. + /// This cmdlet performs the following: + /// + /// On the client: + /// 1. Enables WSMan local configuration on client to enable CredSSP + /// 2. Sets CredSSP policy AllowFreshCredentials to wsman/Delegate. This policy + /// allows delegating explicit credentials to a server when server + /// authentication is achieved via a trusted X509 certificate or Kerberos. + /// + [Cmdlet(VerbsLifecycle.Enable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096719")] + [OutputType(typeof(XmlElement))] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] + public class EnableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable/*, IDynamicParameters*/ + { + /// + /// Delegate parameter. + /// + [Parameter(Position = 1)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public string[] DelegateComputer + { + get { return delegatecomputer; } + + set { delegatecomputer = value; } + } + + private string[] delegatecomputer; + + /// + /// Property that sets force parameter. + /// + [Parameter] + public SwitchParameter Force + { + get { return force; } + + set { force = value; } + } + + private bool force = false; + + // helper variable + private WSManHelper helper; + + // The application name MUST be "wsman" as wsman got approval from security + // folks who suggested to register the SPN with name "wsman". + private const string applicationname = "wsman"; + + #region Cmdlet Overloads + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + // If not running elevated, then throw an "elevation required" error message. + WSManHelper.ThrowIfNotAdministrator(); + helper = new WSManHelper(this); + + // DelegateComputer cannot be specified when Role is other than client + if ((delegatecomputer != null) && !Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) + { + string message = helper.FormatResourceMsgFromResourcetext("CredSSPRoleAndDelegateCannotBeSpecified", + "DelegateComputer", + "Role", + Role, + Client); + + throw new InvalidOperationException(message); + } + + // DelegateComputer must be specified when Role is client + if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase) && (delegatecomputer == null)) + { + string message = helper.FormatResourceMsgFromResourcetext("CredSSPClientAndDelegateMustBeSpecified", + "DelegateComputer", + "Role", + Client); + + throw new InvalidOperationException(message); + } + + if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) + { + EnableClientSideSettings(); + } + + if (Role.Equals(Server, StringComparison.OrdinalIgnoreCase)) + { + EnableServerSideSettings(); + } + } + + #endregion + + /// + /// + /// + /// + private void EnableClientSideSettings() + { + string query = helper.GetResourceMsgFromResourcetext("CredSSPContinueQuery"); + string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); + if (!force && !ShouldContinue(query, caption)) + { + return; + } + + IWSManSession m_SessionObj = CreateWSManSession(); + if (m_SessionObj == null) + { + return; + } + + try + { + // get the credssp node to check if wsman is configured on this machine + string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); + XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); + + if (node == null) + { + InvalidOperationException ex = new InvalidOperationException(); + ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + const string newxmlcontent = @"true"; + try + { + XmlDocument xmldoc = new XmlDocument(); + + // push the xml string with credssp enabled + xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0)); + + // set the Registry using GroupPolicyObject + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + { + this.UpdateCurrentUserRegistrySettings(); + } + else + { + ThreadStart start = new ThreadStart(this.UpdateCurrentUserRegistrySettings); + Thread thread = new Thread(start); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + } + + if (helper.ValidateCreadSSPRegistryRetry(true, delegatecomputer, applicationname)) + { + WriteObject(xmldoc.FirstChild); + } + else + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer); + } + } + catch (COMException) + { + helper.AssertError(m_SessionObj.Error, true, delegatecomputer); + } + } + finally + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + helper.AssertError(m_SessionObj.Error, true, delegatecomputer); + } + + if (m_SessionObj != null) + { + Dispose(m_SessionObj); + } + } + } + + private void EnableServerSideSettings() + { + string query = helper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery"); + string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); + if (!force && !ShouldContinue(query, caption)) + { + return; + } + + IWSManSession m_SessionObj = CreateWSManSession(); + if (m_SessionObj == null) + { + return; + } + + try + { + // get the credssp node to check if wsman is configured on this machine + string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); + XmlNode node = helper.GetXmlNode(result, + helper.CredSSP_SNode, + helper.Service_CredSSP_XMLNmsp); + + if (node == null) + { + InvalidOperationException ex = new InvalidOperationException(); + ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + try + { + XmlDocument xmldoc = new XmlDocument(); + string newxmlcontent = string.Format( + CultureInfo.InvariantCulture, + @"true", + helper.Service_CredSSP_XMLNmsp); + + // push the xml string with credssp enabled + xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0)); + WriteObject(xmldoc.FirstChild); + } + catch (COMException) + { + helper.AssertError(m_SessionObj.Error, true, delegatecomputer); + } + } + finally + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + helper.AssertError(m_SessionObj.Error, true, delegatecomputer); + } + + if (m_SessionObj != null) + { + Dispose(m_SessionObj); + } + } + } + + /// + /// + private void UpdateCurrentUserRegistrySettings() + { + System.IntPtr KeyHandle = System.IntPtr.Zero; + IGroupPolicyObject GPO = (IGroupPolicyObject)new GPClass(); + GPO.OpenLocalMachineGPO(1); + KeyHandle = GPO.GetRegistryKey(2); + RegistryKey rootKey = Registry.CurrentUser; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); + foreach (string keyname in GPOKey.GetSubKeyNames()) + { + if (keyname.EndsWith("Machine", StringComparison.OrdinalIgnoreCase)) + { + string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows"; + UpdateGPORegistrySettings(applicationname, this.delegatecomputer, Registry.CurrentUser, key); + } + } + // saving gpo settings + GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("7A9206BD-33AF-47af-B832-D4128730E990")); + } + + /// + /// Updates the grouppolicy registry settings. + /// + /// + /// + /// + /// + private void UpdateGPORegistrySettings(string applicationname, string[] delegatestring, RegistryKey rootKey, string Registry_Path) + { + // RegistryKey rootKey = Registry.LocalMachine; + RegistryKey Credential_Delegation_Key; + RegistryKey Allow_Fresh_Credential_Key; + int i = 0; + try + { + string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; + // open the registry key.If key is not present,create a new one + Credential_Delegation_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation, RegistryKeyPermissionCheck.ReadWriteSubTree); + + Credential_Delegation_Key.SetValue(helper.Key_Allow_Fresh_Credentials, 1, RegistryValueKind.DWord); + Credential_Delegation_Key.SetValue(helper.Key_Concatenate_Defaults_AllowFresh, 1, RegistryValueKind.DWord); + + // add the delegate value + Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, RegistryKeyPermissionCheck.ReadWriteSubTree); + + if (Allow_Fresh_Credential_Key != null) + { + i = Allow_Fresh_Credential_Key.ValueCount; + foreach (string del in delegatestring) + { + Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), applicationname + @"/" + del, RegistryValueKind.String); + i++; + } + } + } + catch (UnauthorizedAccessException ex) + { + ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccessException", ErrorCategory.PermissionDenied, null); + WriteError(er); + } + catch (SecurityException ex) + { + ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (ArgumentException ex) + { + ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + } + #endregion EnableCredSSP + + #region Get-CredSSP + + /// + /// Gets the CredSSP related configuration on the client. CredSSP authentication + /// enables an application to delegate the user's credentials from the client to + /// the server, hence allowing the user to perform management operations that + /// access a second hop. + /// This cmdlet performs the following: + /// 1. Gets the configuration for WSMan policy on client to enable/disable + /// CredSSP + /// 2. Gets the configuration information for the CredSSP policy + /// AllowFreshCredentials . This policy allows delegating explicit credentials + /// to a server when server authentication is achieved via a trusted X509 + /// certificate or Kerberos. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] + [Cmdlet(VerbsCommon.Get, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096838")] + [OutputType(typeof(string))] + public class GetWSManCredSSPCommand : PSCmdlet, IDisposable + { + #region private + private WSManHelper helper = null; + /// + /// Method to get the values. + /// + private string GetDelegateSettings(string applicationname) + { + RegistryKey rootKey = Registry.LocalMachine; + RegistryKey rKey; + string result = string.Empty; + string[] valuenames = null; + try + { + string Reg_key = helper.Registry_Path_Credentials_Delegation + @"\CredentialsDelegation"; + rKey = rootKey.OpenSubKey(Reg_key); + if (rKey != null) + { + rKey = rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials); + if (rKey != null) + { + valuenames = rKey.GetValueNames(); + if (valuenames.Length > 0) + { + string listvalue = CultureInfo.CurrentCulture.TextInfo.ListSeparator; + foreach (string value in valuenames) + { + object keyvalue = rKey.GetValue(value); + if (keyvalue != null) + { + if (keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) + { + result = keyvalue.ToString() + listvalue + result; + } + } + } + + if (result.EndsWith(listvalue, StringComparison.OrdinalIgnoreCase)) + { + result = result.Remove(result.Length - 1); + } + } + } + } + } + catch (ArgumentException ex) + { + ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.PermissionDenied, null); + WriteError(er); + } + catch (SecurityException ex) + { + ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.PermissionDenied, null); + WriteError(er); + } + catch (ObjectDisposedException ex) + { + ErrorRecord er = new ErrorRecord(ex, "ObjectDisposedException", ErrorCategory.PermissionDenied, null); + WriteError(er); + } + + return result; + } + #endregion private + + #region overrides + /// + /// Method to begin processing. + /// + protected override void BeginProcessing() + { + // If not running elevated, then throw an "elevation required" error message. + WSManHelper.ThrowIfNotAdministrator(); + helper = new WSManHelper(this); + IWSManSession m_SessionObj = null; + try + { + IWSManEx wsmanObject = (IWSManEx)new WSManClass(); + m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); + string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); + XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); + if (node == null) + { + InvalidOperationException ex = new InvalidOperationException(); + ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + // The application name MUST be "wsman" as wsman got approval from security + // folks who suggested to register the SPN with name "wsman". + const string applicationname = "wsman"; + string credsspResult = GetDelegateSettings(applicationname); + if (string.IsNullOrEmpty(credsspResult)) + { + WriteObject(helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred")); + } + else + { + WriteObject(helper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult); + } + + // Get the server side settings + result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); + node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); + if (node == null) + { + InvalidOperationException ex = new InvalidOperationException(); + ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + if (node.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase)) + { + WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured")); + } + else + { + WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured")); + } + } + catch (UnauthorizedAccessException ex) + { + ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.PermissionDenied, null); + WriteError(er); + } + catch (SecurityException ex) + { + ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (ArgumentException ex) + { + ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + catch (System.Xml.XPath.XPathException ex) + { + ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + finally + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + helper.AssertError(m_SessionObj.Error, true, null); + } + + if (m_SessionObj != null) + { + Dispose(m_SessionObj); + } + } + } + #endregion overrides + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + } + + #endregion +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/PowerShell-master/src/Microsoft.WSMan.Management/CurrentConfigurations.cs new file mode 100644 index 0000000000000000000000000000000000000000..3182c04c535e82e0eeaec5f8f95f4aff5727021e --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.Xml; + +namespace Microsoft.WSMan.Management +{ + /// + /// Class that queries the server and gets current configurations. + /// Also provides a generic way to update the configurations. + /// + internal sealed class CurrentConfigurations + { + /// + /// Prefix used to add NameSpace of root element to namespace manager. + /// + public const string DefaultNameSpacePrefix = "defaultNameSpace"; + + /// + /// This holds the current configurations XML. + /// + private readonly XmlDocument rootDocument; + + /// + /// Holds the reference to the current document element. + /// + private XmlElement documentElement; + + /// + /// Holds the Namespace Manager to use for XPATH queries. + /// + private XmlNamespaceManager nameSpaceManger; + + /// + /// Session of the WsMan sserver. + /// + private readonly IWSManSession serverSession; + + /// + /// Gets the server session associated with the configuration. + /// + public IWSManSession ServerSession + { + get { return serverSession; } + } + + /// + /// Gets the current configuration XML. + /// + public XmlDocument RootDocument + { + get { return this.rootDocument; } + } + + /// + /// Gets the current configuration on the given server and for given URI. + /// This issues a GET request to the server. + /// + /// Current server session. + public CurrentConfigurations(IWSManSession serverSession) + { + ArgumentNullException.ThrowIfNull(serverSession); + + this.rootDocument = new XmlDocument(); + this.serverSession = serverSession; + } + + /// + /// Refresh the CurrentConfiguration. This method calls GET operation for the given + /// URI on the server and update the current configuration. It also initialize some + /// of required class members. + /// + /// Plugin configuration. + /// False, if operation failed. + public bool RefreshCurrentConfiguration(string responseOfGet) + { + ArgumentException.ThrowIfNullOrEmpty(responseOfGet); + + this.rootDocument.LoadXml(responseOfGet); + this.documentElement = this.rootDocument.DocumentElement; + + this.nameSpaceManger = new XmlNamespaceManager(this.rootDocument.NameTable); + this.nameSpaceManger.AddNamespace(CurrentConfigurations.DefaultNameSpacePrefix, this.documentElement.NamespaceURI); + + return string.IsNullOrEmpty(this.serverSession.Error); + } + + /// + /// Update the server with updated XML. + /// Issues a PUT request with the ResourceUri provided. + /// + /// Resource URI to use. + /// False, if operation is not successful. + public void PutConfigurationOnServer(string resourceUri) + { + ArgumentException.ThrowIfNullOrEmpty(resourceUri); + + this.serverSession.Put(resourceUri, this.rootDocument.InnerXml, 0); + } + + /// + /// This method will remove the configuration from the XML. + /// Currently the method will only remove the attributes. But it is extensible enough to support + /// Node removals in future. + /// + /// Path with namespace to the node from Root element. Must not end with '/'. + public void RemoveOneConfiguration(string pathToNodeFromRoot) + { + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); + + XmlNode nodeToRemove = + this.documentElement.SelectSingleNode( + pathToNodeFromRoot, + this.nameSpaceManger); + + if (nodeToRemove != null) + { + if (nodeToRemove is XmlAttribute) + { + RemoveAttribute(nodeToRemove as XmlAttribute); + } + } + else + { + throw new ArgumentException("Node is not present in the XML, Please give valid XPath", nameof(pathToNodeFromRoot)); + } + } + + /// + /// Create or Update the value of the configuration on the given Node. Currently this + /// method is supported for updating attributes, but can be easily updated for nodes. + /// Caller should call this method to add a new attribute to the Node. + /// + /// Path with namespace to the node from Root element. Must not end with '/'. + /// Name of the configuration with name space to update or create. + /// Value of the configurations. + public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue) + { + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); + ArgumentException.ThrowIfNullOrEmpty(configurationName); + ArgumentNullException.ThrowIfNull(configurationValue); + + XmlNode nodeToUpdate = + this.documentElement.SelectSingleNode( + pathToNodeFromRoot, + this.nameSpaceManger); + + if (nodeToUpdate != null) + { + foreach (XmlAttribute attribute in nodeToUpdate.Attributes) + { + if (attribute.Name.Equals(configurationName, StringComparison.OrdinalIgnoreCase)) + { + attribute.Value = configurationValue; + return; + } + } + + XmlNode attr = this.rootDocument.CreateNode(XmlNodeType.Attribute, configurationName, string.Empty); + attr.Value = configurationValue; + + nodeToUpdate.Attributes.SetNamedItem(attr); + } + } + + /// + /// Gets the value of the configuration on the given Node or attribute. + /// + /// Path with namespace to the node from Root element. + /// Value of the Node, or Null if no node present. + public string GetOneConfiguration(string pathFromRoot) + { + ArgumentNullException.ThrowIfNull(pathFromRoot); + + XmlNode requiredNode = + this.documentElement.SelectSingleNode( + pathFromRoot, + this.nameSpaceManger); + + if (requiredNode != null) + { + return requiredNode.Value; + } + + return null; + } + + /// + /// Removes the attribute from OwnerNode. + /// + /// Attribute to Remove. + private static void RemoveAttribute(XmlAttribute attributeToRemove) + { + XmlElement ownerElement = attributeToRemove.OwnerElement; + ownerElement.RemoveAttribute(attributeToRemove.Name); + } + } +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/Interop.cs b/PowerShell-master/src/Microsoft.WSMan.Management/Interop.cs new file mode 100644 index 0000000000000000000000000000000000000000..3abb938a5728f89c686402d79de0919fc4b71ac2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/Interop.cs @@ -0,0 +1,1141 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Xml; + +#pragma warning disable 1591 + +namespace Microsoft.WSMan.Management +{ + #region "public Api" + + #region WsManEnumFlags + /// _WSManEnumFlags enumeration. + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] + [TypeLibType((short)0)] + public enum WSManEnumFlags + { + /// WSManFlagNonXmlText constant of _WSManEnumFlags enumeration. Constant value is 1. + WSManFlagNonXmlText = 1, + + /// WSManFlagReturnObject constant of _WSManEnumFlags enumeration. Constant value is 0. + WSManFlagReturnObject = 0, + + /// WSManFlagReturnEPR constant of _WSManEnumFlags enumeration. Constant value is 2. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] + WSManFlagReturnEPR = 2, + + /// WSManFlagReturnObjectAndEPR constant of _WSManEnumFlags enumeration. Constant value is 4. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] + WSManFlagReturnObjectAndEPR = 4, + + /// WSManFlagHierarchyDeep constant of _WSManEnumFlags enumeration. Constant value is 0. + WSManFlagHierarchyDeep = 0, + + /// WSManFlagHierarchyShallow constant of _WSManEnumFlags enumeration. Constant value is 32. + WSManFlagHierarchyShallow = 32, + + /// WSManFlagHierarchyDeepBasePropsOnly constant of _WSManEnumFlags enumeration. Constant value is 64. + WSManFlagHierarchyDeepBasePropsOnly = 64, + + /// WSManFlagAssociationInstance constant of _WSManEnumFlags enumeration. Constant value is 64. + WSManFlagAssociationInstance = 128 + } + + #endregion WsManEnumFlags + + #region WsManSessionFlags + /// WSManSessionFlags enumeration. + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] + [TypeLibType((short)0)] + public enum WSManSessionFlags + { + /// no flag constant of _WSManSessionFlags enumeration. Constant value is 1. + WSManNone = 0, + + /// WSManFlagUTF8 constant of _WSManSessionFlags enumeration. Constant value is 1. + WSManFlagUtf8 = 1, + + /// WSManFlagCredUsernamePassword constant of _WSManSessionFlags enumeration. Constant value is 4096. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + WSManFlagCredUserNamePassword = 4096, + + /// WSManFlagSkipCACheck constant of _WSManSessionFlags enumeration. Constant value is 8192. + WSManFlagSkipCACheck = 8192, + + /// WSManFlagSkipCNCheck constant of _WSManSessionFlags enumeration. Constant value is 16384. + WSManFlagSkipCNCheck = 16384, + + /// WSManFlagUseNoAuthentication constant of _WSManSessionFlags enumeration. Constant value is 32768. + WSManFlagUseNoAuthentication = 32768, + + /// WSManFlagUseDigest constant of _WSManSessionFlags enumeration. Constant value is 65536. + WSManFlagUseDigest = 65536, + + /// WSManFlagUseNegotiate constant of _WSManSessionFlags enumeration. Constant value is 131072. + WSManFlagUseNegotiate = 131072, + + /// WSManFlagUseBasic constant of _WSManSessionFlags enumeration. Constant value is 262144. + WSManFlagUseBasic = 262144, + + /// WSManFlagUseKerberos constant of _WSManSessionFlags enumeration. Constant value is 524288. + WSManFlagUseKerberos = 524288, + + /// WSManFlagNoEncryption constant of _WSManSessionFlags enumeration. Constant value is 1048576. + WSManFlagNoEncryption = 1048576, + + /// WSManFlagEnableSPNServerPort constant of _WSManSessionFlags enumeration. Constant value is 4194304. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Spn")] + WSManFlagEnableSpnServerPort = 4194304, + + /// WSManFlagUTF16 constant of _WSManSessionFlags enumeration. Constant value is 8388608. + WSManFlagUtf16 = 8388608, + + /// WSManFlagUseCredSsp constant of _WSManSessionFlags enumeration. Constant value is 16777216. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ssp")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + WSManFlagUseCredSsp = 16777216, + + /// WSManFlagUseClientCertificate constant of _WSManSessionFlags enumeration. Constant value is 2097152. + WSManFlagUseClientCertificate = 2097152, + + /// WSManFlagSkipRevocationCheck constant of _WSManSessionFlags enumeration. Constant value is 33554432. + WSManFlagSkipRevocationCheck = 33554432, + + /// WSManFlagAllowNegotiateImplicitCredentials constant of _WSManSessionFlags enumeration. Constant value is 67108864. + WSManFlagAllowNegotiateImplicitCredentials = 67108864, + + /// WSManFlagUseSsl constant of _WSManSessionFlags enumeration. Constant value is 134217728. + WSManFlagUseSsl = 134217728 + } + #endregion WsManSessionFlags + + #region AuthenticationMechanism + /// WSManEnumFlags enumeration + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] + public enum AuthenticationMechanism + { + /// + /// Use no authentication. + /// + None = 0x0, + /// + /// Use Default authentication. + /// + Default = 0x1, + /// + /// Use digest authentication for a remote operation. + /// + Digest = 0x2, + /// + /// Use negotiate authentication for a remote operation (may use kerberos or ntlm) + /// + Negotiate = 0x4, + /// + /// Use basic authentication for a remote operation. + /// + Basic = 0x8, + /// + /// Use kerberos authentication for a remote operation. + /// + Kerberos = 0x10, + /// + /// Use client certificate authentication for a remote operation. + /// + ClientCertificate = 0x20, + /// + /// Use CredSSP authentication for a remote operation. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Credssp")] + Credssp = 0x80, + } + + #endregion AuthenticationMechanism + + #region IWsMan + + /// IWSMan interface. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] + [Guid("190D8637-5CD3-496D-AD24-69636BB5A3B5")] + [ComImport] + [TypeLibType((short)4304)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + + public interface IWSMan + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + + /// CreateSession method of IWSMan interface. + /// An original IDL definition of CreateSession method was the following: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); + // IDL: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); + + [DispId(1)] +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions); +#else + [return: MarshalAs(UnmanagedType.IDispatch)] + object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions); +#endif + /// CreateConnectionOptions method of IWSMan interface. + /// An original IDL definition of CreateConnectionOptions method was the following: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); + // IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); + // + [DispId(2)] +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] +#else + [return: MarshalAs(UnmanagedType.IDispatch)] +#endif + object CreateConnectionOptions(); + + /// CommandLine property of IWSMan interface. + /// An original IDL definition of CommandLine property was the following: BSTR CommandLine; + // IDL: BSTR CommandLine; + // + string CommandLine + { + // IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue); + + [DispId(3)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + + /// Error property of IWSMan interface. + /// An original IDL definition of Error property was the following: BSTR Error; + // IDL: BSTR Error; + // + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + string Error + { + // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [DispId(4)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + } + #endregion IWsMan + + #region IWSManConnectionOptions + /// IWSManConnectionOptions interface. + [Guid("F704E861-9E52-464F-B786-DA5EB2320FDD")] + [ComImport] + [TypeLibType((short)4288)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] + public interface IWSManConnectionOptions + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + /// UserName property of IWSManConnectionOptions interface. + /// An original IDL definition of UserName property was the following: BSTR UserName; + // IDL: BSTR UserName; + + string UserName + { + // IDL: HRESULT UserName ([out, retval] BSTR* ReturnValue); + + [DispId(1)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + // IDL: HRESULT UserName (BSTR value); + + [DispId(1)] + set; + } + + /// Password property of IWSManConnectionOptions interface. + /// An original IDL definition of Password property was the following: BSTR Password; + // IDL: BSTR Password; + + [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] + string Password + { + // IDL: HRESULT Password (BSTR value); + + [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] + [DispId(2)] + set; + } + } + + /// IWSManConnectionOptions interface. + [Guid("EF43EDF7-2A48-4d93-9526-8BD6AB6D4A6B")] + [ComImport] + [TypeLibType((short)4288)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] + public interface IWSManConnectionOptionsEx : IWSManConnectionOptions + { + /// CertificateThumbprint property of IWSManConnectionOptionsEx interface. + string CertificateThumbprint + { + [DispId(3)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + + [DispId(1)] + set; + } + } + + /// IWSManConnectionOptions interface. + [Guid("F500C9EC-24EE-48ab-B38D-FC9A164C658E")] + [ComImport] + [TypeLibType((short)4288)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + public interface IWSManConnectionOptionsEx2 : IWSManConnectionOptionsEx + { + /// SetProxy method of IWSManConnectionOptionsEx2 interface. + [DispId(4)] + void SetProxy(int accessType, + int authenticationMechanism, + [In, MarshalAs(UnmanagedType.BStr)] string userName, + [In, MarshalAs(UnmanagedType.BStr)] string password); + + /// ProxyIEConfig method of IWSManConnectionOptionsEx2 interface. + [DispId(5)] + int ProxyIEConfig(); + + /// ProxyWinHttpConfig method of IWSManConnectionOptionsEx2 interface. + [DispId(6)] + int ProxyWinHttpConfig(); + + /// ProxyAutoDetect method of IWSManConnectionOptionsEx2 interface. + [DispId(7)] + int ProxyAutoDetect(); + + /// ProxyNoProxyServer method of IWSManConnectionOptionsEx2 interface. + [DispId(8)] + int ProxyNoProxyServer(); + + /// ProxyAuthenticationUseNegotiate method of IWSManConnectionOptionsEx2 interface. + [DispId(9)] + int ProxyAuthenticationUseNegotiate(); + + /// ProxyAuthenticationUseBasic method of IWSManConnectionOptionsEx2 interface. + [DispId(10)] + int ProxyAuthenticationUseBasic(); + + /// ProxyAuthenticationUseDigest method of IWSManConnectionOptionsEx2 interface. + [DispId(11)] + int ProxyAuthenticationUseDigest(); + } + + #endregion IWSManConnectionOptions + + #region IWSManEnumerator + /// IWSManEnumerator interface. + [Guid("F3457CA9-ABB9-4FA5-B850-90E8CA300E7F")] + [ComImport] + [TypeLibType((short)4288)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + + public interface IWSManEnumerator + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + + /// ReadItem method of IWSManEnumerator interface. + /// An original IDL definition of ReadItem method was the following: HRESULT ReadItem ([out, retval] BSTR* ReturnValue); + // IDL: HRESULT ReadItem ([out, retval] BSTR* ReturnValue); + + [DispId(1)] + [return: MarshalAs(UnmanagedType.BStr)] + string ReadItem(); + + /// AtEndOfStream property of IWSManEnumerator interface. + /// An original IDL definition of AtEndOfStream property was the following: BOOL AtEndOfStream; + // IDL: BOOL AtEndOfStream; + + bool AtEndOfStream + { + // IDL: HRESULT AtEndOfStream ([out, retval] BOOL* ReturnValue); + + [DispId(2)] + [return: MarshalAs(UnmanagedType.Bool)] + get; + } + + /// Error property of IWSManEnumerator interface. + /// An original IDL definition of Error property was the following: BSTR Error; + // IDL: BSTR Error; + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + string Error + { + // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [DispId(8)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + } + #endregion IWSManEnumerator + + #region IWSManEx + /// IWSManEx interface. + [Guid("2D53BDAA-798E-49E6-A1AA-74D01256F411")] + [ComImport] + [TypeLibType((short)4304)] + [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + public interface IWSManEx + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + + /// CreateSession method of IWSManEx interface. + /// An original IDL definition of CreateSession method was the following: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); + // IDL: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); + + [DispId(1)] +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions); +#else + [return: MarshalAs(UnmanagedType.IDispatch)] + object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions); +#endif + + /// CreateConnectionOptions method of IWSManEx interface. + /// An original IDL definition of CreateConnectionOptions method was the following: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); + // IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); + + [DispId(2)] +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] +#else + [return: MarshalAs(UnmanagedType.IDispatch)] +#endif + object CreateConnectionOptions(); + + /// + /// + /// + string CommandLine + { + // IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue); + + [DispId(3)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + + /// Error property of IWSManEx interface. + /// An original IDL definition of Error property was the following: BSTR Error; + // IDL: BSTR Error; + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + string Error + { + // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [DispId(4)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + + /// CreateResourceLocator method of IWSManEx interface. + /// An original IDL definition of CreateResourceLocator method was the following: HRESULT CreateResourceLocator ([optional, defaultvalue(string.Empty)] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue); + // IDL: HRESULT CreateResourceLocator ([optional, defaultvalue(string.Empty)] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")] + [DispId(5)] +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] +#else + [return: MarshalAs(UnmanagedType.IDispatch)] +#endif + object CreateResourceLocator([MarshalAs(UnmanagedType.BStr)] string strResourceLocator); + + /// SessionFlagUTF8 method of IWSManEx interface. + /// An original IDL definition of SessionFlagUTF8 method was the following: HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] + [DispId(6)] + int SessionFlagUTF8(); + + /// SessionFlagCredUsernamePassword method of IWSManEx interface. + /// An original IDL definition of SessionFlagCredUsernamePassword method was the following: HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] + [DispId(7)] + int SessionFlagCredUsernamePassword(); + + /// SessionFlagSkipCACheck method of IWSManEx interface. + /// An original IDL definition of SessionFlagSkipCACheck method was the following: HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue); + + [DispId(8)] + int SessionFlagSkipCACheck(); + + /// SessionFlagSkipCNCheck method of IWSManEx interface. + /// An original IDL definition of SessionFlagSkipCNCheck method was the following: HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue); + + [DispId(9)] + int SessionFlagSkipCNCheck(); + + /// SessionFlagUseDigest method of IWSManEx interface. + /// An original IDL definition of SessionFlagUseDigest method was the following: HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue); + + [DispId(10)] + int SessionFlagUseDigest(); + + /// SessionFlagUseNegotiate method of IWSManEx interface. + /// An original IDL definition of SessionFlagUseNegotiate method was the following: HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue); + + [DispId(11)] + int SessionFlagUseNegotiate(); + + /// SessionFlagUseBasic method of IWSManEx interface. + /// An original IDL definition of SessionFlagUseBasic method was the following: HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue); + + [DispId(12)] + int SessionFlagUseBasic(); + + /// SessionFlagUseKerberos method of IWSManEx interface. + /// An original IDL definition of SessionFlagUseKerberos method was the following: HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue); + + [DispId(13)] + int SessionFlagUseKerberos(); + + /// SessionFlagNoEncryption method of IWSManEx interface. + /// An original IDL definition of SessionFlagNoEncryption method was the following: HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue); + + [DispId(14)] + int SessionFlagNoEncryption(); + + /// SessionFlagEnableSPNServerPort method of IWSManEx interface. + /// An original IDL definition of SessionFlagEnableSPNServerPort method was the following: HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] + [DispId(15)] + int SessionFlagEnableSPNServerPort(); + + /// SessionFlagUseNoAuthentication method of IWSManEx interface. + /// An original IDL definition of SessionFlagUseNoAuthentication method was the following: HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue); + // IDL: HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue); + + [DispId(16)] + int SessionFlagUseNoAuthentication(); + + /// EnumerationFlagNonXmlText method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagNonXmlText method was the following: HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue); + + [DispId(17)] + int EnumerationFlagNonXmlText(); + + /// EnumerationFlagReturnEPR method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagReturnEPR method was the following: HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] + [DispId(18)] + int EnumerationFlagReturnEPR(); + + /// EnumerationFlagReturnObjectAndEPR method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagReturnObjectAndEPR method was the following: HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] + [DispId(19)] + int EnumerationFlagReturnObjectAndEPR(); + + /// GetErrorMessage method of IWSManEx interface. + /// An original IDL definition of GetErrorMessage method was the following: HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue); + // IDL: HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue); + + [DispId(20)] + [return: MarshalAs(UnmanagedType.BStr)] + string GetErrorMessage(uint errorNumber); + + /// EnumerationFlagHierarchyDeep method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagHierarchyDeep method was the following: HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue); + + [DispId(21)] + int EnumerationFlagHierarchyDeep(); + + /// EnumerationFlagHierarchyShallow method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagHierarchyShallow method was the following: HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue); + + [DispId(22)] + int EnumerationFlagHierarchyShallow(); + + /// EnumerationFlagHierarchyDeepBasePropsOnly method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagHierarchyDeepBasePropsOnly method was the following: HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue); + + [DispId(23)] + int EnumerationFlagHierarchyDeepBasePropsOnly(); + + /// EnumerationFlagReturnObject method of IWSManEx interface. + /// An original IDL definition of EnumerationFlagReturnObject method was the following: HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue); + // IDL: HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue); + + [DispId(24)] + int EnumerationFlagReturnObject(); + + /// CommandLine property of IWSManEx interface. + /// An original IDL definition of CommandLine property was the following: BSTR CommandLine; + // IDL: BSTR CommandLine; + [DispId(28)] + int EnumerationFlagAssociationInstance(); + + /// CommandLine property of IWSManEx interface. + /// An original IDL definition of CommandLine property was the following: BSTR CommandLine; + // IDL: BSTR CommandLine; + [DispId(29)] + int EnumerationFlagAssociatedInstance(); + } + #endregion IWsManEx + + #region IWsManResourceLocator + + /// IWSManResourceLocator interface. + [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] + + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")] + + [Guid("A7A1BA28-DE41-466A-AD0A-C4059EAD7428")] + [ComImport] + [TypeLibType((short)4288)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + + public interface IWSManResourceLocator + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + /// resourceUri property of IWSManResourceLocator interface. Set the resource URI. Must contain path only -- query string is not allowed here. + /// An original IDL definition of resourceUri property was the following: BSTR resourceUri; + // Set the resource URI. Must contain path only -- query string is not allowed here. + // IDL: BSTR resourceUri; + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + string ResourceUri + { + // IDL: HRESULT resourceUri (BSTR value); + [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1212:PropertyAccessorsMustFollowOrder", Justification = "COM interface defines put_ before get_.")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + [DispId(1)] + set; + + // IDL: HRESULT resourceUri ([out, retval] BSTR* ReturnValue); + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + [DispId(1)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + + /// AddSelector method of IWSManResourceLocator interface. Add selector to resource locator + /// An original IDL definition of AddSelector method was the following: HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue); + // Add selector to resource locator + // IDL: HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue); + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "sel")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")] + [DispId(2)] + void AddSelector([MarshalAs(UnmanagedType.BStr)] string resourceSelName, object selValue); + + /// ClearSelectors method of IWSManResourceLocator interface. Clear all selectors + /// An original IDL definition of ClearSelectors method was the following: HRESULT ClearSelectors (void); + // Clear all selectors + // IDL: HRESULT ClearSelectors (void); + + [DispId(3)] + void ClearSelectors(); + + /// FragmentPath property of IWSManResourceLocator interface. Gets the fragment path + /// An original IDL definition of FragmentPath property was the following: BSTR FragmentPath; + // Gets the fragment path + // IDL: BSTR FragmentPath; + + string FragmentPath + { + // IDL: HRESULT FragmentPath ([out, retval] BSTR* ReturnValue); + + [DispId(4)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + // IDL: HRESULT FragmentPath (BSTR value); + + [DispId(4)] + set; + } + + /// FragmentDialect property of IWSManResourceLocator interface. Gets the Fragment dialect + /// An original IDL definition of FragmentDialect property was the following: BSTR FragmentDialect; + // Gets the Fragment dialect + // IDL: BSTR FragmentDialect; + + string FragmentDialect + { + // IDL: HRESULT FragmentDialect ([out, retval] BSTR* ReturnValue); + + [DispId(5)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + // IDL: HRESULT FragmentDialect (BSTR value); + + [DispId(5)] + set; + } + + /// AddOption method of IWSManResourceLocator interface. Add option to resource locator + /// An original IDL definition of AddOption method was the following: HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply); + // Add option to resource locator + // IDL: HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply); + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Option")] + [DispId(6)] + void AddOption([MarshalAs(UnmanagedType.BStr)] string OptionName, object OptionValue, int mustComply); + + /// MustUnderstandOptions property of IWSManResourceLocator interface. Sets the MustUnderstandOptions value + /// An original IDL definition of MustUnderstandOptions property was the following: long MustUnderstandOptions; + // Sets the MustUnderstandOptions value + // IDL: long MustUnderstandOptions; + + int MustUnderstandOptions + { + // IDL: HRESULT MustUnderstandOptions (long value); + + [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1212:PropertyAccessorsMustFollowOrder", Justification = "COM interface defines put_ before get_.")] + [DispId(7)] + set; + + // IDL: HRESULT MustUnderstandOptions ([out, retval] long* ReturnValue); + + [DispId(7)] + get; + } + + /// ClearOptions method of IWSManResourceLocator interface. Clear all options + /// An original IDL definition of ClearOptions method was the following: HRESULT ClearOptions (void); + // Clear all options + // IDL: HRESULT ClearOptions (void); + + [DispId(8)] + void ClearOptions(); + + /// Error property of IWSManResourceLocator interface. + /// An original IDL definition of Error property was the following: BSTR Error; + // IDL: BSTR Error; + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + string Error + { + // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [DispId(9)] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + } + #endregion IWsManResourceLocator + + #region IWSManSession + /// IWSManSession interface. + [Guid("FC84FC58-1286-40C4-9DA0-C8EF6EC241E0")] + [ComImport] + [TypeLibType((short)4288)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] + [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public interface IWSManSession + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + + /// Get method of IWSManSession interface. + /// An original IDL definition of Get method was the following: HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + // IDL: HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] + [DispId(1)] + [return: MarshalAs(UnmanagedType.BStr)] + string Get(object resourceUri, int flags); + + /// Put method of IWSManSession interface. + /// An original IDL definition of Put method was the following: HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + // IDL: HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + + [DispId(2)] + [return: MarshalAs(UnmanagedType.BStr)] + string Put(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags); + + /// Create method of IWSManSession interface. + /// An original IDL definition of Create method was the following: HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + // IDL: HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + + [DispId(3)] + [return: MarshalAs(UnmanagedType.BStr)] + string Create(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags); + + /// Delete method of IWSManSession interface. + /// An original IDL definition of Delete method was the following: HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags); + // IDL: HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags); + + [DispId(4)] + void Delete(object resourceUri, int flags); + + /// + /// + /// + /// + /// + /// + /// + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] + [DispId(5)] + string Invoke([MarshalAs(UnmanagedType.BStr)] string actionURI, [In] object resourceUri, [MarshalAs(UnmanagedType.BStr)] string parameters, [In] int flags); + + /// Enumerate method of IWSManSession interface. + /// An original IDL definition of Enumerate method was the following: HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue(string.Empty)] BSTR filter, [optional, defaultvalue(string.Empty)] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue); + // IDL: HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue(string.Empty)] BSTR filter, [optional, defaultvalue(string.Empty)] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue); + + [DispId(6)] +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] +#else + [return: MarshalAs(UnmanagedType.IDispatch)] +#endif + object Enumerate(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string filter, [MarshalAs(UnmanagedType.BStr)] string dialect, int flags); + + /// Identify method of IWSManSession interface. + /// An original IDL definition of Identify method was the following: HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + // IDL: HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); + + [DispId(7)] + [return: MarshalAs(UnmanagedType.BStr)] + string Identify(int flags); + + /// Error property of IWSManSession interface. + /// An original IDL definition of Error property was the following: BSTR Error; + // IDL: BSTR Error; + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + string Error + { + // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] + [DispId(8)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + + /// BatchItems property of IWSManSession interface. + /// An original IDL definition of BatchItems property was the following: long BatchItems; + // IDL: long BatchItems; + + int BatchItems + { + // IDL: HRESULT BatchItems ([out, retval] long* ReturnValue); + + [DispId(9)] + get; + // IDL: HRESULT BatchItems (long value); + + [DispId(9)] + set; + } + + /// Timeout property of IWSManSession interface. + /// An original IDL definition of Timeout property was the following: long Timeout; + // IDL: long Timeout; + + int Timeout + { + // IDL: HRESULT Timeout ([out, retval] long* ReturnValue); + + [DispId(10)] + get; + // IDL: HRESULT Timeout (long value); + + [DispId(10)] + set; + } + } + + #endregion IWSManSession + + #region IWSManResourceLocatorInternal + /// IWSManResourceLocatorInternal interface. + [Guid("EFFAEAD7-7EC8-4716-B9BE-F2E7E9FB4ADB")] + [ComImport] + [TypeLibType((short)400)] +#if CORECLR + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +#else + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] +#endif + [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] + public interface IWSManResourceLocatorInternal + { +#if CORECLR + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfoCount(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetTypeInfo(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetIDsOfNames(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object Invoke(); +#endif + } + + #endregion IWSManResourceLocatorInternal + + /// WSMan interface. + [Guid("BCED617B-EC03-420b-8508-977DC7A686BD")] + [ComImport] +#if CORECLR + [ClassInterface(ClassInterfaceType.None)] +#else + [ClassInterface(ClassInterfaceType.AutoDual)] +#endif + public class WSManClass + { + } + + #region IGroupPolicyObject + + /// GPClass interface. + [Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")] + [ComImport] + [ClassInterface(ClassInterfaceType.None)] + public class GPClass + { + } + + [ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + internal interface IGroupPolicyObject + { + void New( + [MarshalAs(UnmanagedType.LPWStr)] string pszDomainName, + [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, + uint dwFlags); + + void OpenDSGPO( + [MarshalAs(UnmanagedType.LPWStr)] string pszPath, + uint dwFlags); + + void OpenLocalMachineGPO(uint dwFlags); + + void OpenRemoteMachineGPO( + [MarshalAs(UnmanagedType.LPWStr)] string pszComputerName, + uint dwFlags); + + void Save( + [MarshalAs(UnmanagedType.Bool)] bool bMachine, + [MarshalAs(UnmanagedType.Bool)] bool bAdd, + [MarshalAs(UnmanagedType.LPStruct)] Guid pGuidExtension, + [MarshalAs(UnmanagedType.LPStruct)] Guid pGuid); + + void Delete(); + + void GetName( + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, + int cchMaxLength); + + void GetDisplayName( + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, + int cchMaxLength); + + void SetDisplayName( + [MarshalAs(UnmanagedType.LPWStr)] string pszName); + + void GetPath( + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, + int cchMaxPath); + + void GetDSPath( + uint dwSection, + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, + int cchMaxPath); + + void GetFileSysPath( + uint dwSection, + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, + int cchMaxPath); + + IntPtr GetRegistryKey(uint dwSection); + + uint GetOptions(); + + void SetOptions(uint dwOptions, uint dwMask); + + void GetMachineName( + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, + int cchMaxLength); + + uint GetPropertySheetPages(out IntPtr hPages); + } + + #endregion IGroupPolicyObject + + /// GpoNativeApi + public sealed class GpoNativeApi + { + private GpoNativeApi() { } + + [DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern System.IntPtr EnterCriticalPolicySection( + [In, MarshalAs(UnmanagedType.Bool)] bool bMachine); + + [DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool LeaveCriticalPolicySection( + [In] System.IntPtr hSection); + } + #endregion +} + +#pragma warning restore 1591 diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/PowerShell-master/src/Microsoft.WSMan.Management/InvokeWSManAction.cs new file mode 100644 index 0000000000000000000000000000000000000000..da92a680ab35256b632270b1c7b568ad75cdbdde --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Xml; + +namespace Microsoft.WSMan.Management +{ + /// + /// Executes action on a target object specified by RESOURCE_URI, where + /// parameters are specified by key value pairs. + /// eg., Call StartService method on the spooler service + /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service + /// -SelectorSet {Name=Spooler} + /// + [Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096843")] + [OutputType(typeof(XmlElement))] + public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable + { + /// + /// The following is the definition of the input parameter "Action". + /// Indicates the method which needs to be executed on the management object + /// specified by the ResourceURI and selectors. + /// + [Parameter(Mandatory = true, + Position = 1)] + [ValidateNotNullOrEmpty] + public string Action + { + get { return action; } + + set { action = value; } + } + + private string action; + + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = null; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(ParameterSetName = "ComputerName")] + [Alias("cn")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and ApplicationName of the new + /// runspace. The format of this string is: + /// transport://server:port/ApplicationName. + /// + [Parameter(ParameterSetName = "URI")] + [ValidateNotNullOrEmpty] + [Alias("CURI", "CU")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ConnectionURI + { + get { return connectionuri; } + + set { connectionuri = value; } + } + + private Uri connectionuri; + + /// + /// The following is the definition of the input parameter "FilePath". + /// Updates the management resource specified by the ResourceURI and SelectorSet + /// via this input file. + /// + [Parameter] + [Alias("Path")] + [ValidateNotNullOrEmpty] + public string FilePath + { + get { return filepath; } + + set { filepath = value; } + } + + private string filepath; + + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hashtable and is used to pass a set of switches to the + /// service to modify or refine the nature of the request. + /// + [Parameter(ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("os")] + public Hashtable OptionSet + { + get { return optionset; } + + set { optionset = value; } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "SelectorSet". + /// SelectorSet is a hash table which helps in identify an instance of the + /// management resource if there are more than 1 instance of the resource + /// class. + /// + [Parameter(Position = 2, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable SelectorSet + { + get { return selectorset; } + + set { selectorset = value; } + } + + private Hashtable selectorset; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. This hashtable can + /// be created using New-WSManSessionOption. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("so")] + public SessionOption SessionOption + { + get { return sessionoption; } + + set { sessionoption = value; } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "ComputerName")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + /// + /// The following is the definition of the input parameter "ValueSet". + /// ValueSet is a hahs table which helps to modify resource represented by the + /// ResourceURI and SelectorSet. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable ValueSet + { + get { return valueset; } + + set { valueset = value; } + } + + private Hashtable valueset; + + /// + /// The following is the definition of the input parameter "ResourceURI". + /// URI of the resource class/instance representation. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("ruri")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ResourceURI + { + get { return resourceuri; } + + set { resourceuri = value; } + } + + private Uri resourceuri; + + private WSManHelper helper; + private readonly IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + private IWSManSession m_session = null; + private string connectionStr = string.Empty; + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + helper = new WSManHelper(this); + + helper.WSManOp = "invoke"; + + // create the connection string + connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + // create the resourcelocator object + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); + + // create the session object + m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); + + string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); + string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); + string resultXml = m_session.Invoke(action, m_resource, input, 0); + + XmlDocument xmldoc = new XmlDocument(); + xmldoc.LoadXml(resultXml); + WriteObject(xmldoc.DocumentElement); + } + finally + { + if (!string.IsNullOrEmpty(m_wsmanObject.Error)) + { + helper.AssertError(m_wsmanObject.Error, true, resourceuri); + } + + if (!string.IsNullOrEmpty(m_session.Error)) + { + helper.AssertError(m_session.Error, true, resourceuri); + } + + if (m_session != null) + Dispose(m_session); + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + + /// + /// BeginProcessing method. + /// + protected override void EndProcessing() + { + // WSManHelper helper = new WSManHelper(); + helper.CleanUp(); + } + } +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/PowerShell-master/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj new file mode 100644 index 0000000000000000000000000000000000000000..bc6e4b105deb8003fee0204473f068e97d9fac68 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -0,0 +1,24 @@ + + + + PowerShell's Microsoft.WSMan.Management project + $(NoWarn);CA1416 + Microsoft.WSMan.Management + + + + + + + + + + + $(DefineConstants);CORECLR + + + + + + + diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/NewWSManSession.cs b/PowerShell-master/src/Microsoft.WSMan.Management/NewWSManSession.cs new file mode 100644 index 0000000000000000000000000000000000000000..09b22af9924ef9ea43a6b400da9b0c44e94c1311 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -0,0 +1,309 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Net; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Xml; + +namespace Microsoft.WSMan.Management +{ + /// + /// Creates a WSMan Session option hashtable which can be passed into WSMan + /// cmdlets: + /// Get-WSManInstance + /// Set-WSManInstance + /// Invoke-WSManAction + /// Connect-WSMan. + /// + [Cmdlet(VerbsCommon.New, "WSManSessionOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096845")] + [OutputType(typeof(SessionOption))] + public class NewWSManSessionOptionCommand : PSCmdlet + { + /// + /// + [Parameter] + [ValidateNotNullOrEmpty] + public ProxyAccessType ProxyAccessType + { + get + { + return _proxyaccesstype; + } + + set + { + _proxyaccesstype = value; + } + } + + private ProxyAccessType _proxyaccesstype; + + /// + /// The following is the definition of the input parameter "ProxyAuthentication". + /// This parameter takes a set of authentication methods the user can select + /// from. The available options should be as follows: + /// - Negotiate: Use the default authentication (ad defined by the underlying + /// protocol) for establishing a remote connection. + /// - Basic: Use basic authentication for establishing a remote connection + /// - Digest: Use Digest authentication for establishing a remote connection. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public ProxyAuthentication ProxyAuthentication + { + get + { + return proxyauthentication; + } + + set + { + proxyauthentication = value; + } + } + + private ProxyAuthentication proxyauthentication; + + /// + /// The following is the definition of the input parameter "ProxyCredential". + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Credential] + public PSCredential ProxyCredential + { + get + { + return _proxycredential; + } + + set + { + _proxycredential = value; + } + } + + private PSCredential _proxycredential; + + /// + /// The following is the definition of the input parameter "SkipCACheck". + /// When connecting over HTTPS, the client does not validate that the server + /// certificate is signed by a trusted certificate authority (CA). Use only when + /// the remote computer is trusted by other means, for example, if the remote + /// computer is part of a network that is physically secure and isolated or the + /// remote computer is listed as a trusted host in WinRM configuration. + /// + [Parameter] + public SwitchParameter SkipCACheck + { + get + { + return skipcacheck; + } + + set + { + skipcacheck = value; + } + } + + private bool skipcacheck; + + /// + /// The following is the definition of the input parameter "SkipCNCheck". + /// Indicates that certificate common name (CN) of the server need not match the + /// hostname of the server. Used only in remote operations using https. This + /// option should only be used for trusted machines. + /// + [Parameter] + public SwitchParameter SkipCNCheck + { + get + { + return skipcncheck; + } + + set + { + skipcncheck = value; + } + } + + private bool skipcncheck; + + /// + /// The following is the definition of the input parameter "SkipRevocation". + /// Indicates that certificate common name (CN) of the server need not match the + /// hostname of the server. Used only in remote operations using https. This + /// option should only be used for trusted machines. + /// + [Parameter] + public SwitchParameter SkipRevocationCheck + { + get + { + return skiprevocationcheck; + } + + set + { + skiprevocationcheck = value; + } + } + + private bool skiprevocationcheck; + + /// + /// The following is the definition of the input parameter "SPNPort". + /// Appends port number to the connection Service Principal Name SPN of the + /// remote server. + /// SPN is used when authentication mechanism is Kerberos or Negotiate. + /// + [Parameter] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] + [ValidateRange(0, int.MaxValue)] + public int SPNPort + { + get + { + return spnport; + } + + set + { + spnport = value; + } + } + + private int spnport; + + /// + /// The following is the definition of the input parameter "Timeout". + /// Defines the timeout in ms for the wsman operation. + /// + [Parameter] + [Alias("OperationTimeoutMSec")] + [ValidateRange(0, int.MaxValue)] + public int OperationTimeout + { + get + { + return operationtimeout; + } + + set + { + operationtimeout = value; + } + } + + private int operationtimeout; + + /// + /// The following is the definition of the input parameter "UnEncrypted". + /// Specifies that no encryption will be used when doing remote operations over + /// http. Unencrypted traffic is not allowed by default and must be enabled in + /// the local configuration. + /// + [Parameter] + public SwitchParameter NoEncryption + { + get + { + return noencryption; + } + + set + { + noencryption = value; + } + } + + private bool noencryption; + + /// + /// The following is the definition of the input parameter "UTF16". + /// Indicates the request is encoded in UTF16 format rather than UTF8 format; + /// UTF8 is the default. + /// + [Parameter] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] + public SwitchParameter UseUTF16 + { + get + { + return useutf16; + } + + set + { + useutf16 = value; + } + } + + private bool useutf16; + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + WSManHelper helper = new WSManHelper(this); + + if (proxyauthentication.Equals(ProxyAuthentication.Basic) || proxyauthentication.Equals(ProxyAuthentication.Digest)) + { + if (_proxycredential == null) + { + InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionCred")); + ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + } + + if ((_proxycredential != null) && (proxyauthentication == 0)) + { + InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionAuth")); + ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + // Creating the Session Object + SessionOption objSessionOption = new SessionOption(); + + objSessionOption.SPNPort = spnport; + objSessionOption.UseUtf16 = useutf16; + objSessionOption.SkipCNCheck = skipcncheck; + objSessionOption.SkipCACheck = skipcacheck; + objSessionOption.OperationTimeout = operationtimeout; + objSessionOption.SkipRevocationCheck = skiprevocationcheck; + // Proxy Settings + objSessionOption.ProxyAccessType = _proxyaccesstype; + objSessionOption.ProxyAuthentication = proxyauthentication; + + if (noencryption) + { + objSessionOption.UseEncryption = false; + } + + if (_proxycredential != null) + { + NetworkCredential nwCredentials = _proxycredential.GetNetworkCredential(); + objSessionOption.ProxyCredential = nwCredentials; + } + + WriteObject(objSessionOption); + } + } +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/PingWSMan.cs b/PowerShell-master/src/Microsoft.WSMan.Management/PingWSMan.cs new file mode 100644 index 0000000000000000000000000000000000000000..88b443a6ef0c0b6a95c4a21d9268d32d54b2d6ea --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -0,0 +1,208 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Xml; + +namespace Microsoft.WSMan.Management +{ + #region Test-WSMAN + + /// + /// Issues an operation against the remote machine to ensure that the wsman + /// service is running. + /// + [Cmdlet(VerbsDiagnostic.Test, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097114")] + [OutputType(typeof(XmlElement))] + public class TestWSManCommand : AuthenticatingWSManCommand, IDisposable + { + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer. The default is + /// the local computer. Type the fully qualified domain name, NETBIOS name or IP + /// address to indicate the remote host. + /// + [Parameter(Position = 0, ValueFromPipeline = true)] + [Alias("cn")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "Authentication". + /// This parameter takes a set of authentication methods the user can select + /// from. The available method are an enum called AuthenticationMechanism in the + /// System.Management.Automation.Runspaces namespace. The available options + /// should be as follows: + /// - Default : Use the default authentication (ad defined by the underlying + /// protocol) for establishing a remote connection. + /// - Negotiate + /// - Kerberos + /// - Basic: Use basic authentication for establishing a remote connection. + /// -CredSSP: Use CredSSP authentication for establishing a remote connection + /// which will enable the user to perform credential delegation. (i.e. second + /// hop) + /// + /// + /// Overriding to use a different default than the one in AuthenticatingWSManCommand base class + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("auth", "am")] + public override AuthenticationMechanism Authentication + { + get + { + return authentication; + } + + set + { + authentication = value; + ValidateSpecifiedAuthentication(); + } + } + + private AuthenticationMechanism authentication = AuthenticationMechanism.None; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "ComputerName")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = null; + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + WSManHelper helper = new WSManHelper(this); + IWSManEx wsmanObject = (IWSManEx)new WSManClass(); + string connectionStr = string.Empty; + connectionStr = helper.CreateConnectionString(null, port, computername, applicationname); + IWSManSession m_SessionObj = null; + try + { + m_SessionObj = helper.CreateSessionObject(wsmanObject, Authentication, null, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); + m_SessionObj.Timeout = 1000; // 1 sec. we are putting this low so that Test-WSMan can return promptly if the server goes unresponsive. + XmlDocument xmldoc = new XmlDocument(); + xmldoc.LoadXml(m_SessionObj.Identify(0)); + WriteObject(xmldoc.DocumentElement); + } + catch (Exception) + { + try + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + XmlDocument ErrorDoc = new XmlDocument(); + ErrorDoc.LoadXml(m_SessionObj.Error); + InvalidOperationException ex = new InvalidOperationException(ErrorDoc.OuterXml); + ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, computername); + this.WriteError(er); + } + } + catch (Exception) + { } + } + finally + { + if (m_SessionObj != null) + Dispose(m_SessionObj); + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + } + #endregion +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/PowerShell-master/src/Microsoft.WSMan.Management/Set-QuickConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..9ad9e39c33204b0854674c1be7fd851264f66a4f --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Xml; + +namespace Microsoft.WSMan.Management +{ + #region Set-WsManQuickConfig + + // + + /// + /// Performs configuration actions to enable the local machine for remote + /// management. Steps include: + /// 1. Check if WinRM service is running. If not start the WinRM service + /// 2. Set the WinRM service type to auto start + /// 3. Create a listener to accept request on any IP address. By default + /// transport is http + /// 4. Enable firewall exception for WS-Management traffic. + /// + [Cmdlet(VerbsCommon.Set, "WSManQuickConfig", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097112")] + [OutputType(typeof(string))] + public class SetWSManQuickConfigCommand : PSCmdlet, IDisposable + { + /// + /// The following is the definition of the input parameter "UseSSL". + /// Indicates a https listener to be created. If this switch is not specified + /// then by default a http listener will be created. + /// + [Parameter] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + // helper variable + private WSManHelper helper; + + /// + /// Property that sets force parameter. This will allow + /// configuring WinRM without prompting the user. + /// + [Parameter] + public SwitchParameter Force + { + get { return force; } + + set { force = value; } + } + + private bool force = false; + + /// + /// Property that will allow configuring WinRM with Public profile exception enabled. + /// + [Parameter] + public SwitchParameter SkipNetworkProfileCheck + { + get { return skipNetworkProfileCheck; } + + set { skipNetworkProfileCheck = value; } + } + + private bool skipNetworkProfileCheck = false; + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + // If not running elevated, then throw an "elevation required" error message. + WSManHelper.ThrowIfNotAdministrator(); + helper = new WSManHelper(this); + string query = helper.GetResourceMsgFromResourcetext("QuickConfigContinueQuery"); + string caption = helper.GetResourceMsgFromResourcetext("QuickConfigContinueCaption"); + if (!force && !ShouldContinue(query, caption)) + { + return; + } + + QuickConfigRemoting(true); + QuickConfigRemoting(false); + } + + #region private + + private void QuickConfigRemoting(bool serviceonly) + { + IWSManSession m_SessionObj = null; + try + { + string transport; + IWSManEx wsmanObject = (IWSManEx)new WSManClass(); + m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); + string xpathEnabled = string.Empty; + string xpathText = string.Empty; + string xpathUpdate = string.Empty; + string analysisInputXml = string.Empty; + string action = string.Empty; + string xpathStatus = string.Empty; + string xpathResult = string.Empty; + + if (!usessl) + { + transport = "http"; + } + else + { + transport = "https"; + } + + if (serviceonly) + { + analysisInputXml = @""; + action = "AnalyzeService"; + } + else + { + string openAllProfiles = skipNetworkProfileCheck ? "" : string.Empty; + analysisInputXml = @"" + transport + "" + openAllProfiles + ""; + action = "Analyze"; + } + + string analysisOutputXml = m_SessionObj.Invoke(action, "winrm/config/service", analysisInputXml, 0); + XmlDocument resultopxml = new XmlDocument(); + resultopxml.LoadXml(analysisOutputXml); + + if (serviceonly) + { + xpathEnabled = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled"; + xpathText = "/cfg:AnalyzeService_OUTPUT/cfg:Results"; + xpathUpdate = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT"; + } + else + { + xpathEnabled = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled"; + xpathText = "/cfg:Analyze_OUTPUT/cfg:Results"; + xpathUpdate = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT"; + } + + XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); + nsmgr.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service"); + string enabled = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText; + XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source"); + string source = null; + if (sourceAttribute != null) + { + source = sourceAttribute.Value; + } + + string rxml = string.Empty; + if (enabled.Equals("true")) + { + string Err_Msg = string.Empty; + if (serviceonly) + { + Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message"); + } + else + { + Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message"); + } + // ArgumentException e = new ArgumentException(Err_Msg); + // ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null); + // WriteError(er); + WriteObject(Err_Msg); + return; + } + + if (!enabled.Equals("false")) + { + ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage")); + ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText; + if (source != null && source.Equals("GPO")) + { + string Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage"); + Info_Msg += " " + resultAction; + ArgumentException e = new ArgumentException(Info_Msg); + WriteError(new ErrorRecord(e, "NotSpecified", ErrorCategory.NotSpecified, null)); + return; + } + + string inputXml = resultopxml.SelectSingleNode(xpathUpdate, nsmgr).OuterXml; + if (resultAction.Equals(string.Empty) || inputXml.Equals(string.Empty)) + { + ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage")); + ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null); + WriteError(er); + return; + } + + if (serviceonly) + { + action = "EnableService"; + } + else + { + action = "EnableRemoting"; + } + + rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0); + XmlDocument finalxml = new XmlDocument(); + finalxml.LoadXml(rxml); + + if (serviceonly) + { + xpathStatus = "/cfg:EnableService_OUTPUT/cfg:Status"; + xpathResult = "/cfg:EnableService_OUTPUT/cfg:Results"; + } + else + { + xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status"; + xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results"; + } + + if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.Equals("succeeded")) + { + if (serviceonly) + { + WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message")); + } + else + { + WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message")); + } + + WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText); + } + else + { + helper.AssertError(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage"), false, null); + } + } + finally + { + if (!string.IsNullOrEmpty(m_SessionObj.Error)) + { + helper.AssertError(m_SessionObj.Error, true, null); + } + + if (m_SessionObj != null) + Dispose(m_SessionObj); + } + } + #endregion private + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + } + #endregion Set-WsManQuickConfig +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/WSManConnections.cs b/PowerShell-master/src/Microsoft.WSMan.Management/WSManConnections.cs new file mode 100644 index 0000000000000000000000000000000000000000..cac5196740fe63530562f055ca398c5bed1d101c --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -0,0 +1,387 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Management.Automation.Runspaces; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Xml; + +using Dbg = System.Management.Automation; + +namespace Microsoft.WSMan.Management +{ + #region Base class for cmdlets taking credential, authentication, certificatethumbprint + + /// + /// Common base class for all WSMan cmdlets that + /// take Authentication, CertificateThumbprint and Credential parameters. + /// + public class AuthenticatingWSManCommand : PSCmdlet + { + /// + /// The following is the definition of the input parameter "Credential". + /// Specifies a user account that has permission to perform this action. The + /// default is the current user. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Credential] + [Alias("cred", "c")] + public virtual PSCredential Credential + { + get + { + return credential; + } + + set + { + credential = value; + ValidateSpecifiedAuthentication(); + } + } + + private PSCredential credential; + + /// + /// The following is the definition of the input parameter "Authentication". + /// This parameter takes a set of authentication methods the user can select + /// from. The available method are an enum called Authentication in the + /// System.Management.Automation.Runspaces namespace. The available options + /// should be as follows: + /// - Default : Use the default authentication (ad defined by the underlying + /// protocol) for establishing a remote connection. + /// - Negotiate + /// - Kerberos + /// - Basic: Use basic authentication for establishing a remote connection. + /// -CredSSP: Use CredSSP authentication for establishing a remote connection + /// which will enable the user to perform credential delegation. (i.e. second + /// hop) + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("auth", "am")] + public virtual AuthenticationMechanism Authentication + { + get + { + return authentication; + } + + set + { + authentication = value; + ValidateSpecifiedAuthentication(); + } + } + + private AuthenticationMechanism authentication = AuthenticationMechanism.Default; + + /// + /// Specifies the certificate thumbprint to be used to impersonate the user on the + /// remote machine. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public virtual string CertificateThumbprint + { + get + { + return thumbPrint; + } + + set + { + thumbPrint = value; + ValidateSpecifiedAuthentication(); + } + } + + private string thumbPrint = null; + + internal void ValidateSpecifiedAuthentication() + { + WSManHelper.ValidateSpecifiedAuthentication( + this.Authentication, + this.Credential, + this.CertificateThumbprint); + } + } + + #endregion + + #region Connect-WsMan + /// + /// Connect wsman cmdlet. + /// + [Cmdlet(VerbsCommunications.Connect, "WSMan", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096841")] + public class ConnectWSManCommand : AuthenticatingWSManCommand + { + #region Parameters + + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = null; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(ParameterSetName = "ComputerName", Position = 0)] + [Alias("cn")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and ApplicationName of the new + /// runspace. The format of this string is: + /// transport://server:port/ApplicationName. + /// + [Parameter(ParameterSetName = "URI")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ConnectionURI + { + get { return connectionuri; } + + set { connectionuri = value; } + } + + private Uri connectionuri; + + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hash table and is used to pass a set of switches to the + /// service to modify or refine the nature of the request. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("os")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable OptionSet + { + get { return optionset; } + + set { optionset = value; } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Parameter(ParameterSetName = "ComputerName")] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. This hashtable can + /// be created using New-WSManSessionOption. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("so")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public SessionOption SessionOption + { + get { return sessionoption; } + + set { sessionoption = value; } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "ComputerName")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + #endregion + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + WSManHelper helper = new WSManHelper(this); + if (connectionuri != null) + { + try + { + // always in the format http://server:port/applicationname + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + computername = constrsplit1[1].Trim(); + } + catch (IndexOutOfRangeException) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + } + } + + string crtComputerName = computername ?? "localhost"; + + if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.OrdinalIgnoreCase)) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername); + } + + helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint); + } + } + #endregion + + #region Disconnect-WSMAN + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Cmdlet(VerbsCommunications.Disconnect, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096839")] + public class DisconnectWSManCommand : PSCmdlet, IDisposable + { + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(Position = 0)] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(object session) + { + session = null; + this.Dispose(); + } + + #endregion IDisposable Members + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + WSManHelper helper = new WSManHelper(this); + computername ??= "localhost"; + + if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.OrdinalIgnoreCase)) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername); + } + + if (computername.Equals("localhost", StringComparison.OrdinalIgnoreCase)) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername); + } + + object _ws = helper.RemoveFromDictionary(computername); + if (_ws != null) + { + Dispose(_ws); + } + else + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername); + } + } + } + #endregion Disconnect-WSMAN +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/WSManInstance.cs b/PowerShell-master/src/Microsoft.WSMan.Management/WSManInstance.cs new file mode 100644 index 0000000000000000000000000000000000000000..c96b002123d223abbeef0428671b1b5867bbe990 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -0,0 +1,1638 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Management.Automation.Runspaces; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Xml; + +using Dbg = System.Management.Automation; + +namespace Microsoft.WSMan.Management +{ + #region Get-WSManInstance + /// + /// Executes action on a target object specified by RESOURCE_URI, where + /// parameters are specified by key value pairs. + /// eg., Call StartService method on the spooler service + /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service + /// -SelectorSet {Name=Spooler} + /// + [Cmdlet(VerbsCommon.Get, "WSManInstance", DefaultParameterSetName = "GetInstance", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096627")] + [OutputType(typeof(XmlElement))] + public class GetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable + { + #region parameter + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "GetInstance")] + [Parameter(ParameterSetName = "Enumerate")] + public string ApplicationName + { + get + { + return applicationname; + } + + set + { + { applicationname = value; } + } + } + + private string applicationname = null; + + /// + /// The following is the definition of the input parameter "BasePropertiesOnly". + /// Enumerate only those properties that are part of the base class + /// specification in the Resource URI. When + /// Shallow is specified then this flag has no effect. + /// + [Parameter(ParameterSetName = "Enumerate")] + [Alias("UBPO", "Base")] + public SwitchParameter BasePropertiesOnly + { + get + { + return basepropertiesonly; + } + + set + { + { basepropertiesonly = value; } + } + } + + private SwitchParameter basepropertiesonly; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(ParameterSetName = "GetInstance")] + [Parameter(ParameterSetName = "Enumerate")] + [Alias("CN")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and Prefix, needed to connect to the + /// remote machine. The format of this string is: + /// transport://server:port/Prefix. + /// + [Parameter( + ParameterSetName = "GetInstance")] + [Parameter( + ParameterSetName = "Enumerate")] + [Alias("CURI", "CU")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ConnectionURI + { + get + { + return connectionuri; + } + + set + { + { connectionuri = value; } + } + } + + private Uri connectionuri; + + /// + /// The following is the definition of the input parameter "Dialect". + /// Defines the dialect for the filter predicate. + /// + [Parameter] + public Uri Dialect + { + get + { + return dialect; + } + + set + { + { dialect = value; } + } + } + + private Uri dialect; + + /// + /// The following is the definition of the input parameter "Enumerate". + /// Switch indicates list all instances of a management resource. Equivalent to + /// WSManagement Enumerate. + /// + [Parameter(Mandatory = true, + ParameterSetName = "Enumerate")] + public SwitchParameter Enumerate + { + get + { + return enumerate; + } + + set + { + { enumerate = value; } + } + } + + private SwitchParameter enumerate; + + /// + /// The following is the definition of the input parameter "Filter". + /// Indicates the filter expression for the enumeration. + /// + [Parameter(ParameterSetName = "Enumerate")] + [ValidateNotNullOrEmpty] + public string Filter + { + get + { + return filter; + } + + set + { + { filter = value; } + } + } + + private string filter; + + /// + /// The following is the definition of the input parameter "Fragment". + /// Specifies a section inside the instance that is to be updated or retrieved + /// for the given operation. + /// + [Parameter(ParameterSetName = "GetInstance")] + [ValidateNotNullOrEmpty] + public string Fragment + { + get + { + return fragment; + } + + set + { + { fragment = value; } + } + } + + private string fragment; + + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hashtable and is used to pass a set of switches to the + /// service to modify or refine the nature of the request. + /// + [Parameter(ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateNotNullOrEmpty] + [Alias("OS")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable OptionSet + { + get + { + return optionset; + } + + set + { + { optionset = value; } + } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter(ParameterSetName = "Enumerate")] + [Parameter(ParameterSetName = "GetInstance")] + public int Port + { + get + { + return port; + } + + set + { + { port = value; } + } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "Associations". + /// Associations indicates retrieval of association instances as opposed to + /// associated instances. This can only be used when specifying the Dialect as + /// Association. + /// + [Parameter(ParameterSetName = "Enumerate")] + public SwitchParameter Associations + { + get + { + return associations; + } + + set + { + { associations = value; } + } + } + + private SwitchParameter associations; + + /// + /// The following is the definition of the input parameter "ResourceURI". + /// URI of the resource class/instance representation. + /// + [Parameter(Mandatory = true, + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [Alias("RURI")] + public Uri ResourceURI + { + get + { + return resourceuri; + } + + set + { + { resourceuri = value; } + } + } + + private Uri resourceuri; + + /// + /// The following is the definition of the input parameter "ReturnType". + /// Indicates the type of data returned. Possible options are 'Object', 'EPR', + /// and 'ObjectAndEPR'. Default is Object. + /// If Object is specified or if this parameter is absent then only the objects + /// are returned + /// If EPR is specified then only the EPRs of the objects + /// are returned. EPRs contain information about the Resource URI and selectors + /// for the instance + /// If ObjectAndEPR is specified, then both the object and the associated EPRs + /// are returned. + /// + [Parameter(ParameterSetName = "Enumerate")] + + [ValidateNotNullOrEmpty] + [ValidateSet(new string[] { "object", "epr", "objectandepr" })] + [Alias("RT")] + public string ReturnType + { + get + { + return returntype; + } + + set + { + { returntype = value; } + } + } + + private string returntype = "object"; + + /// + /// The following is the definition of the input parameter "SelectorSet". + /// SelectorSet is a hash table which helps in identify an instance of the + /// management resource if there are more than 1 instance of the resource + /// class. + /// + [Parameter( + ParameterSetName = "GetInstance")] + + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable SelectorSet + { + get + { + return selectorset; + } + + set + { + { selectorset = value; } + } + } + + private Hashtable selectorset; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. This can be + /// created by using the cmdlet New-WSManSessionOption. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("SO")] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public SessionOption SessionOption + { + get + { + return sessionoption; + } + + set + { + { sessionoption = value; } + } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "Shallow". + /// Enumerate only instances of the base class specified in the resource URI. If + /// this flag is not specified, instances of the base class specified in the URI + /// and all its derived classes are returned. + /// + [Parameter(ParameterSetName = "Enumerate")] + + public SwitchParameter Shallow + { + get + { + return shallow; + } + + set + { + { shallow = value; } + } + } + + private SwitchParameter shallow; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "GetInstance")] + [Parameter(ParameterSetName = "Enumerate")] + + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + [Alias("SSL")] + public SwitchParameter UseSSL + { + get + { + return usessl; + } + + set + { + { usessl = value; } + } + } + + private SwitchParameter usessl; + + #endregion parameter + + #region private + private WSManHelper helper; + + private string GetFilter() + { + string name; + string value; + string[] Split = filter.Trim().Split(new char[] { '=', ';' }); + if ((Split.Length) % 2 != 0) + { + // mismatched property name/value pair + return null; + } + + filter = ""; + for (int i = 0; i < Split.Length; i += 2) + { + value = Split[i + 1].Substring(1, Split[i + 1].Length - 2); + name = Split[i]; + filter = filter + "" + value + ""; + } + + filter += ""; + return (filter); + } + + private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) + { + string fragment; + try + { + int flags = 0; + IWSManEnumerator obj; + if (returntype != null) + { + if (returntype.Equals("object", StringComparison.OrdinalIgnoreCase)) + { + flags = wsmanObject.EnumerationFlagReturnObject(); + } + else if (returntype.Equals("epr", StringComparison.OrdinalIgnoreCase)) + { + flags = wsmanObject.EnumerationFlagReturnEPR(); + } + else + { + flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); + } + } + + if (shallow) + { + flags |= wsmanObject.EnumerationFlagHierarchyShallow(); + } + else if (basepropertiesonly) + { + flags |= wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); + } + else + { + flags |= wsmanObject.EnumerationFlagHierarchyDeep(); + } + + if (dialect != null && filter != null) + { + if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.OrdinalIgnoreCase)) + { + fragment = helper.URI_WQL_DIALECT; + dialect = new Uri(fragment); + } + else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.OrdinalIgnoreCase)) + { + if (associations) + { + flags |= wsmanObject.EnumerationFlagAssociationInstance(); + } + else + { + flags |= wsmanObject.EnumerationFlagAssociatedInstance(); + } + + fragment = helper.URI_ASSOCIATION_DIALECT; + dialect = new Uri(fragment); + } + else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.OrdinalIgnoreCase)) + { + filter = GetFilter(); + fragment = helper.URI_SELECTOR_DIALECT; + dialect = new Uri(fragment); + } + + obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); + } + else if (filter != null) + { + fragment = helper.URI_WQL_DIALECT; + dialect = new Uri(fragment); + obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); + } + else + { + obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); + } + while (!obj.AtEndOfStream) + { + XmlDocument xmldoc = new XmlDocument(); + xmldoc.LoadXml(obj.ReadItem()); + WriteObject(xmldoc.FirstChild); + } + } + catch (Exception ex) + { + ErrorRecord er = new ErrorRecord(ex, "Exception", ErrorCategory.InvalidOperation, null); + WriteError(er); + } + } + #endregion private + #region override + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + IWSManSession m_session = null; + IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + helper = new WSManHelper(this); + helper.WSManOp = "Get"; + string connectionStr = null; + connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + if (connectionuri != null) + { + try + { + // in the format http(s)://server[:port/applicationname] + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + computername = constrsplit1[1].Trim(); + } + catch (IndexOutOfRangeException) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + } + } + + try + { + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); + m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); + + if (!enumerate) + { + XmlDocument xmldoc = new XmlDocument(); + try + { + xmldoc.LoadXml(m_session.Get(m_resource, 0)); + } + catch (XmlException ex) + { + helper.AssertError(ex.Message, false, computername); + } + + if (!string.IsNullOrEmpty(fragment)) + { + WriteObject(xmldoc.FirstChild.LocalName + "=" + xmldoc.FirstChild.InnerText); + } + else + { + WriteObject(xmldoc.FirstChild); + } + } + else + { + try + { + ReturnEnumeration(m_wsmanObject, m_resource, m_session); + } + catch (Exception ex) + { + helper.AssertError(ex.Message, false, computername); + } + } + } + finally + { + if (!string.IsNullOrEmpty(m_wsmanObject.Error)) + { + helper.AssertError(m_wsmanObject.Error, true, resourceuri); + } + + if (!string.IsNullOrEmpty(m_session.Error)) + { + helper.AssertError(m_session.Error, true, resourceuri); + } + + if (m_session != null) + Dispose(m_session); + } + } + #endregion override + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + + /// + /// BeginProcessing method. + /// + protected override void EndProcessing() + { + helper.CleanUp(); + } + } + #endregion + + #region Set-WsManInstance + + /// + /// Executes action on a target object specified by RESOURCE_URI, where + /// parameters are specified by key value pairs. + /// eg., Call StartService method on the spooler service + /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service + /// -SelectorSet {Name=Spooler} + /// + [Cmdlet(VerbsCommon.Set, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096937")] + [OutputType(typeof(XmlElement), typeof(string))] + public class SetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable + { + #region Parameters + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = null; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(ParameterSetName = "ComputerName")] + [Alias("cn")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and ApplicationName of the new + /// runspace. The format of this string is: + /// transport://server:port/ApplicationName. + /// + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [Parameter(ParameterSetName = "URI")] + [ValidateNotNullOrEmpty] + public Uri ConnectionURI + { + get { return connectionuri; } + + set { connectionuri = value; } + } + + private Uri connectionuri; + + /// + /// The following is the definition of the input parameter "Dialect". + /// Defines the dialect for the filter predicate. + /// + [Parameter] + [ValidateNotNullOrEmpty] + public Uri Dialect + { + get { return dialect; } + + set { dialect = value; } + } + + private Uri dialect; + + /// + /// The following is the definition of the input parameter "FilePath". + /// Updates the management resource specified by the ResourceURI and SelectorSet + /// via this input file. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [Alias("Path")] + [ValidateNotNullOrEmpty] + public string FilePath + { + get { return filepath; } + + set { filepath = value; } + } + + private string filepath; + + /// + /// The following is the definition of the input parameter "Fragment". + /// Specifies a section inside the instance that is to be updated or retrieved + /// for the given operation. + /// + [Parameter(ParameterSetName = "ComputerName")] + [Parameter(ParameterSetName = "URI")] + [ValidateNotNullOrEmpty] + public string Fragment + { + get { return fragment; } + + set { fragment = value; } + } + + private string fragment; + + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hahs table which help modify or refine the nature of the + /// request. These are similar to switches used in command line shells in that + /// they are service-specific. + /// + [Parameter] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("os")] + [ValidateNotNullOrEmpty] + public Hashtable OptionSet + { + get { return optionset; } + + set { optionset = value; } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "ResourceURI". + /// URI of the resource class/instance representation. + /// + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] + + [Parameter(Mandatory = true, Position = 0)] + [Alias("ruri")] + [ValidateNotNullOrEmpty] + public Uri ResourceURI + { + get { return resourceuri; } + + set { resourceuri = value; } + } + + private Uri resourceuri; + + /// + /// The following is the definition of the input parameter "SelectorSet". + /// SelectorSet is a hash table which helps in identify an instance of the + /// management resource if there are more than 1 instance of the resource + /// class. + /// + [Parameter(Position = 1, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [ValidateNotNullOrEmpty] + public Hashtable SelectorSet + { + get { return selectorset; } + + set { selectorset = value; } + } + + private Hashtable selectorset; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. This can be created + /// by using the cmdlet New-WSManSessionOption. + /// + [Parameter] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("so")] + [ValidateNotNullOrEmpty] + public SessionOption SessionOption + { + get { return sessionoption; } + + set { sessionoption = value; } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "ComputerName")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + [Alias("ssl")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + /// + /// The following is the definition of the input parameter "ValueSet". + /// ValueSet is a hash table which helps to modify resource represented by the + /// ResourceURI and SelectorSet. + /// + [Parameter(ValueFromPipelineByPropertyName = true)] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [ValidateNotNullOrEmpty] + public Hashtable ValueSet + { + get { return valueset; } + + set { valueset = value; } + } + + private Hashtable valueset; + + #endregion + + private WSManHelper helper; + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + helper = new WSManHelper(this); + helper.WSManOp = "set"; + IWSManSession m_session = null; + + if (dialect != null) + { + if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase)) + dialect = new Uri(helper.URI_WQL_DIALECT); + if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase)) + dialect = new Uri(helper.URI_SELECTOR_DIALECT); + if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase)) + dialect = new Uri(helper.URI_ASSOCIATION_DIALECT); + } + + try + { + string connectionStr = string.Empty; + connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + if (connectionuri != null) + { + try + { + // in the format http(s)://server[:port/applicationname] + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + computername = constrsplit1[1].Trim(); + } + catch (IndexOutOfRangeException) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + } + } + + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); + m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); + string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); + string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); + + XmlDocument xmldoc = new XmlDocument(); + try + { + xmldoc.LoadXml(m_session.Put(m_resource, input, 0)); + } + catch (XmlException ex) + { + helper.AssertError(ex.Message, false, computername); + } + + if (!string.IsNullOrEmpty(fragment)) + { + if (xmldoc.DocumentElement.ChildNodes.Count > 0) + { + foreach (XmlNode node in xmldoc.DocumentElement.ChildNodes) + { + if (node.Name.Equals(fragment, StringComparison.OrdinalIgnoreCase)) + WriteObject(node.Name + " = " + node.InnerText); + } + } + } + else + WriteObject(xmldoc.DocumentElement); + } + finally + { + if (!string.IsNullOrEmpty(m_wsmanObject.Error)) + { + helper.AssertError(m_wsmanObject.Error, true, resourceuri); + } + + if (!string.IsNullOrEmpty(m_session.Error)) + { + helper.AssertError(m_session.Error, true, resourceuri); + } + + if (m_session != null) + Dispose(m_session); + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + + /// + /// BeginProcessing method. + /// + protected override void EndProcessing() + { + helper.CleanUp(); + } + } + + #endregion + + #region Remove-WsManInstance + + /// + /// Executes action on a target object specified by RESOURCE_URI, where + /// parameters are specified by key value pairs. + /// eg., Call StartService method on the spooler service + /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service + /// -SelectorSet {Name=Spooler} + /// + [Cmdlet(VerbsCommon.Remove, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096721")] + public class RemoveWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable + { + #region Parameters + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = null; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(ParameterSetName = "ComputerName")] + [Alias("cn")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and ApplicationName of the new + /// runspace. The format of this string is: + /// transport://server:port/ApplicationName. + /// + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [Parameter(ParameterSetName = "URI")] + [ValidateNotNullOrEmpty] + public Uri ConnectionURI + { + get { return connectionuri; } + + set { connectionuri = value; } + } + + private Uri connectionuri; + + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hahs table which help modify or refine the nature of the + /// request. These are similar to switches used in command line shells in that + /// they are service-specific. + /// + [Parameter] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("os")] + [ValidateNotNullOrEmpty] + public Hashtable OptionSet + { + get { return optionset; } + + set { optionset = value; } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "ResourceURI". + /// URI of the resource class/instance representation. + /// + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] + + [Parameter(Mandatory = true, Position = 0)] + [Alias("ruri")] + [ValidateNotNullOrEmpty] + public Uri ResourceURI + { + get { return resourceuri; } + + set { resourceuri = value; } + } + + private Uri resourceuri; + + /// + /// The following is the definition of the input parameter "SelectorSet". + /// SelectorSet is a hash table which helps in identify an instance of the + /// management resource if there are more than 1 instance of the resource + /// class. + /// + [Parameter(Position = 1, Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [ValidateNotNullOrEmpty] + public Hashtable SelectorSet + { + get { return selectorset; } + + set { selectorset = value; } + } + + private Hashtable selectorset; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. This can be created + /// by using the cmdlet New-WSManSessionOption. + /// + [Parameter] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("so")] + [ValidateNotNullOrEmpty] + public SessionOption SessionOption + { + get { return sessionoption; } + + set { sessionoption = value; } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "ComputerName")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + [Alias("ssl")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + #endregion + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + WSManHelper helper = new WSManHelper(this); + IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + helper.WSManOp = "remove"; + IWSManSession m_session = null; + try + { + string connectionStr = string.Empty; + connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + if (connectionuri != null) + { + try + { + // in the format http(s)://server[:port/applicationname] + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + computername = constrsplit1[1].Trim(); + } + catch (IndexOutOfRangeException) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + } + } + + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); + m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); + string ResourceURI = helper.GetURIWithFilter(resourceuri.ToString(), null, selectorset, helper.WSManOp); + try + { + ((IWSManSession)m_session).Delete(ResourceURI, 0); + } + catch (Exception ex) + { + helper.AssertError(ex.Message, false, computername); + } + } + finally + { + if (!string.IsNullOrEmpty(m_session.Error)) + { + helper.AssertError(m_session.Error, true, resourceuri); + } + + if (!string.IsNullOrEmpty(m_wsmanObject.Error)) + { + helper.AssertError(m_wsmanObject.Error, true, resourceuri); + } + + if (m_session != null) + Dispose(m_session); + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + } + + #endregion + + #region New-WsManInstance + /// + /// Creates an instance of a management resource identified by the resource URI + /// using specified ValueSet or input File. + /// + [Cmdlet(VerbsCommon.New, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096933")] + [OutputType(typeof(XmlElement))] + public class NewWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable + { + /// + /// The following is the definition of the input parameter "ApplicationName". + /// ApplicationName identifies the remote endpoint. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + public string ApplicationName + { + get { return applicationname; } + + set { applicationname = value; } + } + + private string applicationname = null; + + /// + /// The following is the definition of the input parameter "ComputerName". + /// Executes the management operation on the specified computer(s). The default + /// is the local computer. Type the fully qualified domain name, NETBIOS name or + /// IP address to indicate the remote host(s) + /// + [Parameter(ParameterSetName = "ComputerName")] + [Alias("cn")] + public string ComputerName + { + get + { + return computername; + } + + set + { + computername = value; + if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) + { + computername = "localhost"; + } + } + } + + private string computername = null; + + /// + /// The following is the definition of the input parameter "ConnectionURI". + /// Specifies the transport, server, port, and ApplicationName of the new + /// runspace. The format of this string is: + /// transport://server:port/ApplicationName. + /// + [Parameter(ParameterSetName = "URI")] + [ValidateNotNullOrEmpty] + [Alias("CURI", "CU")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ConnectionURI + { + get { return connectionuri; } + + set { connectionuri = value; } + } + + private Uri connectionuri; + + /// + /// The following is the definition of the input parameter "FilePath". + /// Updates the management resource specified by the ResourceURI and SelectorSet + /// via this input file. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [Alias("Path")] + public string FilePath + { + get { return filepath; } + + set { filepath = value; } + } + + private string filepath; + + /// + /// The following is the definition of the input parameter "OptionSet". + /// OptionSet is a hash table and is used to pass a set of switches to the + /// service to modify or refine the nature of the request. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("os")] + public Hashtable OptionSet + { + get { return optionset; } + + set { optionset = value; } + } + + private Hashtable optionset; + + /// + /// The following is the definition of the input parameter "Port". + /// Specifies the port to be used when connecting to the ws management service. + /// + [Parameter(ParameterSetName = "ComputerName")] + [ValidateNotNullOrEmpty] + [ValidateRange(1, int.MaxValue)] + public int Port + { + get { return port; } + + set { port = value; } + } + + private int port = 0; + + /// + /// The following is the definition of the input parameter "ResourceURI". + /// URI of the resource class/instance representation. + /// + [Parameter(Mandatory = true, Position = 0)] + [ValidateNotNullOrEmpty] + [Alias("ruri")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] + public Uri ResourceURI + { + get { return resourceuri; } + + set { resourceuri = value; } + } + + private Uri resourceuri; + + /// + /// The following is the definition of the input parameter "SelectorSet". + /// SelectorSet is a hash table which helps in identify an instance of the + /// management resource if there are more than 1 instance of the resource + /// class. + /// + [Parameter(Mandatory = true, Position = 1, + ValueFromPipeline = true)] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable SelectorSet + { + get { return selectorset; } + + set { selectorset = value; } + } + + private Hashtable selectorset; + + /// + /// The following is the definition of the input parameter "SessionOption". + /// Defines a set of extended options for the WSMan session. + /// + [Parameter] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + [Alias("so")] + public SessionOption SessionOption + { + get { return sessionoption; } + + set { sessionoption = value; } + } + + private SessionOption sessionoption; + + /// + /// The following is the definition of the input parameter "UseSSL". + /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to + /// the remote computer. If SSL is not available on the port specified by the + /// Port parameter, the command fails. + /// + [Parameter(ParameterSetName = "ComputerName")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] + public SwitchParameter UseSSL + { + get { return usessl; } + + set { usessl = value; } + } + + private SwitchParameter usessl; + + /// + /// The following is the definition of the input parameter "ValueSet". + /// ValueSet is a hash table which helps to modify resource represented by the + /// ResourceURI and SelectorSet. + /// + [Parameter] + [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public Hashtable ValueSet + { + get { return valueset; } + + set { valueset = value; } + } + + private Hashtable valueset; + + private WSManHelper helper; + private readonly IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + private IWSManSession m_session = null; + private string connectionStr = string.Empty; + + /// + /// BeginProcessing method. + /// + protected override void BeginProcessing() + { + helper = new WSManHelper(this); + helper.WSManOp = "new"; + connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + if (connectionuri != null) + { + try + { + // in the format http(s)://server[:port/applicationname] + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + computername = constrsplit1[1].Trim(); + } + catch (IndexOutOfRangeException) + { + helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + } + } + } + + /// + /// ProcessRecord method. + /// + protected override void ProcessRecord() + { + try + { + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); + // create the session object + m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); + string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); + string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); + + try + { + string resultXml = m_session.Create(m_resource, input, 0); + XmlDocument xmldoc = new XmlDocument(); + xmldoc.LoadXml(resultXml); + WriteObject(xmldoc.DocumentElement); + } + catch (Exception ex) + { + helper.AssertError(ex.Message, false, computername); + } + } + finally + { + if (!string.IsNullOrEmpty(m_wsmanObject.Error)) + { + helper.AssertError(m_wsmanObject.Error, true, resourceuri); + } + + if (!string.IsNullOrEmpty(m_session.Error)) + { + helper.AssertError(m_session.Error, true, resourceuri); + } + + if (m_session != null) + { + Dispose(m_session); + } + } + } + + #region IDisposable Members + + /// + /// Public dispose method. + /// + public + void + Dispose() + { + // CleanUp(); + GC.SuppressFinalize(this); + } + /// + /// Public dispose method. + /// + public + void + Dispose(IWSManSession sessionObject) + { + sessionObject = null; + this.Dispose(); + } + + #endregion IDisposable Members + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + helper.CleanUp(); + } + } + + #endregion +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/WsManHelper.cs b/PowerShell-master/src/Microsoft.WSMan.Management/WsManHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..9249c7f4b888eda2b80f9d085498052f96e6a8bf --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -0,0 +1,1121 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Provider; +using System.Reflection; +using System.Resources; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Xml; + +using Microsoft.Win32; + +namespace Microsoft.WSMan.Management +{ + [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] + internal sealed class WSManHelper + { + // regular expressions + private const string PTRN_URI_LAST = @"([a-z_][-a-z0-9._]*)$"; + private const string PTRN_OPT = @"^-([a-z]+):(.*)"; + private const string PTRN_HASH_TOK = @"\s*([\w:]+)\s*=\s*(\$null|""([^""]*)"")\s*"; + + // schemas + private const string URI_IPMI = @"http://schemas.dmtf.org/wbem/wscim/1/cim-schema"; + private const string URI_WMI = @"http://schemas.microsoft.com/wbem/wsman/1/wmi"; + private const string NS_IPMI = @"http://schemas.dmtf.org/wbem/wscim/1/cim-schema"; + private const string NS_CIMBASE = @"http://schemas.dmtf.org/wbem/wsman/1/base"; + private const string NS_WSMANL = @"http://schemas.microsoft.com"; + private const string NS_XSI = @"xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"""; + private const string ATTR_NIL = @"xsi:nil=""true"""; + private const string ATTR_NIL_NAME = @"xsi:nil"; + private const string NS_XSI_URI = @"http://www.w3.org/2001/XMLSchema-instance"; + private const string ALIAS_XPATH = @"xpath"; + private const string URI_XPATH_DIALECT = @"http://www.w3.org/TR/1999/REC-xpath-19991116"; + + // credSSP strings + internal string CredSSP_RUri = "winrm/config/client/auth"; + internal string CredSSP_XMLNmsp = "http://schemas.microsoft.com/wbem/wsman/1/config/client/auth"; + internal string CredSSP_SNode = "/cfg:Auth/cfg:CredSSP"; + internal string Client_uri = "winrm/config/client"; + internal string urlprefix_node = "/cfg:Client/cfg:URLPrefix"; + internal string Client_XMLNmsp = "http://schemas.microsoft.com/wbem/wsman/1/config/client"; + + internal string Service_Uri = "winrm/config/service"; + internal string Service_UrlPrefix_Node = "/cfg:Service/cfg:URLPrefix"; + internal string Service_XMLNmsp = "http://schemas.microsoft.com/wbem/wsman/1/config/service"; + internal string Service_CredSSP_Uri = "winrm/config/service/auth"; + internal string Service_CredSSP_XMLNmsp = "http://schemas.microsoft.com/wbem/wsman/1/config/service/auth"; + + // gpo registry path and keys + internal string Registry_Path_Credentials_Delegation = @"SOFTWARE\Policies\Microsoft\Windows"; + internal string Key_Allow_Fresh_Credentials = "AllowFreshCredentials"; + internal string Key_Concatenate_Defaults_AllowFresh = "ConcatenateDefaults_AllowFresh"; + internal string Delegate = "delegate"; + internal string keyAllowcredssp = "AllowCredSSP"; + + // 'Constants for MS-XML + private const string NODE_ATTRIBUTE = "2"; + private const int NODE_TEXT = 3; + + // strings for dialects + internal string ALIAS_WQL = @"wql"; + internal string ALIAS_ASSOCIATION = @"association"; + internal string ALIAS_SELECTOR = @"selector"; + internal string URI_WQL_DIALECT = @"http://schemas.microsoft.com/wbem/wsman/1/WQL"; + internal string URI_SELECTOR_DIALECT = @"http://schemas.dmtf.org/wbem/wsman/1/wsman/SelectorFilter"; + internal string URI_ASSOCIATION_DIALECT = @" http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associationFilter"; + + // string for operation + internal string WSManOp = null; + + private readonly PSCmdlet cmdletname; + private readonly NavigationCmdletProvider _provider; + + private FileStream _fs; + private StreamReader _sr; + + private static readonly ResourceManager _resourceMgr = new ResourceManager("Microsoft.WSMan.Management.resources.WsManResources", typeof(WSManHelper).GetTypeInfo().Assembly); + + // + // + // Below class is just a static container which would release sessions in case this DLL is unloaded. + internal sealed class Sessions + { + /// + /// Dictionary object to store the connection. + /// + internal static readonly Dictionary SessionObjCache = new Dictionary(); + + ~Sessions() + { + ReleaseSessions(); + } + } + + internal static readonly Sessions AutoSession = new Sessions(); + // + // + // + + internal static void ReleaseSessions() + { + lock (Sessions.SessionObjCache) + { + object sessionobj; + foreach (string key in Sessions.SessionObjCache.Keys) + { + Sessions.SessionObjCache.TryGetValue(key, out sessionobj); + try + { + Marshal.ReleaseComObject(sessionobj); + } + catch (ArgumentException) + { + // Somehow the object was a null reference. Ignore the error + } + + sessionobj = null; + } + + Sessions.SessionObjCache.Clear(); + } + } + + internal WSManHelper() + { + } + + internal WSManHelper(PSCmdlet cmdlet) + { + cmdletname = cmdlet; + } + + internal WSManHelper(NavigationCmdletProvider provider) + { + _provider = provider; + } + + internal static void ThrowIfNotAdministrator() + { + System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); + System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(currentIdentity); + if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) + { + string message = _resourceMgr.GetString("ErrorElevationNeeded"); + throw new InvalidOperationException(message); + } + } + + internal string GetResourceMsgFromResourcetext(string rscname) + { + return _resourceMgr.GetString(rscname); + } + + internal static string FormatResourceMsgFromResourcetextS(string rscname, + params object[] args) + { + return FormatResourceMsgFromResourcetextS(_resourceMgr, rscname, args); + } + + internal string FormatResourceMsgFromResourcetext(string resourceName, + params object[] args) + { + return FormatResourceMsgFromResourcetextS(_resourceMgr, resourceName, args); + } + + private static string FormatResourceMsgFromResourcetextS( + ResourceManager resourceManager, + string resourceName, + object[] args) + { + ArgumentNullException.ThrowIfNull(resourceManager); + ArgumentException.ThrowIfNullOrEmpty(resourceName); + + string template = resourceManager.GetString(resourceName); + + string result = null; + if (template != null) + { + result = string.Format(CultureInfo.CurrentCulture, + template, args); + } + + return result; + } + + /// + /// Add a session to dictionary. + /// + /// Connection string. + /// Session object. + internal void AddtoDictionary(string key, object value) + { + key = key.ToLowerInvariant(); + lock (Sessions.SessionObjCache) + { + if (!Sessions.SessionObjCache.ContainsKey(key)) + { + Sessions.SessionObjCache.Add(key, value); + } + else + { + object objsession = null; + Sessions.SessionObjCache.TryGetValue(key, out objsession); + try + { + Marshal.ReleaseComObject(objsession); + } + catch (ArgumentException) + { + // Somehow the object was a null reference. Ignore the error + } + + Sessions.SessionObjCache.Remove(key); + Sessions.SessionObjCache.Add(key, value); + } + } + } + + internal object RemoveFromDictionary(string computer) + { + object objsession = null; + computer = computer.ToLowerInvariant(); + lock (Sessions.SessionObjCache) + { + if (Sessions.SessionObjCache.ContainsKey(computer)) + { + Sessions.SessionObjCache.TryGetValue(computer, out objsession); + try + { + Marshal.ReleaseComObject(objsession); + } + catch (ArgumentException) + { + // Somehow the object was a null reference. Ignore the error + } + + Sessions.SessionObjCache.Remove(computer); + } + } + + return objsession; + } + + internal static Dictionary GetSessionObjCache() + { + try + { + lock (Sessions.SessionObjCache) + { + if (!Sessions.SessionObjCache.ContainsKey("localhost")) + { + IWSManEx wsmanObject = (IWSManEx)new WSManClass(); + IWSManSession SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); + Sessions.SessionObjCache.Add("localhost", SessionObj); + } + } + } + catch (IOException) + { + } + catch (System.Security.SecurityException) + { + } + catch (System.UnauthorizedAccessException) + { + } + catch (COMException) + { + } + + return Sessions.SessionObjCache; + } + + internal string GetRootNodeName(string operation, string resourceUri, string actionStr) + { + string resultStr = null, sfx = null; + if (resourceUri != null) + { + resultStr = resourceUri; + resultStr = StripParams(resultStr); + + Regex regexpr = new Regex(PTRN_URI_LAST, RegexOptions.IgnoreCase); + MatchCollection matches = regexpr.Matches(resultStr); + if (matches.Count > 0) + { + if (operation.Equals("invoke", StringComparison.OrdinalIgnoreCase)) + { + sfx = "_INPUT"; + resultStr = string.Concat(actionStr, sfx); + } + else + { + resultStr = matches[0].ToString(); + } + } + else + { + // error + } + } + + return resultStr; + } + + internal string StripParams(string uri) + { + int pos = uri.IndexOf('?'); + if (pos > 0) + return uri.Substring(pos, uri.Length - pos); + else + return uri; + } + + internal string ReadFile(string path) + { + if (!File.Exists(path)) + { + throw new ArgumentException(GetResourceMsgFromResourcetext("InvalidFileName")); + } + + string strOut = null; + try + { + _fs = new FileStream(path, FileMode.Open, FileAccess.Read); + // create stream Reader + _sr = new StreamReader(_fs); + strOut = _sr.ReadToEnd(); + } + catch (ArgumentNullException e) + { + ErrorRecord er = new ErrorRecord(e, "ArgumentNullException", ErrorCategory.InvalidArgument, null); + cmdletname.ThrowTerminatingError(er); + } + catch (UnauthorizedAccessException e) + { + ErrorRecord er = new ErrorRecord(e, "UnauthorizedAccessException", ErrorCategory.PermissionDenied, null); + cmdletname.ThrowTerminatingError(er); + } + catch (FileNotFoundException e) + { + ErrorRecord er = new ErrorRecord(e, "FileNotFoundException", ErrorCategory.ObjectNotFound, null); + cmdletname.ThrowTerminatingError(er); + } + catch (DirectoryNotFoundException e) + { + ErrorRecord er = new ErrorRecord(e, "DirectoryNotFoundException", ErrorCategory.ObjectNotFound, null); + cmdletname.ThrowTerminatingError(er); + } + catch (System.Security.SecurityException e) + { + ErrorRecord er = new ErrorRecord(e, "SecurityException", ErrorCategory.SecurityError, null); + cmdletname.ThrowTerminatingError(er); + } + finally + { + _sr?.Dispose(); + _fs?.Dispose(); + } + + return strOut; + } + + internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) + { + string resultString = null; + + // if file path is given + if (!string.IsNullOrEmpty(filepath) && valueset == null) + { + if (!File.Exists(filepath)) + { + throw new FileNotFoundException(_resourceMgr.GetString("InvalidFileName")); + } + + resultString = ReadFile(filepath); + return resultString; + } + + switch (operation) + { + case "new": + case "invoke": + + string parameters = null, nilns = null; + string xmlns = GetXmlNs(resourceUri.ResourceUri); + + // if valueset is given, i.e hashtable + if (valueset != null) + { + foreach (DictionaryEntry entry in valueset) + { + parameters = parameters + "" + entry.Value.ToString() + ""; + } + } + + resultString = "" + parameters + ""; + + break; + case "set": + + string getResult = sessionObj.Get(resourceUri, 0); + XmlDocument xmlfile = new XmlDocument(); + xmlfile.LoadXml(getResult); + + string xpathString = null; + if (valueset != null) + { + foreach (DictionaryEntry entry in valueset) + { + xpathString = @"/*/*[local-name()=""" + entry.Key + @"""]"; + if (entry.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) + { + // 'Ignore cim:Location + xpathString = @"/*/*[local-name()=""" + entry.Key + @""" and namespace-uri() != """ + NS_CIMBASE + @"""]"; + } + + XmlNodeList nodes = xmlfile.SelectNodes(xpathString); + if (nodes.Count == 0) + { + throw new ArgumentException(_resourceMgr.GetString("NoResourceMatch")); + } + else if (nodes.Count > 1) + { + throw new ArgumentException(_resourceMgr.GetString("MultipleResourceMatch")); + } + else + { + XmlNode node = nodes[0]; + if (node.HasChildNodes) + { + if (node.ChildNodes.Count > 1) + { + throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); + } + else + { + XmlNode tmpNode = node.ChildNodes[0]; //.Item[0]; + if (!tmpNode.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); + } + } + } + + if (string.IsNullOrEmpty(entry.Key.ToString())) + { + // XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); + XmlAttribute newnode = xmlfile.CreateAttribute(nameof(XmlNodeType.Attribute), ATTR_NIL_NAME, NS_XSI_URI); + newnode.Value = "true"; + node.Attributes.Append(newnode); + // (newnode.Attributes.Item(0).FirstChild ); + node.Value = string.Empty; + } + else + { + node.Attributes.RemoveNamedItem(ATTR_NIL_NAME); + node.InnerText = entry.Value.ToString(); + } + } + } + } + + resultString = xmlfile.OuterXml; + break; + } + + return resultString; + } + + internal string GetXmlNs(string resUri) + { + return (@"xmlns:p=""" + StripParams(resUri) + @""""); + } + + internal XmlNode GetXmlNode(string xmlString, string xpathpattern, string xmlnamespace) + { + XmlNode node = null; + XmlDocument xDoc = new XmlDocument(); + xDoc.LoadXml(xmlString); + XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable); + if (!string.IsNullOrEmpty(xmlnamespace)) + { + nsmgr.AddNamespace("cfg", xmlnamespace); + } + + node = xDoc.SelectSingleNode(xpathpattern, nsmgr); + return node; + } + + internal string CreateConnectionString(Uri ConnUri, int port, string computername, string applicationname) + { + string ConnectionString = null; + if (ConnUri != null) + { + ConnectionString = ConnUri.OriginalString; + } + else + { + if (computername == null && (port != 0 || applicationname != null)) + { + // the user didn't give us a computer name but he gave a port and/or application name; + // in this case we need to have a computer name, to form the connection string; + // assume localhost + computername = "localhost"; + } + + ConnectionString = computername; + if (port != 0) + { + ConnectionString = ConnectionString + ":" + port; + } + + if (applicationname != null) + { + ConnectionString = ConnectionString + "/" + applicationname; + } + } + + return ConnectionString; + } + + internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) + { + string resource = null; + if (resourceuri != null) + { + resource = resourceuri.ToString(); + } + + if (selectorset != null) + { + resource += "?"; + int i = 0; + foreach (DictionaryEntry entry in selectorset) + { + i++; + resource = resource + entry.Key.ToString() + "=" + entry.Value.ToString(); + if (i < selectorset.Count) + resource += "+"; + } + } + + IWSManResourceLocator m_resource = null; + try + { + m_resource = (IWSManResourceLocator)wsmanObj.CreateResourceLocator(resource); + + if (optionset != null) + { + foreach (DictionaryEntry entry in optionset) + { + if (entry.Value.ToString() == null) + { + m_resource.AddOption(entry.Key.ToString(), null, 1); + } + else + { + m_resource.AddOption(entry.Key.ToString(), entry.Value, 1); + } + } + } + + if (!string.IsNullOrEmpty(fragment)) + { + m_resource.FragmentPath = fragment; + } + + if (dialect != null) + { + m_resource.FragmentDialect = dialect.ToString(); + } + } + catch (COMException ex) + { + AssertError(ex.Message, false, null); + } + + return m_resource; + } + + /// + /// Used to resolve authentication from the parameters chosen by the user. + /// User has the following options: + /// 1. AuthMechanism + Credential + /// 2. CertificateThumbPrint + /// + /// All the above are mutually exclusive. + /// + /// + /// If there is ambiguity as specified above. + /// + internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism authentication, PSCredential credential, string certificateThumbprint) + { + if ((credential != null) && (certificateThumbprint != null)) + { + string message = FormatResourceMsgFromResourcetextS( + "AmbiguousAuthentication", + "CertificateThumbPrint", "credential"); + + throw new InvalidOperationException(message); + } + + if ((authentication != AuthenticationMechanism.Default) && + (authentication != AuthenticationMechanism.ClientCertificate) && + (certificateThumbprint != null)) + { + string message = FormatResourceMsgFromResourcetextS( + "AmbiguousAuthentication", + "CertificateThumbPrint", authentication.ToString()); + + throw new InvalidOperationException(message); + } + } + + internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl) + { + ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint); + + ////if authentication is given + int sessionFlags = 0; + + if (authentication.ToString() != null) + { + if (authentication.Equals(AuthenticationMechanism.None)) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagUseNoAuthentication; + } + + if (authentication.Equals(AuthenticationMechanism.Basic)) + { + sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseBasic | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; + } + + if (authentication.Equals(AuthenticationMechanism.Negotiate)) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagUseNegotiate; + } + + if (authentication.Equals(AuthenticationMechanism.Kerberos)) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagUseKerberos; + } + + if (authentication.Equals(AuthenticationMechanism.Digest)) + { + sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseDigest | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; + } + + if (authentication.Equals(AuthenticationMechanism.Credssp)) + { + sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseCredSsp | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; + } + + if (authentication.Equals(AuthenticationMechanism.ClientCertificate)) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagUseClientCertificate; + } + } + + IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); + if (credential != null) + { + // connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); + System.Net.NetworkCredential nwCredential = new System.Net.NetworkCredential(); + if (credential.UserName != null) + { + nwCredential = credential.GetNetworkCredential(); + if (string.IsNullOrEmpty(nwCredential.Domain)) + { + if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) + { + connObject.UserName = nwCredential.UserName; + } + else + { + // just wanted to not use null domain, empty is actually fine + connObject.UserName = "\\" + nwCredential.UserName; + } + } + else + { + connObject.UserName = nwCredential.Domain + "\\" + nwCredential.UserName; + } + + connObject.Password = nwCredential.Password; + if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagCredUserNamePassword; + } + } + } + + if (certificateThumbprint != null) + { + connObject.CertificateThumbprint = certificateThumbprint; + sessionFlags |= (int)WSManSessionFlags.WSManFlagUseClientCertificate; + } + + if (sessionoption != null) + { + if (sessionoption.ProxyAuthentication != 0) + { + int ProxyAccessflags = 0; + int ProxyAuthenticationFlags = 0; + if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig)) + { + ProxyAccessflags = connObject.ProxyIEConfig(); + } + else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect)) + { + ProxyAccessflags = connObject.ProxyAutoDetect(); + } + else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer)) + { + ProxyAccessflags = connObject.ProxyNoProxyServer(); + } + else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig)) + { + ProxyAccessflags = connObject.ProxyWinHttpConfig(); + } + + if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Basic)) + { + ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseBasic(); + } + else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Negotiate)) + { + ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseNegotiate(); + } + else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Digest)) + { + ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseDigest(); + } + + if (sessionoption.ProxyCredential != null) + { + try + { + connObject.SetProxy(ProxyAccessflags, ProxyAuthenticationFlags, sessionoption.ProxyCredential.UserName, sessionoption.ProxyCredential.Password); + } + catch (Exception ex) + { + AssertError(ex.Message, false, null); + } + } + else + { + connObject.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null); + } + } + + if (sessionoption.SkipCACheck) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagSkipCACheck; + } + + if (sessionoption.SkipCNCheck) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagSkipCNCheck; + } + + if (sessionoption.SPNPort > 0) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagEnableSpnServerPort; + } + + if (sessionoption.UseUtf16) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagUtf16; + } + else + { + // If UseUtf16 is false, then default Encoding is Utf8 + sessionFlags |= (int)WSManSessionFlags.WSManFlagUtf8; + } + + if (!sessionoption.UseEncryption) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagNoEncryption; + } + + if (sessionoption.SkipRevocationCheck) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagSkipRevocationCheck; + } + } + else + { + // If SessionOption is null then, default Encoding is Utf8 + sessionFlags |= (int)WSManSessionFlags.WSManFlagUtf8; + } + + if (usessl) + { + sessionFlags |= (int)WSManSessionFlags.WSManFlagUseSsl; + } + + IWSManSession m_SessionObj = null; + try + { + m_SessionObj = (IWSManSession)wsmanObject.CreateSession(connectionString, sessionFlags, connObject); + if (sessionoption != null) + { + if (sessionoption.OperationTimeout > 0) + { + m_SessionObj.Timeout = sessionoption.OperationTimeout; + } + } + } + catch (COMException ex) + { + AssertError(ex.Message, false, null); + } + + return m_SessionObj; + } + + internal void CleanUp() + { + if (_sr != null) + { + _sr.Dispose(); + _sr = null; + } + + if (_fs != null) + { + _fs.Dispose(); + _fs = null; + } + } + + internal string GetFilterString(Hashtable seletorset) + { + StringBuilder filter = new StringBuilder(); + foreach (DictionaryEntry entry in seletorset) + { + if (entry.Key != null && entry.Value != null) + { + filter.Append(entry.Key.ToString()); + filter.Append('='); + filter.Append(entry.Value.ToString()); + filter.Append('+'); + } + } + + filter.Remove(filter.ToString().Length - 1, 1); + return filter.ToString(); + } + + internal void AssertError(string ErrorMessage, bool IsWSManError, object targetobject) + { + if (IsWSManError) + { + XmlDocument ErrorDoc = new XmlDocument(); + ErrorDoc.LoadXml(ErrorMessage); + InvalidOperationException ex = new InvalidOperationException(ErrorDoc.OuterXml); + ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, targetobject); + if (cmdletname != null) + { + cmdletname.ThrowTerminatingError(er); + } + else + { + _provider.ThrowTerminatingError(er); + } + } + else + { + InvalidOperationException ex = new InvalidOperationException(ErrorMessage); + ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, targetobject); + if (cmdletname != null) + { + cmdletname.ThrowTerminatingError(er); + } + else + { + _provider.ThrowTerminatingError(er); + } + } + } + + internal string GetURIWithFilter(string uri, string filter, Hashtable selectorset, string operation) + { + StringBuilder sburi = new StringBuilder(); + sburi.Append(uri); + sburi.Append('?'); + + if (operation.Equals("remove", StringComparison.OrdinalIgnoreCase)) + { + sburi.Append(GetFilterString(selectorset)); + if (sburi.ToString().EndsWith('?')) + { + sburi.Remove(sburi.Length - 1, 1); + } + } + + return sburi.ToString(); + } + + /// + /// This method is used by Connect-WsMan Cmdlet and New-Item of WsMan Provider to create connection to WsMan. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, int port, string computername, string applicationname, bool usessl, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string certificateThumbprint) + { + IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + try + { + string connectionStr = CreateConnectionString(connectionuri, port, computername, applicationname); + if (connectionuri != null) + { + // in the format http(s)://server[:port/applicationname] + string[] constrsplit = connectionStr.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); + computername = constrsplit1[1].Trim(); + } + + IWSManSession m_session = CreateSessionObject(m_wsmanObject, authentication, sessionoption, credential, connectionStr, certificateThumbprint, usessl); + m_session.Identify(0); + string key = computername ?? "localhost"; + + AddtoDictionary(key, m_session); + } + catch (IndexOutOfRangeException) + { + AssertError(_resourceMgr.GetString("NotProperURI"), false, connectionuri); + } + catch (Exception ex) + { + AssertError(ex.Message, false, computername); + } + finally + { + if (!string.IsNullOrEmpty(m_wsmanObject.Error)) + { + AssertError(m_wsmanObject.Error, true, computername); + } + } + } + + /// + /// Verifies all the registry keys are set as expected. In case of failure .. try ecery second for 60 seconds before returning false. + /// + /// True if trying to Enable CredSSP. + /// Names of the delegate computer. + /// Name of the application. + /// True if valid. + internal bool ValidateCreadSSPRegistryRetry(bool AllowFreshCredentialsValueShouldBePresent, string[] DelegateComputer, string applicationname) + { + for (int i = 0; i < 60; i++) + { + if (!ValidateCredSSPRegistry(AllowFreshCredentialsValueShouldBePresent, DelegateComputer, applicationname)) + { + Thread.Sleep(1000); + } + else + { + return true; + } + } + + return false; + } + + internal bool ValidateCredSSPRegistry(bool AllowFreshCredentialsValueShouldBePresent, string[] DelegateComputer, string applicationname) + { + System.IntPtr NakedGPOCriticalSection = GpoNativeApi.EnterCriticalPolicySection(true); + + try + { + RegistryKey rGPOLocalMachineKey = Registry.LocalMachine.OpenSubKey( + Registry_Path_Credentials_Delegation + @"\CredentialsDelegation", + RegistryKeyPermissionCheck.ReadWriteSubTree, + System.Security.AccessControl.RegistryRights.FullControl); + + if (rGPOLocalMachineKey != null) + { + rGPOLocalMachineKey = rGPOLocalMachineKey.OpenSubKey( + Key_Allow_Fresh_Credentials, + RegistryKeyPermissionCheck.ReadWriteSubTree, + System.Security.AccessControl.RegistryRights.FullControl); + if (rGPOLocalMachineKey == null) + { + return !AllowFreshCredentialsValueShouldBePresent; + } + + string[] valuenames = rGPOLocalMachineKey.GetValueNames(); + if (valuenames.Length == 0) + { + return !AllowFreshCredentialsValueShouldBePresent; + } + + List RegValues = new List(); + foreach (string value in valuenames) + { + object keyvalue = rGPOLocalMachineKey.GetValue(value); + + if (keyvalue != null && keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) + { + if (!AllowFreshCredentialsValueShouldBePresent) + { + // If calling Disable-CredSSP .. no value should start with "applicationName" regardless of the computer. + return false; + } + + RegValues.Add(keyvalue.ToString()); + } + } + + if (AllowFreshCredentialsValueShouldBePresent) + { + // For all the keys that starts with "applicationName" make sure the delegated computer is listed. + foreach (string comp in DelegateComputer) + { + if (!RegValues.Contains(applicationname + "/" + comp)) + { + return false; + } + } + } + } + } + finally + { + bool GPOReleaseCriticalSection = GpoNativeApi.LeaveCriticalPolicySection(NakedGPOCriticalSection); + } + + return true; + } + } + + internal static class WSManResourceLoader + { + internal static void LoadResourceData() + { + try + { + string winDir = System.Environment.ExpandEnvironmentVariables("%Windir%"); + uint lcid = checked((uint)CultureInfo.CurrentUICulture.LCID); + string filepath = string.Create(CultureInfo.CurrentCulture, $@"{winDir}\System32\Winrm\0{lcid:x2}\winrm.ini"); + + if (File.Exists(filepath)) + { + FileStream _fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); + StreamReader _sr = new StreamReader(_fs); + while (!_sr.EndOfStream) + { + string Line = _sr.ReadLine(); + if (Line.Contains('=')) + { + string[] arr = Line.Split('=', count: 2); + if (!ResourceValueCache.ContainsKey(arr[0].Trim())) + { + string value = arr[1].Trim('"'); + ResourceValueCache.Add(arr[0].Trim(), value.Trim()); + } + } + } + } + } + catch (IOException) + { + throw; + } + } + + /// + /// Get the resource value from WinRm.ini + /// from %windir%\system32\winrm\[Hexadecimal Language Folder]\winrm.ini. + /// + /// + /// + internal static string GetResourceString(string Key) + { + // Checks whether resource values already loaded and loads. + if (ResourceValueCache.Count == 0) + { + LoadResourceData(); + } + + string value = string.Empty; + if (ResourceValueCache.ContainsKey(Key.Trim())) + { + ResourceValueCache.TryGetValue(Key.Trim(), out value); + } + + return value.Trim(); + } + + /// + /// + private static readonly Dictionary ResourceValueCache = new Dictionary(); + } +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/WsManSnapin.cs b/PowerShell-master/src/Microsoft.WSMan.Management/WsManSnapin.cs new file mode 100644 index 0000000000000000000000000000000000000000..4093caf12db0ec790d166ae59e1059b4c6d293bf --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/WsManSnapin.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Management; +using System.Management.Automation; +using System.Runtime.InteropServices; +using System.Text; + +namespace Microsoft.WSMan.Management +{ + #region SnapIn + + /// + /// Create the PowerShell snap-in used to register the + /// WsManPSSnapIn cmdlets. Declaring the PSSnapIn class identifies + /// this .cs file as a PowerShell snap-in. + /// + [RunInstaller(true)] + public class WSManPSSnapIn : PSSnapIn + { + /// + /// Create an instance of the WsManSnapin class. + /// + public WSManPSSnapIn() + : base() + { + } + + /// + /// Specify the name of the PowerShell snap-in. + /// + public override string Name + { + get + { + return "WsManPSSnapIn"; + } + } + + /// + /// Specify the vendor for the PowerShell snap-in. + /// + public override string Vendor + { + get + { + return "Microsoft"; + } + } + + /// + /// Specify the localization resource information for the vendor. + /// Use the format: resourceBaseName,VendorName. + /// + public override string VendorResource + { + get + { + return "WsManPSSnapIn,Microsoft"; + } + } + + /// + /// Specify a description of the PowerShell snap-in. + /// + public override string Description + { + get + { + return "This is a PowerShell snap-in that includes the WsMan cmdlets."; + } + } + + /// + /// Specify the localization resource information for the description. + /// Use the format: resourceBaseName,Description. + /// + public override string DescriptionResource + { + get + { + return "WsManPSSnapIn,This is a PowerShell snap-in that includes the WsMan cmdlets."; + } + } + } + + #endregion SnapIn +} diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/resources/WsManResources.resx b/PowerShell-master/src/Microsoft.WSMan.Management/resources/WsManResources.resx new file mode 100644 index 0000000000000000000000000000000000000000..a25f6c4801fc772e4d9f6c69c7749aec40e323a4 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/resources/WsManResources.resx @@ -0,0 +1,331 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This command cannot be used because file does not exist.Check the file existence and run your command. + + + Creates a new ClientCertificate item. + + + This command cannot be executed because the Connection URI is not in correct format. Please check the connection uri and Run your command again. + + + CredSSP authentication allows the user credentials on this computer to be sent to a remote computer. If you use CredSSP authentication for a connection to a malicious or compromised computer, that computer will have access to your user name and password. For more information, see the Enable-WSManCredSSP Help topic. +Do you want to enable CredSSP authentication? + + + Creates a new Listener item. + + + This command modifies the security settings on a resource in the following WinRM plug-in: {0}. +Do you want to continue? + + + "Set-Item" on the WinRM configuration setting "{0}" to update the value to "{1}" + + + This command cannot be executed because the setting cannot be enabled. + + + This command creates a new Listener item. + +Do you want to continue? + + + Access is denied. You need to run this cmdlet from an elevated process. + + + This command cannot be used because WsMan drive root is not supported on this version of Windows OS. + + + Start WinRM Service + + + CredSSP authentication allows the server to accept user credentials from a remote computer. If you enable CredSSP authentication on the server, the server will have access to the user name and password of the client computer if the client computer sends them. For more information, see the Enable-WSManCredSSP Help topic. +Do you want to enable CredSSP authentication? + + + WinRM Quick Configuration + + + Microsoft + + + This command cannot set the input value because these values are Primary keys or Container items of the resource object. Change the input value and Run your command. + + + CredSSP Authentication Configuration for WS-Management + + + Set the value of the item + + + Cannot convert 'System.Object[]' to the type 'System.String' required by the parameter. Specified method is not supported. + + + This computer is not configured to receive credentials from a remote client computer. + + + This command cannot be used from the current path. Move to root path of the provider using cd\ and run your command again. + + + This PowerShell cmdlet is not available on for Windows XP and Windows Server 2003. + + + This command cannot be used because the parameter matches a non-text property on the ResourceURI.Check the input parameters and run your command. + + + A {0} cannot be specified when {1} is specified. + + + The WinRM client cannot complete the operation.Check if the computer name is valid. + + + The {0} parameter is mandatory when the {1} parameter value is {2}. + + + This command cannot be used because Parameter Value is not supplied. Check the value again and run your command. + + + This command cannot be used because path does not exist.Check the path existence and run your command. + + + Security Configuration for WinRM Plug-in. + + + This command cannot be used in the current path because this cmdlet is not supported at this level of Provider path. + + + The machine is not configured to allow delegating fresh credentials. + + + The configuration changes you made will only be effective after the WinRM service is restarted. To restart the WinRM service, run the following command: 'Restart-Service winrm' + + + Running the Set-WSManQuickConfig command has significant security implications, as it enables remote management through the WinRM service on this computer. +This command: + 1. Checks whether the WinRM service is running. If the WinRM service is not running, the service is started. + 2. Sets the WinRM service startup type to automatic. + 3. Creates a listener to accept requests on any IP address. By default, the transport is HTTP. + 4. Enables a firewall exception for WS-Management traffic. + 5. Enables Kerberos and Negotiate service authentication. +Do you want to enable remote management through the WinRM service on this computer? + + + The value for RunAsPassword cannot be set without a value set for RunAsUser. Set the value for both RunAsUser and RunAsPassword in Powershell by calling the Set-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser. + + + The updated configuration might affect the operation of the plugins having a per plugin quota value greater than {0}. Verify the configuration of all the registered plugins and change the per plugin quota values for the affected plugins. + + + This command set the value of the Item. + +Do you want to continue? + + + The machine is configured to allow delegating fresh credentials to the following target(s): + + + Root of WsMan Config Storage. + + + This command cannot be executed because the WinRM Service is not started. + + + This command cannot be used because root path does not exist.Check the root path and run your command. + + + This command cannot be used in the current path because Remove-Item is not supported at this level of Provider path. + + + This command modifies the TrustedHosts list for the WinRM client. The computers in the TrustedHosts list might not be authenticated. The client might send credential information to these computers. Are you sure that you want to modify this list? + + + This command modifies the RootSDDL setting for the WinRM service. The RootSDDL stores the default security settings for any WinRM securable resource that does not specify its own SDDL. Changing the SDDL might affect security for many WinRM resources. Are you sure that you want to modify these default settings? + + + This command cannot be used without credential because the authentication algorithm is Basic or Digest. Use Credentials parameter to specify value and run your command. + + + The updated configuration is effective only if it is less than or equal to the value of global quota {0}. Verify the value for the global quota using the PowerShell cmdlet "Get-Item {0}". + + + This command cannot be executed because the setting cannot be disabled. + + + Unable to find value for "{0}" element in the path {1}. + + + This command cannot be used without Basic or Digest authentication algorithm because credentials are specified.Use Basic or Digest authentication algorithm and run your command. + + + WinRM Security Configuration. + + + This command cannot be used in the current path because New-Item is not supported at this level of Provider path. + + + This command cannot be used because the configuration is corrupted. Run WinRM invoke Restore WinRM/config to restore the default configuration + + + This command cannot be used because the parameter value type is invalid. {0} configuration expects a value of Type {1}. Verify that the value is correct and try again. + + + WinRM service is not started currently. Running this command will start the WinRM service. + +Do you want to continue? + + + This command cannot be used because the parameter does not match any properties on the ResourceURI.Check the input parameters and run your command. + + + This computer is configured to receive credentials from a remote client computer. + + + The {0} parameter cannot be used when the {1} parameter value is {2}. The {0} parameter can be used only when the {1} parameter value is {3}. + + + The configuration changes you made will only be effective after the WinRM service is restarted on {0}. + + + This command cannot be used from the current path. Move to root path of the provider using cd\ and run your command again. + + + This PowerShell snap-in contains cmdlets (such as Get-WSManInstance and Set-WSManInstance) that are used by the PowerShell host to manage WSMan operations. + + + This command cannot be used to remove the computer 'localhost' because it will always be connected. Give some other connected computer and run your command. + + + This command creates a new ClientCertificate item. + +Do you want to continue? + + + The RunAsPassword value cannot be removed. Remove the values for RunAsUser and RunAsPassword in PowerShell by calling the Clear-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser. + + + Unable to create a drive with the specified root. The root path does not exist. + + + This command cannot be used because the parameter matches multiple properties on the ResourceURI.Check the input parameters and run your command. + + + diff --git a/PowerShell-master/src/Microsoft.WSMan.Management/resources/WsManResources.txt b/PowerShell-master/src/Microsoft.WSMan.Management/resources/WsManResources.txt new file mode 100644 index 0000000000000000000000000000000000000000..10702e5ccea9fcf6d1bc1904d8f46fd0c1b59b47 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Management/resources/WsManResources.txt @@ -0,0 +1,68 @@ +# Copyright (c) Microsoft Corporation. + +# {0} = Delegate + +Vendor=Microsoft +Description=This PowerShell snap-in contains cmdlets (such as Get-WSManInstance and Set-WSManInstance) that are used by the PowerShell host to manage WSMan operations. +InvalidComputerName=The WinRM client cannot complete the operation.Check if the computer name is valid. +InvalidFileName=This command cannot be used because file does not exist.Check the file existence and run your command. +InvalidPath=This command cannot be used because root path does not exist.Check the root path and run your command. +NoResourceMatch=This command cannot be used because the parameter does not match any properties on the ResourceURI.Check the input parameters and run your command. +MultipleResourceMatch=This command cannot be used because the parameter matches multiple properties on the ResourceURI.Check the input parameters and run your command. +NoAttributeMatch=This command cannot be used because the parameter matches a non-text property on the ResourceURI.Check the input parameters and run your command. +WinrmNotConfigured=This command cannot be used because the configuration is corrupted. Run WinRM invoke Restore WinRM/config to restore the default configuration +DelegateFreshCred=The machine is configured to allow delegating fresh credentials to the following target(s): +NoDelegateFreshCred=The machine is not configured to allow delegating fresh credentials. +LocalHost=This command cannot be used to remove the computer 'localhost' because it will always be connected. Give some other connected computer and run your command. +ConnectFailure=This command cannot be used from the current path. Move to root path of the provider using cd\\ and run your command again. +DisconnectFailure=This command cannot be used from the current path. Move to root path of the provider using cd\\ and run your command again. +value=This command cannot be used because Parameter Value is not supplied. Check the value again and run your command. +SetItemNotSupported=This command cannot be used in the current path because this cmdlet is not supported at this level of Provider path. +RemoveItemNotSupported=This command cannot be used in the current path because Remove-Item is not supported at this level of Provider path. +NewItemNotSupported=This command cannot be used in the current path because New-Item is not supported at this level of Provider path. +NoChangeValue=This command cannot set the input value because these values are Primary keys or Container items of the resource object. Change the input value and Run your command. +ConfigStorage=Root of WsMan Config Storage. +NewWSManSessionOptionCred=This command cannot be used without credential because the authentication algorithm is Basic or Digest. Use Credentials parameter to specify value and run your command. +NewWSManSessionOptionAuth=This command cannot be used without Basic or Digest authentication algorithm because credentials are specified.Use Basic or Digest authentication algorithm and run your command. +DriveRootError=This command cannot be used because WsMan drive root is not supported on this version of Windows OS. +ItemDoesNotExist=This command cannot be used because path does not exist.Check the path existence and run your command. +ErrorElevationNeeded=Access is denied. You need to run this cmdlet from an elevated process. +NewDriveRootDoesNotExist=Unable to create a drive with the specified root. The root path does not exist. +NotProperURI=This command cannot be executed because the Connection URI is not in correct format. Please check the connection uri and Run your command again. +WSManServiceStartCaption=Start WinRM Service +WSManServiceStartQuery=WinRM service is not started currently. Running this command will start the WinRM service.\n\nDo you want to continue? +WinRMServiceError=This command cannot be executed because the WinRM Service is not started. +SetItemShouldContinueCaption=Set the value of the item +SetItemShouldContinueQuery=This command set the value of the Item.\n\nDo you want to continue? +EnableCredSSPPolicyValidateError=This command cannot be executed because the setting cannot be enabled. +DisableCredSSPPolicyValidateError=This command cannot be executed because the setting cannot be disabled. +TrustedHostValueTypeError=Cannot convert 'System.Object[]' to the type 'System.String' required by the parameter. Specified method is not supported. +ShouldContinueSecurityCaption=Security Configuration for WinRM Plug-in. +ShouldContinueSecurityQuery=This command modifies the security settings on a resource in the following WinRM plug-in: {0}.\nDo you want to continue? +NewItemShouldContinueListenerCaption=Creates a new Listener item. +NewItemShouldContinueListenerQuery=This command creates a new Listener item.\n\nDo you want to continue? +NewItemShouldContinueClientCertCaption=Creates a new ClientCertificate item. +NewItemShouldContinueClientCertQuery=This command creates a new ClientCertificate item.\n\nDo you want to continue? +SetItemTrustedHostsWarningQuery=This command modifies the TrustedHosts list for the WinRM client. The computers in the TrustedHosts list might not be authenticated. The client might send credential information to these computers. Are you sure that you want to modify this list? +SetItemRootSDDLWarningQuery=This command modifies the RootSDDL setting for the WinRM service. The RootSDDL stores the default security settings for any WinRM securable resource that does not specify its own SDDL. Changing the SDDL might affect security for many WinRM resources. Are you sure that you want to modify these default settings? +SetItemGeneralSecurityCaption=WinRM Security Configuration. +ResourceURIMissingInResourceDir=Unable to find value for "{0}" element in the path {1}. +CredSSPContinueCaption=CredSSP Authentication Configuration for WS-Management +CredSSPContinueQuery=CredSSP authentication allows the user credentials on this computer to be sent to a remote computer. If you use CredSSP authentication for a connection to a malicious or compromised computer, that computer will have access to your user name and password. For more information, see the Enable-WSManCredSSP Help topic.\nDo you want to enable CredSSP authentication? +CredSSPServerContinueQuery=CredSSP authentication allows the server to accept user credentials from a remote computer. If you enable CredSSP authentication on the server, the server will have access to the user name and password of the client computer if the client computer sends them. For more information, see the Enable-WSManCredSSP Help topic. \nDo you want to enable CredSSP authentication? +CredSSPRoleAndDelegateCannotBeSpecified=The {0} parameter cannot be used when the {1} parameter value is {2}. The {0} parameter can be used only when the {1} parameter value is {3}. +CredSSPClientAndDelegateMustBeSpecified=The {0} parameter is mandatory when the {1} parameter value is {2}. +CredSSPServiceConfigured=This computer is configured to receive credentials from a remote client computer. +CredSSPServiceNotConfigured=This computer is not configured to receive credentials from a remote client computer. +QuickConfigContinueCaption=WinRM Quick Configuration +QuickConfigContinueQuery=Running the Set-WSManQuickConfig command has significant security implications, as it enables remote management through the WinRM service on this computer.\nThis command:\n 1. Checks whether the WinRM service is running. If the WinRM service is not running, the service is started.\n 2. Sets the WinRM service startup type to automatic.\n 3. Creates a listener to accept requests on any IP address. By default, the transport is HTTP.\n 4. Enables a firewall exception for WS-Management traffic.\n 5. Enables Kerberos and Negotiate service authentication.\nDo you want to enable remote management through the WinRM service on this computer? +AmbiguousAuthentication=A {0} cannot be specified when {1} is specified. +CmdletNotAvailable=This PowerShell cmdlet is not available on for Windows XP and Windows Server 2003. +InvalidValueType=This command cannot be used because the parameter value type is invalid. {0} configuration expects a value of Type {1}. Verify that the value is correct and try again. +ClearItemOnRunAsPassword=The RunAsPassword value cannot be removed. Remove the values for RunAsUser and RunAsPassword in PowerShell by calling the Clear-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser. +SetItemOnRunAsPasswordNoRunAsUser=The value for RunAsPassword cannot be set without a value set for RunAsUser. Set the value for both RunAsUser and RunAsPassword in Powershell by calling the Set-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser. +SetItemWhatIfAndConfirmText= "Set-Item" on the WinRM configuration setting "{0}" to update the value to "{1}" +SetItemWarnigForPPQ=The updated configuration is effective only if it is less than or equal to the value of global quota {0}. Verify the value for the global quota using the PowerShell cmdlet "Get-Item {0}". +SetItemWarningForGlobalQuota=The updated configuration might affect the operation of the plugins having a per plugin quota value greater than {0}. Verify the configuration of all the registered plugins and change the per plugin quota values for the affected plugins. +SetItemServiceRestartWarning= The configuration changes you made will only be effective after the WinRM service is restarted. To restart the WinRM service, run the following command: 'Restart-Service winrm' +SetItemServiceRestartWarningRemote= The configuration changes you made will only be effective after the WinRM service is restarted on {0}. diff --git a/PowerShell-master/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj b/PowerShell-master/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj new file mode 100644 index 0000000000000000000000000000000000000000..2a9439c02749e3f71ebc73a6ea9ff84b9db649d2 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj @@ -0,0 +1,8 @@ + + + + PowerShell's Microsoft.WSMan.Runtime project + Microsoft.WSMan.Runtime + + + diff --git a/PowerShell-master/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/PowerShell-master/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs new file mode 100644 index 0000000000000000000000000000000000000000..13dc8bbea2c39a4af6b538bea0a3845a04119871 --- /dev/null +++ b/PowerShell-master/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; + +[assembly: CLSCompliant(true)] + +namespace Microsoft.WSMan.Management +{ + /// + /// Session option class. + /// + public sealed class SessionOption + { + /// + /// Property. + /// + public bool SkipCACheck { get; set; } + + /// + /// Property. + /// + public bool SkipCNCheck { get; set; } + + /// + /// Property. + /// + public bool SkipRevocationCheck { get; set; } + + /// + /// Property. + /// + public bool UseEncryption { get; set; } = true; + + /// + /// Property. + /// + public bool UseUtf16 { get; set; } + + /// + /// Property. + /// + public ProxyAuthentication ProxyAuthentication { get; set; } + + /// + /// Property. + /// + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] + public int SPNPort { get; set; } + + /// + /// Property. + /// + public int OperationTimeout { get; set; } + + /// + /// Property. + /// + public NetworkCredential ProxyCredential { get; set; } + + /// + /// Property. + /// + public ProxyAccessType ProxyAccessType { get; set; } + } + + /// + /// Property. + /// + public enum ProxyAccessType + { + /// + /// Property. + /// + ProxyIEConfig = 0, + /// + /// Property. + /// + ProxyWinHttpConfig = 1, + /// + /// Property. + /// + ProxyAutoDetect = 2, + /// + /// Property. + /// + ProxyNoProxyServer = 3 + } + + /// + /// Property. + /// + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] + public enum ProxyAuthentication + { + /// + /// Property. + /// + Negotiate = 1, + /// + /// Property. + /// + Basic = 2, + /// + /// Property. + /// + Digest = 4 + } +} diff --git a/PowerShell-master/src/Modules/PSGalleryModules.csproj b/PowerShell-master/src/Modules/PSGalleryModules.csproj new file mode 100644 index 0000000000000000000000000000000000000000..3903b164b09071fdb6ddf27f4996e82f67a18e2c --- /dev/null +++ b/PowerShell-master/src/Modules/PSGalleryModules.csproj @@ -0,0 +1,22 @@ + + + + PowerShell + Microsoft Corporation + (c) Microsoft Corporation. + + net11.0 + + true + + + + + + + + + + + + diff --git a/PowerShell-master/src/Modules/README.md b/PowerShell-master/src/Modules/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5911951a5ad23f03a2a5b9a5b4c74e13f0015886 --- /dev/null +++ b/PowerShell-master/src/Modules/README.md @@ -0,0 +1,24 @@ +Modules +========== + +There are 3 directories with **content** files. +Content files includes: + +- ps1xml +- psm1 +- psd1 +- ps1 + +These files are copied as-is by `dotnet` + +- Shared (shared between Windows and Unix) +- Windows +- Unix + +Notes +----------- + +We have files with the same names in different folders. +That means that the contents of these two files are different. +I.e. if it's .psd1 file, it could be because `CmdletsToExport` +are different for different runtimes (platforms) or frameworks. diff --git a/PowerShell-master/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 b/PowerShell-master/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..3c2581795f7b36695ddf1ac9be284cdee7350aaa --- /dev/null +++ b/PowerShell-master/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 @@ -0,0 +1,14 @@ +@{ +GUID="56D66100-99A0-4FFC-A12D-EEE9A6718AEF" +Author="PowerShell" +CompanyName="Microsoft Corporation" +Copyright="Copyright (c) Microsoft Corporation." +ModuleVersion="7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion="3.0" +FunctionsToExport = @() +CmdletsToExport="Start-Transcript", "Stop-Transcript" +AliasesToExport = @() +NestedModules="Microsoft.PowerShell.ConsoleHost.dll" +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..21563c1da7c766a0e33f8884d5507b6b9010e608 --- /dev/null +++ b/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -0,0 +1,60 @@ +@{ +GUID="EEFCB906-B326-4E99-9F54-8B4BB6EF3C6D" +Author="PowerShell" +CompanyName="Microsoft Corporation" +Copyright="Copyright (c) Microsoft Corporation." +ModuleVersion="7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion="3.0" +NestedModules="Microsoft.PowerShell.Commands.Management.dll" +HelpInfoURI = 'https://aka.ms/powershell75-help' +FunctionsToExport = @() +AliasesToExport = @("gcb", "gtz", "scb") +CmdletsToExport=@("Add-Content", + "Clear-Content", + "Clear-ItemProperty", + "Join-Path", + "Convert-Path", + "Copy-ItemProperty", + "Get-ChildItem", + "Get-Clipboard", + "Set-Clipboard", + "Get-Content", + "Get-ItemProperty", + "Get-ItemPropertyValue", + "Move-ItemProperty", + "Get-Location", + "Set-Location", + "Push-Location", + "Pop-Location", + "New-PSDrive", + "Remove-PSDrive", + "Get-PSDrive", + "Get-Item", + "New-Item", + "Set-Item", + "Remove-Item", + "Move-Item", + "Rename-Item", + "Copy-Item", + "Clear-Item", + "Invoke-Item", + "Get-PSProvider", + "New-ItemProperty", + "Split-Path", + "Test-Path", + "Get-Process", + "Stop-Process", + "Wait-Process", + "Debug-Process", + "Start-Process", + "Test-Connection", + "Remove-ItemProperty", + "Rename-ItemProperty", + "Resolve-Path", + "Set-Content", + "Set-ItemProperty", + "Get-TimeZone", + "Stop-Computer", + "Restart-Computer") +} diff --git a/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 b/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..adab0df2849628675705099fea6f6c0bf174c556 --- /dev/null +++ b/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 @@ -0,0 +1,14 @@ +@{ +GUID = "A94C8C7E-9810-47C0-B8AF-65089C13A35A" +Author = "PowerShell" +CompanyName = "Microsoft Corporation" +Copyright = "Copyright (c) Microsoft Corporation." +ModuleVersion = "7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion = "3.0" +FunctionsToExport = @() +CmdletsToExport = "Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "ConvertFrom-SecureString", "ConvertTo-SecureString", "Get-PfxCertificate" , "Protect-CmsMessage", "Unprotect-CmsMessage", "Get-CmsMessage" +AliasesToExport = @() +NestedModules = "Microsoft.PowerShell.Security.dll" +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..df8418376964d7c8d71af5970c562b5a0ba15339 --- /dev/null +++ b/PowerShell-master/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -0,0 +1,35 @@ +@{ +GUID = "1DA87E53-152B-403E-98DC-74D7B4D63D59" +Author = "PowerShell" +CompanyName = "Microsoft Corporation" +Copyright = "Copyright (c) Microsoft Corporation." +ModuleVersion = "7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion = "3.0" +CmdletsToExport = @( + 'Export-Alias', 'Get-Alias', 'Import-Alias', 'New-Alias', 'Remove-Alias', 'Set-Alias', 'Export-Clixml', + 'Import-Clixml', 'Measure-Command', 'Trace-Command', 'ConvertFrom-Csv', 'ConvertTo-Csv', 'Export-Csv', + 'Import-Csv', 'Get-Culture', 'Format-Custom', 'Get-Date', 'Set-Date', 'Write-Debug', 'Wait-Debugger', + 'Register-EngineEvent', 'Write-Error', 'Get-Event', 'New-Event', 'Remove-Event', 'Unregister-Event', + 'Wait-Event', 'Get-EventSubscriber', 'Invoke-Expression', 'Out-File', 'Get-FileHash', 'Export-FormatData', + 'Get-FormatData', 'Update-FormatData', 'New-Guid', 'Format-Hex', 'Get-Host', 'Read-Host', 'Write-Host', + 'ConvertTo-Html', 'Write-Information', 'ConvertFrom-Json', 'ConvertTo-Json', 'Test-Json', 'Format-List', + 'Import-LocalizedData', 'Send-MailMessage', 'ConvertFrom-Markdown', 'Show-Markdown', 'Get-MarkdownOption', + 'Set-MarkdownOption', 'Add-Member', 'Get-Member', 'Compare-Object', 'Group-Object', 'Measure-Object', + 'New-Object', 'Select-Object', 'Sort-Object', 'Tee-Object', 'Register-ObjectEvent', 'Write-Output', + 'Import-PowerShellDataFile', 'Write-Progress', 'Disable-PSBreakpoint', 'Enable-PSBreakpoint', + 'Get-PSBreakpoint', 'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession', + 'Import-PSSession', 'Get-Random', 'Get-SecureRandom', 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', + 'Disable-RunspaceDebug', 'Enable-RunspaceDebug', 'Get-RunspaceDebug', 'Start-Sleep', 'Join-String', + 'Out-String', 'Select-String', 'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryFile', 'New-TimeSpan', + 'Get-TraceSource', 'Set-TraceSource', 'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData', + 'Get-UICulture', 'Get-Unique', 'Get-Uptime', 'Clear-Variable', 'Get-Variable', 'New-Variable', + 'Remove-Variable', 'Set-Variable', 'Get-Verb', 'Write-Verbose', 'Write-Warning', 'Invoke-WebRequest', + 'Format-Wide', 'ConvertTo-Xml', 'Select-Xml', 'Get-Error', 'Update-List', 'Unblock-File', 'ConvertTo-CliXml', + 'ConvertFrom-CliXml' +) +FunctionsToExport = @() +AliasesToExport = @('fhx') +NestedModules = @("Microsoft.PowerShell.Commands.Utility.dll") +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 b/PowerShell-master/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..734fe45016d7d7d065bf642797bf873167aa4f6f --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 @@ -0,0 +1,18 @@ +@{ +GUID="{Fb6cc51d-c096-4b38-b78d-0fed6277096a}" +Author="PowerShell" +CompanyName="Microsoft Corporation" +Copyright="Copyright (c) Microsoft Corporation." +ModuleVersion="7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion="3.0" +RootModule="Microsoft.Management.Infrastructure.CimCmdlets" +RequiredAssemblies="Microsoft.Management.Infrastructure.CimCmdlets.dll","Microsoft.Management.Infrastructure.Dll" +FunctionsToExport = @() +CmdletsToExport= "Get-CimAssociatedInstance", "Get-CimClass", "Get-CimInstance", "Get-CimSession", "Invoke-CimMethod", + "New-CimInstance","New-CimSession","New-CimSessionOption","Register-CimIndicationEvent","Remove-CimInstance", + "Remove-CimSession","Set-CimInstance", + "Export-BinaryMiLog","Import-BinaryMiLog" +AliasesToExport = "gcim","scim","ncim", "rcim","icim","gcai","rcie","ncms","rcms","gcms","ncso","gcls" +HelpInfoUri="https://aka.ms/powershell75-help" +} diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml new file mode 100644 index 0000000000000000000000000000000000000000..8e0c106f7dd2bdbcb7f17f6ce3371e9b26a2cf92 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml @@ -0,0 +1,79 @@ + + + + + + + + Counter + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet + + + + + + 25 + left + + + + left + 100 + + + + + + + + Timestamp + + + Readings + + + + + + + + Counter + + Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo + + + + + 30 + left + + + 30 + left + + + 30 + left + + + + + + + + OldestRecord + + + NewestRecord + + + SampleCount + + + + + + + + diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml new file mode 100644 index 0000000000000000000000000000000000000000..3d105bc7c313e6c4d4860b9f2721417686cf6223 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml @@ -0,0 +1,121 @@ + + + + + Default + + System.Diagnostics.Eventing.Reader.EventLogRecord + + + ProviderName + + + + + + 25 + + + 8 + right + + + 16 + + + + + + + + + TimeCreated + + + Id + + + LevelDisplayName + + + Message + + + + + + + + + Default + + System.Diagnostics.Eventing.Reader.EventLogConfiguration + + + + + + + 9 + + + + 18 + right + + + + 11 + right + + + + + + + + LogMode + + + MaximumSizeInBytes + + + RecordCount + + + LogName + + + + + + + + Default + + System.Diagnostics.Eventing.Reader.ProviderMetadata + + + + + + + Name + + + LogLinks + + + Opcodes + + + Tasks + + + + + + + + + diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml new file mode 100644 index 0000000000000000000000000000000000000000..e63a9b56d9462b565e6968b0ee657f441d926bdd --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml @@ -0,0 +1,139 @@ + + + + + + System.Diagnostics.Eventing.Reader.EventLogConfiguration + + + PSStandardMembers + + + DefaultDisplayPropertySet + + LogName + MaximumSizeInBytes + RecordCount + LogMode + + + + + + + + System.Diagnostics.Eventing.Reader.EventLogRecord + + + PSStandardMembers + + + DefaultDisplayPropertySet + + TimeCreated + ProviderName + Id + Message + + + + + + + + System.Diagnostics.Eventing.Reader.ProviderMetadata + + + ProviderName + Name + + + PSStandardMembers + + + DefaultDisplayPropertySet + + Name + LogLinks + + + + + + + + Microsoft.PowerShell.Commands.GetCounter.CounterSet + + + Counter + Paths + + + + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample + + + PSStandardMembers + + + DefaultDisplayPropertySet + + Path + InstanceName + CookedValue + + + + + + + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet + + + PSStandardMembers + + + DefaultDisplayPropertySet + + Timestamp + Readings + + + + + + + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet + + + Readings + + $strPaths = "" + foreach ($ctr in $this.CounterSamples) + { + $strPaths += ($ctr.Path + " :" + "`n") + $strPaths += ($ctr.CookedValue.ToString() + "`n`n") + } + return $strPaths + + + + + diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..7f77777b137fdfee3646a084146f3e7c5468a0bd --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 @@ -0,0 +1,16 @@ +@{ +GUID="CA046F10-CA64-4740-8FF9-2565DBA61A4F" +Author="PowerShell" +CompanyName="Microsoft Corporation" +Copyright="Copyright (c) Microsoft Corporation." +ModuleVersion="7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion="3.0" +FunctionsToExport = @() +CmdletsToExport="Get-WinEvent", "New-WinEvent", "Get-Counter" +AliasesToExport = @() +NestedModules="Microsoft.PowerShell.Commands.Diagnostics.dll" +TypesToProcess="GetEvent.types.ps1xml" +FormatsToProcess="Event.format.ps1xml", "Diagnostics.format.ps1xml" +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..f75829209354fcc91265c341981854a3c62bab09 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -0,0 +1,74 @@ +@{ +GUID="EEFCB906-B326-4E99-9F54-8B4BB6EF3C6D" +Author="PowerShell" +CompanyName="Microsoft Corporation" +Copyright="Copyright (c) Microsoft Corporation." +ModuleVersion="7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion="3.0" +NestedModules="Microsoft.PowerShell.Commands.Management.dll" +HelpInfoURI = 'https://aka.ms/powershell75-help' +FunctionsToExport = @() +AliasesToExport = @("gcb", "gin", "gtz", "scb", "stz") +CmdletsToExport=@("Add-Content", + "Clear-Content", + "Get-Clipboard", + "Set-Clipboard", + "Clear-ItemProperty", + "Join-Path", + "Convert-Path", + "Copy-ItemProperty", + "Get-ChildItem", + "Get-Content", + "Get-ItemProperty", + "Get-ItemPropertyValue", + "Move-ItemProperty", + "Get-Location", + "Set-Location", + "Push-Location", + "Pop-Location", + "New-PSDrive", + "Remove-PSDrive", + "Get-PSDrive", + "Get-Item", + "New-Item", + "Set-Item", + "Remove-Item", + "Move-Item", + "Rename-Item", + "Copy-Item", + "Clear-Item", + "Invoke-Item", + "Get-PSProvider", + "New-ItemProperty", + "Split-Path", + "Test-Path", + "Test-Connection", + "Get-Process", + "Stop-Process", + "Wait-Process", + "Debug-Process", + "Start-Process", + "Remove-ItemProperty", + "Rename-ItemProperty", + "Resolve-Path", + "Get-Service", + "Stop-Service", + "Start-Service", + "Suspend-Service", + "Resume-Service", + "Restart-Service", + "Set-Service", + "New-Service", + "Remove-Service", + "Set-Content", + "Set-ItemProperty", + "Restart-Computer", + "Stop-Computer", + "Rename-Computer", + "Get-ComputerInfo", + "Get-TimeZone", + "Set-TimeZone", + "Get-HotFix", + "Clear-RecycleBin") +} diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..0953b2d1ccad4889a86afa0e721117c02a3f5602 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 @@ -0,0 +1,18 @@ +@{ +GUID = "A94C8C7E-9810-47C0-B8AF-65089C13A35A" +Author = "PowerShell" +CompanyName = "Microsoft Corporation" +Copyright = "Copyright (c) Microsoft Corporation." +ModuleVersion = "7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion = "3.0" +FunctionsToExport = @() +CmdletsToExport = "Get-Acl", "Set-Acl", "Get-PfxCertificate", "Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "Get-AuthenticodeSignature", "Set-AuthenticodeSignature", "ConvertFrom-SecureString", "ConvertTo-SecureString", "Get-CmsMessage", "Unprotect-CmsMessage", "Protect-CmsMessage" , "New-FileCatalog" , "Test-FileCatalog" +AliasesToExport = @() +NestedModules = "Microsoft.PowerShell.Security.dll" +# 'Security.types.ps1xml' refers to types from 'Microsoft.PowerShell.Security.dll' and thus requiring to load the assembly before processing the type file. +# We declare 'Microsoft.PowerShell.Security.dll' in 'RequiredAssemblies' so as to make sure it's loaded before the type file processing. +RequiredAssemblies = "Microsoft.PowerShell.Security.dll" +TypesToProcess = "Security.types.ps1xml" +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Security/Security.types.ps1xml b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Security/Security.types.ps1xml new file mode 100644 index 0000000000000000000000000000000000000000..b1171c98e6a5ae05166223fecfa51bc0db67b751 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Security/Security.types.ps1xml @@ -0,0 +1,124 @@ + + + + + + System.Security.AccessControl.ObjectSecurity + + + Path + + Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase + GetPath + + + + Owner + + Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase + GetOwner + + + + Group + + Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase + GetGroup + + + + Access + + Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase + GetAccess + + + + Sddl + + Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase + GetSddl + + + + AccessToString + + $toString = ""; + $first = $true; + if ( ! $this.Access ) { return "" } + foreach($ace in $this.Access) + { + if($first) + { + $first = $false; + } + else + { + $tostring += "`n"; + } + $toString += $ace.IdentityReference.ToString(); + $toString += " "; + $toString += $ace.AccessControlType.ToString(); + $toString += " "; + if($ace -is [System.Security.AccessControl.FileSystemAccessRule]) + { + $toString += $ace.FileSystemRights.ToString(); + } + elseif($ace -is [System.Security.AccessControl.RegistryAccessRule]) + { + $toString += $ace.RegistryRights.ToString(); + } + } + return $toString; + + + + AuditToString + + $toString = ""; + $first = $true; + if ( ! (& { Set-StrictMode -Version 1; $this.audit }) ) { return "" } + foreach($ace in (& { Set-StrictMode -Version 1; $this.audit })) + { + if($first) + { + $first = $false; + } + else + { + $tostring += "`n"; + } + $toString += $ace.IdentityReference.ToString(); + $toString += " "; + $toString += $ace.AuditFlags.ToString(); + $toString += " "; + if($ace -is [System.Security.AccessControl.FileSystemAuditRule]) + { + $toString += $ace.FileSystemRights.ToString(); + } + elseif($ace -is [System.Security.AccessControl.RegistryAuditRule]) + { + $toString += $ace.RegistryRights.ToString(); + } + } + return $toString; + + + + + + diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..2043543a8a56273778297244c08cc629cb3c2f70 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -0,0 +1,33 @@ +@{ +GUID = "1DA87E53-152B-403E-98DC-74D7B4D63D59" +Author = "PowerShell" +CompanyName = "Microsoft Corporation" +Copyright = "Copyright (c) Microsoft Corporation." +ModuleVersion = "7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion = "3.0" +CmdletsToExport = @( + 'Export-Alias', 'Get-Alias', 'Import-Alias', 'New-Alias', 'Remove-Alias', 'Set-Alias', 'Export-Clixml', 'Import-Clixml', + 'Measure-Command', 'Trace-Command', 'ConvertFrom-Csv', 'ConvertTo-Csv', 'Export-Csv', 'Import-Csv', 'Get-Culture', + 'Format-Custom', 'Get-Date', 'Set-Date', 'Write-Debug', 'Wait-Debugger', 'Register-EngineEvent', 'Write-Error', + 'Get-Event', 'New-Event', 'Remove-Event', 'Unregister-Event', 'Wait-Event', 'Get-EventSubscriber', 'Invoke-Expression', + 'Out-File', 'Unblock-File', 'Get-FileHash', 'Export-FormatData', 'Get-FormatData', 'Update-FormatData', 'New-Guid', + 'Format-Hex', 'Get-Host', 'Read-Host', 'Write-Host', 'ConvertTo-Html', 'Write-Information', 'ConvertFrom-Json', + 'ConvertTo-Json', 'Test-Json', 'Format-List', 'Import-LocalizedData', 'Send-MailMessage', 'ConvertFrom-Markdown', + 'Show-Markdown', 'Get-MarkdownOption', 'Set-MarkdownOption', 'Add-Member', 'Get-Member', 'Compare-Object', 'Group-Object', + 'Measure-Object', 'New-Object', 'Select-Object', 'Sort-Object', 'Tee-Object', 'Register-ObjectEvent', 'Write-Output', + 'Import-PowerShellDataFile', 'Write-Progress', 'Disable-PSBreakpoint', 'Enable-PSBreakpoint', 'Get-PSBreakpoint', + 'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession', 'Import-PSSession', 'Get-Random', 'Get-SecureRandom' + 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', 'Disable-RunspaceDebug', 'Enable-RunspaceDebug', + 'Get-RunspaceDebug', 'ConvertFrom-SddlString', 'Start-Sleep', 'Join-String', 'Out-String', 'Select-String', + 'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryFile', 'New-TimeSpan', 'Get-TraceSource', 'Set-TraceSource', + 'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData', 'Get-UICulture', 'Get-Unique', 'Get-Uptime', + 'Clear-Variable', 'Get-Variable', 'New-Variable', 'Remove-Variable', 'Set-Variable', 'Get-Verb', 'Write-Verbose', + 'Write-Warning', 'Invoke-WebRequest', 'Format-Wide', 'ConvertTo-Xml', 'Select-Xml', 'Get-Error', 'Update-List', + 'Out-GridView', 'Show-Command', 'Out-Printer', 'ConvertTo-CliXml', 'ConvertFrom-CliXml' +) +FunctionsToExport = @() +AliasesToExport = @('fhx') +NestedModules = @("Microsoft.PowerShell.Commands.Utility.dll") +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 b/PowerShell-master/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..ced706c9fdecfba414746424dec41d2d2b79276f --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 @@ -0,0 +1,15 @@ +@{ +GUID="766204A6-330E-4263-A7AB-46C87AFC366C" +Author="PowerShell" +CompanyName="Microsoft Corporation" +Copyright="Copyright (c) Microsoft Corporation." +ModuleVersion="7.0.0.0" +CompatiblePSEditions = @("Core") +PowerShellVersion="3.0" +FunctionsToExport = @() +CmdletsToExport="Disable-WSManCredSSP", "Enable-WSManCredSSP", "Get-WSManCredSSP", "Set-WSManQuickConfig", "Test-WSMan", "Invoke-WSManAction", "Connect-WSMan", "Disconnect-WSMan", "Get-WSManInstance", "Set-WSManInstance", "Remove-WSManInstance", "New-WSManInstance", "New-WSManSessionOption" +AliasesToExport = @() +NestedModules="Microsoft.WSMan.Management.dll" +FormatsToProcess="WSMan.format.ps1xml" +HelpInfoURI = 'https://aka.ms/powershell75-help' +} diff --git a/PowerShell-master/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml b/PowerShell-master/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml new file mode 100644 index 0000000000000000000000000000000000000000..bbee94971d5e8d4365afc3b7eb1ab8beaad415d4 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml @@ -0,0 +1,236 @@ + + + + + + + System.Xml.XmlElement#http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd#IdentifyResponse + + System.Xml.XmlElement#http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd#IdentifyResponse + + + + + + + wsmid + + + ProtocolVersion + + + ProductVendor + + + ProductVersion + + + + + + + + Microsoft.WSMan.Management.WSManConfigElement + + Microsoft.WSMan.Management.WSManConfigElement + + + PSParentPath + + + + + + + 15 + + + + 30 + + + + + + + TypeNameOfElement + + + Name + + + + + + + + Microsoft.WSMan.Management.WSManConfigContainerElement + + Microsoft.WSMan.Management.WSManConfigContainerElement + + + PSParentPath + + + + + + + 15 + + + + 35 + + + + + + + + + + TypeNameOfElement + + + Keys + + + Name + + + + + + + + Microsoft.WSMan.Management.WSManConfigLeafElement + + Microsoft.WSMan.Management.WSManConfigLeafElement + + + PSParentPath + + + + + + + 15 + + + + 30 + + + + 15 + + + + + + + + + + TypeNameOfElement + + + Name + + + SourceOfValue + + + Value + + + + + + + + Microsoft.WSMan.Management.WSManConfigLeafElement#InitParams + + Microsoft.WSMan.Management.WSManConfigLeafElement#InitParams + + + PSParentPath + + + + + + + 30 + + + + 20 + + + + + + + Name + + + Value + + + + + + + + Microsoft.WSMan.Management.WSManConfigContainerElement#ComputerLevel + + Microsoft.WSMan.Management.WSManConfigContainerElement#ComputerLevel + + + PSParentPath + + + + + + + 45 + + + + 20 + + + + + + + Name + + + TypeNameOfElement + + + + + + + + diff --git a/PowerShell-master/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 b/PowerShell-master/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..3b53d6740e547821f66c488166de61d11e1aaafe --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 @@ -0,0 +1,14 @@ +@{ + GUID="c61d6278-02a3-4618-ae37-a524d40a7f44 " + Author="PowerShell" + CompanyName="Microsoft Corporation" + Copyright="Copyright (c) Microsoft Corporation." + ModuleVersion="7.0.0.0" + CompatiblePSEditions = @("Core") + PowerShellVersion="3.0" + ModuleToProcess="PSDiagnostics.psm1" + FunctionsToExport="Disable-PSTrace","Disable-PSWSManCombinedTrace","Disable-WSManTrace","Enable-PSTrace","Enable-PSWSManCombinedTrace","Enable-WSManTrace","Get-LogProperties","Set-LogProperties","Start-Trace","Stop-Trace" + CmdletsToExport = @() + AliasesToExport = @() + HelpInfoUri="https://aka.ms/powershell75-help" +} diff --git a/PowerShell-master/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 b/PowerShell-master/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 new file mode 100644 index 0000000000000000000000000000000000000000..c31e9f2596349e0590921827da56d1c8ad938da7 --- /dev/null +++ b/PowerShell-master/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 @@ -0,0 +1,448 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +<# + PowerShell Diagnostics Module + This module contains a set of wrapper scripts that + enable a user to use ETW tracing in PowerShell 7. + #> + +$script:windir = [System.Environment]::GetEnvironmentVariable("windir", [System.EnvironmentVariableTarget]::Machine) + +$script:Logman = "${script:windir}\system32\logman.exe" +$script:wsmanlogfile = "${script:windir}\system32\wsmtraces.log" +$script:wsmprovfile = "${script:windir}\system32\wsmtraceproviders.txt" +$script:wsmsession = "wsmlog" +$script:pssession = "PSTrace" +$script:psprovidername = "PowerShellCore" +$script:wsmprovidername = "Microsoft-Windows-WinRM" +$script:oplog = "/Operational" +$script:analyticlog = "/Analytic" +$script:debuglog = "/Debug" +$script:wevtutil = "${script:windir}\system32\wevtutil.exe" +$script:slparam = "sl" +$script:glparam = "gl" + +function Start-Trace +{ + Param( + [Parameter(Mandatory=$true, + Position=0)] + [string] + $SessionName, + [Parameter(Position=1)] + [ValidateNotNullOrEmpty()] + [string] + $OutputFilePath, + [Parameter(Position=2)] + [ValidateNotNullOrEmpty()] + [string] + $ProviderFilePath, + [Parameter()] + [Switch] + $ETS, + [Parameter()] + [ValidateSet("bin", "bincirc", "csv", "tsv", "sql")] + $Format, + [Parameter()] + [int] + $MinBuffers=0, + [Parameter()] + [int] + $MaxBuffers=256, + [Parameter()] + [int] + $BufferSizeInKB = 0, + [Parameter()] + [int] + $MaxLogFileSizeInMB=0 + ) + + Process + { + $executestring = " start $SessionName" + + if ($ETS) + { + $executestring += " -ets" + } + + if ($null -ne $OutputFilePath) + { + $executestring += " -o ""$OutputFilePath""" + } + + if ($null -ne $ProviderFilePath) + { + $executestring += " -pf ""$ProviderFilePath""" + } + + if ($null -ne $Format) + { + $executestring += " -f $Format" + } + + if ($MinBuffers -ne 0 -or $MaxBuffers -ne 256) + { + $executestring += " -nb $MinBuffers $MaxBuffers" + } + + if ($BufferSizeInKB -ne 0) + { + $executestring += " -bs $BufferSizeInKB" + } + + if ($MaxLogFileSizeInMB -ne 0) + { + $executestring += " -max $MaxLogFileSizeInMB" + } + + & $script:Logman $executestring.Split(" ") + } +} + +function Stop-Trace +{ + param( + [Parameter(Mandatory=$true, + Position=0)] + $SessionName, + [Parameter()] + [switch] + $ETS + ) + + Process + { + if ($ETS) + { + & $script:Logman update $SessionName -ets + & $script:Logman stop $SessionName -ets + } + else + { + & $script:Logman update $SessionName + & $script:Logman stop $SessionName + } + } +} + +function Enable-WSManTrace +{ + + # winrm + "{04c6e16d-b99f-4a3a-9b3e-b8325bbc781e} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii + + # winrsmgr + "{c0a36be8-a515-4cfa-b2b6-2676366efff7} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + # WinrsExe + "{f1cab2c0-8beb-4fa2-90e1-8f17e0acdd5d} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + # WinrsCmd + "{03992646-3dfe-4477-80e3-85936ace7abb} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + # IPMIPrv + "{651d672b-e11f-41b7-add3-c2f6a4023672} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + #IpmiDrv + "{D5C6A3E9-FA9C-434e-9653-165B4FC869E4} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + # WSManProvHost + "{6e1b64d7-d3be-4651-90fb-3583af89d7f1} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + # Event Forwarding + "{6FCDF39A-EF67-483D-A661-76D715C6B008} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append + + Start-Trace -SessionName $script:wsmsession -ETS -OutputFilePath $script:wsmanlogfile -Format bincirc -MinBuffers 16 -MaxBuffers 256 -BufferSizeInKB 64 -MaxLogFileSizeInMB 256 -ProviderFilePath $script:wsmprovfile +} + +function Disable-WSManTrace +{ + Stop-Trace $script:wsmsession -ETS +} + +function Enable-PSWSManCombinedTrace +{ + param ( + [switch] $DoNotOverwriteExistingTrace + ) + + $provfile = [io.path]::GetTempFilename() + + if ($DoNotOverwriteExistingTrace) { + $fileName = [string][guid]::newguid() + $logfile = $PSHOME + "\\Traces\\PSTrace_$fileName.etl" + } else { + $logfile = $PSHOME + "\\Traces\\PSTrace.etl" + } + + "$script:psprovidername 0 5" | Out-File $provfile -Encoding ascii + "$script:wsmprovidername 0 5" | Out-File $provfile -Encoding ascii -Append + + if (!(Test-Path $PSHOME\Traces)) + { + New-Item -ItemType Directory -Force $PSHOME\Traces | Out-Null + } + + if (Test-Path $logfile) + { + Remove-Item -Force $logfile | Out-Null + } + + Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ETS + + Remove-Item $provfile -Force -ErrorAction SilentlyContinue +} + +function Disable-PSWSManCombinedTrace +{ + Stop-Trace -SessionName $script:pssession -ETS +} + +function Set-LogProperties +{ + param( + [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] + [Microsoft.PowerShell.Diagnostics.LogDetails] + $LogDetails, + [switch] $Force + ) + + Process + { + if ($LogDetails.AutoBackup -and !$LogDetails.Retention) + { + throw (New-Object System.InvalidOperationException) + } + + $enabled = $LogDetails.Enabled.ToString() + $retention = $LogDetails.Retention.ToString() + $autobackup = $LogDetails.AutoBackup.ToString() + $maxLogSize = $LogDetails.MaxLogSize.ToString() + $osVersion = [Version] (Get-CimInstance Win32_OperatingSystem).Version + + if (($LogDetails.Type -eq "Analytic") -or ($LogDetails.Type -eq "Debug")) + { + if ($LogDetails.Enabled) + { + if($osVersion -lt 6.3.7600) + { + & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled + } + else + { + & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled + } + } + else + { + if($osVersion -lt 6.3.7600) + { + & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize + } + else + { + & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize + } + } + } + else + { + if($osVersion -lt 6.3.7600) + { + & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize + } + else + { + & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize + } + } + } +} + +function ConvertTo-Bool([string]$value) +{ + if ($value -ieq "true") + { + return $true + } + else + { + return $false + } +} + +function Get-LogProperties +{ + param( + [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] $Name + ) + + Process + { + $details = & $script:wevtutil $script:glparam $Name + $indexes = @(1,2,8,9,10) + $value = @() + foreach($index in $indexes) + { + $value += @(($details[$index].SubString($details[$index].IndexOf(":")+1)).Trim()) + } + + $enabled = ConvertTo-Bool $value[0] + $retention = ConvertTo-Bool $value[2] + $autobackup = ConvertTo-Bool $value[3] + + New-Object Microsoft.PowerShell.Diagnostics.LogDetails $Name, $enabled, $value[1], $retention, $autobackup, $value[4] + } +} + +function Enable-PSTrace +{ + param( + [switch] $Force, + [switch] $AnalyticOnly + ) + + $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog) + + if (!$Properties.Enabled) { + $Properties.Enabled = $true + if ($Force) { + Set-LogProperties $Properties -Force + } else { + Set-LogProperties $Properties + } + } + + if (!$AnalyticOnly) { + $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog) + if (!$Properties.Enabled) { + $Properties.Enabled = $true + if ($Force) { + Set-LogProperties $Properties -Force + } else { + Set-LogProperties $Properties + } + } + } +} + +function Disable-PSTrace +{ + param( + [switch] $AnalyticOnly + ) + $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog) + if ($Properties.Enabled) { + $Properties.Enabled = $false + Set-LogProperties $Properties + } + + if (!$AnalyticOnly) { + $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog) + if ($Properties.Enabled) { + $Properties.Enabled = $false + Set-LogProperties $Properties + } + } +} +Add-Type @" +using System; + +namespace Microsoft.PowerShell.Diagnostics +{ + public class LogDetails + { + public string Name + { + get + { + return name; + } + } + private string name; + + public bool Enabled + { + get + { + return enabled; + } + set + { + enabled = value; + } + } + private bool enabled; + + public string Type + { + get + { + return type; + } + } + private string type; + + public bool Retention + { + get + { + return retention; + } + set + { + retention = value; + } + } + private bool retention; + + public bool AutoBackup + { + get + { + return autoBackup; + } + set + { + autoBackup = value; + } + } + private bool autoBackup; + + public int MaxLogSize + { + get + { + return maxLogSize; + } + set + { + maxLogSize = value; + } + } + private int maxLogSize; + + public LogDetails(string name, bool enabled, string type, bool retention, bool autoBackup, int maxLogSize) + { + this.name = name; + this.enabled = enabled; + this.type = type; + this.retention = retention; + this.autoBackup = autoBackup; + this.maxLogSize = maxLogSize; + } + } +} +"@ + +if (Get-Command logman.exe -Type Application -ErrorAction SilentlyContinue) +{ + Export-ModuleMember Disable-PSTrace, Disable-PSWSManCombinedTrace, Disable-WSManTrace, Enable-PSTrace, Enable-PSWSManCombinedTrace, Enable-WSManTrace, Get-LogProperties, Set-LogProperties, Start-Trace, Stop-Trace +} +else +{ + # Currently we only support these cmdlets as logman.exe is not available on systems like Nano and IoT + Export-ModuleMember Disable-PSTrace, Enable-PSTrace, Get-LogProperties, Set-LogProperties +} diff --git a/PowerShell-master/src/Modules/nuget.config b/PowerShell-master/src/Modules/nuget.config new file mode 100644 index 0000000000000000000000000000000000000000..388a65572dd1d20625911c0acb3731dcb6ca9110 --- /dev/null +++ b/PowerShell-master/src/Modules/nuget.config @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/PowerShell-master/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man b/PowerShell-master/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man new file mode 100644 index 0000000000000000000000000000000000000000..fb221cfe9644821aa47bef3a8eff82218cfdccba --- /dev/null +++ b/PowerShell-master/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man @@ -0,0 +1,5725 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + 15728640 + + + + + + true + + 1048985600 + + + + 64 + + + + + + true + + 1048985600 + + + + 64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +